history_task.py 12 KB

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