Exemplo n.º 1
0
 def __init__(self, API_KEY):
     tinify.key = API_KEY
     try:
         tinify.validate()
     except Exception as e:
         print("Wrong account details")
         sys.exit(1)
Exemplo n.º 2
0
def main():
    try:

        tinify.key = settings.API_KEY
        tinify.validate()
        ct = 1

        create_dirs()
        raw_image_pull = get_raw_images()
        for image in raw_image_pull:
            change_dir(image)
            compress_and_save(image, ct)
            ct += 1
        print('All optimized images have been saved')

    except tinify.AccountError:
        print(
            'AccountError: Please verify your Tinify API key and account limit...'
        )
    except tinify.ClientError:
        print('ClientError: Please check your source image...')
    except tinify.ServerError:
        print(
            'ServerError: Temporary issue with the Tinify API. Please try again later...\n'
        )
    except tinify.ConnectionError:
        print(
            'ConnectionError: A network connection error occurred. Please try again later...\n'
        )
    except Exception as e:
        print(
            'UnknownError: Something went wrong. Please try again later...\n',
            e)
Exemplo n.º 3
0
 def validate_key():
     try:
         tinify.validate()
         print(f'校验成功')
         print(f'本月已压缩 {tinify.compression_count} 张')
     except tinify.Error as e:
         print('校验失败')
         print(e)
Exemplo n.º 4
0
def setkey():
    try:
        tinify.key = gsecrets.get_tinify_apikey()
        tinify.validate()  # pylint: disable=no-member
    except tinify.Error:
        log.warning("Tinify key failed - dropping secret cache, retrying")
        gsecrets.reset()
        tinify.key = gsecrets.get_tinify_apikey()
Exemplo n.º 5
0
def ting_pic(filename, savename):
    try:
        tinify.key = "******"
        tinify.validate()
    except tinify.Error, e:
        # Validation of API key failed.
        current_app.logger.error(tinify.Error)
        current_app.logger.error(e)
Exemplo n.º 6
0
 def __init__(self, key):
     self._init = False
     try:
         tinify.key = key
         tinify.validate()
     except tinify.Error as e:
         logging.error(e.message)
         raise Tinifier.Error("Failed to validate key with Tinify")
     self._init = True
Exemplo n.º 7
0
 def test_with_error_should_raise_error(self):
     httpretty.register_uri(
         httpretty.POST,
         'https://api.tinify.com/shrink',
         status=401,
         body='{"error":"Unauthorized","message":"Credentials are invalid"}'
     )
     tinify.key = 'valid'
     with self.assertRaises(tinify.AccountError):
         tinify.validate()
Exemplo n.º 8
0
def check_api_key():
    global keys_index
    global keys_len
    while keys_index < keys_len:
        valid = True
        try:
            tinify.key = ting_keys[keys_index]
            tinify.validate()
        except tinify.AccountError, e:
            print "Your free API Key %s validate failed!!!\n" % ting_keys[
                keys_index]
            valid = False
        except Exception, e:
            valid = False
Exemplo n.º 9
0
def check_informations():
    from GUI import tk

    if vc.var_extension.get() == '':
        vc.files_log_dialog.insert(
            tk.END,
            '\nChoose an extension to file before begining to optimize')
        return False

    try:
        for i in vc.var_images:
            pass
    except:
        vc.files_log_dialog.insert(tk.END, '\nNo Images Added')
        return False

    try:
        vc.files_log_dialog.insert(tk.END, '\nValidating API Key')
        vc.files_log_dialog.update_idletasks()

        tf.key = vc.api_entry.get()
        tf.validate()

    except tf.Error:
        vc.files_log_dialog.insert(
            tk.END,
            '\nAPI Key Authentication Failed. Try another API key or check Internet connection...'
        )
        vc.files_log_dialog.update_idletasks()
        return False

    vc.files_log_dialog.insert(tk.END, '\nAPI Authentication Succeeded.')
    vc.files_log_dialog.update_idletasks()

    # If there is no api key stored it will grab api key from entry and store it in vc file
    try:
        tf.key = vc.var_api_key
    except AttributeError:
        with open('test_only_temp.py', 'w') as file:
            file.write('var_api_key = \'' + vc.api_entry.get() + '\'\n')
            with open('variable_container.py', 'r') as original:
                file.write(original.read())
        with open('variable_container.py', 'w') as original:
            with open('test_only_temp.py', 'r') as to_be_copied:
                original.write(to_be_copied.read())
            os.remove('test_only_temp.py')
        vc.files_log_dialog.insert(tk.END, '\nAPI Key updated successfully')
    return True
