video_to_text.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. """
  2. @author: luojunhui
  3. """
  4. import os
  5. import time
  6. import datetime
  7. import traceback
  8. from pymysql.cursors import DictCursor
  9. from tqdm import tqdm
  10. from applications import log
  11. from applications.api import GoogleAIAPI
  12. from applications.const import VideoToTextConst
  13. from applications.db import DatabaseConnector
  14. from config import long_articles_config
  15. from config import apolloConfig
  16. from coldStartTasks.ai_pipeline.basic import download_file
  17. from coldStartTasks.ai_pipeline.basic import update_task_queue_status
  18. from coldStartTasks.ai_pipeline.basic import roll_back_lock_tasks
  19. # 办公室网络调试需要打开代理
  20. # os.environ["HTTP_PROXY"] = "http://192.168.100.20:1087"
  21. # os.environ["HTTPS_PROXY"] = "http://192.168.100.20:1087"
  22. const = VideoToTextConst()
  23. config = apolloConfig(env="prod")
  24. # pool_size
  25. POOL_SIZE = int(config.getConfigValue("video_extract_pool_size"))
  26. # batch_size
  27. BATCH_SIZE = int(config.getConfigValue("video_extract_batch_size"))
  28. class GenerateTextFromVideo(object):
  29. """
  30. 从视频中生成文本
  31. """
  32. def __init__(self):
  33. self.google_ai_api = GoogleAIAPI()
  34. self.db = DatabaseConnector(db_config=long_articles_config)
  35. self.db.connect()
  36. def get_upload_task_list(self, task_length: int) -> list[dict]:
  37. """
  38. 获取上传视频任务,优先处理高流量池视频内容
  39. """
  40. fetch_query = f"""
  41. select t1.id, t1.video_oss_path
  42. from video_content_understanding t1
  43. join publish_single_video_source t2 on t1.content_trace_id = t2.content_trace_id
  44. where t1.upload_status = {const.INIT_STATUS}
  45. and t2.video_pool_audit_status = {const.AUDIT_SUCCESS_STATUS}
  46. and t2.bad_status = {const.ARTICLE_GOOD_STATUS}
  47. order by t2.flow_pool_level
  48. limit {task_length};
  49. """
  50. task_list = self.db.fetch(query=fetch_query, cursor_type=DictCursor)
  51. return task_list
  52. def get_extract_task_list(self) -> list[dict]:
  53. """
  54. 获取处理视频转文本任务
  55. """
  56. fetch_query = f"""
  57. select id, file_name, video_ori_title
  58. from video_content_understanding
  59. where upload_status = {const.SUCCESS_STATUS} and understanding_status = {const.INIT_STATUS}
  60. order by file_expire_time
  61. limit {BATCH_SIZE};
  62. """
  63. task_list = self.db.fetch(query=fetch_query, cursor_type=DictCursor)
  64. return task_list
  65. def get_processing_task_num(self) -> int:
  66. """
  67. get the number of processing task
  68. """
  69. select_query = f"""
  70. select count(1) as processing_count
  71. from video_content_understanding
  72. where file_state = 'PROCESSING' and upload_status = {const.SUCCESS_STATUS};
  73. """
  74. fetch_response = self.db.fetch(query=select_query, cursor_type=DictCursor)
  75. processing_task_num = (
  76. fetch_response[0]["processing_count"] if fetch_response else 0
  77. )
  78. return processing_task_num
  79. def set_upload_result_for_task(
  80. self, task_id: str, file_name: str, file_state: str, expire_time: str
  81. ) -> int:
  82. """
  83. set upload result for task
  84. """
  85. update_query = f"""
  86. update video_content_understanding
  87. set upload_status = %s, upload_status_ts = %s,
  88. file_name = %s, file_state = %s, file_expire_time = %s
  89. where id = %s and upload_status = %s;
  90. """
  91. affected_rows = self.db.save(
  92. query=update_query,
  93. params=(
  94. const.SUCCESS_STATUS,
  95. datetime.datetime.now(),
  96. file_name,
  97. file_state,
  98. expire_time,
  99. task_id,
  100. const.PROCESSING_STATUS,
  101. ),
  102. )
  103. return affected_rows
  104. def set_understanding_result_for_task(
  105. self, task_id: str, state: str, text: str
  106. ) -> int:
  107. update_query = f"""
  108. update video_content_understanding
  109. set understanding_status = %s, video_text = %s, file_state = %s
  110. where id = %s and understanding_status = %s;
  111. """
  112. affected_rows = self.db.save(
  113. query=update_query,
  114. params=(
  115. const.SUCCESS_STATUS,
  116. text,
  117. state,
  118. task_id,
  119. const.PROCESSING_STATUS,
  120. ),
  121. )
  122. return affected_rows
  123. def upload_video_to_google_ai_task(
  124. self, max_processing_video_count: int = POOL_SIZE
  125. ):
  126. """
  127. upload video to google AI and wait for processing
  128. """
  129. # rollback lock tasks
  130. rollback_rows = roll_back_lock_tasks(
  131. db_client=self.db,
  132. process="upload",
  133. init_status=const.INIT_STATUS,
  134. processing_status=const.PROCESSING_STATUS,
  135. max_process_time=const.MAX_PROCESSING_TIME,
  136. )
  137. tqdm.write("upload rollback_lock_tasks: {}".format(rollback_rows))
  138. processing_task_num = self.get_processing_task_num()
  139. rest_video_count = max_processing_video_count - processing_task_num
  140. if rest_video_count:
  141. task_list = self.get_upload_task_list(rest_video_count)
  142. for task in tqdm(task_list, desc="upload_video_task"):
  143. lock_rows = update_task_queue_status(
  144. db_client=self.db,
  145. task_id=task["id"],
  146. process="upload",
  147. ori_status=const.INIT_STATUS,
  148. new_status=const.PROCESSING_STATUS,
  149. )
  150. if not lock_rows:
  151. continue
  152. try:
  153. file_path = download_file(task["id"], task["video_oss_path"])
  154. google_upload_result = self.google_ai_api.upload_file(file_path)
  155. if google_upload_result:
  156. file_name, file_state, expire_time = google_upload_result
  157. self.set_upload_result_for_task(
  158. task_id=task["id"],
  159. file_name=file_name,
  160. file_state=file_state,
  161. expire_time=expire_time,
  162. )
  163. else:
  164. # roll back status
  165. update_task_queue_status(
  166. db_client=self.db,
  167. task_id=task["id"],
  168. process="upload",
  169. ori_status=const.PROCESSING_STATUS,
  170. new_status=const.FAIL_STATUS,
  171. )
  172. log(
  173. task="video_to_text",
  174. function="upload_video_to_google_ai_task",
  175. message="upload_video_to_google_ai_task failed",
  176. data={
  177. "task_id": task["id"],
  178. },
  179. )
  180. except Exception as e:
  181. log(
  182. task="video_to_text",
  183. function="upload_video_to_google_ai_task",
  184. message="upload_video_to_google_ai_task failed",
  185. data={
  186. "error": str(e),
  187. "traceback": traceback.format_exc(),
  188. "task_id": task["id"],
  189. },
  190. )
  191. # roll back status
  192. update_task_queue_status(
  193. db_client=self.db,
  194. task_id=task["id"],
  195. process="upload",
  196. ori_status=const.PROCESSING_STATUS,
  197. new_status=const.FAIL_STATUS,
  198. )
  199. else:
  200. log(
  201. task="video_to_text",
  202. function="upload_video_to_google_ai_task",
  203. message="task pool is full",
  204. )
  205. def convert_video_to_text_with_google_ai_task(self):
  206. """
  207. 处理视频转文本任务
  208. """
  209. rollback_rows = roll_back_lock_tasks(
  210. db_client=self.db,
  211. process="understanding",
  212. init_status=const.INIT_STATUS,
  213. processing_status=const.PROCESSING_STATUS,
  214. max_process_time=const.MAX_PROCESSING_TIME,
  215. )
  216. tqdm.write("extract rollback_lock_tasks: {}".format(rollback_rows))
  217. task_list = self.get_extract_task_list()
  218. for task in tqdm(task_list, desc="convert video to text"):
  219. # LOCK TASK
  220. lock_row = update_task_queue_status(
  221. db_client=self.db,
  222. task_id=task["id"],
  223. process="understanding",
  224. ori_status=const.INIT_STATUS,
  225. new_status=const.PROCESSING_STATUS,
  226. )
  227. if not lock_row:
  228. print("Task has benn locked by other process")
  229. continue
  230. file_name = task["file_name"]
  231. video_local_path = "static/{}.mp4".format(task["id"])
  232. try:
  233. google_file = self.google_ai_api.get_google_file(file_name)
  234. state = google_file.state.name
  235. match state:
  236. case "ACTIVE":
  237. try:
  238. video_text = self.google_ai_api.get_video_text(
  239. prompt="分析我上传的视频的画面和音频,用叙述故事的风格将视频所描述的事件进行总结,需要保证视频内容的完整性,并且用中文进行输出,直接返回生成的文本",
  240. video_file=google_file,
  241. )
  242. if video_text:
  243. self.set_understanding_result_for_task(
  244. task_id=task["id"], state=state, text=video_text
  245. )
  246. # delete local file and google file
  247. if os.path.exists(video_local_path):
  248. os.remove(video_local_path)
  249. tqdm.write(
  250. "video transform to text success, delete local file"
  251. )
  252. task_list.remove(task)
  253. self.google_ai_api.delete_video(file_name)
  254. tqdm.write(
  255. "delete video from google success: {}".format(
  256. file_name
  257. )
  258. )
  259. else:
  260. # roll back status and wait for next process
  261. update_task_queue_status(
  262. db_client=self.db,
  263. task_id=task["id"],
  264. process="understanding",
  265. ori_status=const.PROCESSING_STATUS,
  266. new_status=const.INIT_STATUS,
  267. )
  268. except Exception as e:
  269. # roll back status
  270. update_task_queue_status(
  271. db_client=self.db,
  272. task_id=task["id"],
  273. process="understanding",
  274. ori_status=const.PROCESSING_STATUS,
  275. new_status=const.FAIL_STATUS,
  276. )
  277. tqdm.write(str(e))
  278. continue
  279. case "PROCESSING":
  280. update_task_queue_status(
  281. db_client=self.db,
  282. task_id=task["id"],
  283. process="understanding",
  284. ori_status=const.PROCESSING_STATUS,
  285. new_status=const.INIT_STATUS,
  286. )
  287. tqdm.write("video is still processing")
  288. case "FAILED":
  289. update_sql = f"""
  290. update video_content_understanding
  291. set file_state = %s, understanding_status = %s, understanding_status_ts = %s
  292. where id = %s and understanding_status = %s;
  293. """
  294. self.db.save(
  295. query=update_sql,
  296. params=(
  297. state,
  298. const.FAIL_STATUS,
  299. datetime.datetime.now(),
  300. task["id"],
  301. const.PROCESSING_STATUS,
  302. ),
  303. )
  304. # delete local file and google file
  305. if os.path.exists(video_local_path):
  306. os.remove(video_local_path)
  307. self.google_ai_api.delete_video(file_name)
  308. task_list.remove(task)
  309. tqdm.write("video process failed, delete local file")
  310. time.sleep(const.SLEEP_SECONDS)
  311. except Exception as e:
  312. log(
  313. task="video_to_text",
  314. function="extract_video_to_text_task",
  315. message="extract video to text task failed",
  316. data={
  317. "error": str(e),
  318. "traceback": traceback.format_exc(),
  319. "task_id": task["id"],
  320. },
  321. )
  322. update_task_queue_status(
  323. db_client=self.db,
  324. task_id=task["id"],
  325. process="understanding",
  326. ori_status=const.PROCESSING_STATUS,
  327. new_status=const.FAIL_STATUS,
  328. )