generate_text_from_video.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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 input_task_list(self):
  52. """
  53. 输入任务列表, 从single_video_pool中获取
  54. """
  55. sql = f"""
  56. select article_title, concat('https://rescdn.yishihui.com/', video_oss_path ) as video_url, audit_video_id
  57. from publish_single_video_source
  58. where audit_status = {const.AUDIT_SUCCESS_STATUS} and bad_status = {const.ARTICLE_GOOD_STATUS} and extract_status = {const.EXTRACT_INIT_STATUS}
  59. order by id desc;
  60. """
  61. task_list = self.db.fetch(sql, cursor_type=DictCursor)
  62. insert_sql = f"""
  63. insert ignore into video_content_understanding
  64. (pq_vid, video_ori_title, video_oss_path)
  65. values (%s, %s, %s);
  66. """
  67. affected_rows = self.db.save_many(
  68. insert_sql,
  69. params_list=[(i['audit_video_id'], i['article_title'], i['video_url']) for i in task_list]
  70. )
  71. print(affected_rows)
  72. def roll_back_processing_videos(self):
  73. """
  74. 回滚长时间处于处理中的视频
  75. """
  76. sql = f"""
  77. select id, status_update_timestamp
  78. from video_content_understanding
  79. where status in ({const.VIDEO_UNDERSTAND_PROCESSING_STATUS}, {const.VIDEO_LOCK});
  80. """
  81. task_list = self.db.fetch(sql, cursor_type=DictCursor)
  82. now_timestamp = int(time.time())
  83. id_list = []
  84. for task in tqdm(task_list):
  85. if task['status_update_timestamp']:
  86. if now_timestamp - task['status_update_timestamp'] >= const.MAX_PROCESSING_TIME:
  87. id_list.append(task['id'])
  88. if id_list:
  89. update_sql = f"""
  90. update video_content_understanding
  91. set status = %s
  92. where id in %s;
  93. """
  94. self.db.save(
  95. query=update_sql,
  96. params=(
  97. const.VIDEO_UNDERSTAND_INIT_STATUS,
  98. tuple(id_list)
  99. )
  100. )
  101. def update_video_status(self, ori_status, new_status, pq_vid):
  102. """
  103. 更新视频状态
  104. """
  105. sql = f"""
  106. update video_content_understanding
  107. set status = %s, status_update_timestamp = %s
  108. WHERE pq_vid = %s and status = %s;
  109. """
  110. affected_rows = self.db.save(
  111. query=sql,
  112. params=(new_status, pq_vid, ori_status, int(time.time()))
  113. )
  114. return affected_rows
  115. def upload_video_to_google_ai(self, max_processing_video_count=POOL_SIZE):
  116. """
  117. 上传视频到Google AI
  118. max_processing_video_count: 处理中的最大视频数量,默认20
  119. video_content_understanding 表status字段
  120. 0: 未处理
  121. 1: 处理中
  122. 2: 处理完成
  123. """
  124. # 查询出在视频处于PROCESSING状态的视频数量
  125. select_sql = f"""
  126. select count(1) as processing_count
  127. from video_content_understanding
  128. where status = {const.VIDEO_UNDERSTAND_PROCESSING_STATUS};
  129. """
  130. count = self.db.fetch(select_sql, cursor_type=DictCursor)[0]['processing_count']
  131. rest_video_count = max_processing_video_count - count
  132. success_upload_count = 0
  133. if rest_video_count:
  134. sql = f"""
  135. select pq_vid, video_oss_path
  136. from video_content_understanding
  137. where status = {const.VIDEO_UNDERSTAND_INIT_STATUS}
  138. order by id desc
  139. limit {rest_video_count};
  140. """
  141. task_list = self.db.fetch(sql, cursor_type=DictCursor)
  142. for task in tqdm(task_list, desc="upload_video_task"):
  143. lock_rows = self.update_video_status(
  144. ori_status=const.VIDEO_UNDERSTAND_INIT_STATUS,
  145. new_status=const.VIDEO_LOCK,
  146. pq_vid=task['pq_vid'],
  147. )
  148. if not lock_rows:
  149. continue
  150. try:
  151. file_path = download_file(task['pq_vid'], task['video_oss_path'])
  152. google_upload_result = self.google_ai_api.upload_file(file_path)
  153. if google_upload_result:
  154. file_name, file_state, expire_time = google_upload_result
  155. update_sql = f"""
  156. update video_content_understanding
  157. set status = %s, file_name = %s, file_state = %s, file_expire_time = %s
  158. where pq_vid = %s and status = %s;
  159. """
  160. self.db.save(
  161. update_sql,
  162. params=(
  163. const.VIDEO_UNDERSTAND_PROCESSING_STATUS,
  164. file_name,
  165. file_state,
  166. expire_time,
  167. task['pq_vid'],
  168. const.VIDEO_LOCK
  169. )
  170. )
  171. success_upload_count += 1
  172. except Exception as e:
  173. print("task upload failed because of {}".format(e))
  174. print("trace_back: ", traceback.format_exc())
  175. # roll back status
  176. self.update_video_status(
  177. ori_status=const.VIDEO_LOCK,
  178. new_status=const.VIDEO_UNDERSTAND_INIT_STATUS,
  179. pq_vid=task['pq_vid'],
  180. )
  181. return success_upload_count
  182. def delete_video_from_google(self, file_name):
  183. """
  184. 删除视频文件
  185. """
  186. self.google_ai_api.delete_video(file_name)
  187. def get_tasks(self):
  188. """
  189. 获取处理视频转文本任务
  190. """
  191. sql = f"""
  192. select pq_vid, file_name
  193. from video_content_understanding
  194. where status = {const.VIDEO_UNDERSTAND_PROCESSING_STATUS}
  195. order by file_expire_time
  196. limit {BATCH_SIZE};
  197. """
  198. task_list = self.db.fetch(sql, cursor_type=DictCursor)
  199. return task_list
  200. def convert_video_to_text_with_google_ai(self):
  201. """
  202. 处理视频转文本任务
  203. """
  204. self.roll_back_processing_videos()
  205. task_list = self.get_tasks()
  206. while task_list:
  207. for task in tqdm(task_list, desc="convert video to text"):
  208. print(task['pq_vid'], task['file_name'])
  209. # LOCK TASK
  210. lock_row = self.update_video_status(
  211. ori_status=const.VIDEO_UNDERSTAND_PROCESSING_STATUS,
  212. new_status=const.VIDEO_LOCK,
  213. pq_vid=task['pq_vid'],
  214. )
  215. if not lock_row:
  216. print("Lock")
  217. continue
  218. file_name = task['file_name']
  219. video_local_path = "static/{}.mp4".format(task['pq_vid'])
  220. google_file = self.google_ai_api.get_google_file(file_name)
  221. state = google_file.state.name
  222. match state:
  223. case 'ACTIVE':
  224. try:
  225. video_text = self.google_ai_api.get_video_text(
  226. prompt="分析我上传的视频的画面和音频,用叙述故事的风格将视频所描述的事件进行总结,需要保证视频内容的完整性,并且用中文进行输出,直接返回生成的文本。",
  227. video_file=google_file
  228. )
  229. if video_text:
  230. update_sql = f"""
  231. update video_content_understanding
  232. set status = %s, video_text = %s, file_state = %s
  233. where pq_vid = %s and status = %s;
  234. """
  235. self.db.save(
  236. update_sql,
  237. params=(
  238. const.VIDEO_UNDERSTAND_SUCCESS_STATUS,
  239. video_text,
  240. state,
  241. task['pq_vid'],
  242. const.VIDEO_LOCK
  243. )
  244. )
  245. # delete local file and google file
  246. if os.path.exists(video_local_path):
  247. os.remove(video_local_path)
  248. tqdm.write("video transform to text success, delete local file")
  249. task_list.remove(task)
  250. self.google_ai_api.delete_video(file_name)
  251. tqdm.write("delete video from google success: {}".format(file_name))
  252. else:
  253. # roll back status
  254. self.update_video_status(
  255. ori_status=const.VIDEO_LOCK,
  256. new_status=const.VIDEO_UNDERSTAND_PROCESSING_STATUS,
  257. pq_vid=task['pq_vid'],
  258. )
  259. except Exception as e:
  260. # roll back status
  261. self.update_video_status(
  262. ori_status=const.VIDEO_LOCK,
  263. new_status=const.VIDEO_UNDERSTAND_PROCESSING_STATUS,
  264. pq_vid=task['pq_vid'],
  265. )
  266. tqdm.write(str(e))
  267. continue
  268. case 'PROCESSING':
  269. tqdm.write("video is still processing")
  270. # roll back status
  271. self.update_video_status(
  272. ori_status=const.VIDEO_LOCK,
  273. new_status=const.VIDEO_UNDERSTAND_PROCESSING_STATUS,
  274. pq_vid=task['pq_vid'],
  275. )
  276. case 'FAILED':
  277. self.update_video_status(
  278. ori_status=const.VIDEO_LOCK,
  279. new_status=const.VIDEO_UNDERSTAND_FAIL_STATUS,
  280. pq_vid=task['pq_vid']
  281. )
  282. if os.path.exists(video_local_path):
  283. os.remove(video_local_path)
  284. self.google_ai_api.delete_video(file_name)
  285. tqdm.write("video process failed, delete local file")
  286. time.sleep(const.SLEEP_SECONDS)
  287. tqdm.write("执行完一轮任务,剩余数量:{}".format(len(task_list)))
  288. time.sleep(const.SLEEP_SECONDS)