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

207 lines
6.4 KiB
Python

#!/usr/bin/env python3
"""
Test Scene Detection Fix
测试场景检测修复
"""
import sys
from pathlib import Path
# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
from python_core.scene_detection.services import SceneDetectorService
from python_core.scene_detection.types import DetectorType
def test_basic_detection():
"""测试基础场景检测"""
print("🧪 测试基础场景检测...")
try:
# 创建检测服务
detector_service = SceneDetectorService()
# 测试视频路径
video_path = Path("assets/1/1752032011698.mp4")
if not video_path.exists():
print(f"❌ 测试视频不存在: {video_path}")
return False
print(f"📹 测试视频: {video_path}")
# 执行检测
result = detector_service.detect_scenes(
video_path,
DetectorType.CONTENT,
30.0,
1.0
)
if result.success:
print(f"✅ 检测成功!")
print(f" 场景数量: {result.total_scenes}")
print(f" 检测时间: {result.detection_time:.2f}")
print(f" 视频时长: {result.total_duration:.2f}")
# 显示前几个场景
for i, scene in enumerate(result.scenes[:3]):
print(f" 场景 {i+1}: {scene.start_time:.2f}s - {scene.end_time:.2f}s (时长: {scene.duration:.2f}s)")
if len(result.scenes) > 3:
print(f" ... 还有 {len(result.scenes) - 3} 个场景")
return True
else:
print(f"❌ 检测失败: {result.error}")
return False
except Exception as e:
print(f"❌ 测试异常: {e}")
import traceback
print(f"详细错误: {traceback.format_exc()}")
return False
def test_video_info():
"""测试视频信息提取"""
print("\n🧪 测试视频信息提取...")
try:
from python_core.scene_detection.services import VideoInfoService
video_info_service = VideoInfoService()
video_path = Path("assets/1/1752032011698.mp4")
if not video_path.exists():
print(f"❌ 测试视频不存在: {video_path}")
return False
info = video_info_service.extract_video_info(video_path)
print(f"✅ 视频信息提取成功!")
print(f" 文件名: {info['filename']}")
print(f" 分辨率: {info['resolution']}")
print(f" 帧率: {info['fps']:.2f} fps")
print(f" 时长: {info['duration']:.2f}")
print(f" 文件大小: {info['file_size']:,} 字节")
return True
except Exception as e:
print(f"❌ 测试异常: {e}")
import traceback
print(f"详细错误: {traceback.format_exc()}")
return False
def test_pyscenedetect_version():
"""测试PySceneDetect版本和API"""
print("\n🧪 测试PySceneDetect版本和API...")
try:
import scenedetect
print(f"📦 PySceneDetect版本: {scenedetect.__version__}")
# 测试基本API
from scenedetect import open_video, SceneManager
from scenedetect.detectors import ContentDetector
video_path = Path("assets/1/1752032011698.mp4")
if not video_path.exists():
print(f"❌ 测试视频不存在: {video_path}")
return False
# 打开视频
video = open_video(str(video_path))
scene_manager = SceneManager()
scene_manager.add_detector(ContentDetector(threshold=30.0))
print("📊 执行基础场景检测...")
scene_manager.detect_scenes(video, show_progress=False)
scene_list = scene_manager.get_scene_list()
print(f"✅ 基础检测成功,找到 {len(scene_list)} 个场景")
# 测试时间码API
if scene_list:
start_time, end_time = scene_list[0]
print(f"📋 第一个场景时间码类型: {type(start_time)}")
# 测试不同的时间获取方法
methods = []
if hasattr(start_time, 'total_seconds'):
try:
seconds = start_time.total_seconds()
methods.append(f"total_seconds(): {seconds:.2f}")
except Exception as e:
methods.append(f"total_seconds() 失败: {e}")
if hasattr(start_time, 'get_seconds'):
try:
seconds = start_time.get_seconds()
methods.append(f"get_seconds(): {seconds:.2f}")
except Exception as e:
methods.append(f"get_seconds() 失败: {e}")
try:
seconds = float(start_time)
methods.append(f"float(): {seconds:.2f}")
except Exception as e:
methods.append(f"float() 失败: {e}")
print("🔍 可用的时间获取方法:")
for method in methods:
print(f" - {method}")
return True
except Exception as e:
print(f"❌ 测试异常: {e}")
import traceback
print(f"详细错误: {traceback.format_exc()}")
return False
def main():
"""主函数"""
print("🚀 开始测试场景检测修复")
print("=" * 60)
tests = [
("PySceneDetect版本和API", test_pyscenedetect_version),
("视频信息提取", test_video_info),
("基础场景检测", test_basic_detection),
]
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} 通过")
if passed == total:
print("🎊 所有测试都通过了!场景检测修复成功!")
else:
print("⚠️ 部分测试失败,需要进一步调试")
return passed == total
if __name__ == "__main__":
success = main()
sys.exit(0 if success else 1)