pipeline.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. import os
  2. import re
  3. import sys
  4. import time
  5. from datetime import datetime, timezone
  6. from core.models.rule_models import RuleModel
  7. from core.utils.feishu_data_async import FeishuDataAsync
  8. from core.utils.log.logger_manager import LoggerManager
  9. from services.async_mysql_service import AsyncMysqlService
  10. class PiaoQuanPipeline:
  11. """
  12. 完整异步爬虫管道 - 每个校验不通过都详细记录本地日志+阿里云日志
  13. """
  14. def __init__(self, platform, mode, rule_dict, env, item, trace_id, account=None):
  15. self.platform = platform
  16. self.mode = mode
  17. self.rule_dict = rule_dict
  18. self.env = env
  19. self.item = item
  20. self.trace_id = trace_id
  21. self.account = account
  22. # 使用Pydantic模型验证规则字典
  23. # try:
  24. # self.validated_rules = RuleModel(**rule_dict)
  25. # except Exception as e:
  26. # LoggerManager.get_logger(platform=platform, mode=mode).warning(f"规则验证失败: {e}")
  27. # self.validated_rules = None
  28. self.mysql = AsyncMysqlService(platform=platform, mode=mode)
  29. self.logger = LoggerManager.get_logger(platform=platform, mode=mode)
  30. self.aliyun_log = LoggerManager.get_aliyun_logger(platform=platform, mode=mode)
  31. self.feishu_spreadsheet_token = "KsoMsyP2ghleM9tzBfmcEEXBnXg"
  32. self.test_account = [58528285, 58527674, 58528085, 58527582, 58527601, 58527612, 58528281, 58528095, 58527323,
  33. 58528071, 58527278]
  34. async def feishu_time_list(self):
  35. async with FeishuDataAsync() as feishu_data:
  36. summary = await feishu_data.get_values(
  37. spreadsheet_token=self.feishu_spreadsheet_token,
  38. sheet_id="RuLK77"
  39. )
  40. for row in summary[1:]:
  41. if row[0] == self.platform:
  42. return row[1]
  43. return None
  44. async def feishu_list(self):
  45. async with FeishuDataAsync() as feishu_data:
  46. summary = await feishu_data.get_values(
  47. spreadsheet_token=self.feishu_spreadsheet_token,
  48. sheet_id="letS93"
  49. )
  50. for row in summary[1:]:
  51. if row[0] == self.platform:
  52. return row[1]
  53. return None
  54. async def publish_time_flag(self) -> bool:
  55. publish_ts = self.item.get("publish_time_stamp")
  56. update_ts = self.item.get("update_time_stamp")
  57. max_d = self.rule_dict.get("period", {}).get("max", 1000)
  58. min_d = self.rule_dict.get("period", {}).get("min", 1000)
  59. days = int(max(max_d, min_d))
  60. now_ts = int(time.time())
  61. if self.platform == "gongzhonghao":
  62. if (now_ts - publish_ts > 86400 * days) and (now_ts - update_ts > 86400 * days):
  63. msg = f"[发布时间过期] now={now_ts}, publish={publish_ts}, update={update_ts}, limit_days={days}"
  64. self.logger.warning(msg)
  65. self.aliyun_log.logging(
  66. code="2004",
  67. trace_id=self.trace_id,
  68. data={
  69. "item": self.item,
  70. "now_ts": now_ts,
  71. "publish_ts": publish_ts,
  72. "update_ts": update_ts,
  73. "days_limit": days
  74. },
  75. message=msg,
  76. account=self.account
  77. )
  78. return False
  79. else:
  80. if days == 0 or (self.platform == "xiaoniangao" and self.item["out_user_id"] in self.test_account) :
  81. # 使用UTC时间进行比较,避免时区问题
  82. is_today = datetime.fromtimestamp(publish_ts, tz=timezone.utc).date() == datetime.now(timezone.utc).date()
  83. if not is_today:
  84. msg = "[发布时间] 不在今日"
  85. self.logger.warning(msg)
  86. self.aliyun_log.logging(
  87. code="2004",
  88. trace_id=self.trace_id,
  89. data={
  90. "item": self.item,
  91. "publish_ts": publish_ts
  92. },
  93. message=msg,
  94. account=self.account
  95. )
  96. return False
  97. elif now_ts - publish_ts > 86400 * days:
  98. msg = f"[发布时间超限制] now={now_ts}, publish={publish_ts}, limit_days={days}"
  99. self.logger.warning(msg)
  100. self.aliyun_log.logging(
  101. code="2004",
  102. trace_id=self.trace_id,
  103. data={
  104. "item": self.item,
  105. "now_ts": now_ts,
  106. "publish_ts": publish_ts,
  107. "days_limit": days
  108. },
  109. message=msg,
  110. account=self.account
  111. )
  112. return False
  113. return True
  114. def title_flag(self) -> bool:
  115. """
  116. 标题敏感词过滤
  117. :return:
  118. """
  119. title = self.item.get("video_title", "")
  120. if not title:
  121. return True
  122. # 清理标题,移除空白字符
  123. cleaned_title = re.sub(r"\s+", " ", title).strip()
  124. # 异步获取敏感词列表
  125. sensitive_words = [] # 这里应该从飞书表格或其他配置源获取敏感词
  126. # 检查是否包含敏感词
  127. for word in sensitive_words:
  128. if word and word in cleaned_title:
  129. msg = f"[标题包含敏感词] {word} in {title}"
  130. self.logger.warning(msg)
  131. self.aliyun_log.logging(
  132. code="2003",
  133. trace_id=self.trace_id,
  134. data={
  135. "item": self.item,
  136. "title": title,
  137. "matched_word": word
  138. },
  139. message=msg,
  140. account=self.account
  141. )
  142. return False
  143. return True
  144. def download_rule_flag(self) -> bool:
  145. """
  146. 视频基础下载规则
  147. :return:
  148. "rule": "[{\"period\":{\"min\":15,\"max\":3}},{\"duration\":{\"min\":50,\"max\":0}},{\"share_cnt\":{\"min\":2,\"max\":0}},{\"videos_cnt\":{\"min\":300,\"max\":0}}]",
  149. """
  150. for key in self.item:
  151. if self.rule_dict.get(key):
  152. max_value = (
  153. int(self.rule_dict[key]["max"])
  154. if int(self.rule_dict[key]["max"]) > 0
  155. else 999999999999999
  156. )
  157. if key == "peroid": # peroid是抓取周期天数
  158. continue
  159. else:
  160. flag = int(self.rule_dict[key]["min"]) <= int(self.item[key]) <= max_value
  161. if not flag:
  162. self.logger.info(f"校验结束: 下载规则不符合{flag}")
  163. self.aliyun_log.logging(
  164. code="2005",
  165. trace_id=self.trace_id,
  166. data=self.item,
  167. message="{}: {} <= {} <= {}, {}".format(
  168. key,
  169. self.rule_dict[key]["min"],
  170. self.item[key],
  171. max_value,
  172. flag,
  173. ),
  174. account=self.account
  175. )
  176. return flag
  177. else:
  178. continue
  179. return True
  180. async def repeat_video(self) -> bool:
  181. out_id = self.item.get("out_video_id")
  182. title = self.item.get("video_title", "")
  183. bypass_platforms = {
  184. "zhufuniannianshunxinjixiang", "weiquanshipin", "piaoquangushi", "lepaoledong", "zhufukuaizhuan",
  185. "linglingkuailezhufu", "lepaoledongdijie", "jierizhufuhuakaifugui","yuannifuqimanman", "haoyunzhufuduo",
  186. "quzhuan", "zhufudewenhou", "jierizhufuxingfujixiang", "haoyoushipin", "xinshiquan",
  187. "laonianshenghuokuaile", "laonianquan"
  188. }
  189. if self.platform in bypass_platforms or (self.platform, self.mode) in [
  190. ("zhuwanwufusunew", "recommend"),
  191. ("jixiangxingfu", "recommend"),
  192. ("yuannifuqichangzai", "recommend"),
  193. ("benshanzhufu", "recommend"),
  194. ("zuihaodesongni", "recommend"),
  195. ("tiantianjufuqi", "recommend")
  196. ]:
  197. self.logger.info("[去重] 平台配置无需去重,直接通过")
  198. return True
  199. day_count = await self.feishu_list()
  200. if day_count:
  201. sql = """
  202. SELECT UNIX_TIMESTAMP(create_time) as ts FROM crawler_video
  203. WHERE platform = %s AND out_video_id = %s AND create_time >= DATE_SUB(NOW(), INTERVAL %s DAY)
  204. """
  205. rows = await self.mysql.fetch_all(sql, [self.platform, out_id, int(day_count)])
  206. if rows:
  207. msg = f"[去重失败] {out_id} 在 {day_count} 天内已存在"
  208. self.logger.warning(msg)
  209. self.aliyun_log.logging(
  210. code="2002",
  211. trace_id=self.trace_id,
  212. data={
  213. "item": self.item,
  214. "existing_timestamps": [r["ts"] for r in rows],
  215. "day_count": day_count
  216. },
  217. message=msg,
  218. account=self.account
  219. )
  220. return False
  221. if self.platform == "zhufuhaoyunbaofu" and self.mode == "recommend":
  222. sql = """
  223. SELECT 1 FROM crawler_video WHERE platform = %s AND out_video_id = %s AND video_title = %s
  224. """
  225. result = await self.mysql.fetch_one(sql, [self.platform, out_id, title])
  226. else:
  227. sql = """
  228. SELECT 1 FROM crawler_video WHERE platform = %s AND out_video_id = %s
  229. """
  230. result = await self.mysql.fetch_one(sql, [self.platform, out_id])
  231. if result:
  232. msg = f"[去重失败] {out_id} 已存在"
  233. self.logger.warning(msg)
  234. self.aliyun_log.logging(
  235. code="2002",
  236. trace_id=self.trace_id,
  237. data={
  238. "item": self.item,
  239. "out_video_id": out_id
  240. },
  241. message=msg,
  242. account=self.account
  243. )
  244. return False
  245. self.logger.info("[去重] 校验通过")
  246. return True
  247. async def process_item(self) -> bool:
  248. """
  249. 异步执行完整规则流程,并输出详细本地日志和云日志
  250. """
  251. self.logger.info(f"开始校验: {self.item.get('out_video_id', '')}")
  252. if not await self.publish_time_flag():
  253. self.logger.info("校验结束: 发布时间不符合")
  254. return False
  255. if not self.title_flag():
  256. self.logger.info("校验结束: 标题不符合")
  257. return False
  258. if not await self.repeat_video():
  259. self.logger.info("校验结束: 去重不符合")
  260. return False
  261. if not self.download_rule_flag():
  262. return False
  263. self.logger.info("校验结束: 全部通过")
  264. return True