优化图片的存储,及时删除处理过程中产生的图片

This commit is contained in:
2024-10-15 10:17:01 +08:00
parent 15ea3ff96f
commit 5af6256376
5 changed files with 141 additions and 94 deletions

View File

@@ -2,8 +2,12 @@ import logging
import os
from datetime import datetime
import requests
from opencc import OpenCC
from tenacity import retry, stop_after_attempt, wait_random
from log import PROJECT_ROOT
from photo_review import BATCH_ID
from util import string_util, model_util
@@ -255,3 +259,51 @@ def chinese_money_to_number(chinese_money_amount):
def traditional_to_simple_chinese(traditional_chinese):
converter = OpenCC('t2s')
return converter.convert(traditional_chinese)
def parse_img_url(url):
"""
解析图片url
:param url: 图片url
:return: 图片名称和图片后缀
"""
url = url.split('?')[0]
return os.path.basename(url)
@retry(stop=stop_after_attempt(3), wait=wait_random(1, 3), reraise=True,
after=lambda x: logging.warning('保存图片失败!'))
def save_to_local(img_url):
"""
保存图片到本地
:param img_url: 图片url
:return: 本地保存地址
"""
response = requests.get(img_url)
response.raise_for_status() # 检查响应状态码是否正常
save_path = get_tmp_img_path(parse_img_url(img_url))
with open(save_path, 'wb') as file:
file.write(response.content)
return save_path
def get_img_path(img_full_name):
save_path = get_tmp_img_path(img_full_name)
if os.path.exists(save_path):
return save_path
return None
def get_tmp_img_path(img_full_name):
return os.path.join(PROJECT_ROOT, 'tmp_img', img_full_name)
def get_processed_img_path(img_full_name):
return os.path.join(str(get_tmp_img_path(BATCH_ID)), img_full_name)
def parse_save_path(img_path):
img_full_name = os.path.basename(img_path)
img_name, img_ext = img_full_name.rsplit('.', 1)
return img_name, img_ext