From 7edf8b7335534613e317efdebd0e01c42eb0d9e7 Mon Sep 17 00:00:00 2001 From: root Date: Thu, 10 Jul 2025 21:07:14 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E7=A7=BB=E5=8A=A8JSON-RPC=E6=A8=A1?= =?UTF-8?q?=E5=9D=97=E5=88=B0=E5=85=AC=E5=85=B1=E4=BD=8D=E7=BD=AE=E5=B9=B6?= =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E6=A8=A1=E6=9D=BF=E5=AF=BC=E5=85=A5=E6=98=BE?= =?UTF-8?q?=E7=A4=BA=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 将JSON-RPC模块从ai_video移动到utils作为公共模块 - 更新所有相关文件的导入路径 - 重构template_manager.py使用标准JSON-RPC协议 - 修复模板导入成功但前端显示失败的问题 - 添加模板相关的错误码定义 - 改进进度报告使用JSON-RPC通知 - 移除旧的直接JSON输出代码 修复内容: - python_core/utils/jsonrpc.py: 新增公共JSON-RPC模块 - python_core/services/template_manager.py: 使用JSON-RPC协议 - python_core/ai_video/video_generator.py: 更新导入路径 - python_core/ai_video/api_client.py: 更新导入路径 --- python_core/ai_video/api_client.py | 2 +- python_core/ai_video/video_generator.py | 2 +- python_core/services/template_manager.py | 64 ++++++++++------------ python_core/{ai_video => utils}/jsonrpc.py | 3 +- 4 files changed, 33 insertions(+), 38 deletions(-) rename python_core/{ai_video => utils}/jsonrpc.py (99%) diff --git a/python_core/ai_video/api_client.py b/python_core/ai_video/api_client.py index 92c3382..f42c085 100644 --- a/python_core/ai_video/api_client.py +++ b/python_core/ai_video/api_client.py @@ -14,7 +14,7 @@ from typing import Dict, Any, Optional, Callable import sys from python_core.config import settings from python_core.utils import setup_logger -from python_core.ai_video.jsonrpc import create_progress_reporter +from python_core.utils.jsonrpc import create_progress_reporter logger = setup_logger(__name__) diff --git a/python_core/ai_video/video_generator.py b/python_core/ai_video/video_generator.py index ec3f15a..77c04bb 100644 --- a/python_core/ai_video/video_generator.py +++ b/python_core/ai_video/video_generator.py @@ -17,7 +17,7 @@ from python_core.utils import setup_logger # 导入同目录下的模块 from python_core.ai_video.cloud_storage import CloudStorage from python_core.ai_video.api_client import APIClient -from python_core.ai_video.jsonrpc import create_response_handler, create_progress_reporter, JSONRPCError +from python_core.utils.jsonrpc import create_response_handler, create_progress_reporter, JSONRPCError logger = setup_logger(__name__) diff --git a/python_core/services/template_manager.py b/python_core/services/template_manager.py index a34bd7b..a7961d7 100644 --- a/python_core/services/template_manager.py +++ b/python_core/services/template_manager.py @@ -13,6 +13,7 @@ from dataclasses import dataclass, asdict from datetime import datetime from ..utils.logger import setup_logger +from ..utils.jsonrpc import create_response_handler, create_progress_reporter, JSONRPCError from ..config import settings logger = setup_logger(__name__) @@ -367,31 +368,41 @@ def main(): args = parser.parse_args() + # Create JSON-RPC response handler + rpc = create_response_handler("template_manager") + progress = create_progress_reporter() + try: manager = TemplateManager() if args.action == "batch_import": if not args.source_folder: - raise ValueError("Source folder is required for batch import") + rpc.error(JSONRPCError.INVALID_PARAMS, "Source folder is required for batch import") + return def progress_callback(message): - print(message) + progress.step("import", message) result = manager.batch_import_templates(args.source_folder, progress_callback) # Convert TemplateInfo objects to dictionaries for JSON serialization if 'imported_templates' in result: result['imported_templates'] = [asdict(template) for template in result['imported_templates']] + # Send successful result via JSON-RPC + rpc.success(result) + elif args.action == "get_templates": templates = manager.get_templates() result = { "status": True, "templates": [asdict(template) for template in templates] } + rpc.success(result) elif args.action == "get_template": if not args.template_id: - raise ValueError("Template ID is required") + rpc.error(JSONRPCError.INVALID_PARAMS, "Template ID is required") + return template = manager.get_template(args.template_id) if template: @@ -399,48 +410,31 @@ def main(): "status": True, "template": asdict(template) } + rpc.success(result) else: - result = { - "status": False, - "msg": f"Template not found: {args.template_id}" - } + rpc.error(JSONRPCError.TEMPLATE_NOT_FOUND, f"Template not found: {args.template_id}") elif args.action == "delete_template": if not args.template_id: - raise ValueError("Template ID is required") + rpc.error(JSONRPCError.INVALID_PARAMS, "Template ID is required") + return success = manager.delete_template(args.template_id) - result = { - "status": success, - "msg": "Template deleted successfully" if success else "Failed to delete template" - } + if success: + result = { + "status": True, + "msg": "Template deleted successfully" + } + rpc.success(result) + else: + rpc.error(JSONRPCError.TEMPLATE_NOT_FOUND, "Failed to delete template") else: - raise ValueError(f"Unknown action: {args.action}") - - # Use safe encoding for final output - result_json = json.dumps(result, ensure_ascii=True, indent=2) - if hasattr(sys.stdout, 'buffer'): - sys.stdout.buffer.write(result_json.encode('utf-8')) - sys.stdout.buffer.write(b'\n') - sys.stdout.buffer.flush() - else: - print(result_json) - sys.stdout.flush() + rpc.error(JSONRPCError.METHOD_NOT_FOUND, f"Unknown action: {args.action}") except Exception as e: - error_result = { - "status": False, - "error": str(e) - } - error_json = json.dumps(error_result, ensure_ascii=True, indent=2) - if hasattr(sys.stdout, 'buffer'): - sys.stdout.buffer.write(error_json.encode('utf-8')) - sys.stdout.buffer.write(b'\n') - sys.stdout.buffer.flush() - else: - print(error_json) - sys.stdout.flush() + # Send error via JSON-RPC + rpc.error(JSONRPCError.INTERNAL_ERROR, f"Template manager error: {str(e)}", str(e)) sys.exit(1) diff --git a/python_core/ai_video/jsonrpc.py b/python_core/utils/jsonrpc.py similarity index 99% rename from python_core/ai_video/jsonrpc.py rename to python_core/utils/jsonrpc.py index 52862a0..5c2ae7d 100644 --- a/python_core/ai_video/jsonrpc.py +++ b/python_core/utils/jsonrpc.py @@ -159,6 +159,8 @@ class JSONRPCError: GENERATION_FAILED = -32003 DOWNLOAD_FAILED = -32004 TIMEOUT_ERROR = -32005 + TEMPLATE_IMPORT_FAILED = -32006 + TEMPLATE_NOT_FOUND = -32007 def create_response_handler(request_id: Optional[Union[str, int]] = None) -> JSONRPCResponse: @@ -190,7 +192,6 @@ def parse_request(request_str: str) -> Dict[str, Any]: raise ValueError(f"Invalid JSON: {e}") -# Example usage functions def example_video_generation(): """Example of how to use JSON-RPC for video generation""" rpc = create_response_handler("video_gen_001")