history_task.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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. class historyContentIdTask(object):
  12. """
  13. 处理已经匹配过小程序的文章
  14. """
  15. TASK_PROCESSING_STATUS = 101
  16. EXIT_STATUS = 97
  17. MISMATCH_STATUS = 96
  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. self.account_negative_category = json.loads(self.config.get_config_value("account_negative_category"))
  32. async def get_tasks(self):
  33. """
  34. 获取任务
  35. :return:
  36. """
  37. select_sql1 = f"""
  38. SELECT
  39. ART.trace_id,
  40. ART.content_id,
  41. ART.flow_pool_level,
  42. ART.gh_id,
  43. ART.process_times
  44. FROM {self.article_match_video_table} ART
  45. JOIN (
  46. select content_id, count(1) as cnt
  47. from {self.article_crawler_video_table}
  48. where download_status = 2
  49. group by content_id
  50. ) VID on ART.content_id = VID.content_id and VID.cnt >= 3
  51. WHERE ART.content_status = 0 and ART.process_times <= 3
  52. ORDER BY ART.flow_pool_level, ART.request_timestamp
  53. LIMIT {self.history_coroutines};
  54. """
  55. tasks = await self.mysql_client.async_select(sql=select_sql1)
  56. task_obj_list = [
  57. {
  58. "trace_id": item[0],
  59. "content_id": item[1],
  60. "flow_pool_level": item[2],
  61. "gh_id": item[3],
  62. "process_times": item[4]
  63. } for item in tasks
  64. ]
  65. logging(
  66. code="9001",
  67. info="本次任务获取到 {} 条视频".format(len(task_obj_list)),
  68. data=task_obj_list
  69. )
  70. return task_obj_list
  71. async def get_video_list(self, content_id):
  72. """
  73. content_id
  74. :return:
  75. """
  76. sql = f"""
  77. SELECT platform, play_count, like_count, video_oss_path, cover_oss_path, user_id
  78. FROM {self.article_crawler_video_table}
  79. WHERE content_id = '{content_id}' and download_status = 2
  80. ORDER BY score DESC;
  81. """
  82. res_tuple = await self.mysql_client.async_select(sql)
  83. if len(res_tuple) >= 3:
  84. return [
  85. {
  86. "platform": i[0],
  87. "play_count": i[1],
  88. "like_count": i[2],
  89. "video_oss_path": i[3],
  90. "cover_oss_path": i[4],
  91. "uid": i[5]
  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):
  134. """
  135. 发布至 pq
  136. :param process_times:
  137. :param trace_id:
  138. :param download_videos: 已下载的视频---> list [{}, {}, {}.... ]
  139. :param gh_id: 公众号 id ---> str
  140. :param kimi_title: kimi 标题 ---> str
  141. :param flow_pool_level: 流量池层级 ---> str
  142. :return:
  143. """
  144. match flow_pool_level:
  145. case "autoArticlePoolLevel4":
  146. # 冷启层, 全量做
  147. video_list = shuffle_list(download_videos)[:3]
  148. case "autoArticlePoolLevel3":
  149. # 次条,只针对具体账号做
  150. if self.gh_id_dict.get(gh_id):
  151. video_list = shuffle_list(download_videos)[:3]
  152. else:
  153. video_list = download_videos[:3]
  154. case "autoArticlePoolLevel2":
  155. video_list = []
  156. case "autoArticlePoolLevel1":
  157. # 头条,先不做
  158. video_list = download_videos[:3]
  159. case _:
  160. print("未传流量池信息")
  161. video_list = download_videos[:3]
  162. L = []
  163. for video_obj in video_list:
  164. params = {
  165. "videoPath": video_obj['video_oss_path'],
  166. "uid": video_obj['uid'],
  167. "title": kimi_title
  168. }
  169. publish_response = await publish_to_pq(params)
  170. video_id = publish_response['data']['id']
  171. response = await get_pq_video_detail(video_id)
  172. # time.sleep(2)
  173. obj = {
  174. "uid": video_obj['uid'],
  175. "source": video_obj['platform'],
  176. "kimiTitle": kimi_title,
  177. "videoId": response['data'][0]['id'],
  178. "videoCover": response['data'][0]['shareImgPath'],
  179. "videoPath": response['data'][0]['videoPath'],
  180. "videoOss": video_obj['video_oss_path']
  181. }
  182. L.append(obj)
  183. update_sql = f"""
  184. UPDATE {self.article_match_video_table}
  185. SET content_status = %s, response = %s, process_times = %s
  186. WHERE trace_id = %s and content_status = %s;
  187. """
  188. await self.mysql_client.async_insert(
  189. sql=update_sql,
  190. params=(
  191. self.TASK_PUBLISHED_STATUS,
  192. json.dumps(L, ensure_ascii=False),
  193. process_times + 1,
  194. trace_id,
  195. self.TASK_PROCESSING_STATUS
  196. )
  197. )
  198. logging(
  199. code="9002",
  200. info="已经从历史文章更新",
  201. trace_id=trace_id
  202. )
  203. async def roll_back_content_status_when_fails(self, process_times, trace_id):
  204. """
  205. 处理失败,回滚至初始状态,处理次数加 1
  206. :param process_times:
  207. :param trace_id:
  208. :return:
  209. """
  210. update_article_sql = f"""
  211. UPDATE {self.article_match_video_table}
  212. SET
  213. content_status = %s,
  214. content_status_update_time = %s,
  215. process_times = %s
  216. WHERE trace_id = %s and content_status = %s;
  217. """
  218. await self.mysql_client.async_insert(
  219. sql=update_article_sql,
  220. params=(
  221. self.TASK_INIT_STATUS,
  222. int(time.time()),
  223. process_times + 1,
  224. trace_id,
  225. self.TASK_PROCESSING_STATUS
  226. )
  227. )
  228. async def check_title_whether_exit(self, content_id):
  229. """
  230. 校验文章是标题是否晋升 or 退场
  231. :return:
  232. """
  233. UP_LEVEL_STATUS = 1
  234. TITLE_EXIT_STATUS = -1
  235. sql = f"""
  236. SELECT lat.article_title, cstp.status
  237. FROM long_articles_text lat
  238. JOIN cold_start_title_pool cstp ON lat.article_title = cstp.title
  239. WHERE lat.content_id = '{content_id}';
  240. """
  241. result = await self.mysql_client.async_select(sql)
  242. if result:
  243. status = result[0][1]
  244. if status in {UP_LEVEL_STATUS, TITLE_EXIT_STATUS}:
  245. return True
  246. else:
  247. return False
  248. else:
  249. return False
  250. async def check_title_category(self, content_id, gh_id) -> bool:
  251. """
  252. 判断该文章的品类是否属于该账号的品类
  253. :param content_id:
  254. :param gh_id:
  255. :return:
  256. """
  257. bad_category_set = set(self.account_negative_category.get(gh_id, []))
  258. if bad_category_set:
  259. sql = f"""
  260. SELECT category
  261. FROM article_category
  262. WHERE produce_content_id = '{content_id}';
  263. """
  264. result = await self.mysql_client.async_select(sql)
  265. if result:
  266. category = result[0][0]
  267. if category in bad_category_set:
  268. return True
  269. return False
  270. async def process_task(self, params):
  271. """
  272. 异步执行
  273. :param params:
  274. :return:
  275. """
  276. content_id = params['content_id']
  277. trace_id = params['trace_id']
  278. flow_pool_level = params['flow_pool_level']
  279. if flow_pool_level == "autoArticlePoolLevel4":
  280. # 校验文章是否不属于账号所属于的品类
  281. category_status = await self.check_title_whether_exit(content_id)
  282. if category_status:
  283. # 修改状态为品类不匹配状态
  284. affected_rows = await self.update_content_status(
  285. trace_id=trace_id,
  286. new_content_status=self.MISMATCH_STATUS,
  287. ori_content_status=self.TASK_INIT_STATUS
  288. )
  289. if affected_rows == 0:
  290. print("修改行数为 0,多个进程抢占同一个 task, 抢占失败,进程退出")
  291. return
  292. # 校验文章是否晋升 or 退场
  293. exit_status = await self.check_title_whether_exit(content_id)
  294. if exit_status:
  295. # 修改状态为退出状态
  296. affected_rows = await self.update_content_status(
  297. trace_id=trace_id,
  298. new_content_status=self.EXIT_STATUS,
  299. ori_content_status=self.TASK_INIT_STATUS
  300. )
  301. if affected_rows == 0:
  302. print("修改行数为 0,多个进程抢占同一个 task, 抢占失败,进程退出")
  303. return
  304. gh_id = params['gh_id']
  305. process_times = params['process_times']
  306. download_videos = await self.get_video_list(content_id=content_id)
  307. # time.sleep(3)
  308. if download_videos:
  309. # 修改状态为执行状态,获取该任务的锁
  310. affected_rows = await self.update_content_status(
  311. trace_id=trace_id,
  312. new_content_status=self.TASK_PROCESSING_STATUS,
  313. ori_content_status=self.TASK_INIT_STATUS
  314. )
  315. if affected_rows == 0:
  316. print("修改行数为 0,多个进程抢占同一个 task, 抢占失败,进程退出")
  317. return
  318. try:
  319. kimi_title = await self.get_kimi_title(content_id)
  320. await self.publish_videos_to_pq(
  321. flow_pool_level=flow_pool_level,
  322. kimi_title=kimi_title,
  323. gh_id=gh_id,
  324. trace_id=trace_id,
  325. download_videos=download_videos,
  326. process_times=process_times
  327. )
  328. except Exception as e:
  329. logging(
  330. code="5003",
  331. info="history task 在发布的时候出现异常, error = {}".format(e),
  332. trace_id=trace_id
  333. )
  334. await self.roll_back_content_status_when_fails(
  335. trace_id=trace_id,
  336. process_times=process_times
  337. )
  338. else:
  339. return
  340. async def deal(self):
  341. """
  342. 处理
  343. :return:
  344. """
  345. task_list = await self.get_tasks()
  346. logging(
  347. code="5002",
  348. info="History content_task Task Got {} this time".format(len(task_list)),
  349. function="History Contents Task"
  350. )
  351. if task_list:
  352. a = time.time()
  353. tasks = [self.process_task(params) for params in task_list]
  354. await asyncio.gather(*tasks)
  355. b = time.time()
  356. print("{} s 内处理了{}个任务".format(b - a, len(task_list)))
  357. else:
  358. print("暂时未获得历史已存在文章")