google_ai_api.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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):
  12. self.api_key = 'AIzaSyBAFFL6yHa4kUK-YcuAw8tbiSHQB6oJG34'
  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-2.0-flash',
  61. contents=[
  62. video_file,
  63. prompt
  64. ]
  65. )
  66. return response.text
  67. except ClientError as e:
  68. print(e.response.status_code)
  69. return None
  70. def delete_video(self, file_name: str):
  71. """
  72. 删除视频
  73. """
  74. self.client.files.delete(name=file_name)
  75. def get_file_list(self):
  76. """
  77. 获取文件列表
  78. """
  79. file_list = self.client.files.list()
  80. return file_list