google_ai_studio.py 3.2 KB

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