google_ai_api.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. """
  2. @author: luojunhui
  3. """
  4. from google import genai
  5. from google.genai.errors import ClientError
  6. from tqdm import tqdm
  7. class GoogleAIAPI(object):
  8. """
  9. Google 视频内容理解API
  10. """
  11. def __init__(self, api_key):
  12. self.api_key = api_key
  13. self.client = genai.Client(api_key=self.api_key)
  14. def upload_file(self, file_path: str):
  15. """
  16. file_path: 文件路径
  17. """
  18. tqdm.write("start uploading file: {}".format(file_path))
  19. try:
  20. video_file = self.client.files.upload(file=file_path)
  21. file_name = video_file.name
  22. file_state = video_file.state.name
  23. expire_time = video_file.expiration_time
  24. tqdm.write("success uploaded file: {}".format(file_path))
  25. return file_name, file_state, expire_time
  26. except Exception as e:
  27. tqdm.write("fail to upload file: {} because {}".format(file_path, e))
  28. return None
  29. def get_file_status(self, file_name: str,):
  30. """
  31. 获取文件的状态
  32. file_name: 文件名称
  33. """
  34. try:
  35. video_file = self.client.files.get(name=file_name)
  36. state = video_file.state.name
  37. return state
  38. except Exception as e:
  39. print(e)
  40. return None
  41. def get_google_file(self, file_name: str):
  42. """
  43. 获取文件
  44. file_name: 文件名称
  45. """
  46. try:
  47. video_file = self.client.files.get(name=file_name)
  48. return video_file
  49. except Exception as e:
  50. print(e)
  51. return None
  52. def fetch_info_from_google_ai(self, prompt, video_file):
  53. """
  54. 获取视频文本
  55. prompt: 提示词
  56. video_file: <class 'google.genai.types.File'>
  57. """
  58. try:
  59. response = self.client.models.generate_content(
  60. model='gemini-1.5-flash',
  61. contents=[
  62. video_file,
  63. prompt
  64. ]
  65. )
  66. return {
  67. 'code': 200,
  68. 'text': response.text
  69. }
  70. except ClientError as e:
  71. return {
  72. 'code': e.response.status_code,
  73. 'text': 'resource exhausted'
  74. }
  75. except Exception as e:
  76. return {
  77. 'code': 500,
  78. 'text': str(e)
  79. }
  80. def delete_video(self, file_name: str):
  81. """
  82. 删除视频
  83. """
  84. self.client.files.delete(name=file_name)
  85. def get_file_list(self):
  86. """
  87. 获取文件列表
  88. """
  89. file_list = self.client.files.list()
  90. return file_list