Files
mxivideo/examples/test_jsonrpc_workflow.py
2025-07-12 13:44:57 +08:00

272 lines
9.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""
测试JSON-RPC工作流进度反馈
Test JSON-RPC Workflow Progress Feedback
"""
import json
import requests
import time
import threading
import websocket
from typing import Dict, Any
class JSONRPCWorkflowTester:
"""JSON-RPC工作流测试器"""
def __init__(self, server_url: str = "http://localhost:8081"):
self.server_url = server_url
self.request_id = 0
self.progress_updates = []
def _call_method(self, method: str, params: Dict[str, Any]) -> Dict[str, Any]:
"""调用JSON-RPC方法"""
self.request_id += 1
payload = {
"jsonrpc": "2.0",
"method": method,
"params": params,
"id": self.request_id
}
print(f"📤 发送请求 (ID: {self.request_id}): {method}")
print(f" 参数: {json.dumps(params, indent=2, ensure_ascii=False)}")
try:
response = requests.post(
self.server_url,
json=payload,
headers={'Content-Type': 'application/json'},
timeout=120 # 增加超时时间
)
if response.status_code == 200:
result = response.json()
print(f"📥 收到响应 (ID: {self.request_id}): {response.status_code}")
return result
else:
print(f"❌ HTTP错误: {response.status_code}")
return {
"error": {
"code": response.status_code,
"message": f"HTTP Error: {response.text}"
}
}
except requests.exceptions.RequestException as e:
print(f"❌ 请求失败: {str(e)}")
return {
"error": {
"code": -1,
"message": f"Request failed: {str(e)}"
}
}
def test_basic_detection(self):
"""测试基础场景检测"""
print("\n" + "="*60)
print("🎯 测试基础场景检测")
print("="*60)
params = {
"video_path": "assets/1/1752032011698.mp4",
"detector_type": "content",
"threshold": 15.0,
"min_scene_length": 1.0
}
start_time = time.time()
result = self._call_method("scene.detect", params)
end_time = time.time()
if "error" in result:
print(f"❌ 检测失败: {result['error']}")
return False
detection_result = result.get("result", {})
if detection_result.get("success"):
print(f"✅ 基础检测成功!")
print(f" 场景数量: {detection_result['total_scenes']}")
print(f" 检测时间: {detection_result['detection_time']:.2f}")
print(f" API调用时间: {end_time - start_time:.2f}")
return True
else:
print(f"❌ 检测失败: {detection_result.get('error', '未知错误')}")
return False
def test_workflow_detection(self):
"""测试工作流场景检测"""
print("\n" + "="*60)
print("🔄 测试LangGraph工作流检测")
print("="*60)
params = {
"video_path": "assets/1/1752032011698.mp4",
"detector_type": "content",
"threshold": 15.0,
"min_scene_length": 1.0,
"enable_ai_analysis": False # 禁用AI分析避免API密钥问题
}
start_time = time.time()
result = self._call_method("scene.detect_workflow", params)
end_time = time.time()
if "error" in result:
print(f"❌ 工作流检测失败: {result['error']}")
return False
workflow_result = result.get("result", {})
detection_result = workflow_result.get("detection_result", {})
if detection_result.get("success"):
print(f"✅ 工作流检测成功!")
print(f" 工作流状态: {workflow_result.get('workflow_state')}")
print(f" 场景数量: {detection_result['total_scenes']}")
print(f" 检测时间: {detection_result['detection_time']:.2f}")
print(f" API调用时间: {end_time - start_time:.2f}")
# 显示视频信息
video_info = workflow_result.get("video_info", {})
if video_info:
print(f" 视频信息: {video_info.get('resolution')}, {video_info.get('fps'):.2f}fps")
# 显示AI分析结果
ai_analysis = workflow_result.get("ai_analysis")
if ai_analysis:
print(f" AI分析: {ai_analysis[:100]}...")
return True
else:
print(f"❌ 工作流检测失败: {detection_result.get('error', '未知错误')}")
return False
def test_video_info(self):
"""测试视频信息获取"""
print("\n" + "="*60)
print("📊 测试视频信息获取")
print("="*60)
params = {
"video_path": "assets/1/1752032011698.mp4"
}
start_time = time.time()
result = self._call_method("scene.get_video_info", params)
end_time = time.time()
if "error" in result:
print(f"❌ 获取失败: {result['error']}")
return False
info_result = result.get("result", {})
if info_result.get("success"):
info = info_result.get("info", {})
print(f"✅ 信息获取成功!")
print(f" 文件名: {info.get('filename')}")
print(f" 分辨率: {info.get('resolution')}")
print(f" 帧率: {info.get('fps'):.2f} fps")
print(f" 时长: {info.get('duration'):.2f}")
print(f" 文件大小: {info.get('file_size'):,} 字节")
print(f" API调用时间: {end_time - start_time:.2f}")
return True
else:
print(f"❌ 获取失败: {info_result.get('error', '未知错误')}")
return False
def test_error_handling(self):
"""测试错误处理"""
print("\n" + "="*60)
print("🚨 测试错误处理")
print("="*60)
# 测试不存在的文件
params = {
"video_path": "nonexistent_video.mp4",
"threshold": 15.0
}
result = self._call_method("scene.detect", params)
if "error" in result:
print(f"✅ 正确处理了请求错误: {result['error']['message']}")
else:
detection_result = result.get("result", {})
if not detection_result.get("success"):
print(f"✅ 正确处理了应用错误: {detection_result.get('error')}")
else:
print(f"❌ 应该返回错误,但返回了成功结果")
return False
# 测试无效的方法
result = self._call_method("scene.invalid_method", {})
if "error" in result and result["error"]["code"] == -32601:
print(f"✅ 正确处理了方法不存在错误")
else:
print(f"❌ 没有正确处理方法不存在错误")
return False
return True
def run_all_tests(self):
"""运行所有测试"""
print("🚀 JSON-RPC工作流测试开始")
print("="*60)
# 检查服务器连接
try:
test_result = self._call_method("scene.get_video_info", {"video_path": "test.mp4"})
if "error" in test_result and "Request failed" in str(test_result["error"]):
print("❌ 无法连接到JSON-RPC服务器")
print("💡 请先启动服务器: python3 -m python_core.cli jsonrpc start --port 8081")
return False
except Exception as e:
print(f"❌ 连接测试失败: {e}")
return False
print("✅ 服务器连接正常")
# 运行测试
tests = [
("视频信息获取", self.test_video_info),
("基础场景检测", self.test_basic_detection),
("工作流场景检测", self.test_workflow_detection),
("错误处理", self.test_error_handling),
]
passed = 0
total = len(tests)
for test_name, test_func in tests:
try:
if test_func():
passed += 1
print(f"{test_name} - 通过")
else:
print(f"{test_name} - 失败")
except Exception as e:
print(f"{test_name} - 异常: {e}")
print("\n" + "="*60)
print(f"🎉 测试完成: {passed}/{total} 通过")
print("="*60)
if passed == total:
print("🎊 所有测试都通过了JSON-RPC工作流功能正常")
else:
print("⚠️ 部分测试失败,请检查服务器和配置")
return passed == total
def main():
"""主函数"""
tester = JSONRPCWorkflowTester("http://localhost:8081")
tester.run_all_tests()
if __name__ == "__main__":
main()