generate_text_from_video.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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 update_video_status(self, ori_status, new_status, pq_vid):
  73. """
  74. 更新视频状态
  75. """
  76. sql = f"""
  77. update video_content_understanding
  78. set status = %s, status_update_timestamp = %s
  79. WHERE pq_vid = %s and status = %s;
  80. """
  81. affected_rows = self.db.save(
  82. query=sql,
  83. params=(new_status, pq_vid, ori_status, int(time.time()))
  84. )
  85. return affected_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. # 查询出在视频处于PROCESSING状态的视频数量
  96. select_sql = f"""
  97. select count(1) as processing_count
  98. from video_content_understanding
  99. where status = {const.VIDEO_UNDERSTAND_PROCESSING_STATUS};
  100. """
  101. count = self.db.fetch(select_sql, cursor_type=DictCursor)[0]['processing_count']
  102. rest_video_count = max_processing_video_count - count
  103. success_upload_count = 0
  104. if rest_video_count:
  105. sql = f"""
  106. select pq_vid, video_oss_path
  107. from video_content_understanding
  108. where status = {const.VIDEO_UNDERSTAND_INIT_STATUS}
  109. limit {rest_video_count};
  110. """
  111. task_list = self.db.fetch(sql, cursor_type=DictCursor)
  112. for task in tqdm(task_list, desc="upload_video_task"):
  113. lock_rows = self.update_video_status(
  114. ori_status=const.VIDEO_UNDERSTAND_INIT_STATUS,
  115. new_status=const.VIDEO_LOCK,
  116. pq_vid=task['pq_vid'],
  117. )
  118. if not lock_rows:
  119. continue
  120. try:
  121. file_path = download_file(task['pq_vid'], 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 status = %s, file_name = %s, file_state = %s, file_expire_time = %s
  128. where pq_vid = %s and status = %s;
  129. """
  130. self.db.save(
  131. update_sql,
  132. params=(
  133. const.VIDEO_UNDERSTAND_PROCESSING_STATUS,
  134. file_name,
  135. file_state,
  136. expire_time,
  137. task['pq_vid'],
  138. const.VIDEO_LOCK
  139. )
  140. )
  141. success_upload_count += 1
  142. except Exception as e:
  143. print("task upload failed because of {}".format(e))
  144. print("trace_back: ", traceback.format_exc())
  145. # roll back status
  146. self.update_video_status(
  147. ori_status=const.VIDEO_LOCK,
  148. new_status=const.VIDEO_UNDERSTAND_INIT_STATUS,
  149. pq_vid=task['pq_vid'],
  150. )
  151. return success_upload_count
  152. def delete_video_from_google(self, file_name):
  153. """
  154. 删除视频文件
  155. """
  156. self.google_ai_api.delete_video(file_name)
  157. def get_tasks(self):
  158. """
  159. 获取处理视频转文本任务
  160. """
  161. sql = f"""
  162. select pq_vid, file_name
  163. from video_content_understanding
  164. where status = {const.VIDEO_UNDERSTAND_PROCESSING_STATUS}
  165. order by file_expire_time
  166. limit {BATCH_SIZE};
  167. """
  168. task_list = self.db.fetch(sql, cursor_type=DictCursor)
  169. return task_list
  170. def convert_video_to_text_with_google_ai(self):
  171. """
  172. 处理视频转文本任务
  173. """
  174. task_list = self.get_tasks()
  175. while task_list:
  176. for task in tqdm(task_list, desc="convert video to text"):
  177. print(task['pq_vid'], task['file_name'])
  178. # LOCK TASK
  179. lock_row = self.update_video_status(
  180. ori_status=const.VIDEO_UNDERSTAND_PROCESSING_STATUS,
  181. new_status=const.VIDEO_LOCK,
  182. pq_vid=task['pq_vid'],
  183. )
  184. if not lock_row:
  185. continue
  186. file_name = task['file_name']
  187. video_local_path = "static/{}.mp4".format(task['pq_vid'])
  188. google_file = self.google_ai_api.get_google_file(file_name)
  189. state = google_file.state.name
  190. match state:
  191. case 'ACTIVE':
  192. try:
  193. video_text = self.google_ai_api.get_video_text(
  194. prompt="分析我上传的视频的画面和音频,用叙述故事的风格将视频所描述的事件进行总结,需要保证视频内容的完整性,并且用中文进行输出,直接返回生成的文本。",
  195. video_file=google_file
  196. )
  197. if video_text:
  198. update_sql = f"""
  199. update video_content_understanding
  200. set status = %s, video_text = %s, file_state = %s
  201. where pq_vid = %s and status = %s;
  202. """
  203. self.db.save(
  204. update_sql,
  205. params=(
  206. const.VIDEO_UNDERSTAND_SUCCESS_STATUS,
  207. video_text,
  208. state,
  209. task['pq_vid'],
  210. const.VIDEO_LOCK
  211. )
  212. )
  213. # delete local file and google file
  214. if os.path.exists(video_local_path):
  215. os.remove(video_local_path)
  216. tqdm.write("video transform to text success, delete local file")
  217. task_list.remove(task)
  218. self.google_ai_api.delete_video(file_name)
  219. tqdm.write("delete video from google success: {}".format(file_name))
  220. else:
  221. # roll back status
  222. self.update_video_status(
  223. ori_status=const.VIDEO_LOCK,
  224. new_status=const.VIDEO_UNDERSTAND_PROCESSING_STATUS,
  225. pq_vid=task['pq_vid'],
  226. )
  227. except Exception as e:
  228. # roll back status
  229. self.update_video_status(
  230. ori_status=const.VIDEO_LOCK,
  231. new_status=const.VIDEO_UNDERSTAND_PROCESSING_STATUS,
  232. pq_vid=task['pq_vid'],
  233. )
  234. tqdm.write(str(e))
  235. continue
  236. case 'PROCESSING':
  237. tqdm.write("video is still processing")
  238. # roll back status
  239. self.update_video_status(
  240. ori_status=const.VIDEO_LOCK,
  241. new_status=const.VIDEO_UNDERSTAND_PROCESSING_STATUS,
  242. pq_vid=task['pq_vid'],
  243. )
  244. case 'FAILED':
  245. self.update_video_status(
  246. ori_status=const.VIDEO_LOCK,
  247. new_status=const.VIDEO_UNDERSTAND_FAIL_STATUS,
  248. pq_vid=task['pq_vid']
  249. )
  250. if os.path.exists(video_local_path):
  251. os.remove(video_local_path)
  252. self.google_ai_api.delete_video(file_name)
  253. tqdm.write("video process failed, delete local file")
  254. time.sleep(const.SLEEP_SECONDS)
  255. tqdm.write("执行完一轮任务,剩余数量:{}".format(len(task_list)))
  256. time.sleep(const.SLEEP_SECONDS)