Skip to content

Commit

Permalink
Modify logger msg
Browse files Browse the repository at this point in the history
  • Loading branch information
AkiChase committed Nov 9, 2022
1 parent b969ede commit fe23990
Show file tree
Hide file tree
Showing 5 changed files with 42 additions and 42 deletions.
16 changes: 8 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,20 @@

TinyPNG使用将WebP, PNG and JPEG图片进行智能有损压缩,该压缩对视觉的影响几乎不可见,但是能显著压缩文件体积,以节省空间储存,方便网络传输。

通过邮箱免费申请TinyPNG官方API秘钥,可以获得每月500张图片的免费压缩次数(不限文件大小)。
通过邮箱免费申请TinyPNG官方API密钥,可以获得每月500张图片的免费压缩次数(不限文件大小)。

因此,通过API进行图片批量压缩是相对理想的形式,[申请地址]([TinyPNG – Developer API](https://tinypng.com/developers))

### tinypng-unlimited

> 本项目仅供技术研究使用,请勿用于任何商业及非法用途,任何后果作者概不负责!
**本项目可自动申请API秘钥,以多线程形式批量进行TinyPNG压缩,并附带上传、下载和总体任务的进度条,旨在提供最方便快捷的云压缩功能**
**本项目可自动申请API密钥,以多线程形式批量进行TinyPNG压缩,并附带上传、下载和总体任务的进度条,旨在提供最方便快捷的云压缩功能**

本项目实现的功能:

1. 通过多个临时邮箱自动申请TinyPNG官方API秘钥,以实现**无限制使用TinyPNG**
2. **自动切换不可用秘钥**即将达到500次免费压缩的秘钥
1. 通过多个临时邮箱自动申请TinyPNG官方API密钥,以实现**无限制使用TinyPNG**
2. **自动切换不可用密钥**即将达到500次免费压缩的密钥
3. 多线程上传下载图片,**加快批量压缩进度**
4. 可选**使用代理**上传、下载图片
5. 可选**递归子文件夹**,可通过**正则匹配**需要压缩的文件名
Expand Down Expand Up @@ -80,17 +80,17 @@ TinyPNG使用将WebP, PNG and JPEG图片进行智能有损压缩,该压缩对

参考 [tasks-help.txt](https://github.com/ruchuby/TinyPNG-Unlimited/blob/develop/bin/tasks-help.txt)

4. 申请API秘钥
4. 申请API密钥

程序运行时会自动申请秘钥,但也可以通过此方式再次申请
程序运行时会自动申请密钥,但也可以通过此方式再次申请
```bash
path\to\your\python main.py apply 4
TinyPNG-Unlimited.exe apply 4
```

5. 重新排列API秘钥顺序
5. 重新排列API密钥顺序

依次请求获取本地储存的API秘钥压缩次数,重新排列秘钥顺序
依次请求获取本地储存的API密钥压缩次数,重新排列密钥顺序

```bash
path\to\your\python main.py rearrange
Expand Down
2 changes: 1 addition & 1 deletion bin/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def init(proxy=None):
os.removedirs(tmp_dir) # 清空之前的临时下载文件夹

if not len(KeyManager.Keys.available):
logger.error('无可用秘钥,请稍后重试')
logger.error('无可用密钥,请稍后重试')
exit()

TinyImg.set_key(KeyManager.Keys.available[0])
Expand Down
4 changes: 2 additions & 2 deletions tinypng_unlimited/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@ def __init__(self, msg: str, detail: Any = None):

class ApplyKeyException(CustomException):
"""
申请新秘钥相关错误
申请新密钥相关错误
"""

def __init__(self, msg: str, detail: Any = None):
super().__init__('申请新秘钥相关错误', msg, detail)
super().__init__('申请新密钥相关错误', msg, detail)


class ProxyManagerException(CustomException):
Expand Down
38 changes: 19 additions & 19 deletions tinypng_unlimited/key_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,18 +26,18 @@ def load(cls, obj: dict):
@classmethod
def init(cls, working_dir):
"""
秘钥初始化,请在所有需要秘钥的操作之前执行
密钥初始化,请在所有需要密钥的操作之前执行
"""
cls.working_dir = working_dir
cls.load_keys()
if len(cls.Keys.available) < 3:
logger.warning('当前可用秘钥少于3条,优先申请新秘钥')
logger.warning('当前可用密钥少于3条,优先申请新密钥')
cls.apply_store_key()

@classmethod
def load_keys(cls):
"""
加载本地存储的秘钥
加载本地存储的密钥
"""
path = os.path.abspath(os.path.join(cls.working_dir, 'keys.json'))
if not os.path.exists(path):
Expand All @@ -49,7 +49,7 @@ def load_keys(cls):
@classmethod
def store_key(cls):
"""
秘钥保存到本地
密钥保存到本地
"""
path = os.path.abspath(os.path.join(cls.working_dir, 'keys.json'))
with open(path, 'w', encoding='utf-8') as f:
Expand All @@ -62,7 +62,7 @@ def store_key(cls):
def get_api_count(s, key):
url = 'https://api.tinify.com/shrink'
retry = 0
logger.info('正在获取秘钥可用性信息...', key)
logger.info('正在获取密钥可用性信息...', key)
while True:
try:
res = s.post(url, auth=('api', key))
Expand Down Expand Up @@ -97,30 +97,30 @@ def rearrange_keys(cls):

cls.Keys.load(out)
cls.store_key()
logger.success('秘钥已按统计信息重新排列')
logger.success('密钥已按统计信息重新排列')

@classmethod
def next_key(cls) -> str:
"""
删除当前秘钥并返回下一条
删除当前密钥并返回下一条
"""
cls.load_keys()

if len(cls.Keys.available) < 3:
logger.warning('可用秘钥少于3条,优先申请新秘钥')
logger.warning('可用密钥少于3条,优先申请新密钥')
cls.apply_store_key()

if not len(cls.Keys.available):
raise Exception('无可用秘钥,请申请后重试')
raise Exception('无可用密钥,请申请后重试')
cls.Keys.unavailable.append(cls.Keys.available.pop(0))
cls.store_key()
logger.debug('秘钥已切换,等待载入')
logger.debug('密钥已切换,等待载入')
return cls.Keys.available[0]

@classmethod
def _apply_api_key(cls) -> str:
"""
申请新秘钥
申请新密钥
"""
with requests.Session() as session:
# 注册新账号(发送确认邮件)
Expand Down Expand Up @@ -148,7 +148,7 @@ def _apply_api_key(cls) -> str:
raise ApplyKeyException('注册链接提取失败', e)
logger.info('注册链接提取成功')

# 访问控制台,生成秘钥
# 访问控制台,生成密钥
retry = 0
while True:
try:
Expand All @@ -157,33 +157,33 @@ def _apply_api_key(cls) -> str:
headers = {
'authorization': f"Bearer {auth}"
}
session.post('https://api.tinify.com/api/keys', headers=headers) # 添加新秘钥
res = session.get('https://api.tinify.com/api', headers=headers) # 获取秘钥
session.post('https://api.tinify.com/api/keys', headers=headers) # 添加新密钥
res = session.get('https://api.tinify.com/api', headers=headers) # 获取密钥
key = res.json()['keys'][-1]['key']
break
except Exception as e:
retry += 1
if retry <= 3:
logger.error('新秘钥生成失败, 3s后进行第{}次重试 {}', retry, e)
logger.error('新密钥生成失败, 3s后进行第{}次重试 {}', retry, e)
time.sleep(3)
else:
raise ApplyKeyException(f'超出重试次数, 新秘钥生成失败: {url}', e)
raise ApplyKeyException(f'超出重试次数, 新密钥生成失败: {url}', e)

logger.success('新秘钥生成成功')
logger.success('新密钥生成成功')
return key

@classmethod
def apply_store_key(cls, times=None):
"""
申请并保存秘钥
申请并保存密钥
"""

# 允许申请次数(包括失败重试)
times = 4 - len(cls.Keys.available) if times is None else times
while times > 0:
try:
times -= 1
logger.info('正在申请新秘钥,剩余次数: {}', times)
logger.info('正在申请新密钥,剩余次数: {}', times)
key = cls._apply_api_key()
cls.Keys.available.append(key)
cls.store_key()
Expand Down
24 changes: 12 additions & 12 deletions tinypng_unlimited/tiny_img.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,15 @@ class TinyImg:
@classmethod
def set_key(cls, key):
"""
设置新秘钥并进行验证
设置新密钥并进行验证
"""

with cls._lock: # 加锁避免多个线程尝试切换秘钥
with cls._lock: # 加锁避免多个线程尝试切换密钥
cls.tmp_dir = os.path.abspath(os.path.join(tinypng_unlimited.KeyManager.working_dir, 'tmp'))
logger.debug('正在载入秘钥: {}', key)
logger.debug('正在载入密钥: {}', key)
tinify.key = key
tinify.validate()
logger.success('秘钥已载入,当前秘钥可用性: [{}/500]', cls.compression_count())
logger.success('密钥已载入,当前密钥可用性: [{}/500]', cls.compression_count())
cls.check_compression_count()

@classmethod
Expand All @@ -50,7 +50,7 @@ def to_file_save(cls, path, url, timeout=30):
file_name = os.path.basename(path)
if not os.path.exists(cls.tmp_dir):
os.mkdir(cls.tmp_dir)
tmp_path = os.path.abspath(os.path.join(cls.tmp_dir, f'{os.path.basename(path)}_{round(time.time())}'))
tmp_path = os.path.abspath(os.path.join(cls.tmp_dir, f'{file_name}_{round(time.time())}'))
res = cls._session.get(url, stream=True, timeout=timeout)
file_size = int(res.headers.get('content-length', 0))
with tqdm(file=sys.stdout, desc=f'[下载进度]: {file_name}', colour='red', ncols=120, leave=False,
Expand All @@ -76,12 +76,12 @@ def compression_count(cls) -> int:
@classmethod
def check_compression_count(cls):
"""
检测秘钥是否限额,限额则替换为下一条
检测密钥是否限额,限额则替换为下一条
"""
count = cls.compression_count()
# logger.debug('当前秘钥可用性: [{}/500]', count)
if count >= 490: # 即将达到限额,更换新秘钥(多线程,提前留好余量)
logger.warning('当前秘钥即将达到限额: [{}/500], 正在切换新秘钥', count)
# logger.debug('当前密钥可用性: [{}/500]', count)
if count >= 490: # 即将达到限额,更换新密钥(多线程,提前留好余量)
logger.warning('当前密钥即将达到限额: [{}/500], 正在切换新密钥', count)
cls.set_key(tinypng_unlimited.KeyManager.next_key())

@classmethod
Expand Down Expand Up @@ -129,7 +129,7 @@ def compress_from_file(cls, path, new_path, check_compressed=True,
while True:
try:
# 加锁保证只有一个线程能进行检查(避免多线程同时检查,同时切换api)
# 但是切换秘钥会中断其他请求,因为tinify库中是共享同一个client
# 但是切换密钥会中断其他请求,因为tinify库中是共享同一个client
with cls._lock:
cls.check_compression_count() # 检验压缩次数是否足够
old_key = tinify.key
Expand All @@ -141,11 +141,11 @@ def compress_from_file(cls, path, new_path, check_compressed=True,
url = cls.upload_from_file(wrapped_file, timeout=upload_timeout)
# 上传完成得到图片链接,并更新了api调用次数
with cls._lock:
# 新旧秘钥切换时,使用旧秘钥上传图片的响应会覆盖新秘钥的值,所以需要刷新一下
# 新旧密钥切换时,使用旧密钥上传图片的响应会覆盖新密钥的值,所以需要刷新一下
if tinify.key != old_key:
tinify.validate()
logger.success('云端压缩成功,正在下载: {}', file_name)
logger.info('当前秘钥可用性: [{}/500]', cls.compression_count())
logger.info('当前密钥可用性: [{}/500]', cls.compression_count())
cls.to_file_save(new_path, url, timeout=download_timeout)
new_size = os.path.getsize(new_path)
return file_name, old_size, new_size, f'{round(100 * new_size / old_size, 2)}%'
Expand Down

0 comments on commit fe23990

Please sign in to comment.