diff --git a/dsLightRag/KeLing/Kit/KlCommon.py b/dsLightRag/KeLing/Kit/KlCommon.py index 695e40ce..05aa7269 100644 --- a/dsLightRag/KeLing/Kit/KlCommon.py +++ b/dsLightRag/KeLing/Kit/KlCommon.py @@ -29,15 +29,24 @@ class KlCommon: # 构建JWT令牌 payload = { 'iss': KlCommon.ak, - 'exp': expired_at, - 'nbf': not_before + 'exp': int(expired_at.timestamp()), # 转换为Unix时间戳 + 'nbf': int(not_before.timestamp()) # 转换为Unix时间戳 + } + + # 定义JWT头部 + headers = { + 'alg': 'HS256', + 'typ': 'JWT' # 添加类型声明 } # 使用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 except Exception as e: - log.error(f"获取JWT令牌失败: {str(e)}") + log.error(f"获取JWT令牌失败: {str(e)}", exc_info=True) return None @staticmethod diff --git a/dsLightRag/KeLing/Kit/__pycache__/KlCommon.cpython-310.pyc b/dsLightRag/KeLing/Kit/__pycache__/KlCommon.cpython-310.pyc index 7b10a58d..00c75f78 100644 Binary files a/dsLightRag/KeLing/Kit/__pycache__/KlCommon.cpython-310.pyc and b/dsLightRag/KeLing/Kit/__pycache__/KlCommon.cpython-310.pyc differ diff --git a/dsLightRag/KeLing/KlTxt2Img.py b/dsLightRag/KeLing/KlTxt2Img.py index 77ae7cee..153be2ce 100644 --- a/dsLightRag/KeLing/KlTxt2Img.py +++ b/dsLightRag/KeLing/KlTxt2Img.py @@ -9,6 +9,7 @@ from KeLing.Kit.KlErrorCode import KlErrorCode logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') log = logging.getLogger(__name__) + class KlTxt2Img(KlCommon): BASE_URL = "https://api.klingai.com" GENERATION_PATH = "/v1/images/generations" @@ -43,7 +44,8 @@ class KlTxt2Img(KlCommon): log.info(f"生成图片请求体:{json.dumps(request_body)}") 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: @@ -94,22 +96,24 @@ class KlTxt2Img(KlCommon): """ return KlCommon.query_task_status(task_id, KlTxt2Img.QUERY_PATH, "文生图") + if __name__ == "__main__": try: # 提示词和模型名称 prompt = "一只可爱的小猫咪在草地上玩耍,阳光明媚" 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 max_generate_retries = 5 # 最大重试次数 - generate_retry_interval = 5000 # 重试间隔(毫秒) + initial_retry_interval = 2000 # 初始重试间隔(毫秒) + max_retry_interval = 30000 # 最大重试间隔(毫秒) task_id = None account_issue = False - while not account_issue: + while generate_retry_count < max_generate_retries and not account_issue: try: task_id = KlTxt2Img.generate_image(prompt, model_name) break @@ -118,18 +122,22 @@ if __name__ == "__main__": # 检查是否是账户问题 error_msg = str(e) - if "资源包已耗尽" in error_msg or - "账户欠费" in error_msg or - "无权限" in error_msg: + if "资源包已耗尽" in error_msg or "账户欠费" in error_msg or "无权限" in error_msg: log.error("账户问题,停止重试") account_issue = True else: generate_retry_count += 1 if generate_retry_count < max_generate_retries: - log.warn(f"等待{generate_retry_interval}毫秒后重试...") - time.sleep(generate_retry_interval / 1000) # 转换为秒 + # 指数退避策略: 基础延迟 * 2^(重试次数-1),但不超过最大延迟 + 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: - raise e # 达到最大重试次数,抛出异常 + log.error(f"生成图片失败,已达到最大重试次数: {max_generate_retries}") if task_id is None: if account_issue: @@ -180,8 +188,7 @@ if __name__ == "__main__": else: raise e # 达到最大重试次数,抛出异常 - if query_retry_count >= max_query_retries: - log.error(f"任务查询超时,已达到最大查询次数: {max_query_retries}") - + if query_retry_count >= max_query_retries: + log.error(f"任务查询超时,已达到最大查询次数: {max_query_retries}") except Exception as e: log.error(f"程序执行异常: {str(e)}", exc_info=True) \ No newline at end of file