def cStart():

    finder = os.getcwd()
    try:
        tinify.validate()
        if tinify.compression_count < 500:
            print(f'本月已压缩图片次数{tinify.compression_count}')
            ci = CompressImg(finder)
            ci.get_img_path(finder)
            ci.handle_compress()
            # ci.handle_copy()

        else:
            print(f'本月压缩图片次数不足')
    except tinify.Error as e:
        print(f'{e}error')
Exemplo n.º 11
0
 def test_with_valid_key_should_return_true(self):
     httpretty.register_uri(
         httpretty.POST,
         'https://api.tinify.com/shrink',
         status=400,
         body='{"error":"Input missing","message":"No input"}')
     tinify.key = 'valid'
     self.assertEqual(True, tinify.validate())
Exemplo n.º 12
0
 def test_with_limited_key_should_return_true(self):
     httpretty.register_uri(
         httpretty.POST,
         'https://api.tinify.com/shrink',
         status=429,
         body=
         '{"error":"Too many requests","message":"Your monthly limit has been exceeded"}'
     )
     tinify.key = 'valid'
     self.assertEqual(True, tinify.validate())
Exemplo n.º 13
0
def init_tiny(start):
    global current_key_index

    current_key_index = 0
    for i in range(start, len(KEYS)):
        tinify.key = KEYS[current_key_index]
        if tinify.validate():
            current_key_index = i
            return True
    return False
Exemplo n.º 14
0
def validate_key(key: str) -> bool:
    """Validate the Tinify API key."""
    if not key:
        return False

    tinify.key = key
    try:
        return tinify.validate()
    except tinify.Error:
        return False
def CompressByTinypng(fromFile, out_dir):
    print("do CompressByTinypng..")
    try:
        for root, dir, files in os.walk(fromFile):
            print(
                "****************************************************************************************"
            )
            print("root dir:" + root)
            print("dir:" + str(dir))
            for file in files:
                current_file = os.path.join(root, file)
                dirName = os.path.basename(root)
                # 如果没有指定输出路径,则默认覆盖当前文件
                if not out_dir:
                    out_dir = fromFile
                targetDir = os.path.join(out_dir, dirName)
                if not os.path.exists(targetDir):
                    os.makedirs(targetDir)
                # 如果是.9图片或者非图片文件不做处理,直接做拷贝
                if not file.endswith(".9.png") and (file.endswith(".png")
                                                    or file.endswith(".jpg")):
                    print(
                        "--------------------------------------------------------------------------------------------"
                    )
                    # for key in tinify_keys:
                    # 验证当前API key是否可以用,不可以用就切换下一个账号
                    tinify.key = tinify_keys[0]
                    try:
                        valid = tinify.validate()
                        if valid:
                            print("currrent file:" + current_file)
                            origin_size = os.path.getsize(current_file)
                            source = tinify.from_file(current_file)
                            target_file = os.path.join(targetDir, file)
                            source.to_file(target_file)
                            compress_size = os.path.getsize(target_file)
                            print(
                                '%.2f' %
                                ((origin_size - compress_size) / origin_size))
                        else:
                            continue
                    except Exception as e:
                        # Something else went wrong, unrelated to the Tinify API.
                        print("error while compressing png image:" + e.message)
                        continue
                else:
                    if not out_dir or out_dir == fromFile:
                        continue
                    shutil.copy(current_file, os.path.join(targetDir, file))

    except Exception as e:
        print(e.message)
Exemplo n.º 16
0
 def validate(apiKey: str):
     """
     验证用户的api key是否有效
     :param apiKey: 用户的api key
     :return: True 有效用户
     """
     try:
         tinify.key = apiKey
         return tinify.validate()
     except tinify.Error as e:
         # Validation of API key failed.
         LogUtil.e('TinifyUtil Validation of API key failed. 错误信息:', e)
         return False
