history_task.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. if fission_dict:
  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. # 使用fission_list中的oss路径替换, 若替换失败则使用原来的视频
  170. try:
  171. video['video_oss_path'] = sorted_fission_list[index][0]
  172. video["fission_0_on_read"] = sorted_fission_list[index][1]
  173. except IndexError:
  174. continue
  175. download_videos_with_fission_info.append(video)
  176. video_list = download_videos_with_fission_info
  177. else:
  178. # 未找到裂变信息,采用原来的顺序
  179. video_list = download_videos[:3]
  180. case _:
  181. print("未传流量池信息")
  182. video_list = download_videos[:3]
  183. L = []
  184. for video_obj in video_list:
  185. params = {
  186. "videoPath": video_obj['video_oss_path'],
  187. "uid": video_obj['uid'],
  188. "title": kimi_title
  189. }
  190. publish_response = await publish_to_pq(params)
  191. video_id = publish_response['data']['id']
  192. response = await get_pq_video_detail(video_id)
  193. # time.sleep(2)
  194. obj = {
  195. "uid": video_obj['uid'],
  196. "source": video_obj['platform'],
  197. "kimiTitle": kimi_title,
  198. "videoId": response['data'][0]['id'],
  199. "videoCover": response['data'][0]['shareImgPath'],
  200. "videoPath": response['data'][0]['videoPath'],
  201. "videoOss": video_obj['video_oss_path']
  202. }
  203. L.append(obj)
  204. update_sql = f"""
  205. UPDATE {self.article_match_video_table}
  206. SET content_status = %s, response = %s, process_times = %s
  207. WHERE trace_id = %s and content_status = %s;
  208. """
  209. await self.mysql_client.async_insert(
  210. sql=update_sql,
  211. params=(
  212. self.TASK_PUBLISHED_STATUS,
  213. json.dumps(L, ensure_ascii=False),
  214. process_times + 1,
  215. trace_id,
  216. self.TASK_PROCESSING_STATUS
  217. )
  218. )
  219. logging(
  220. code="9002",
  221. info="已经从历史文章更新",
  222. trace_id=trace_id
  223. )
  224. async def roll_back_content_status_when_fails(self, process_times, trace_id):
  225. """
  226. 处理失败,回滚至初始状态,处理次数加 1
  227. :param process_times:
  228. :param trace_id:
  229. :return:
  230. """
  231. update_article_sql = f"""
  232. UPDATE {self.article_match_video_table}
  233. SET
  234. content_status = %s,
  235. content_status_update_time = %s,
  236. process_times = %s
  237. WHERE trace_id = %s and content_status = %s;
  238. """
  239. await self.mysql_client.async_insert(
  240. sql=update_article_sql,
  241. params=(
  242. self.TASK_INIT_STATUS,
  243. int(time.time()),
  244. process_times + 1,
  245. trace_id,
  246. self.TASK_PROCESSING_STATUS
  247. )
  248. )
  249. async def process_task(self, params):
  250. """
  251. 异步执行
  252. :param params:
  253. :return:
  254. """
  255. content_id = params['content_id']
  256. trace_id = params['trace_id']
  257. flow_pool_level = params['flow_pool_level']
  258. gh_id = params['gh_id']
  259. process_times = params['process_times']
  260. download_videos = await self.get_video_list(content_id=content_id)
  261. # time.sleep(3)
  262. if download_videos:
  263. # 修改状态为执行状态,获取该任务的锁
  264. affected_rows = await self.update_content_status(
  265. trace_id=trace_id,
  266. new_content_status=self.TASK_PROCESSING_STATUS,
  267. ori_content_status=self.TASK_INIT_STATUS
  268. )
  269. if affected_rows == 0:
  270. print("修改行数为 0,多个进程抢占同一个 task, 抢占失败,进程退出")
  271. return
  272. try:
  273. kimi_title = await self.get_kimi_title(content_id)
  274. await self.publish_videos_to_pq(
  275. flow_pool_level=flow_pool_level,
  276. kimi_title=kimi_title,
  277. gh_id=gh_id,
  278. trace_id=trace_id,
  279. download_videos=download_videos,
  280. process_times=process_times,
  281. content_id=content_id
  282. )
  283. except Exception as e:
  284. logging(
  285. code="5003",
  286. info="history task 在发布的时候出现异常, error = {}".format(e),
  287. trace_id=trace_id
  288. )
  289. await self.roll_back_content_status_when_fails(
  290. trace_id=trace_id,
  291. process_times=process_times
  292. )
  293. else:
  294. return
  295. async def deal(self):
  296. """
  297. 处理
  298. :return:
  299. """
  300. task_list = await self.get_tasks()
  301. logging(
  302. code="5002",
  303. info="History content_task Task Got {} this time".format(len(task_list)),
  304. function="History Contents Task"
  305. )
  306. if task_list:
  307. a = time.time()
  308. tasks = [self.process_task(params) for params in task_list]
  309. await asyncio.gather(*tasks)
  310. b = time.time()
  311. print("{} s 内处理了{}个任务".format(b - a, len(task_list)))
  312. else:
  313. print("暂时未获得历史已存在文章")