analyze_video.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import uvicorn
  2. import asyncio
  3. from fastapi import FastAPI
  4. from pydantic import BaseModel
  5. from google_ai.generativeai_video import main
  6. app = FastAPI()
  7. api_keys = [
  8. {'key': 'AIzaSyB2kjF2-S2B5cJiosx_LpApd227w33CVvs', 'locked': False},
  9. {'key': 'AIzaSyCor0q5w37Dy6fGxloLlCT7KqyEFU3PWP8', 'locked': False},
  10. ]
  11. lock = asyncio.Lock()
  12. class VideoRequest(BaseModel):
  13. video_path: str
  14. prompt: str
  15. mark: str
  16. sample_data: str
  17. async def get_available_api_key():
  18. """获取一个未锁定的 API key,如果没有可用的则等待 5 秒后重试"""
  19. while True:
  20. async with lock:
  21. for key_data in api_keys:
  22. if not key_data['locked']:
  23. key_data['locked'] = True # 锁定该 key
  24. return key_data['key']
  25. print( "没有可用的 API key,等待 5 秒后重试..." )
  26. await asyncio.sleep( 5 )
  27. async def release_api_key(api_key):
  28. """释放已锁定的 API key,并将其放到列表末尾"""
  29. async with lock:
  30. for i, key_data in enumerate( api_keys ):
  31. if key_data['key'] == api_key:
  32. key_data['locked'] = False # 释放该 key
  33. # 将释放的 key 移动到列表末尾
  34. api_keys.append( api_keys.pop( i ) )
  35. break
  36. @app.post("/process_video/")
  37. async def process_video(request: VideoRequest):
  38. """处理视频请求"""
  39. global api_key_index # 引用全局索引
  40. video_path = request.video_path
  41. prompt = request.prompt
  42. mark = request.mark
  43. sample_data = request.sample_data
  44. api_key = await get_available_api_key()
  45. try:
  46. print("来一个请求,使用 API key:", api_key)
  47. result = await main(video_path, api_key, prompt, sample_data)
  48. return {
  49. "code": 0,
  50. "message": "视频处理成功",
  51. "result": result,
  52. "mark": str(mark)
  53. }
  54. except Exception as e:
  55. print(f"处理失败: {str(e)}")
  56. return {
  57. "code": 1,
  58. "message": f"处理失败: {e}",
  59. "result": f"处理失败: {e}",
  60. "mark": f"处理失败: {e}"
  61. }
  62. finally:
  63. await release_api_key( api_key )
  64. if __name__ == "__main__":
  65. uvicorn.run(app, host="0.0.0.0", port=8080)