generate_text_from_video.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. """
  2. @author: luojunhui
  3. todo: 加上多进程锁
  4. """
  5. import os
  6. import time
  7. import requests
  8. from pymysql.cursors import DictCursor
  9. from tqdm import tqdm
  10. from applications.api import GoogleAIAPI
  11. from applications.db import DatabaseConnector
  12. from config import long_articles_config
  13. # 办公室网络调试需要打开代理
  14. # os.environ["HTTP_PROXY"] = "http://192.168.100.20:1087"
  15. # os.environ["HTTPS_PROXY"] = "http://192.168.100.20:1087"
  16. def download_file(pq_vid, video_url):
  17. """
  18. 下载视频文件
  19. """
  20. file_name = "static/{}.mp4".format(pq_vid)
  21. if os.path.exists(file_name):
  22. return file_name
  23. proxies = {
  24. "http": None,
  25. "https": None
  26. }
  27. with open(file_name, 'wb') as f:
  28. response = requests.get(video_url, proxies=proxies)
  29. f.write(response.content)
  30. return file_name
  31. class GenerateTextFromVideo(object):
  32. """
  33. 从视频中生成文本
  34. """
  35. def __init__(self):
  36. self.google_ai_api = GoogleAIAPI()
  37. self.db = DatabaseConnector(db_config=long_articles_config)
  38. def connect_db(self):
  39. """
  40. 连接数据库
  41. """
  42. self.db.connect()
  43. def input_task_list(self):
  44. """
  45. 输入任务列表, 从single_video_pool中获取
  46. """
  47. sql = f"""
  48. select article_title, concat('https://rescdn.yishihui.com/', video_oss_path ) as video_url, audit_video_id
  49. from publish_single_video_source
  50. where audit_status = 1 and bad_status = 0 and extract_status = 0
  51. order by id desc;
  52. """
  53. task_list = self.db.fetch(sql, cursor_type=DictCursor)
  54. insert_sql = f"""
  55. insert ignore into video_content_understanding
  56. (pq_vid, video_ori_title, video_oss_path)
  57. values (%s, %s, %s)
  58. """
  59. affected_rows = self.db.save_many(
  60. insert_sql,
  61. params_list=[(i['audit_video_id'], i['article_title'], i['video_url']) for i in task_list]
  62. )
  63. print(affected_rows)
  64. def upload_video_to_google_ai(self, max_processing_video_count=20):
  65. """
  66. 上传视频到Google AI
  67. max_processing_video_count: 处理中的最大视频数量,默认1000
  68. video_content_understanding 表status字段
  69. 0: 未处理
  70. 1: 处理中
  71. 2: 处理完成
  72. """
  73. # 查询出在视频处于PROCESSING状态的视频数量
  74. select_sql = "select count(1) as processing_count from video_content_understanding where status = 1;"
  75. count = self.db.fetch(select_sql, cursor_type=DictCursor)[0]['processing_count']
  76. rest_video_count = max_processing_video_count - count
  77. success_upload_count = 0
  78. if rest_video_count:
  79. sql = f"""select pq_vid, video_oss_path from video_content_understanding where status = 0 limit {rest_video_count};"""
  80. task_list = self.db.fetch(sql, cursor_type=DictCursor)
  81. for task in tqdm(task_list, desc="upload_video_task"):
  82. file_path = download_file(task['pq_vid'], task['video_oss_path'])
  83. google_upload_result = self.google_ai_api.upload_file(file_path)
  84. if google_upload_result:
  85. file_name, file_state, expire_time = google_upload_result
  86. update_sql = f"""
  87. update video_content_understanding
  88. set status = %s, file_name = %s, file_state = %s, file_expire_time = %s
  89. where pq_vid = %s;
  90. """
  91. self.db.save(
  92. update_sql,
  93. params=(1, file_name, file_state, expire_time, task['pq_vid'])
  94. )
  95. success_upload_count += 1
  96. else:
  97. continue
  98. return success_upload_count
  99. def delete_video_from_google(self, file_name):
  100. """
  101. 删除视频文件
  102. """
  103. self.google_ai_api.delete_video(file_name)
  104. def get_tasks(self):
  105. """
  106. 获取处理视频转文本任务
  107. """
  108. sql = "select pq_vid, file_name from video_content_understanding where status = 1 order by file_expire_time limit 5;"
  109. task_list = self.db.fetch(sql, cursor_type=DictCursor)
  110. return task_list
  111. def convert_video_to_text_with_google_ai(self):
  112. """
  113. 处理视频转文本任务
  114. """
  115. task_list = self.get_tasks()
  116. while task_list:
  117. for task in tqdm(task_list, desc="convert video to text"):
  118. file_name = task['file_name']
  119. video_local_path = "static/{}.mp4".format(task['pq_vid'])
  120. google_file = self.google_ai_api.get_google_file(file_name)
  121. state = google_file.state.name
  122. match state:
  123. case 'ACTIVE':
  124. try:
  125. video_text = self.google_ai_api.get_video_text(
  126. prompt="分析我上传的视频的画面和音频,用叙述故事的风格将视频所描述的事件进行总结,需要保证视频内容的完整性,并且用中文进行输出,直接返回生成的文本。",
  127. video_file=google_file
  128. )
  129. if video_text:
  130. update_sql = f"""
  131. update video_content_understanding
  132. set status = %s, video_text = %s, file_state = %s
  133. where pq_vid = %s;
  134. """
  135. self.db.save(
  136. update_sql,
  137. params=(2, video_text, state, task['pq_vid'])
  138. )
  139. if os.path.exists(video_local_path):
  140. os.remove(video_local_path)
  141. tqdm.write("video transform to text success, delete local file, sleep 1 min...")
  142. task_list.remove(task)
  143. self.google_ai_api.delete_video(file_name)
  144. print("delete video from google success: {}".format(file_name))
  145. except Exception as e:
  146. tqdm.write(str(e))
  147. continue
  148. case 'PROCESSING':
  149. tqdm.write("video is still processing")
  150. continue
  151. case 'FAILED':
  152. update_sql = f"""
  153. update video_content_understanding
  154. set status = %s, file_state = %s
  155. where pq_vid = %s;
  156. """
  157. self.db.save(
  158. update_sql,
  159. params=(99, state, task['pq_vid'])
  160. )
  161. if os.path.exists(video_local_path):
  162. os.remove(video_local_path)
  163. tqdm.write("video process failed, delete local file")
  164. continue
  165. time.sleep(10)
  166. tqdm.write("执行完一轮任务,剩余数量:{}".format(len(task_list)))
  167. time.sleep(60)