video_identifier.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 视频识别脚本
  5. 主要功能:使用 Gemini API 分析视频内容
  6. """
  7. import os
  8. import json
  9. import time
  10. import sys
  11. from typing import Dict, Any, List, Optional
  12. from dotenv import load_dotenv
  13. # 导入自定义模块
  14. sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  15. from gemini import GeminiProcessor
  16. class VideoIdentifier:
  17. def __init__(self):
  18. # 加载环境变量
  19. load_dotenv()
  20. # 初始化Gemini客户端
  21. self.gemini = GeminiProcessor()
  22. # 系统提示词
  23. self.video_system_prompt = """你是一个专业的视频内容分析专家。请分析视频中的内容,包括:
  24. 1. 视频的主要内容和主题
  25. 2. 视频中的文字内容(如果有)
  26. 3. 视频的风格和特点
  27. 4. 视频可能表达的情感或意图
  28. 5. 视频的背景音乐或语音内容(如果有)
  29. 请用简洁、准确的语言描述视频内容,重点关注文字内容和主要视觉元素。"""
  30. def extract_video_urls(self, formatted_content: Dict[str, Any]) -> List[Dict[str, Any]]:
  31. """提取视频URL列表"""
  32. video_data = []
  33. video_url_list = formatted_content.get('video_url_list', [])
  34. for video_item in video_url_list:
  35. if isinstance(video_item, dict) and 'video_url' in video_item:
  36. video_data.append({
  37. 'url': video_item['video_url'],
  38. 'duration': video_item.get('video_duration', 0)
  39. })
  40. return video_data
  41. def analyze_videos_with_gemini(self, video_data: List[Dict[str, Any]]) -> Dict[str, Any]:
  42. """使用Gemini API分析视频内容"""
  43. try:
  44. if not video_data:
  45. return {"videos_comprehension": [], "error": "没有视频需要分析"}
  46. print(f"正在使用Gemini API分析 {len(video_data)} 个视频...")
  47. videos_comprehension = []
  48. for i, video in enumerate(video_data):
  49. print(f" 分析视频 {i+1}/{len(video_data)}: {video['url'][:50]}...")
  50. # 构建分析提示
  51. prompt = f"""请分析以下视频内容:
  52. 视频时长: {video['duration']}秒
  53. 视频链接: {video['url']}
  54. 请从以下角度分析视频内容:
  55. 1. 视频的主要内容和主题
  56. 2. 视频中的文字内容(如果有)
  57. 3. 视频的风格和特点
  58. 4. 视频可能表达的情感或意图
  59. 5. 视频的背景音乐或语音内容(如果有)
  60. 请用简洁、准确的语言描述视频内容。"""
  61. # 调用Gemini API
  62. try:
  63. response = self.gemini.process(
  64. content=prompt,
  65. system_prompt=self.video_system_prompt,
  66. model_name="gemini-2.5-flash"
  67. )
  68. if response:
  69. videos_comprehension.append({
  70. 'video_url': video['url'],
  71. 'duration': video['duration'],
  72. 'comprehension': response,
  73. 'analysis_timestamp': int(time.time() * 1000)
  74. })
  75. else:
  76. videos_comprehension.append({
  77. 'video_url': video['url'],
  78. 'duration': video['duration'],
  79. 'comprehension': 'Gemini API分析失败',
  80. 'analysis_timestamp': int(time.time() * 1000)
  81. })
  82. # 添加延迟避免API限制
  83. time.sleep(1)
  84. except Exception as e:
  85. print(f" 视频 {i+1} 分析失败: {e}")
  86. videos_comprehension.append({
  87. 'video_url': video['url'],
  88. 'duration': video['duration'],
  89. 'comprehension': f'分析失败: {str(e)}',
  90. 'analysis_timestamp': int(time.time() * 1000)
  91. })
  92. return {"videos_comprehension": videos_comprehension}
  93. except Exception as e:
  94. print(f"Gemini API调用失败: {e}")
  95. return {"videos_comprehension": [], "error": f"Gemini API调用失败: {str(e)}"}
  96. def process_videos(self, formatted_content: Dict[str, Any]) -> Dict[str, Any]:
  97. """处理视频识别的主函数"""
  98. print("开始视频识别处理...")
  99. # 提取视频URL
  100. video_data = self.extract_video_urls(formatted_content)
  101. print(f"提取到 {len(video_data)} 个视频")
  102. if not video_data:
  103. print("没有视频需要分析")
  104. return {"videos_comprehension": [], "error": "没有视频需要分析"}
  105. # 分析视频
  106. result = self.analyze_videos_with_gemini(video_data)
  107. if result.get("videos_comprehension"):
  108. print(f"视频识别完成,共分析 {len(result['videos_comprehension'])} 个视频")
  109. else:
  110. print("视频识别失败")
  111. return result
  112. def main():
  113. """测试函数"""
  114. # 模拟数据
  115. test_content = {
  116. "video_url_list": [
  117. {
  118. "video_url": "http://example.com/video1.mp4",
  119. "video_duration": 30
  120. }
  121. ]
  122. }
  123. identifier = VideoIdentifier()
  124. result = identifier.process_videos(
  125. test_content["title"],
  126. test_content["body_text"],
  127. test_content
  128. )
  129. print(f"识别结果: {json.dumps(result, ensure_ascii=False, indent=2)}")
  130. if __name__ == '__main__':
  131. main()