Exemplo n.º 17
0
    def compress_execute(self):
        try:

            tinify.key = self._api_key.get()
            tinify.validate()

            self._status.set('Calculating Raw Images...')
            self.status_label.update()

            self.raw_images = get_raw_images(self._folder_url1.get())
            if not self.raw_images:
                self._status.set('No images found within supported formats!!!'
                                 )
                self.status_label.update()
                messagebox.showinfo('Compresssio',
                                    'No images found within supported formats. Please check the INPUT Folder and Try Again!!!'
                                    )
                self.reset_callback()
            else:
                create_dirs(self.raw_images, self._folder_url2.get())

                self._status.set('Compression in Progress....')
                self.status_label.update()
                length = len(self.raw_images)

                for (index, image) in enumerate(self.raw_images):
                    if self.stopFlag:
                        self.stopFlag = False
                        return

                    (only_image_path, image_info) = os.path.split(image)
                    self._status.set('Compressing Image [{}/{}] : {}'.format(index
                            + 1, length, image_info))
                    self.status_label.update()
                    change_dir(image, self._folder_url1.get(),
                               self._folder_url2.get())
                    compress_and_save(self._folder_url1.get() + '/'
                            + image)
                self._status.set('Compression Completed !!')
                self.status_label.update()
                self.stopFlag = False
                self.enable()
                messagebox.showinfo('Compresssio',
                                    'Compression Completed !!')
        except tinify.AccountError:

            messagebox.showinfo('AccountError',
                                'Please verify your Tinify API key and account limit...'
                                )
        except tinify.ClientError:
            messagebox.showinfo('ClientError',
                                'Please check your source images...')
        except tinify.ServerError:
            messagebox.showinfo('ServerError',
                                """Temporary issue with the Tinify API. 
            	Please try again later..."""
                                )
        except tinify.ConnectionError:
            messagebox.showinfo('ConnectionError',
                                """A network connection error occurred. 
            	Please check your Internet Connection and Try again..."""
                                )
        except Exception as e:
            messagebox.showinfo('UnknownError',
                                'Something went wrong. Please try again later...'
                                )
        self.enable()
Exemplo n.º 18
0
def compression_count():
    tinify.validate()
    compressions_this_month = tinify.compression_count
    # print("{} images you have made this month.".format(compressions_this_month))
    logger.info("{} images you have made this month.".format(compressions_this_month))
Exemplo n.º 19
0
 def test_with_limited_key_should_return_true(self):
     httpretty.register_uri(httpretty.POST, 'https://api.tinify.com/shrink', status=429,
         body='{"error":"Too many requests","message":"Your monthly limit has been exceeded"}')
     tinify.key = 'valid'
     self.assertEqual(True, tinify.validate())
Exemplo n.º 20
0
def validate(key):
    try:
        tinify.key = key
        tinify.validate()
    except tinify.Error as e:
        raise Exception(e)
Exemplo n.º 21
0
def do_tinify_list():
    print("validate keys ...")
    input_dir = sys.argv[1]
    now_dir_name = input_dir.split("\\")[-1]
    new_dir_name = "new_image_{0}".format(int(time.time()))
    output_dir = "./"+new_dir_name

    #建立新的目录及子目录
    dir_list = dirlist(input_dir,[],now_dir_name,new_dir_name)
    os.mkdir(output_dir)
    for dir_path in dir_list[::-1]:
        os.mkdir(dir_path)

    image_names = get_all_images(input_dir)
    total = len(image_names)

    #判断使用哪个Key,一个Key只能使用500次
    key_effective = False
    for key in keys:
        tinify.key = key
        tinify.validate()
        remain = 500-tinify.compression_count
        if remain>total:
            key_effective = True
            break

    if key_effective:
        print("now_key:"+tinify.key)
        #get scale

        mode = input("\nselect scale mode :\n[1]scale by percentage\n[2]scale by fixed width\nenter your choice (default=1):")
        if mode is not "2" :
            mode = 1
        else:
            mode = 2
        print("Scale mode is {0}".format(mode))

        if mode is 1:
            scale_percentage = input("enter scale_percentage,0<scale_percentage<=100,default = 100 :")
            try:
                scale_percentage = float(scale_percentage);
                if scale_percentage>=100.0 or scale_percentage<0:
                    scale_percentage = 100.0
            except:
                scale_percentage = 100.0
            print("convert scale_percentage is "+str(scale_percentage)+"%")
            scale_percentage = scale_percentage/100

            print("convert start ...")
            threads = []
            for index,image_name in enumerate(image_names):
               #threads.append(threading.Thread(target=do_timo,args=(image_name,total,now_dir_name,new_dir_name,index,scale_percentage,2)))
               threads.append(threading.Thread(target=do_timo,args=(image_name,total,now_dir_name,new_dir_name,index,scale_percentage,1)))
            for t in threads:
                t.start()
        elif mode is 2:
            fixedWidth = input("enter fixed width(integer) ,default or wrong input cause no scale:")
            try:
                fixedWidth = int(fixedWidth)
                print("fixed width is {0}".format(fixedWidth))
            except:
                fixedWidth = None
                print("will be no scale")

            print("convert start ...")
            threads = []
            for index,image_name in enumerate(image_names):
               #threads.append(threading.Thread(target=do_timo,args=(image_name,total,now_dir_name,new_dir_name,index,scale_percentage,2)))
               threads.append(threading.Thread(target=do_timo,args=(image_name,total,now_dir_name,new_dir_name,index,fixedWidth,2)))
            for t in threads:
                t.start()
    else:
        print("please check your key list,compression count may be full !!!")
