history_task.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. """
  2. @author: luojunhui
  3. """
  4. import json
  5. import time
  6. import asyncio
  7. from applications.config import Config
  8. from applications.log import logging
  9. from applications.functions.pqFunctions import publish_to_pq, get_pq_video_detail
  10. from applications.functions.common import shuffle_list
  11. from applications.match_algorithm.rank import get_title_oss_fission_dict
  12. class historyContentIdTask(object):
  13. """
  14. 处理已经匹配过小程序的文章
  15. """
  16. TASK_PROCESSING_STATUS = 101
  17. TASK_INIT_STATUS = 0
  18. TASK_PUBLISHED_STATUS = 4
  19. def __init__(self, mysql_client):
  20. """
  21. :param mysql_client:
  22. """
  23. self.mysql_client = mysql_client
  24. self.config = Config()
  25. self.article_match_video_table = self.config.article_match_video_table
  26. self.article_text_table = self.config.article_text_table
  27. self.article_crawler_video_table = self.config.article_crawler_video_table
  28. self.gh_id_dict = json.loads(self.config.get_config_value("testAccountLevel2"))
  29. self.history_coroutines = self.config.get_config_value("historyArticleCoroutines")
  30. async def get_tasks(self):
  31. """
  32. 获取任务
  33. :return:
  34. """
  35. select_sql1 = f"""
  36. SELECT
  37. ART.trace_id,
  38. ART.content_id,
  39. ART.flow_pool_level,
  40. ART.gh_id,
  41. ART.process_times
  42. FROM {self.article_match_video_table} ART
  43. JOIN (
  44. select content_id, count(1) as cnt
  45. from {self.article_crawler_video_table}
  46. where download_status = 2
  47. group by content_id
  48. ) VID on ART.content_id = VID.content_id and VID.cnt >= 3
  49. WHERE ART.content_status = 0 and ART.process_times <= 3
  50. ORDER BY request_timestamp
  51. LIMIT {self.history_coroutines};
  52. """
  53. tasks = await self.mysql_client.async_select(sql=select_sql1)
  54. task_obj_list = [
  55. {
  56. "trace_id": item[0],
  57. "content_id": item[1],
  58. "flow_pool_level": item[2],
  59. "gh_id": item[3],
  60. "process_times": item[4]
  61. } for item in tasks
  62. ]
  63. logging(
  64. code="9001",
  65. info="本次任务获取到 {} 条视频".format(len(task_obj_list)),
  66. data=task_obj_list
  67. )
  68. return task_obj_list
  69. async def get_video_list(self, content_id) -> list[dict]:
  70. """
  71. content_id
  72. :return:
  73. """
  74. sql = f"""
  75. SELECT platform, play_count, like_count, video_oss_path, cover_oss_path, user_id
  76. FROM {self.article_crawler_video_table}
  77. WHERE content_id = '{content_id}' and download_status = 2
  78. ORDER BY score DESC;
  79. """
  80. res_tuple = await self.mysql_client.async_select(sql)
  81. if len(res_tuple) >= 3:
  82. return [
  83. {
  84. "platform": i[0],
  85. "play_count": i[1],
  86. "like_count": i[2],
  87. "video_oss_path": i[3],
  88. "cover_oss_path": i[4],
  89. "uid": i[5]
  90. # "fission_0_rate": fission_dict.get(i[3], {}).get("fission_0_rate", 0),
  91. # "fission_0_on_read": fission_dict.get(i[3], {}).get("fission_0_on_read", 0)
  92. }
  93. for i in res_tuple
  94. ]
  95. else:
  96. return []
  97. async def get_kimi_title(self, content_id):
  98. """
  99. 获取 kimiTitle
  100. :param content_id:
  101. :return:
  102. """
  103. select_sql = f"""
  104. select kimi_title from {self.article_text_table} where content_id = '{content_id}';
  105. """
  106. res_tuple = await self.mysql_client.async_select(select_sql)
  107. if res_tuple:
  108. return res_tuple[0][0]
  109. else:
  110. return False
  111. async def update_content_status(self, new_content_status, trace_id, ori_content_status):
  112. """
  113. :param new_content_status:
  114. :param trace_id:
  115. :param ori_content_status:
  116. :return:
  117. """
  118. update_sql = f"""
  119. UPDATE {self.article_match_video_table}
  120. SET content_status = %s, content_status_update_time = %s
  121. WHERE trace_id = %s and content_status = %s;
  122. """
  123. row_counts = await self.mysql_client.async_insert(
  124. sql=update_sql,
  125. params=(
  126. new_content_status,
  127. int(time.time()),
  128. trace_id,
  129. ori_content_status
  130. )
  131. )
  132. return row_counts
  133. async def publish_videos_to_pq(self, trace_id, flow_pool_level, kimi_title, gh_id, download_videos, process_times, content_id):
  134. """
  135. 发布至 pq
  136. :param content_id:
  137. :param process_times:
  138. :param trace_id:
  139. :param download_videos: 已下载的视频---> list [{}, {}, {}.... ]
  140. :param gh_id: 公众号 id ---> str
  141. :param kimi_title: kimi 标题 ---> str
  142. :param flow_pool_level: 流量池层级 ---> str
  143. :return:
  144. """
  145. match flow_pool_level:
  146. case "autoArticlePoolLevel4":
  147. # 冷启层, 全量做
  148. video_list = shuffle_list(download_videos)[:3]
  149. case "autoArticlePoolLevel3":
  150. # 次条,只针对具体账号做
  151. if self.gh_id_dict.get(gh_id):
  152. video_list = shuffle_list(download_videos)[:3]
  153. else:
  154. video_list = download_videos[:3]
  155. case "autoArticlePoolLevel2":
  156. video_list = []
  157. case "autoArticlePoolLevel1":
  158. # 头条内容,使用重排后结果
  159. fission_dict = await get_title_oss_fission_dict(
  160. db_client=self.mysql_client,
  161. config=self.config,
  162. content_id=content_id
  163. )
  164. fission_list = [[i] + [fission_dict[i]['fission_0_on_read']] for i in fission_dict.keys()]
  165. sorted_fission_list = sorted(fission_list, key=lambda x: x[1], reverse=True)
  166. download_videos_with_fission_info = []
  167. for index, video in enumerate(download_videos[:3]):
  168. video['video_oss_path'] = sorted_fission_list[index][0]
  169. video["fission_0_on_read"] = sorted_fission_list[index][1]
  170. download_videos_with_fission_info.append(video)
  171. # for video in download_videos:
  172. # video["fission_0_rate"] = fission_dict.get(video['video_oss_path'], {}).get("fission_0_rate", 0)
  173. # video["fission_0_on_read"] = fission_dict.get(video['video_oss_path'], {}).get("fission_0_on_read", 0)
  174. # download_videos_with_fission_info.append(video)
  175. # sorted_videos = sorted(download_videos_with_fission_info, key=lambda x: x['fission_0_rate'], reverse=True)
  176. # sorted_videos = sorted(download_videos_with_fission_info, key=lambda x: x['fission_0_on_read'], reverse=True)
  177. video_list = download_videos_with_fission_info
  178. case _:
  179. print("未传流量池信息")
  180. video_list = download_videos[:3]
  181. L = []
  182. for video_obj in video_list:
  183. params = {
  184. "videoPath": video_obj['video_oss_path'],
  185. "uid": video_obj['uid'],
  186. "title": kimi_title
  187. }
  188. publish_response = await publish_to_pq(params)
  189. video_id = publish_response['data']['id']
  190. response = await get_pq_video_detail(video_id)
  191. # time.sleep(2)
  192. obj = {
  193. "uid": video_obj['uid'],
  194. "source": video_obj['platform'],
  195. "kimiTitle": kimi_title,
  196. "videoId": response['data'][0]['id'],
  197. "videoCover": response['data'][0]['shareImgPath'],
  198. "videoPath": response['data'][0]['videoPath'],
  199. "videoOss": video_obj['video_oss_path']
  200. }
  201. L.append(obj)
  202. update_sql = f"""
  203. UPDATE {self.article_match_video_table}
  204. SET content_status = %s, response = %s, process_times = %s
  205. WHERE trace_id = %s and content_status = %s;
  206. """
  207. await self.mysql_client.async_insert(
  208. sql=update_sql,
  209. params=(
  210. self.TASK_PUBLISHED_STATUS,
  211. json.dumps(L, ensure_ascii=False),
  212. process_times + 1,
  213. trace_id,
  214. self.TASK_PROCESSING_STATUS
  215. )
  216. )
  217. logging(
  218. code="9002",
  219. info="已经从历史文章更新",
  220. trace_id=trace_id
  221. )
  222. async def roll_back_content_status_when_fails(self, process_times, trace_id):
  223. """
  224. 处理失败,回滚至初始状态,处理次数加 1
  225. :param process_times:
  226. :param trace_id:
  227. :return:
  228. """
  229. update_article_sql = f"""
  230. UPDATE {self.article_match_video_table}
  231. SET
  232. content_status = %s,
  233. content_status_update_time = %s,
  234. process_times = %s
  235. WHERE trace_id = %s and content_status = %s;
  236. """
  237. await self.mysql_client.async_insert(
  238. sql=update_article_sql,
  239. params=(
  240. self.TASK_INIT_STATUS,
  241. int(time.time()),
  242. process_times + 1,
  243. trace_id,
  244. self.TASK_PROCESSING_STATUS
  245. )
  246. )
  247. async def process_task(self, params):
  248. """
  249. 异步执行
  250. :param params:
  251. :return:
  252. """
  253. content_id = params['content_id']
  254. trace_id = params['trace_id']
  255. flow_pool_level = params['flow_pool_level']
  256. gh_id = params['gh_id']
  257. process_times = params['process_times']
  258. download_videos = await self.get_video_list(content_id=content_id)
  259. # time.sleep(3)
  260. if download_videos:
  261. # 修改状态为执行状态,获取该任务的锁
  262. affected_rows = await self.update_content_status(
  263. trace_id=trace_id,
  264. new_content_status=self.TASK_PROCESSING_STATUS,
  265. ori_content_status=self.TASK_INIT_STATUS
  266. )
  267. if affected_rows == 0:
  268. print("修改行数为 0,多个进程抢占同一个 task, 抢占失败,进程退出")
  269. return
  270. try:
  271. kimi_title = await self.get_kimi_title(content_id)
  272. await self.publish_videos_to_pq(
  273. flow_pool_level=flow_pool_level,
  274. kimi_title=kimi_title,
  275. gh_id=gh_id,
  276. trace_id=trace_id,
  277. download_videos=download_videos,
  278. process_times=process_times,
  279. content_id=content_id
  280. )
  281. except Exception as e:
  282. logging(
  283. code="5003",
  284. info="history task 在发布的时候出现异常, error = {}".format(e),
  285. trace_id=trace_id
  286. )
  287. await self.roll_back_content_status_when_fails(
  288. trace_id=trace_id,
  289. process_times=process_times
  290. )
  291. else:
  292. return
  293. async def deal(self):
  294. """
  295. 处理
  296. :return:
  297. """
  298. task_list = await self.get_tasks()
  299. logging(
  300. code="5002",
  301. info="History content_task Task Got {} this time".format(len(task_list)),
  302. function="History Contents Task"
  303. )
  304. if task_list:
  305. a = time.time()
  306. tasks = [self.process_task(params) for params in task_list]
  307. await asyncio.gather(*tasks)
  308. b = time.time()
  309. print("{} s 内处理了{}个任务".format(b - a, len(task_list)))
  310. else:
  311. print("暂时未获得历史已存在文章")