ai_tag_task.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. import os
  2. import json
  3. import datetime
  4. import time
  5. import traceback
  6. import requests
  7. from threading import Timer
  8. from utils import data_check, get_feature_data, asr_validity_discrimination
  9. from whisper_asr import get_whisper_asr
  10. from gpt_tag import request_gpt
  11. from config import set_config
  12. from log import Log
  13. config_ = set_config()
  14. log_ = Log()
  15. features = ['videoid', 'title', 'video_path']
  16. def get_video_ai_tags(video_id, video_file, video_info):
  17. try:
  18. log_message = {
  19. 'videoId': int(video_id),
  20. }
  21. title = video_info.get('title')
  22. log_message['videoPath'] = video_info.get('video_path')
  23. log_message['title'] = video_info.get('title')
  24. # 1. asr
  25. asr_res_initial = get_whisper_asr(video=video_file)
  26. log_message['asrRes'] = asr_res_initial
  27. # 2. 判断asr识别的文本是否有效
  28. validity = asr_validity_discrimination(text=asr_res_initial)
  29. log_message['asrValidity'] = validity
  30. if validity is True:
  31. # 3. 对asr结果进行清洗
  32. asr_res = asr_res_initial.replace('\n', '')
  33. for stop_word in config_.STOP_WORDS:
  34. asr_res = asr_res.replace(stop_word, '')
  35. # token限制: 字数 <= 2500
  36. asr_res = asr_res[-2500:]
  37. # 4. gpt产出结果
  38. # 4.1 gpt产出summary, keywords,
  39. prompt1 = f"{config_.GPT_PROMPT['tags']['prompt6']}{asr_res.strip()}"
  40. log_message['gptPromptSummaryKeywords'] = prompt1
  41. gpt_res1 = request_gpt(prompt=prompt1)
  42. log_message['gptResSummaryKeywords'] = gpt_res1
  43. if gpt_res1 is not None:
  44. # 4.2 获取summary, keywords, title进行分类
  45. try:
  46. gpt_res1_json = json.loads(gpt_res1)
  47. summary = gpt_res1_json['summary']
  48. keywords = gpt_res1_json['keywords']
  49. log_message['summary'] = summary
  50. log_message['keywords'] = keywords
  51. prompt2_param = f"标题:{title}\n概况:{summary}\n关键词:{keywords}"
  52. prompt2 = f"{config_.GPT_PROMPT['tags']['prompt7']}{prompt2_param}"
  53. log_message['gptPromptTag'] = prompt2
  54. gpt_res2 = request_gpt(prompt=prompt2)
  55. log_message['gptResTag'] = gpt_res2
  56. if gpt_res2 is not None:
  57. confidence_up_list = []
  58. try:
  59. for item in json.loads(gpt_res2):
  60. if item['confidence'] > 0.5 and item['category'] in config_.TAGS_NEW:
  61. confidence_up_list.append(f"AI标签-{item['category']}")
  62. except:
  63. pass
  64. confidence_up = ','.join(confidence_up_list)
  65. log_message['AITags'] = confidence_up
  66. # 5. 调用后端接口,结果传给后端
  67. if len(confidence_up) > 0:
  68. response = requests.post(url=config_.ADD_VIDEO_AI_TAGS_URL,
  69. json={'videoId': int(video_id), 'tagNames': confidence_up})
  70. res_data = json.loads(response.text)
  71. if res_data['code'] != 0:
  72. log_.error({'videoId': video_id, 'msg': 'add video ai tags fail!'})
  73. except:
  74. pass
  75. else:
  76. pass
  77. log_.info(log_message)
  78. except Exception as e:
  79. log_.error(e)
  80. log_.error(traceback.format_exc())
  81. def ai_tags(project, table, dt):
  82. # 获取特征数据
  83. feature_df = get_feature_data(project=project, table=table, dt=dt, features=features)
  84. video_id_list = feature_df['videoid'].to_list()
  85. video_info = {}
  86. for video_id in video_id_list:
  87. title = feature_df[feature_df['videoid'] == video_id]['title'].values[0]
  88. video_path = feature_df[feature_df['videoid'] == video_id]['video_path'].values[0]
  89. if title is None:
  90. continue
  91. title = title.strip()
  92. if len(title) > 0:
  93. video_info[video_id] = {'title': title, 'video_path': video_path}
  94. # print(video_id, title)
  95. print(len(video_info))
  96. # 获取已下载视频
  97. download_folder = 'videos'
  98. retry = 0
  99. while retry > 3:
  100. video_folder_list = os.listdir(download_folder)
  101. if len(video_folder_list) < 2:
  102. retry += 1
  103. time.sleep(60)
  104. continue
  105. for video_id in video_folder_list:
  106. if video_id not in video_id_list:
  107. continue
  108. if video_info.get(video_id, None) is None:
  109. os.rmdir(os.path.join(download_folder, video_id))
  110. else:
  111. video_folder = os.path.join(download_folder, video_id)
  112. for filename in os.listdir(video_folder):
  113. video_type = filename.split('.')[-1]
  114. if video_type in ['mp4', 'm3u8']:
  115. video_file = os.path.join(video_folder, filename)
  116. get_video_ai_tags(video_id=video_id, video_file=video_file, video_info=video_info.get(video_id))
  117. # 将处理过的视频进行删除
  118. os.rmdir(os.path.join(download_folder, video_id))
  119. def timer_check():
  120. try:
  121. project = config_.DAILY_VIDEO['project']
  122. table = config_.DAILY_VIDEO['table']
  123. now_date = datetime.datetime.today()
  124. print(f"now_date: {datetime.datetime.strftime(now_date, '%Y%m%d')}")
  125. dt = datetime.datetime.strftime(now_date-datetime.timedelta(days=1), '%Y%m%d')
  126. # 查看数据是否已准备好
  127. data_count = data_check(project=project, table=table, dt=dt)
  128. if data_count > 0:
  129. print(f'videos count = {data_count}')
  130. # 数据准备好,进行视频下载
  131. ai_tags(project=project, table=table, dt=dt)
  132. print(f"videos ai tag finished!")
  133. else:
  134. # 数据没准备好,1分钟后重新检查
  135. Timer(60, timer_check).start()
  136. except Exception as e:
  137. print(f"视频ai打标签失败, exception: {e}, traceback: {traceback.format_exc()}")
  138. if __name__ == '__main__':
  139. timer_check()