refactor: 移动JSON-RPC模块到公共位置并修复模板导入显示问题
- 将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: 更新导入路径
This commit is contained in:
parent
855a3bc757
commit
7edf8b7335
|
|
@ -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__)
|
||||
|
||||
|
|
|
|||
|
|
@ -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__)
|
||||
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
if success:
|
||||
result = {
|
||||
"status": success,
|
||||
"msg": "Template deleted successfully" if success else "Failed to delete template"
|
||||
"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)
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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")
|
||||
Loading…
Reference in New Issue