google_ai_studio.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import os
  2. import time
  3. import uuid
  4. from typing import Optional
  5. import google.generativeai as genai
  6. import orjson
  7. import requests
  8. from google.generativeai.types import (HarmBlockThreshold, HarmCategory)
  9. from loguru import logger
  10. CACHE_DIR = '/app/cache/'
  11. # CACHE_DIR = '/Users/z/Downloads/'
  12. # PROXY_ADDR = 'http://localhost:1081'
  13. # os.environ['http_proxy'] = PROXY_ADDR
  14. # os.environ['https_proxy'] = PROXY_ADDR
  15. class GoogleAI(object):
  16. @classmethod
  17. def download_video(cls, video_link: str) -> Optional[str]:
  18. file_path = os.path.join(CACHE_DIR, f'{str(uuid.uuid4())}.mp4')
  19. for _ in range(3):
  20. try:
  21. response = requests.get(url=video_link, timeout=60)
  22. if response.status_code == 200:
  23. with open(file_path, 'wb') as f:
  24. f.write(response.content)
  25. logger.info(f'[内容分析] 视频链接: {video_link}, 存储地址: {file_path}')
  26. return file_path
  27. except Exception:
  28. time.sleep(1)
  29. continue
  30. return
  31. @classmethod
  32. def run(cls, api_key, video_path):
  33. try:
  34. genai.configure(api_key=api_key)
  35. video = genai.upload_file(path=video_path, mime_type='video/mp4')
  36. while video.state.name == 'PROCESSING':
  37. time.sleep(1)
  38. video = genai.get_file(name=video.name)
  39. if video.state.name != 'ACTIVE':
  40. genai.delete_file(name=video.name)
  41. return
  42. model = genai.GenerativeModel(
  43. model_name='gemini-1.5-flash',
  44. generation_config=genai.GenerationConfig(response_mime_type='application/json'),
  45. safety_settings={
  46. HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_NONE,
  47. },
  48. )
  49. response = model.generate_content(
  50. contents=[
  51. video,
  52. "你是一名专业的短视频分析师,请你输出这个视频的完整口播,只输出文字即可。使用一下JSON格式输出:{'text': string}",
  53. ],
  54. stream=False,
  55. request_options={
  56. 'timeout': 600,
  57. },
  58. )
  59. text = orjson.loads(response.text.strip())['text']
  60. genai.delete_file(name=video.name)
  61. return text
  62. except Exception as e:
  63. logger.error(f"[内容分析] 处理异常,异常信息{e}")
  64. return
  65. if __name__ == '__main__':
  66. GoogleAI.run("AIzaSyAwGqthDADh5NPVe3BMcOJBQkJaf0HWBuQ",
  67. "http://rescdn.yishihui.com/jq_oss/video/2025012215472528213")