zhangyong 6 months ago
parent
commit
a71f9e3d0a
2 changed files with 10 additions and 20 deletions
  1. 1 0
      analyze_video.py
  2. 9 20
      google_ai/generativeai_video.py

+ 1 - 0
analyze_video.py

@@ -3,6 +3,7 @@ import asyncio
 from fastapi import FastAPI
 from pydantic import BaseModel
 from google_ai.generativeai_video import main
+import google.generativeai as genai
 
 app = FastAPI()
 api_keys = [

+ 9 - 20
google_ai/generativeai_video.py

@@ -28,12 +28,11 @@ class VideoAnalyzer:
     # async def download_video(self, video_url, save_directory='/Users/tzld/Desktop/google_ai_studio/path'):
 
         """从给定的视频链接下载视频并保存到指定路径"""
-        random_filename = f"{uuid.uuid4()}.mp4"
-        save_path = os.path.join(save_directory, random_filename)
-
         max_retries = 3  # 最大重试次数
         for attempt in range(max_retries):
             try:
+                random_filename = f"{uuid.uuid4()}.mp4"
+                save_path = os.path.join( save_directory, random_filename )
                 # 发送 GET 请求获取视频内容
                 headers = {}
                 payload = {}
@@ -47,7 +46,6 @@ class VideoAnalyzer:
                     return save_path
                 else:
                     print(f"请求失败,状态码: {response.status_code}")
-
             except requests.exceptions.RequestException as e:
                 print(f"下载视频时出现错误: {e}")
 
@@ -57,16 +55,10 @@ class VideoAnalyzer:
         print("达到最大重试次数,视频下载失败")
         return None
 
-    async def delete_video(self):
-        try:
-            self.video_file.delete()
-        except Exception as e:
-            Common.logger( "ai" ).info( f'视频删除异常{e}' )
-
-    async def upload_video(self, save_path, mime_type = None):
+    async def upload_video(self, save_path):
         """上传视频文件并获取视频文件对象"""
         try:
-            self.video_file = genai.upload_file(save_path, mime_type=mime_type)
+            self.video_file = genai.upload_file(save_path)
             await self._wait_for_processing()
         except Exception as e:
             Common.logger("ai").info(f'上传视频文件并获取视频文件对象失败异常信息{e}')
@@ -91,7 +83,7 @@ class VideoAnalyzer:
                 model_name="gemini-1.5-flash",
                 generation_config=generation_config,
                 safety_settings={
-                    HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_NONE,
+                    HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_NONE,
                 }
 
             )
@@ -114,6 +106,7 @@ class VideoAnalyzer:
                 ]
             }
             response = chat_session.send_message( message_content )
+            self.video_file.delete()
             return response
         except Exception as e:
             Common.logger("ai").info(f'视频处理请求失败:{e}')
@@ -137,9 +130,9 @@ async def main(video_path, api_key, prompt, sample_data):
         try:
             # 初始化视频分析类
             analyzer = VideoAnalyzer(api_key )
-            for file in genai.list_files():
-                # file.delete()
-                print( "  ", file.name )
+            # for file in genai.list_files():
+            #     file.delete()
+            #     print( "  ", file.name )
             duration = analyzer.video_duration( video_path )
             print( f"视频时长为{duration}秒" )
             if int( duration ) >= 600 or int( duration ) == 0:
@@ -154,12 +147,10 @@ async def main(video_path, api_key, prompt, sample_data):
             # 上传并处理视频
             upload_response = await analyzer.upload_video( save_path )
             if upload_response:
-                await analyzer.delete_video()
                 return upload_response
             # 创建缓存模型
             model =await analyzer.create_cache()
             if isinstance( model, str ):
-                await analyzer.delete_video()
                 return model
             print("创建缓存模型成功")
             # sample_data = {
@@ -197,14 +188,12 @@ async def main(video_path, api_key, prompt, sample_data):
             # }
             response =await analyzer.analyze_video( model, prompt, sample_data )
             if isinstance( response, str ):
-                await analyzer.delete_video()
                 return response
             print( response.usage_metadata )
             print(response.text)
             if os.path.exists( save_path ):
                 os.remove( save_path )
                 print( f"文件已删除: {save_path}" )
-            await analyzer.delete_video()
             return response.text
         except Exception as e:
             attempt += 1  # 增加尝试次数