publishCategoryArticles.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. """
  2. @author: luojunhui
  3. 品类文章发布到aigc系统的冷启层
  4. """
  5. import datetime
  6. import json
  7. import time
  8. import traceback
  9. from pandas import DataFrame
  10. from applications import aiditApi, log, bot, llm_sensitivity
  11. from config import apolloConfig
  12. apollo = apolloConfig()
  13. DAILY_CRAWLER_MAX_NUM = 1000
  14. SIMILARITY_MIN_SCORE = 0.4
  15. TITLE_NOT_SENSITIVE = 0
  16. class CategoryColdStartTask(object):
  17. """
  18. 品类冷启动发布任务
  19. """
  20. PUBLISHED_STATUS = 2
  21. INIT_STATUS = 1
  22. BAD_STATUS = 0
  23. def __init__(self, db_client):
  24. """
  25. :param db_client:
  26. """
  27. self.db_client = db_client
  28. self.category_map = json.loads(apollo.getConfigValue("category_cold_start_map"))
  29. self.category_cold_start_threshold = json.loads(apollo.getConfigValue("category_cold_start_threshold"))
  30. self.article_category_list = json.loads(apollo.getConfigValue("category_list"))
  31. self.READ_THRESHOLD = self.category_cold_start_threshold.get("READ_THRESHOLD", 5000)
  32. self.READ_TIMES_THRESHOLD = self.category_cold_start_threshold.get("READ_TIMES_THRESHOLD", 1.3)
  33. self.LIMIT_TITLE_LENGTH = self.category_cold_start_threshold.get("LIMIT_TITLE_LENGTH", 15)
  34. self.TITLE_LENGTH_MAX = self.category_cold_start_threshold.get("TITLE_LENGTH_MAX", 50)
  35. log(
  36. task="category_publish_task",
  37. function="__init__",
  38. message="数据库初始化连接完成,apollo配置获取完成",
  39. data={
  40. "category": self.category_map,
  41. "threshold": self.category_cold_start_threshold
  42. }
  43. )
  44. def insert_into_db(self, crawler_plan_id, crawler_plan_name, create_timestamp):
  45. """
  46. 插入抓取计划到数据库中
  47. :param create_timestamp:
  48. :param crawler_plan_id:
  49. :param crawler_plan_name:
  50. :return:
  51. """
  52. insert_sql = f"""
  53. INSERT INTO article_crawler_plan
  54. (crawler_plan_id, name, create_timestamp)
  55. values
  56. (%s, %s, %s)
  57. """
  58. try:
  59. self.db_client.update(
  60. sql=insert_sql,
  61. params=(crawler_plan_id, crawler_plan_name, create_timestamp)
  62. )
  63. except Exception as e:
  64. bot(
  65. title="品类冷启任务,记录抓取计划id失败",
  66. detail={
  67. "error": str(e),
  68. "error_msg": traceback.format_exc(),
  69. "crawler_plan_id": crawler_plan_id,
  70. "crawler_plan_name": crawler_plan_name
  71. }
  72. )
  73. def get_articles_from_meta_table(self, category, article_source):
  74. """
  75. 从长文 meta 库中获取冷启文章
  76. :return:
  77. """
  78. sql = f"""
  79. SELECT
  80. article_id, out_account_id, article_index, title, link, read_cnt, status, llm_sensitivity, score, category_by_ai
  81. FROM
  82. crawler_meta_article
  83. WHERE
  84. category = "{category}" and platform = "{article_source}" and title_sensitivity = {TITLE_NOT_SENSITIVE}
  85. ORDER BY score DESC;
  86. """
  87. article_list = self.db_client.select(sql)
  88. log(
  89. task="category_publish_task",
  90. function="get_articles_from_meta_table",
  91. message="获取品类文章总数",
  92. data={
  93. "total_articles": len(article_list),
  94. "category": category
  95. }
  96. )
  97. article_df = DataFrame(article_list,
  98. columns=['article_id', 'gh_id', 'position', 'title', 'link', 'read_cnt', 'status',
  99. 'llm_sensitivity', 'score', 'category_by_ai'])
  100. return article_df
  101. def filter_each_category(self, category):
  102. """
  103. 过滤单个生成计划类别的文章
  104. """
  105. plan_id = self.category_map.get(category)
  106. if plan_id:
  107. article_list = aiditApi.get_generated_article_list(plan_id)
  108. title_list = [i[1] for i in article_list]
  109. if title_list:
  110. # update
  111. update_sql = f"""
  112. UPDATE
  113. crawler_meta_article
  114. SET
  115. status = %s
  116. WHERE
  117. title in %s and status = %s;
  118. """
  119. affected_rows = self.db_client.update(
  120. sql=update_sql,
  121. params=(self.PUBLISHED_STATUS, tuple(title_list), self.INIT_STATUS)
  122. )
  123. print(affected_rows)
  124. else:
  125. print("未获取到计划id")
  126. return
  127. def published_articles_title_filter(self):
  128. """
  129. 已经发布到生成计划中的 id,
  130. :return:
  131. """
  132. category_list = list(self.category_map.keys())
  133. for category in category_list:
  134. try:
  135. self.filter_each_category(category)
  136. except Exception as e:
  137. log(
  138. task="category_publish_task",
  139. function="published_articles_title_filter",
  140. message="过滤已发布文章失败",
  141. data={
  142. "error": str(e),
  143. "error_msg": traceback.format_exc(),
  144. "category": category
  145. }
  146. )
  147. def change_article_status_while_publishing(self, article_id_list):
  148. """
  149. :param: article_id_list: 文章的唯一 id
  150. :return:
  151. """
  152. update_sql = f"""
  153. UPDATE
  154. crawler_meta_article
  155. SET
  156. status = %s
  157. WHERE
  158. article_id in %s and status = %s;
  159. """
  160. affect_rows = self.db_client.update(
  161. sql=update_sql,
  162. params=(self.PUBLISHED_STATUS, tuple(article_id_list), self.INIT_STATUS)
  163. )
  164. if affect_rows != len(article_id_list):
  165. bot(
  166. title="品类冷启任务中,出现更新状文章状态失败异常",
  167. detail={
  168. "affected_rows": affect_rows,
  169. "task_rows": len(article_id_list)
  170. }
  171. )
  172. def filter_weixin_articles(self, articles_df, category):
  173. """
  174. 微信抓取文章过滤漏斗
  175. """
  176. articles_df['average_read'] = articles_df.groupby(['gh_id', 'position'])['read_cnt'].transform('mean')
  177. articles_df['read_times'] = articles_df['read_cnt'] / articles_df['average_read']
  178. total_length = articles_df.shape[0]
  179. # 第0层过滤已经发布的文章
  180. filter_df = articles_df[articles_df['status'] == self.INIT_STATUS]
  181. length_level0 = filter_df.shape[0]
  182. # 第一层漏斗通过阅读均值倍数过滤
  183. filter_df = filter_df[filter_df['read_times'] >= self.READ_TIMES_THRESHOLD]
  184. length_level1 = filter_df.shape[0]
  185. # 第二层漏斗通过阅读量过滤
  186. filter_df = filter_df[
  187. filter_df['read_cnt'] >= self.READ_THRESHOLD
  188. ]
  189. length_level2 = filter_df.shape[0]
  190. # 第三层漏斗通过标题长度过滤
  191. filter_df = filter_df[
  192. (filter_df['title'].str.len() >= self.LIMIT_TITLE_LENGTH)
  193. & (filter_df['title'].str.len() <= self.TITLE_LENGTH_MAX)
  194. ]
  195. length_level3 = filter_df.shape[0]
  196. # 第四层通过敏感词过滤
  197. filter_df = filter_df[
  198. (~filter_df['title'].str.contains('农历'))
  199. & (~filter_df['title'].str.contains('太极'))
  200. & (~filter_df['title'].str.contains('节'))
  201. & (~filter_df['title'].str.contains('早上好'))
  202. & (~filter_df['title'].str.contains('赖清德'))
  203. & (~filter_df['title'].str.contains('普京'))
  204. & (~filter_df['title'].str.contains('俄'))
  205. & (~filter_df['title'].str.contains('南海'))
  206. & (~filter_df['title'].str.contains('台海'))
  207. & (~filter_df['title'].str.contains('解放军'))
  208. & (~filter_df['title'].str.contains('蔡英文'))
  209. & (~filter_df['title'].str.contains('中国'))
  210. ]
  211. length_level4 = filter_df.shape[0]
  212. # 第五层通过LLM敏感度过滤
  213. filter_df = filter_df[
  214. ~(filter_df['llm_sensitivity'] > 0)
  215. ]
  216. length_level5 = filter_df.shape[0]
  217. # 第六层通过相关性分数过滤
  218. filter_df = filter_df[filter_df['score'] > SIMILARITY_MIN_SCORE]
  219. length_level6 = filter_df.shape[0]
  220. log(
  221. task="category_publish_task",
  222. function="publish_filter_articles",
  223. message="过滤后文章总数",
  224. data={
  225. "total_articles": length_level5,
  226. "category": category
  227. }
  228. )
  229. bot(
  230. title="冷启任务发布通知",
  231. detail={
  232. "总文章数量": total_length,
  233. "通过已经发布状态过滤": "过滤数量: {} 剩余数量: {}".format(
  234. total_length - length_level0, length_level0),
  235. "通过阅读均值倍数过滤": "过滤数量: {} 剩余数量: {}".format(
  236. length_level0 - length_level1, length_level1),
  237. "通过阅读量过滤": "过滤数量: {} 剩余数量: {}".format(
  238. length_level1 - length_level2, length_level2),
  239. "通过标题长度过滤": "过滤数量: {} 剩余数量: {}".format(
  240. length_level2 - length_level3, length_level3),
  241. "通过敏感词过滤": "过滤数量: {} 剩余数量: {}".format(
  242. length_level3 - length_level4, length_level4),
  243. "通过LLM敏感度过滤": "过滤数量: {} 剩余数量: {}".format(
  244. length_level4 - length_level5, length_level5
  245. ),
  246. "通过相关性分数过滤": "过滤数量: {} 剩余数量: {}".format(
  247. length_level5 - length_level6, length_level6
  248. ),
  249. "品类": category,
  250. "阅读均值倍数阈值": self.READ_TIMES_THRESHOLD,
  251. "阅读量阈值": self.READ_THRESHOLD,
  252. "标题长度阈值": self.LIMIT_TITLE_LENGTH
  253. },
  254. mention=False
  255. )
  256. return filter_df[:DAILY_CRAWLER_MAX_NUM]
  257. def filter_toutiao_articles(self, articles_df, category):
  258. """
  259. 头条文章过滤漏斗
  260. """
  261. total_length = articles_df.shape[0]
  262. # 第一层漏斗通过状态过滤
  263. zero_level_funnel_df = articles_df[articles_df['status'] == self.INIT_STATUS]
  264. zero_level_funnel_length = zero_level_funnel_df.shape[0]
  265. bot(
  266. title="账号冷启动---头条推荐流发布",
  267. detail={
  268. "category": category,
  269. "总文章数量": total_length,
  270. "通过已经发布状态过滤": "过滤数量: {} 剩余数量: {}".format(total_length - zero_level_funnel_length,
  271. zero_level_funnel_length),
  272. },
  273. mention=False
  274. )
  275. return zero_level_funnel_df
  276. def update_article_sensitive_status(self, article_id, status):
  277. """
  278. 更新文章敏感状态
  279. :return:
  280. """
  281. update_sql = f"""
  282. update crawler_meta_article
  283. set llm_sensitivity = %s
  284. where article_id = %s;
  285. """
  286. self.db_client.update(sql=update_sql, params=(status, article_id))
  287. def publish_filter_articles(self, category, articles_df, article_source):
  288. """
  289. 过滤文章
  290. :param category: 文章品类
  291. :param articles_df: 该品类下的文章data_frame
  292. :param article_source: 文章来源
  293. :return:
  294. """
  295. match article_source:
  296. case "weixin":
  297. filtered_articles_df = self.filter_weixin_articles(articles_df, category)
  298. input_source_channel = 5
  299. case "toutiao":
  300. filtered_articles_df = self.filter_toutiao_articles(articles_df, category)
  301. input_source_channel = 6
  302. case _:
  303. return
  304. success_titles = filtered_articles_df['title'].values.tolist()
  305. article_id_list = filtered_articles_df['article_id'].values.tolist()
  306. if success_titles:
  307. try:
  308. sensitive_results = llm_sensitivity.check_titles(success_titles)
  309. for article_id, sensitive_result in zip(article_id_list, sensitive_results):
  310. self.update_article_sensitive_status(
  311. article_id=article_id,
  312. status=sensitive_result['hit_rule']
  313. )
  314. if sensitive_result['hit_rule'] > TITLE_NOT_SENSITIVE:
  315. filtered_articles_df = filtered_articles_df[filtered_articles_df['article_id'] != article_id]
  316. except Exception as e:
  317. print("failed to update sensitive status: {}".format(e))
  318. # split into different category
  319. for ai_category in self.article_category_list:
  320. filter_category_df = filtered_articles_df[filtered_articles_df['ai_category'] == ai_category]
  321. url_list = filter_category_df['link'].values.tolist()
  322. if url_list:
  323. # create_crawler_plan
  324. crawler_plan_response = aiditApi.auto_create_crawler_task(
  325. plan_id=None,
  326. plan_name="自动绑定-{}-{}-{}--{}".format(category, ai_category,datetime.date.today().__str__(), len(url_list)),
  327. plan_tag="品类冷启动",
  328. article_source=article_source,
  329. url_list=url_list
  330. )
  331. log(
  332. task="category_publish_task",
  333. function="publish_filter_articles",
  334. message="成功创建抓取计划",
  335. data=crawler_plan_response
  336. )
  337. # save to db
  338. create_timestamp = int(time.time()) * 1000
  339. crawler_plan_id = crawler_plan_response['data']['id']
  340. crawler_plan_name = crawler_plan_response['data']['name']
  341. self.insert_into_db(crawler_plan_id, crawler_plan_name, create_timestamp)
  342. # auto bind to generate plan
  343. new_crawler_task_list = [
  344. {
  345. "contentType": 1,
  346. "inputSourceType": 2,
  347. "inputSourceSubType": None,
  348. "fieldName": None,
  349. "inputSourceValue": crawler_plan_id,
  350. "inputSourceLabel": crawler_plan_name,
  351. "inputSourceModal": 3,
  352. "inputSourceChannel": input_source_channel
  353. }
  354. ]
  355. generate_plan_response = aiditApi.bind_crawler_task_to_generate_task(
  356. crawler_task_list=new_crawler_task_list,
  357. generate_task_id=self.category_map[category]
  358. )
  359. log(
  360. task="category_publish_task",
  361. function="publish_filter_articles",
  362. message="成功绑定到生成计划",
  363. data=generate_plan_response
  364. )
  365. # change article status
  366. article_id_list = filter_category_df['article_id'].values.tolist()
  367. self.change_article_status_while_publishing(article_id_list=article_id_list)
  368. def do_job(self, article_source, category_list=None):
  369. """
  370. 执行任务
  371. :return:
  372. """
  373. if not category_list:
  374. category_list = self.category_map.keys()
  375. log(
  376. task="category_publish_task",
  377. function="do_job",
  378. message="开始自动创建品类文章抓取计划",
  379. data={
  380. "category_list": list(category_list)
  381. }
  382. )
  383. for category in category_list:
  384. try:
  385. # 已发布标题去重
  386. self.published_articles_title_filter()
  387. category_df = self.get_articles_from_meta_table(category=category, article_source=article_source)
  388. self.publish_filter_articles(
  389. category=category,
  390. articles_df=category_df,
  391. article_source=article_source
  392. )
  393. except Exception as e:
  394. bot(
  395. title="品类冷启任务报错",
  396. detail={
  397. "category": category,
  398. "error": str(e),
  399. "function": "do_job",
  400. "traceback": traceback.format_exc()
  401. }
  402. )