generate_text_from_video.py 11 KB

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