google_ai_api.py 2.3 KB

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