from datetime import datetime
from qcloud_cos.cos_comm import re
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
def handler(args: Args[Input])->Output:
apikey=args.input.apikey
requrl=args.input.requrl
prompt=args.input.prompt
times_id=args.input.times_id
req_retry=args.input.req_retry
secret_id= "" # 腾讯云APi秘钥
secret_key="" # 腾讯云secret_key
region="ap-guangzhou" # 存储桶地址
bucket="img-1305440391" # 存储桶名称
# 按照原始maque.py的格式构建payload
# 按照原始maque.py的格式构建headers
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + apikey
if req_retry == 0 or req_retry is None:
max_attempts = int(req_retry)
retry_429_wait_base = 3 # 基础等待时间(秒)
retry_429_max_wait = 18 # 最大等待时间(秒)
while attempts < max_attempts:
response = requests.request("POST", requrl, headers=headers, data=payload,timeout=600)
if response.status_code == 401:
error_msg = f"认证失败: 无效的API令牌,请检查apikey是否正确。状态码: {response.status_code}"
return {"url": '', "prompt": '', "times_id": times_id, "error": error_msg}
elif response.status_code == 429:
# 对于429错误(请求过多),使用特殊的重试策略
error_msg = f"请求过于频繁: API服务器负载已饱和。状态码: {response.status_code}"
if attempts >= max_attempts:
print(f"达到最大重试次数 ({req_retry}次重试),放弃")
return {"url": '', "prompt": prompt, "times_id": times_id, "error": error_msg}
wait_time = min(retry_429_wait_base * (2 ** (attempts - 1)), retry_429_max_wait)
print(f"将在 {wait_time} 秒后进行第 {attempts + 1} 次重试...")
response.raise_for_status()
"created": res.get("created"),
"content": res["choices"][0]["message"]["content"] if res.get("choices") and len(res["choices"]) > 0 else "",
"finish_reason": res["choices"][0]["finish_reason"] if res.get("choices") and len(res["choices"]) > 0 else "",
"usage": res.get("usage", {})
content = result.get("content", "")
url_match = re.search(r'!\[图片\]\((https://[^)]+)\)', content)
url_match = re.search(r'!\[image\]\((https://[^)]+)\)', content)
url_match = re.search(r'!\[gen_\w+\]\((https://filesystem\.site/cdn/[^)]+)\)', content)
url_match = re.search(r'(https://filesystem\.site/cdn/[^)\s]+\.(?:png|jpg|jpeg|gif))', content)
url_match = re.search(r'!\[图片\]\((https://[^)]+)\)', content)
url_match = re.search(r'(https://[^)\s]+\.(?:png|jpg|jpeg|gif))', content)
image_url = url_match.group(1)
download_max_attempts = 3 # 固定为3次尝试
while download_attempts < download_max_attempts:
img_response = requests.get(image_url, timeout=20) # 固定20秒超时
img_response.raise_for_status()
if download_attempts >= download_max_attempts:
print(f"下载图片失败,已尝试{download_max_attempts}次: {str(e)}")
return {"url": '', "prompt": prompt, "times_id": times_id, "error": f"下载图片失败: {str(e)}"}
print(f"下载图片失败(尝试 {download_attempts}/{download_max_attempts}),立即重试...")
return {"url": imgUrl, "prompt": prompt, "times_id": times_id}
print(f"上传图片失败: {str(e)}")
print(f"返回原始图片URL: {image_url}")
return {"url": image_url, "prompt": prompt, "times_id": times_id, "error": f"上传图片失败,使用原始URL"}
print(f"\n下载图片时出错: {e}")
return {"url": '', "prompt": prompt, "times_id": times_id, "error": f"下载图片时出错: {str(e)}"}
return {"url": '', "prompt": prompt, "times_id": times_id, "error": "未找到图片URL"}
except requests.exceptions.RequestException as e:
print(f"请求失败: {str(e)}")
if attempts >= max_attempts:
print(f"达到最大重试次数 ({req_retry}次重试),放弃")
return {"url": '', "prompt": prompt, "times_id": times_id, "error": str(e)}
wait_time = min(2 ** (attempts - 1), 30)
print(f"将在 {wait_time} 秒后进行第 {attempts + 1} 次重试...")
except json.JSONDecodeError as e:
print(f"JSON解析失败: {str(e)}")
if attempts >= max_attempts:
print(f"达到最大重试次数 ({req_retry}次重试),放弃")
return {"url": '', "prompt": prompt, "times_id": times_id, "error": f"JSON解析失败: {str(e)}"}
wait_time = min(2 ** (attempts - 1), 30)
print(f"将在 {wait_time} 秒后进行第 {attempts + 1} 次重试...")
print(f"发生错误: {str(e)}")
if attempts >= max_attempts:
print(f"达到最大重试次数 ({req_retry}次重试),放弃")
return {"url": '', "prompt": prompt, "times_id": times_id, "error": str(e)}
wait_time = min(2 ** (attempts - 1), 30)
print(f"将在 {wait_time} 秒后进行第 {attempts + 1} 次重试...")
def upload_img(img, secret_id, secret_key, region, bucket):
client = CosS3Client(config)
timestamp = int(time.time())
random_suffix = os.urandom(4).hex()
current_date = datetime.now()
object_name = f"{current_date.year}/{current_date.month}/{current_date.day}/{timestamp}_{random_suffix}.png"
response = client.put_object(
url = f"https://{bucket}.cos.{region}.myqcloud.com/{object_name}"
print(f"图片已上传到腾讯云COS,URL: {url}")
error_msg = f"上传到腾讯云COS失败: {str(e)}"
if 'image_url' in globals() or 'image_url' in locals():
raise Exception(error_msg)