ai_tag_task.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. import os
  2. import shutil
  3. import json
  4. import datetime
  5. import time
  6. import traceback
  7. import requests
  8. import multiprocessing
  9. import ODPSQueryUtil
  10. from threading import Timer
  11. from utils import data_check, get_feature_data, asr_validity_discrimination
  12. from whisper_asr import get_whisper_asr
  13. from gpt_tag import request_gpt
  14. from config import set_config
  15. from log import Log
  16. config_ = set_config()
  17. log_ = Log()
  18. features = ['videoid', 'title', 'video_path']
  19. def get_video_ai_tags(video_id, asr_file, video_info):
  20. try:
  21. st_time = time.time()
  22. log_message = {
  23. 'videoId': int(video_id),
  24. }
  25. title = video_info.get('title')
  26. log_message['videoPath'] = video_info.get('video_path')
  27. log_message['title'] = video_info.get('title')
  28. # 1. 获取asr结果
  29. # asr_res_initial = get_whisper_asr(video=video_file)
  30. with open(asr_file, 'r', encoding='utf-8') as rf:
  31. asr_res_initial = rf.read()
  32. log_message['asrRes'] = asr_res_initial
  33. # 2. 判断asr识别的文本是否有效
  34. validity = asr_validity_discrimination(text=asr_res_initial)
  35. log_message['asrValidity'] = validity
  36. if validity is True:
  37. # 3. 对asr结果进行清洗
  38. asr_res = asr_res_initial.replace('\n', '')
  39. for stop_word in config_.STOP_WORDS:
  40. asr_res = asr_res.replace(stop_word, '')
  41. # token限制: 字数 <= 2500
  42. asr_res = asr_res[-2500:]
  43. # 4. gpt产出结果
  44. # 4.1 gpt产出summary, keywords,
  45. prompt1 = f"{config_.GPT_PROMPT['tags']['prompt6']}{asr_res.strip()}"
  46. log_message['gptPromptSummaryKeywords'] = prompt1
  47. gpt_res1 = request_gpt(prompt=prompt1)
  48. log_message['gptResSummaryKeywords'] = gpt_res1
  49. if gpt_res1 is not None:
  50. # 4.2 获取summary, keywords, title进行分类
  51. try:
  52. gpt_res1_json = json.loads(gpt_res1)
  53. summary = gpt_res1_json['summary']
  54. keywords = gpt_res1_json['keywords']
  55. log_message['summary'] = summary
  56. log_message['keywords'] = str(keywords)
  57. prompt2_param = f"标题:{title}\n概况:{summary}\n关键词:{keywords}"
  58. prompt2 = f"{config_.GPT_PROMPT['tags']['prompt7']}{prompt2_param}"
  59. log_message['gptPromptTag'] = prompt2
  60. gpt_res2 = request_gpt(prompt=prompt2)
  61. log_message['gptResTag'] = gpt_res2
  62. if gpt_res2 is not None:
  63. confidence_up_list = []
  64. try:
  65. for item in json.loads(gpt_res2):
  66. if item['confidence'] > 0.5 and item['category'] in config_.TAGS_NEW:
  67. confidence_up_list.append(
  68. f"AI标签-{item['category']}")
  69. except:
  70. pass
  71. confidence_up = ','.join(confidence_up_list)
  72. log_message['AITags'] = confidence_up
  73. # 5. 调用后端接口,结果传给后端
  74. if len(confidence_up) > 0:
  75. response = requests.post(url=config_.ADD_VIDEO_AI_TAGS_URL,
  76. json={'videoId': int(video_id), 'tagNames': confidence_up})
  77. res_data = json.loads(response.text)
  78. if res_data['code'] != 0:
  79. log_.error(
  80. {'videoId': video_id, 'msg': 'add video ai tags fail!'})
  81. except:
  82. pass
  83. else:
  84. pass
  85. log_message['executeTime'] = (time.time() - st_time) * 1000
  86. log_.info(log_message)
  87. except Exception as e:
  88. log_.error(e)
  89. log_.error(traceback.format_exc())
  90. def process(video_id, video_info, download_folder):
  91. if video_info.get(video_id, None) is None:
  92. shutil.rmtree(os.path.join(download_folder, video_id))
  93. else:
  94. video_folder = os.path.join(download_folder, video_id)
  95. for filename in os.listdir(video_folder):
  96. video_type = filename.split('.')[-1]
  97. if video_type in ['mp4', 'm3u8']:
  98. video_file = os.path.join(video_folder, filename)
  99. get_video_ai_tags(
  100. video_id=video_id, video_file=video_file, video_info=video_info.get(video_id))
  101. # 将处理过的视频进行删除
  102. shutil.rmtree(os.path.join(download_folder, video_id))
  103. else:
  104. shutil.rmtree(os.path.join(download_folder, video_id))
  105. def ai_tags(project, table, dt):
  106. # 获取特征数据
  107. feature_df = get_feature_data(
  108. project=project, table=table, dt=dt, features=features)
  109. video_id_list = feature_df['videoid'].to_list()
  110. video_info = {}
  111. for video_id in video_id_list:
  112. title = feature_df[feature_df['videoid']
  113. == video_id]['title'].values[0]
  114. video_path = feature_df[feature_df['videoid']
  115. == video_id]['video_path'].values[0]
  116. if title is None:
  117. continue
  118. title = title.strip()
  119. if len(title) > 0:
  120. video_info[video_id] = {'title': title, 'video_path': video_path}
  121. # print(video_id, title)
  122. print(len(video_info))
  123. # 获取已下载视频
  124. download_folder = 'videos'
  125. retry = 0
  126. while retry < 3:
  127. video_folder_list = os.listdir(download_folder)
  128. if len(video_folder_list) < 2:
  129. retry += 1
  130. time.sleep(60)
  131. continue
  132. # pool = multiprocessing.Pool(processes=5)
  133. # for video_id in video_folder_list:
  134. # if video_id not in video_id_list:
  135. # continue
  136. # pool.apply_async(
  137. # func=process,
  138. # args=(video_id, video_info, download_folder)
  139. # )
  140. # pool.close()
  141. # pool.join()
  142. for video_id in video_folder_list:
  143. if video_id not in video_id_list:
  144. continue
  145. if video_info.get(video_id, None) is None:
  146. shutil.rmtree(os.path.join(download_folder, video_id))
  147. else:
  148. video_folder = os.path.join(download_folder, video_id)
  149. for filename in os.listdir(video_folder):
  150. video_type = filename.split('.')[-1]
  151. if video_type in ['mp4', 'm3u8']:
  152. video_file = os.path.join(video_folder, filename)
  153. get_video_ai_tags(
  154. video_id=video_id, video_file=video_file, video_info=video_info.get(video_id))
  155. # 将处理过的视频进行删除
  156. shutil.rmtree(os.path.join(download_folder, video_id))
  157. else:
  158. shutil.rmtree(os.path.join(download_folder, video_id))
  159. def ai_tags_new(project, table, dt):
  160. # 获取特征数据
  161. feature_df = get_feature_data(
  162. project=project, table=table, dt=dt, features=features)
  163. video_id_list = feature_df['videoid'].to_list()
  164. video_info = {}
  165. for video_id in video_id_list:
  166. title = feature_df[feature_df['videoid']
  167. == video_id]['title'].values[0]
  168. video_path = feature_df[feature_df['videoid']
  169. == video_id]['video_path'].values[0]
  170. if title is None:
  171. continue
  172. title = title.strip()
  173. if len(title) > 0:
  174. video_info[video_id] = {'title': title, 'video_path': video_path}
  175. # print(video_id, title)
  176. print(len(video_info))
  177. # 获取已asr识别的视频
  178. asr_folder = 'asr_res'
  179. retry = 0
  180. while retry < 30:
  181. asr_file_list = os.listdir(asr_folder)
  182. if len(asr_file_list) < 1:
  183. retry += 1
  184. time.sleep(60)
  185. continue
  186. retry = 0
  187. for asr_filename in asr_file_list:
  188. video_id = asr_filename[:-4]
  189. if video_id not in video_id_list:
  190. continue
  191. asr_file = os.path.join(asr_folder, asr_filename)
  192. if video_info.get(video_id, None) is None:
  193. os.remove(asr_file)
  194. else:
  195. get_video_ai_tags(
  196. video_id=video_id, asr_file=asr_file, video_info=video_info.get(video_id))
  197. os.remove(asr_file)
  198. def timer_check():
  199. try:
  200. project = config_.DAILY_VIDEO['project']
  201. table = config_.DAILY_VIDEO['table']
  202. now_date = datetime.datetime.today()
  203. print(f"now_date: {datetime.datetime.strftime(now_date, '%Y%m%d')}")
  204. dt = datetime.datetime.strftime(
  205. now_date-datetime.timedelta(days=1), '%Y%m%d')
  206. # 查看数据是否已准备好
  207. data_count = data_check(project=project, table=table, dt=dt)
  208. if data_count > 0:
  209. print(f'videos count = {data_count}')
  210. asr_folder = 'asr_res'
  211. if not os.path.exists(asr_folder):
  212. # 1分钟后重新检查
  213. Timer(60, timer_check).start()
  214. else:
  215. # 数据准备好,进行aiTag
  216. ai_tags_new(project=project, table=table, dt=dt)
  217. print(f"videos ai tag finished!")
  218. else:
  219. # 数据没准备好,1分钟后重新检查
  220. Timer(60, timer_check).start()
  221. except Exception as e:
  222. print(
  223. f"视频ai打标签失败, exception: {e}, traceback: {traceback.format_exc()}")
  224. if __name__ == '__main__':
  225. # timer_check()
  226. size = 10000
  227. for i in range(0, 10000, size):
  228. print(f"query_videos start i = {i} ...")
  229. records = ODPSQueryUtil.query_videos(i, size)
  230. if records is None or len(records) == 0:
  231. continue
  232. print(f"Got {len(records)} records")
  233. video_info = {}
  234. # 遍历 records,将每个视频的信息添加到字典中
  235. for record in records:
  236. # 将 video_id 从字符串转换为整数,这里假设 video_id 格式总是 "vid" 后跟数字
  237. video_id = int(record['videoid'])
  238. title = record['title']
  239. video_path = record['video_path']
  240. # 使用 video_id 作为键,其他信息作为值
  241. video_info[video_id] = {'title': title, 'video_path': video_path}
  242. # 打印结果查看
  243. print(video_info)
  244. asr_folder = 'asr_res'
  245. retry = 0
  246. while retry < 30:
  247. asr_file_list = os.listdir(asr_folder)
  248. if len(asr_file_list) < 1:
  249. retry += 1
  250. time.sleep(60)
  251. continue
  252. retry = 0
  253. for asr_filename in asr_file_list:
  254. video_id = int(asr_filename[:-4])
  255. if video_id not in video_info:
  256. continue
  257. asr_file = os.path.join(asr_folder, asr_filename)
  258. if video_info.get(video_id, None) is None:
  259. os.remove(asr_file)
  260. else:
  261. get_video_ai_tags(
  262. video_id=video_id, asr_file=asr_file, video_info=video_info.get(video_id))
  263. os.remove(asr_file)