generate_text_from_video.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. """
  2. @author: luojunhui
  3. """
  4. import os
  5. import time
  6. import traceback
  7. import requests
  8. from pymysql.cursors import DictCursor
  9. from tqdm import tqdm
  10. from applications.api import GoogleAIAPI
  11. from applications.const import VideoToTextConst
  12. from applications.db import DatabaseConnector
  13. from config import long_articles_config
  14. from config import apolloConfig
  15. # 办公室网络调试需要打开代理
  16. # os.environ["HTTP_PROXY"] = "http://192.168.100.20:1087"
  17. # os.environ["HTTPS_PROXY"] = "http://192.168.100.20:1087"
  18. const = VideoToTextConst()
  19. config = apolloConfig(env="prod")
  20. # pool_size
  21. POOL_SIZE = int(config.getConfigValue("video_extract_pool_size"))
  22. # batch_size
  23. BATCH_SIZE = int(config.getConfigValue("video_extract_batch_size"))
  24. def download_file(pq_vid, video_url):
  25. """
  26. 下载视频文件
  27. """
  28. file_name = "static/{}.mp4".format(pq_vid)
  29. if os.path.exists(file_name):
  30. return file_name
  31. proxies = {
  32. "http": None,
  33. "https": None
  34. }
  35. with open(file_name, 'wb') as f:
  36. response = requests.get(video_url, proxies=proxies)
  37. f.write(response.content)
  38. return file_name
  39. class GenerateTextFromVideo(object):
  40. """
  41. 从视频中生成文本
  42. """
  43. def __init__(self):
  44. self.google_ai_api = GoogleAIAPI()
  45. self.db = DatabaseConnector(db_config=long_articles_config)
  46. def connect_db(self):
  47. """
  48. 连接数据库
  49. """
  50. self.db.connect()
  51. def update_task_status(self, task_id, process, ori_status, new_status):
  52. """
  53. 回滚长时间处于处理中的任务
  54. """
  55. match process:
  56. case "upload":
  57. status = 'upload_status'
  58. update_timestamp = 'upload_status_ts'
  59. case "understanding":
  60. status = 'understanding_status'
  61. update_timestamp = 'understanding_status_ts'
  62. case "summary":
  63. status = 'summary_status'
  64. update_timestamp = 'summary_status_ts'
  65. case "rewrite":
  66. status = 'rewrite_status'
  67. update_timestamp = 'rewrite_status_ts'
  68. case _:
  69. raise ValueError(f"Unexpected task: {process}")
  70. update_sql = f"""
  71. update video_content_understanding
  72. set {status} = %s, {update_timestamp} = %s
  73. where {status} = %s and id = %s;
  74. """
  75. roll_back_rows = self.db.save(
  76. query=update_sql,
  77. params=(
  78. new_status,
  79. int(time.time()),
  80. ori_status,
  81. task_id,
  82. )
  83. )
  84. return roll_back_rows
  85. def upload_video_to_google_ai(self, max_processing_video_count=POOL_SIZE):
  86. """
  87. 上传视频到Google AI
  88. max_processing_video_count: 处理中的最大视频数量,默认20
  89. video_content_understanding 表status字段
  90. 0: 未处理
  91. 1: 处理中
  92. 2: 处理完成
  93. """
  94. select_sql = f"""
  95. select count(1) as processing_count
  96. from video_content_understanding
  97. where understanding_status = {const.PROCESSING_STATUS};
  98. """
  99. count = self.db.fetch(select_sql, cursor_type=DictCursor)[0]['processing_count']
  100. rest_video_count = max_processing_video_count - count
  101. success_upload_count = 0
  102. if rest_video_count:
  103. sql = f"""
  104. select id, video_oss_path
  105. from video_content_understanding
  106. where upload_status = {const.INIT_STATUS}
  107. limit {rest_video_count};
  108. """
  109. task_list = self.db.fetch(sql, cursor_type=DictCursor)
  110. for task in tqdm(task_list, desc="upload_video_task"):
  111. lock_rows = self.update_task_status(
  112. task_id=task['id'],
  113. process='upload',
  114. ori_status=const.INIT_STATUS,
  115. new_status=const.PROCESSING_STATUS
  116. )
  117. if not lock_rows:
  118. continue
  119. try:
  120. file_path = download_file(task['id'], task['video_oss_path'])
  121. google_upload_result = self.google_ai_api.upload_file(file_path)
  122. if google_upload_result:
  123. file_name, file_state, expire_time = google_upload_result
  124. update_sql = f"""
  125. update video_content_understanding
  126. set
  127. upload_status = %s,
  128. upload_status_ts = %s,
  129. file_name = %s,
  130. file_state = %s,
  131. file_expire_time = %s
  132. where id = %s and upload_status = %s;
  133. """
  134. self.db.save(
  135. update_sql,
  136. params=(
  137. const.SUCCESS_STATUS,
  138. int(time.time()),
  139. file_name,
  140. file_state,
  141. expire_time,
  142. task['id'],
  143. const.PROCESSING_STATUS
  144. )
  145. )
  146. success_upload_count += 1
  147. except Exception as e:
  148. print("task upload failed because of {}".format(e))
  149. print("trace_back: ", traceback.format_exc())
  150. # roll back status
  151. self.update_task_status(
  152. task_id=task['id'],
  153. process='upload',
  154. ori_status=const.PROCESSING_STATUS,
  155. new_status=const.FAIL_STATUS
  156. )
  157. return success_upload_count
  158. def delete_video_from_google(self, file_name):
  159. """
  160. 删除视频文件
  161. """
  162. self.google_ai_api.delete_video(file_name)
  163. def get_task_list(self):
  164. """
  165. 获取处理视频转文本任务
  166. """
  167. sql = f"""
  168. select id, file_name
  169. from video_content_understanding
  170. where upload_status = {const.SUCCESS_STATUS} and understanding_status = {const.INIT_STATUS}
  171. order by file_expire_time
  172. limit {BATCH_SIZE};
  173. """
  174. task_list = self.db.fetch(sql, cursor_type=DictCursor)
  175. return task_list
  176. def convert_video_to_text_with_google_ai(self):
  177. """
  178. 处理视频转文本任务
  179. """
  180. task_list = self.get_task_list()
  181. while task_list:
  182. for task in tqdm(task_list, desc="convert video to text"):
  183. print(task['pq_vid'], task['file_name'])
  184. # LOCK TASK
  185. lock_row = self.update_task_status(
  186. task_id=task['id'],
  187. process='understanding',
  188. ori_status=const.INIT_STATUS,
  189. new_status=const.PROCESSING_STATUS
  190. )
  191. if not lock_row:
  192. print("Lock")
  193. continue
  194. file_name = task['file_name']
  195. video_local_path = "static/{}.mp4".format(task['id'])
  196. google_file = self.google_ai_api.get_google_file(file_name)
  197. state = google_file.state.name
  198. match state:
  199. case 'ACTIVE':
  200. try:
  201. video_text = self.google_ai_api.get_video_text(
  202. prompt="分析我上传的视频的画面和音频,用叙述故事的风格将视频所描述的事件进行总结,需要保证视频内容的完整性,并且用中文进行输出,直接返回生成的文本。",
  203. video_file=google_file
  204. )
  205. if video_text:
  206. update_sql = f"""
  207. update video_content_understanding
  208. set understanding_status = %s, video_text = %s, file_state = %s
  209. where id = %s and understanding_status = %s;
  210. """
  211. self.db.save(
  212. update_sql,
  213. params=(
  214. const.SUCCESS_STATUS,
  215. video_text,
  216. state,
  217. task['id'],
  218. const.PROCESSING_STATUS
  219. )
  220. )
  221. # delete local file and google file
  222. if os.path.exists(video_local_path):
  223. os.remove(video_local_path)
  224. tqdm.write("video transform to text success, delete local file")
  225. task_list.remove(task)
  226. self.google_ai_api.delete_video(file_name)
  227. tqdm.write("delete video from google success: {}".format(file_name))
  228. else:
  229. # roll back status
  230. self.update_task_status(
  231. task_id=task['id'],
  232. process='understanding',
  233. ori_status=const.PROCESSING_STATUS,
  234. new_status=const.INIT_STATUS
  235. )
  236. except Exception as e:
  237. # roll back status
  238. self.update_task_status(
  239. task_id=task['id'],
  240. process='understanding',
  241. ori_status=const.PROCESSING_STATUS,
  242. new_status=const.FAIL_STATUS
  243. )
  244. tqdm.write(str(e))
  245. continue
  246. case 'PROCESSING':
  247. tqdm.write("video is still processing")
  248. case 'FAILED':
  249. self.update_task_status(
  250. task_id=task['id'],
  251. process='understanding',
  252. ori_status=const.PROCESSING_STATUS,
  253. new_status=const.FAIL_STATUS
  254. )
  255. if os.path.exists(video_local_path):
  256. os.remove(video_local_path)
  257. self.google_ai_api.delete_video(file_name)
  258. task_list.remove(task)
  259. tqdm.write("video process failed, delete local file")
  260. time.sleep(const.SLEEP_SECONDS)
  261. tqdm.write("执行完一轮任务,剩余数量:{}".format(len(task_list)))
  262. time.sleep(const.SLEEP_SECONDS)