Exemplo n.º 22
0
var_location = None
var_output_path = 'Current path'

# Values are the row information and respective checkbox variables
metadata_list = {
    'copyright': [0, var_copyright],
    'location': [1, var_location],
    'creation': [2, var_creation]
}

# To Avoid Circular Import
files_log_dialog = None
api_entry = None
optimization_number_entry = None
compression_status_counter = None

# List of File Types Supported
filetypes = [("PNG File", ".png"), ("JPG File", ".jpg"),
             ("JPEG File", ".jpeg"), ('WEBP File', '.webp')]

try:
    tf.key = var_api_key
    tf.validate()
    compression_counter_data = {
        'Current API:\n': api_entry,
        'Compressions Done:': tf.compression_count,
        'Compressions Remaining:': 500 - tf.compression_count
    }
except:
    print("No key")
Exemplo n.º 23
0
 def test_with_valid_key_should_return_true(self):
     httpretty.register_uri(httpretty.POST, 'https://api.tinify.com/shrink', status=400,
         body='{"error":"InputMissing","message":"No input"}')
     tinify.key = 'valid'
     self.assertEqual(True, tinify.validate())
Exemplo n.º 24
0
def backup_files(directory, backup_directory):
    copytree(directory, backup_directory)


if __name__ == '__main__':

    parser = argparse.ArgumentParser(description='Compress images using TinyPNG')
    parser.add_argument(
        'directory', help='Directory which contains images to be compressed'
    )
    parser.add_argument(
        'backup_dir',
        help='Backup directory for original files'
    )

    args = parser.parse_args()

    try:
        tinify.key = config.TINYPNG_KEY
        tinify.validate()
    except tinify.Error:
        message = ('ERROR: Invalid/Expired Key: {}'.format(config.TINYPNG_KEY))
        raise Exception(message)

    directory = valid_directory(args.directory)
    backup_files(directory, args.backup_dir)

    pool = Pool(processes=4)
    pool.map(convert_files, get_convertible_files(directory))
Exemplo n.º 25
0
 def getBalance(self):
     tinify.validate()
     idx = 500 - tinify.compression_count
     return f'本月还剩图片压缩{idx}次'
Exemplo n.º 26
0
 def test_with_error_should_raise_error(self):
     httpretty.register_uri(httpretty.POST, 'https://api.tinify.com/shrink', status=401,
         body='{"error":"Unauthorized","message":"Credentials are invalid"}')
     tinify.key = 'valid'
     with self.assertRaises(tinify.AccountError):
         tinify.validate()
Exemplo n.º 27
0
    return os.path.normpath(os.path.realpath(directory))


def backup_files(directory, backup_directory):
    copytree(directory, backup_directory)


if __name__ == '__main__':

    parser = argparse.ArgumentParser(
        description='Compress images using TinyPNG')
    parser.add_argument(
        'directory', help='Directory which contains images to be compressed')
    parser.add_argument('backup_dir',
                        help='Backup directory for original files')

    args = parser.parse_args()

    try:
        tinify.key = config.TINYPNG_KEY
        tinify.validate()
    except tinify.Error:
        message = ('ERROR: Invalid/Expired Key: {}'.format(config.TINYPNG_KEY))
        raise Exception(message)

    directory = valid_directory(args.directory)
    backup_files(directory, args.backup_dir)

    pool = Pool(processes=4)
    pool.map(convert_files, get_convertible_files(directory))