history_task.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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_content_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(env="dev")
  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. fission_dict = await get_content_oss_fission_dict(
  82. db_client=self.mysql_client,
  83. config=self.config,
  84. content_id=content_id
  85. )
  86. if len(res_tuple) >= 3:
  87. return [
  88. {
  89. "platform": i[0],
  90. "play_count": i[1],
  91. "like_count": i[2],
  92. "video_oss_path": i[3],
  93. "cover_oss_path": i[4],
  94. "uid": i[5],
  95. "fission_0_rate": fission_dict.get(i[3], {}).get("fission_0_rate", 0),
  96. "fission_0_on_read": fission_dict.get(i[3], {}).get("fission_0_on_read", 0)
  97. }
  98. for i in res_tuple
  99. ]
  100. else:
  101. return []
  102. async def get_kimi_title(self, content_id):
  103. """
  104. 获取 kimiTitle
  105. :param content_id:
  106. :return:
  107. """
  108. select_sql = f"""
  109. select kimi_title from {self.article_text_table} where content_id = '{content_id}';
  110. """
  111. res_tuple = await self.mysql_client.async_select(select_sql)
  112. if res_tuple:
  113. return res_tuple[0][0]
  114. else:
  115. return False
  116. async def update_content_status(self, new_content_status, trace_id, ori_content_status):
  117. """
  118. :param new_content_status:
  119. :param trace_id:
  120. :param ori_content_status:
  121. :return:
  122. """
  123. update_sql = f"""
  124. UPDATE {self.article_match_video_table}
  125. SET content_status = %s, content_status_update_time = %s
  126. WHERE trace_id = %s and content_status = %s;
  127. """
  128. row_counts = await self.mysql_client.async_insert(
  129. sql=update_sql,
  130. params=(
  131. new_content_status,
  132. int(time.time()),
  133. trace_id,
  134. ori_content_status
  135. )
  136. )
  137. return row_counts
  138. async def publish_videos_to_pq(self, trace_id, flow_pool_level, kimi_title, gh_id, download_videos, process_times):
  139. """
  140. 发布至 pq
  141. :param process_times:
  142. :param trace_id:
  143. :param download_videos: 已下载的视频---> list [{}, {}, {}.... ]
  144. :param gh_id: 公众号 id ---> str
  145. :param kimi_title: kimi 标题 ---> str
  146. :param flow_pool_level: 流量池层级 ---> str
  147. :return:
  148. """
  149. match flow_pool_level:
  150. case "autoArticlePoolLevel4":
  151. # 冷启层, 全量做
  152. video_list = shuffle_list(download_videos)[:3]
  153. case "autoArticlePoolLevel3":
  154. # 次条,只针对具体账号做
  155. if self.gh_id_dict.get(gh_id):
  156. video_list = shuffle_list(download_videos)[:3]
  157. else:
  158. video_list = download_videos[:3]
  159. case "autoArticlePoolLevel2":
  160. video_list = []
  161. case "autoArticlePoolLevel1":
  162. # 头条内容,使用重排后结果
  163. sorted_videos = sorted(download_videos, key=lambda x: x['fission_0_rate'], reverse=True)
  164. video_list = sorted_videos[:3]
  165. case _:
  166. print("未传流量池信息")
  167. video_list = download_videos[:3]
  168. L = []
  169. for video_obj in video_list:
  170. params = {
  171. "videoPath": video_obj['video_oss_path'],
  172. "uid": video_obj['uid'],
  173. "title": kimi_title
  174. }
  175. publish_response = await publish_to_pq(params)
  176. video_id = publish_response['data']['id']
  177. response = await get_pq_video_detail(video_id)
  178. # time.sleep(2)
  179. obj = {
  180. "uid": video_obj['uid'],
  181. "source": video_obj['platform'],
  182. "kimiTitle": kimi_title,
  183. "videoId": response['data'][0]['id'],
  184. "videoCover": response['data'][0]['shareImgPath'],
  185. "videoPath": response['data'][0]['videoPath'],
  186. "videoOss": video_obj['video_oss_path']
  187. }
  188. L.append(obj)
  189. update_sql = f"""
  190. UPDATE {self.article_match_video_table}
  191. SET content_status = %s, response = %s, process_times = %s
  192. WHERE trace_id = %s and content_status = %s;
  193. """
  194. await self.mysql_client.async_insert(
  195. sql=update_sql,
  196. params=(
  197. self.TASK_PUBLISHED_STATUS,
  198. json.dumps(L, ensure_ascii=False),
  199. process_times + 1,
  200. trace_id,
  201. self.TASK_PROCESSING_STATUS
  202. )
  203. )
  204. logging(
  205. code="9002",
  206. info="已经从历史文章更新",
  207. trace_id=trace_id
  208. )
  209. async def roll_back_content_status_when_fails(self, process_times, trace_id):
  210. """
  211. 处理失败,回滚至初始状态,处理次数加 1
  212. :param process_times:
  213. :param trace_id:
  214. :return:
  215. """
  216. update_article_sql = f"""
  217. UPDATE {self.article_match_video_table}
  218. SET
  219. content_status = %s,
  220. content_status_update_time = %s,
  221. process_times = %s
  222. WHERE trace_id = %s and content_status = %s;
  223. """
  224. await self.mysql_client.async_insert(
  225. sql=update_article_sql,
  226. params=(
  227. self.TASK_INIT_STATUS,
  228. int(time.time()),
  229. process_times + 1,
  230. trace_id,
  231. self.TASK_PROCESSING_STATUS
  232. )
  233. )
  234. async def process_task(self, params):
  235. """
  236. 异步执行
  237. :param params:
  238. :return:
  239. """
  240. content_id = params['content_id']
  241. trace_id = params['trace_id']
  242. flow_pool_level = params['flow_pool_level']
  243. gh_id = params['gh_id']
  244. process_times = params['process_times']
  245. download_videos = await self.get_video_list(content_id=content_id)
  246. # time.sleep(3)
  247. if download_videos:
  248. # 修改状态为执行状态,获取该任务的锁
  249. affected_rows = await self.update_content_status(
  250. trace_id=trace_id,
  251. new_content_status=self.TASK_PROCESSING_STATUS,
  252. ori_content_status=self.TASK_INIT_STATUS
  253. )
  254. if affected_rows == 0:
  255. print("修改行数为 0,多个进程抢占同一个 task, 抢占失败,进程退出")
  256. return
  257. try:
  258. kimi_title = await self.get_kimi_title(content_id)
  259. await self.publish_videos_to_pq(
  260. flow_pool_level=flow_pool_level,
  261. kimi_title=kimi_title,
  262. gh_id=gh_id,
  263. trace_id=trace_id,
  264. download_videos=download_videos,
  265. process_times=process_times
  266. )
  267. except Exception as e:
  268. logging(
  269. code="5003",
  270. info="history task 在发布的时候出现异常, error = {}".format(e),
  271. trace_id=trace_id
  272. )
  273. await self.roll_back_content_status_when_fails(
  274. trace_id=trace_id,
  275. process_times=process_times
  276. )
  277. else:
  278. return
  279. async def deal(self):
  280. """
  281. 处理
  282. :return:
  283. """
  284. task_list = await self.get_tasks()
  285. logging(
  286. code="5002",
  287. info="History content_task Task Got {} this time".format(len(task_list)),
  288. function="History Contents Task"
  289. )
  290. if task_list:
  291. a = time.time()
  292. tasks = [self.process_task(params) for params in task_list]
  293. await asyncio.gather(*tasks)
  294. b = time.time()
  295. print("{} s 内处理了{}个任务".format(b - a, len(task_list)))
  296. else:
  297. print("暂时未获得历史已存在文章")