zhangyong hai 6 meses
pai
achega
a547894b01
Modificáronse 2 ficheiros con 51 adicións e 23 borrados
  1. 48 20
      analyze_video.py
  2. 3 3
      google_ai/generativeai_video.py

+ 48 - 20
analyze_video.py

@@ -1,23 +1,55 @@
-from fastapi import FastAPI, HTTPException
+import asyncio
+from fastapi import FastAPI
 from pydantic import BaseModel
-import uvicorn
+
 from google_ai.generativeai_video import main
 
 app = FastAPI()
 
-class VideoRequest(BaseModel):
+api_keys = [
+    {'key': 'AIzaSyAa4H7YzIOiqA0QIDuO6kNErFBoWT-BEtc', 'locked': False},
+    {'key': 'AIzaSyC-IxUvJhbiKWA7uN1RTtVbOjt3pj_-Apc', 'locked': False},
+    {'key': 'AIzaSyB43Pvugb-CMkEXJUSubXEAxKxYflCPPNU', 'locked': False}
+]
+
+lock = asyncio.Lock()
+
+
+class VideoRequest( BaseModel ):
     video_path: str
 
-@app.post("/process_video/")
+async def get_available_api_key():
+    """获取一个未锁定的 API key,如果没有可用的则等待 60 秒后重试"""
+    while True:  # 无限循环,直到找到可用的 key
+        async with lock:
+            for key_data in api_keys:
+                if not key_data['locked']:
+                    key_data['locked'] = True  # 锁定该 key
+                    return key_data['key']
+        # 如果没有找到可用的 key,等待 60 秒后重试
+        print( "没有可用的 API key,等待 60 秒后重试..." )
+        await asyncio.sleep( 60 )
+
+async def release_api_key(api_key):
+    """释放已锁定的 API key"""
+    async with lock:
+        for key_data in api_keys:
+            if key_data['key'] == api_key:
+                key_data['locked'] = False  # 释放该 key
+                break
+
+
+@app.post( "/process_video/" )
 async def process_video(request: VideoRequest):
     """处理视频请求"""
     video_path = request.video_path
 
-    # 调用 main 函数进行视频处理
+    # 获取一个可用的 API key
+    api_key = await get_available_api_key()
+
     try:
-        print("来一个请求")
-        # 确保 main 函数是异步的
-        result, mark = await main(video_path)
+        print( "来一个请求,使用 API key:", api_key )
+        result, mark = await main( video_path, api_key )
         return {
             "code": 0,
             "message": "视频处理成功",
@@ -25,17 +57,13 @@ async def process_video(request: VideoRequest):
             "mark": mark
         }
     except Exception as e:
-        print(f"视频处理失败: {str(e)}")
+        print( f"视频处理失败: {str( e )}" )
         return {
-            "code": 0,
-            "message": f"视频处理失败:{e}",
-            "result": f"视频处理失败:{e}",
-            "mark": f"视频处理失败:{e}"
+            "code": 1,
+            "message": f"视频处理失败: {e}",
+            "result": f"视频处理失败: {e}",
+            "mark": f"视频处理失败: {e}"
         }
-
-
-if __name__ == "__main__":
-    # proxy_url = 'http://127.0.0.1:1081'
-    # os.environ["http_proxy"] = proxy_url
-    # os.environ["https_proxy"] = proxy_url
-    uvicorn.run(app, host="0.0.0.0", port=8080)
+    finally:
+        # 释放 API key,确保后续请求可以使用
+        await release_api_key( api_key )

+ 3 - 3
google_ai/generativeai_video.py

@@ -92,9 +92,9 @@ class VideoAnalyzer:
             response = chat_session.send_message( message_content )
             return response
 
-async def main(video_path):
+async def main(video_path, api_key):
     """主函数,执行视频上传、缓存创建、问题生成"""
-    api_key = 'AIzaSyAUvBSpjFcm7b8FsgRUTG6anzoalDp9gYg'
+    # api_key = 'AIzaSyAa4H7YzIOiqA0QIDuO6kNErFBoWT-BEtc'
     mark, prompt = Material.feishu_list()
     attempt = 0
     max_attempts = 1
@@ -144,7 +144,7 @@ async def main(video_path):
                 "七、时效性与分类": {
                     "时效性": {},
                     "视频一级分类": "",
-                    "二级分类": ["品类- ,分数-", "品类- ,分数-", "品类- ,分数-"]
+                    "二级分类": ["品类- 、分数-", "品类- 、分数-", "品类- 、分数-"]
                 }
             }
             # 视频分析问题