candidate_account_process.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. import json
  2. import traceback
  3. from typing import List, Dict
  4. from tqdm import tqdm
  5. from applications.api import fetch_deepseek_completion
  6. from applications.utils import ci_lower
  7. class CandidateAccountProcessConst:
  8. INIT_STATUS = 0
  9. PROCESSING_STATUS = 1
  10. SUCCESS_STATUS = 2
  11. FAILED_STATUS = 99
  12. LACK_ARTICLE_STATUS = 11
  13. TITLE_TOO_LONG_STATUS = 14
  14. AVG_SCORE_THRESHOLD = 65
  15. ARTICLE_COUNT_THRESHOLD = 13
  16. AVG_TITLE_LENGTH_THRESHOLD = 45
  17. ACCOUNT_GOOD_STATUS = 1
  18. @staticmethod
  19. def generate_title_match_score_prompt(title_list):
  20. title_list_string = "\n".join(title_list)
  21. prompt = f"""
  22. ** 任务指令 **
  23. 你是一名资深中文新闻编辑,需根据以下标准对一批标题进行主题匹配度评分(0-100分)
  24. ** 评估维度及权重 **
  25. 1. 受众精准度(50%)
  26. 正向匹配:存款/养老/健康/饮食/疾病警示/家庭伦理/近现代战争历史/老知青/奇闻异事
  27. 负向排除:影视解说/文学解读/个人收藏(钱币/邮票)/机械科普/数码测评/电子游戏/时尚潮流/明星八卦/极限运动/学术研究/网络热梗/宠物饲养/音乐/棋牌
  28. 2. 标题技法(40%)
  29. 悬念设计:疑问句/省略号/反转结构(例:"打开后瞬间愣住...")
  30. 情感强度:使用"痛心!""寒心!"等情绪词
  31. 数据冲击:具体数字增强可信度(例:"存款180万消失")
  32. 口语化表达:使用"涨知识了""别不当回事"等日常用语
  33. 3. 内容调性(10%)
  34. 煽情猎奇:家庭悲剧/离奇事件(例:"棺材板挖出金条")
  35. 警示价值:健康建议/法律案例(例:"三种食物禁止二次加热")
  36. 历史揭秘:人物秘闻/老照片故事
  37. 爱国情怀:军事突破/资源发现(例:"南极发现巨型粮仓")
  38. ** 评分规则 **
  39. 90-100分:同时满足3个维度且要素齐全,无负向内容
  40. 70-89分:满足2个核心维度,无负向内容
  41. 50-69分:仅满足受众群体正向匹配,无负向内容
  42. 30-49分:存在轻微关联但要素缺失
  43. 0-29分:完全无关或包含任意负向品类内容
  44. ** 待评估标题 **
  45. {title_list_string}
  46. ** 输出要求 **
  47. 输出结果为JSON,仅输出这一批标题的评分,用数组 List 返回 [score1, score2, score3,...] 不要包含任何解释或说明。
  48. """
  49. return prompt
  50. class CandidateAccountQualityScoreRecognizer(CandidateAccountProcessConst):
  51. def __init__(self, pool, log_client, trace_id):
  52. self.pool = pool
  53. self.log_client = log_client
  54. self.trace_id = trace_id
  55. async def get_task_list(self) -> List[Dict]:
  56. """
  57. get account tasks from the database
  58. """
  59. fetch_query = f"""
  60. select id, title_list, platform, account_id, account_name
  61. from crawler_candidate_account_pool
  62. where avg_score is null and status = {self.INIT_STATUS} and title_list is not null;
  63. """
  64. fetch_response = await self.pool.async_fetch(
  65. fetch_query,
  66. )
  67. return fetch_response
  68. async def update_account_status(
  69. self, account_id: int, ori_status: int, new_status: int
  70. ) -> int:
  71. """update account status"""
  72. update_query = f"""
  73. update crawler_candidate_account_pool
  74. set status = %s
  75. where id = %s and status = %s;
  76. """
  77. return await self.pool.async_save(
  78. update_query, (new_status, account_id, ori_status)
  79. )
  80. async def insert_account_into_crawler_queue(self, score_list: List[int], account: dict) -> None:
  81. """
  82. 计算账号的得分置信区间下限,若置信区间下限的分数大于阈值,则认为是好的账号
  83. """
  84. if ci_lower(score_list) > self.AVG_SCORE_THRESHOLD:
  85. query = f"""
  86. insert into article_meta_accounts (platform, account_id, account_name, account_source, status)
  87. values (%s, %s, %s, %s, %s);
  88. """
  89. await self.pool.async_save(
  90. query=query,
  91. params=(account["platform"], account["account_id"], account["account_name"], 'ai_recognize', self.ACCOUNT_GOOD_STATUS)
  92. )
  93. async def score_for_each_account_by_llm(self, account):
  94. account_id = account["id"]
  95. # lock
  96. if not await self.update_account_status(
  97. account_id, self.INIT_STATUS, self.PROCESSING_STATUS
  98. ):
  99. return
  100. # start processing
  101. title_list = json.loads(account["title_list"])
  102. if (
  103. len(title_list) < self.ARTICLE_COUNT_THRESHOLD
  104. and account["platform"] == "toutiao"
  105. ):
  106. await self.update_account_status(
  107. account_id, self.PROCESSING_STATUS, self.LACK_ARTICLE_STATUS
  108. )
  109. return
  110. # 平均标题过长
  111. avg_title_length = sum([len(title) for title in title_list]) / len(title_list)
  112. if avg_title_length > self.AVG_TITLE_LENGTH_THRESHOLD:
  113. await self.update_account_status(
  114. account_id, self.PROCESSING_STATUS, self.TITLE_TOO_LONG_STATUS
  115. )
  116. return
  117. prompt = self.generate_title_match_score_prompt(title_list)
  118. try:
  119. completion = fetch_deepseek_completion(
  120. model="DeepSeek-V3", prompt=prompt, output_type="json"
  121. )
  122. avg_score = sum(completion) / len(completion)
  123. query = f"""
  124. update crawler_candidate_account_pool
  125. set score_list = %s, avg_score = %s, status = %s
  126. where id = %s and status = %s;
  127. """
  128. await self.pool.async_save(
  129. query=query,
  130. params=(
  131. json.dumps(completion),
  132. avg_score,
  133. self.PROCESSING_STATUS,
  134. account_id,
  135. self.SUCCESS_STATUS,
  136. ),
  137. )
  138. # 判断置信区间下限, 并且插入账号
  139. await self.insert_account_into_crawler_queue(score_list=completion, account=account)
  140. except Exception as e:
  141. await self.log_client.log(
  142. contents={
  143. "task": "candidate_account_analysis",
  144. "trace_id": self.trace_id,
  145. "function": "score_for_each_account_by_llm",
  146. "message": "大模型识别账号失败",
  147. "status": "fail",
  148. "data": {
  149. "error": str(e),
  150. "title_list": json.dumps(title_list),
  151. },
  152. }
  153. )
  154. await self.update_account_status(
  155. account_id, self.PROCESSING_STATUS, self.FAILED_STATUS
  156. )
  157. async def deal(self):
  158. task_list = await self.get_task_list()
  159. for task in tqdm(task_list, desc="use llm to analysis each account"):
  160. try:
  161. await self.score_for_each_account_by_llm(task)
  162. except Exception as e:
  163. await self.log_client.log(
  164. contents={
  165. "task": "candidate_account_analysis",
  166. "trace_id": self.trace_id,
  167. "function": "deal",
  168. "status": "fail",
  169. "data": {
  170. "error": str(e),
  171. "traceback": traceback.format_exc(),
  172. "task": task,
  173. },
  174. }
  175. )