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")