'commit'
This commit is contained in:
@@ -29,15 +29,24 @@ class KlCommon:
|
|||||||
# 构建JWT令牌
|
# 构建JWT令牌
|
||||||
payload = {
|
payload = {
|
||||||
'iss': KlCommon.ak,
|
'iss': KlCommon.ak,
|
||||||
'exp': expired_at,
|
'exp': int(expired_at.timestamp()), # 转换为Unix时间戳
|
||||||
'nbf': not_before
|
'nbf': int(not_before.timestamp()) # 转换为Unix时间戳
|
||||||
|
}
|
||||||
|
|
||||||
|
# 定义JWT头部
|
||||||
|
headers = {
|
||||||
|
'alg': 'HS256',
|
||||||
|
'typ': 'JWT' # 添加类型声明
|
||||||
}
|
}
|
||||||
|
|
||||||
# 使用HS256算法签名
|
# 使用HS256算法签名
|
||||||
jwt_token = jwt.encode(payload, KlCommon.sk, algorithm='HS256', headers={'alg': 'HS256'})
|
jwt_token = jwt.encode(payload, KlCommon.sk, algorithm='HS256', headers=headers)
|
||||||
|
# 增强调试信息
|
||||||
|
log.info(f"生成JWT令牌: {jwt_token[:10]}...{jwt_token[-10:]}") # 只打印部分令牌
|
||||||
|
log.debug(f"JWT过期时间: {expired_at}")
|
||||||
return jwt_token
|
return jwt_token
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
log.error(f"获取JWT令牌失败: {str(e)}")
|
log.error(f"获取JWT令牌失败: {str(e)}", exc_info=True)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
|
Binary file not shown.
@@ -9,6 +9,7 @@ from KeLing.Kit.KlErrorCode import KlErrorCode
|
|||||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class KlTxt2Img(KlCommon):
|
class KlTxt2Img(KlCommon):
|
||||||
BASE_URL = "https://api.klingai.com"
|
BASE_URL = "https://api.klingai.com"
|
||||||
GENERATION_PATH = "/v1/images/generations"
|
GENERATION_PATH = "/v1/images/generations"
|
||||||
@@ -43,7 +44,8 @@ class KlTxt2Img(KlCommon):
|
|||||||
log.info(f"生成图片请求体:{json.dumps(request_body)}")
|
log.info(f"生成图片请求体:{json.dumps(request_body)}")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response = requests.post(url, headers=headers, json=request_body)
|
# 添加超时设置,避免请求长时间挂起
|
||||||
|
response = requests.post(url, headers=headers, json=request_body, timeout=30)
|
||||||
|
|
||||||
# 检查响应状态码
|
# 检查响应状态码
|
||||||
if response.status_code != 200:
|
if response.status_code != 200:
|
||||||
@@ -94,22 +96,24 @@ class KlTxt2Img(KlCommon):
|
|||||||
"""
|
"""
|
||||||
return KlCommon.query_task_status(task_id, KlTxt2Img.QUERY_PATH, "文生图")
|
return KlCommon.query_task_status(task_id, KlTxt2Img.QUERY_PATH, "文生图")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
try:
|
try:
|
||||||
# 提示词和模型名称
|
# 提示词和模型名称
|
||||||
prompt = "一只可爱的小猫咪在草地上玩耍,阳光明媚"
|
prompt = "一只可爱的小猫咪在草地上玩耍,阳光明媚"
|
||||||
model_name = "kling-v1" # 可选:kling-v1, kling-v1-5, kling-v2
|
model_name = "kling-v1" # 可选:kling-v1, kling-v1-5, kling-v2
|
||||||
save_image_path = f"{KlCommon.base_path}KeLing_Txt_2_Image.png"
|
save_image_path = f"{KlCommon.base_path}\KeLing_Txt_2_Image.png"
|
||||||
|
|
||||||
# 添加重试逻辑
|
# 添加重试逻辑
|
||||||
generate_retry_count = 0
|
generate_retry_count = 0
|
||||||
max_generate_retries = 5 # 最大重试次数
|
max_generate_retries = 5 # 最大重试次数
|
||||||
generate_retry_interval = 5000 # 重试间隔(毫秒)
|
initial_retry_interval = 2000 # 初始重试间隔(毫秒)
|
||||||
|
max_retry_interval = 30000 # 最大重试间隔(毫秒)
|
||||||
|
|
||||||
task_id = None
|
task_id = None
|
||||||
account_issue = False
|
account_issue = False
|
||||||
|
|
||||||
while not account_issue:
|
while generate_retry_count < max_generate_retries and not account_issue:
|
||||||
try:
|
try:
|
||||||
task_id = KlTxt2Img.generate_image(prompt, model_name)
|
task_id = KlTxt2Img.generate_image(prompt, model_name)
|
||||||
break
|
break
|
||||||
@@ -118,18 +122,22 @@ if __name__ == "__main__":
|
|||||||
|
|
||||||
# 检查是否是账户问题
|
# 检查是否是账户问题
|
||||||
error_msg = str(e)
|
error_msg = str(e)
|
||||||
if "资源包已耗尽" in error_msg or
|
if "资源包已耗尽" in error_msg or "账户欠费" in error_msg or "无权限" in error_msg:
|
||||||
"账户欠费" in error_msg or
|
|
||||||
"无权限" in error_msg:
|
|
||||||
log.error("账户问题,停止重试")
|
log.error("账户问题,停止重试")
|
||||||
account_issue = True
|
account_issue = True
|
||||||
else:
|
else:
|
||||||
generate_retry_count += 1
|
generate_retry_count += 1
|
||||||
if generate_retry_count < max_generate_retries:
|
if generate_retry_count < max_generate_retries:
|
||||||
log.warn(f"等待{generate_retry_interval}毫秒后重试...")
|
# 指数退避策略: 基础延迟 * 2^(重试次数-1),但不超过最大延迟
|
||||||
time.sleep(generate_retry_interval / 1000) # 转换为秒
|
current_interval = min(initial_retry_interval * (2 ** (generate_retry_count - 1)), max_retry_interval)
|
||||||
|
log.warning(f"等待{current_interval}毫秒后重试...")
|
||||||
|
try:
|
||||||
|
time.sleep(current_interval / 1000) # 转换为秒
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
log.error("用户中断了程序执行")
|
||||||
|
exit(1)
|
||||||
else:
|
else:
|
||||||
raise e # 达到最大重试次数,抛出异常
|
log.error(f"生成图片失败,已达到最大重试次数: {max_generate_retries}")
|
||||||
|
|
||||||
if task_id is None:
|
if task_id is None:
|
||||||
if account_issue:
|
if account_issue:
|
||||||
@@ -182,6 +190,5 @@ if __name__ == "__main__":
|
|||||||
|
|
||||||
if query_retry_count >= max_query_retries:
|
if query_retry_count >= max_query_retries:
|
||||||
log.error(f"任务查询超时,已达到最大查询次数: {max_query_retries}")
|
log.error(f"任务查询超时,已达到最大查询次数: {max_query_retries}")
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
log.error(f"程序执行异常: {str(e)}", exc_info=True)
|
log.error(f"程序执行异常: {str(e)}", exc_info=True)
|
Reference in New Issue
Block a user