candidate_account_process.py 8.7 KB

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