__main__.py 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785
  1. # coding=utf-8
  2. """
  3. TrendRadar 主程序
  4. 热点新闻聚合与分析工具
  5. 支持: python -m trendradar
  6. """
  7. import argparse
  8. import os
  9. import re
  10. import webbrowser
  11. from pathlib import Path
  12. from typing import Dict, List, Tuple, Optional
  13. import requests
  14. from trendradar.context import AppContext
  15. from trendradar import __version__
  16. from trendradar.core import load_config
  17. from trendradar.core.analyzer import convert_keyword_stats_to_platform_stats
  18. from trendradar.crawler import DataFetcher
  19. from trendradar.storage import convert_crawl_results_to_news_data
  20. from trendradar.utils.time import DEFAULT_TIMEZONE, is_within_days, calculate_days_old
  21. from trendradar.ai import AIAnalyzer, AIAnalysisResult
  22. from trendradar.core.scheduler import ResolvedSchedule
  23. def _parse_version(version_str: str) -> Tuple[int, int, int]:
  24. """解析版本号字符串为元组"""
  25. try:
  26. parts = version_str.strip().split(".")
  27. if len(parts) >= 3:
  28. return int(parts[0]), int(parts[1]), int(parts[2])
  29. return 0, 0, 0
  30. except:
  31. return 0, 0, 0
  32. def _compare_version(local: str, remote: str) -> str:
  33. """比较版本号,返回状态文字"""
  34. local_tuple = _parse_version(local)
  35. remote_tuple = _parse_version(remote)
  36. if local_tuple < remote_tuple:
  37. return "⚠️ 需要更新"
  38. elif local_tuple > remote_tuple:
  39. return "🔮 超前版本"
  40. else:
  41. return "✅ 已是最新"
  42. def _fetch_remote_version(version_url: str, proxy_url: Optional[str] = None) -> Optional[str]:
  43. """获取远程版本号"""
  44. try:
  45. proxies = None
  46. if proxy_url:
  47. proxies = {"http": proxy_url, "https": proxy_url}
  48. headers = {
  49. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
  50. "Accept": "text/plain, */*",
  51. "Cache-Control": "no-cache",
  52. }
  53. response = requests.get(version_url, proxies=proxies, headers=headers, timeout=10)
  54. response.raise_for_status()
  55. return response.text.strip()
  56. except Exception as e:
  57. print(f"[版本检查] 获取远程版本失败: {e}")
  58. return None
  59. def _parse_config_versions(content: str) -> Dict[str, str]:
  60. """解析配置文件版本内容为字典"""
  61. versions = {}
  62. try:
  63. if not content:
  64. return versions
  65. for line in content.splitlines():
  66. line = line.strip()
  67. if not line or "=" not in line:
  68. continue
  69. name, version = line.split("=", 1)
  70. versions[name.strip()] = version.strip()
  71. except Exception as e:
  72. print(f"[版本检查] 解析配置版本失败: {e}")
  73. return versions
  74. def check_all_versions(
  75. version_url: str,
  76. configs_version_url: Optional[str] = None,
  77. proxy_url: Optional[str] = None
  78. ) -> Tuple[bool, Optional[str]]:
  79. """
  80. 统一版本检查:程序版本 + 配置文件版本
  81. Args:
  82. version_url: 远程程序版本检查 URL
  83. configs_version_url: 远程配置文件版本检查 URL (返回格式: filename=version)
  84. proxy_url: 代理 URL
  85. Returns:
  86. (need_update, remote_version): 程序是否需要更新及远程版本号
  87. """
  88. # 获取远程版本
  89. remote_version = _fetch_remote_version(version_url, proxy_url)
  90. # 获取远程配置版本(如果有提供 URL)
  91. remote_config_versions = {}
  92. if configs_version_url:
  93. content = _fetch_remote_version(configs_version_url, proxy_url)
  94. if content:
  95. remote_config_versions = _parse_config_versions(content)
  96. print("=" * 60)
  97. print("版本检查")
  98. print("=" * 60)
  99. if remote_version:
  100. print(f"远程程序版本: {remote_version}")
  101. else:
  102. print("远程程序版本: 获取失败")
  103. if configs_version_url:
  104. if remote_config_versions:
  105. print(f"远程配置清单: 获取成功 ({len(remote_config_versions)} 个文件)")
  106. else:
  107. print("远程配置清单: 获取失败或为空")
  108. print("-" * 60)
  109. program_status = _compare_version(__version__, remote_version) if remote_version else "(无法比较)"
  110. print(f" 主程序版本: {__version__} {program_status}")
  111. config_files = [
  112. Path("config/config.yaml"),
  113. Path("config/frequency_words.txt"),
  114. Path("config/ai_analysis_prompt.txt"),
  115. Path("config/ai_translation_prompt.txt"),
  116. ]
  117. version_pattern = re.compile(r"Version:\s*(\d+\.\d+\.\d+)", re.IGNORECASE)
  118. for config_file in config_files:
  119. if not config_file.exists():
  120. print(f" {config_file.name}: 文件不存在")
  121. continue
  122. try:
  123. with open(config_file, "r", encoding="utf-8") as f:
  124. local_version = None
  125. for i, line in enumerate(f):
  126. if i >= 20:
  127. break
  128. match = version_pattern.search(line)
  129. if match:
  130. local_version = match.group(1)
  131. break
  132. # 获取该文件的远程版本
  133. target_remote_version = remote_config_versions.get(config_file.name)
  134. if local_version:
  135. if target_remote_version:
  136. status = _compare_version(local_version, target_remote_version)
  137. print(f" {config_file.name}: {local_version} {status}")
  138. else:
  139. print(f" {config_file.name}: {local_version} (未找到远程版本)")
  140. else:
  141. print(f" {config_file.name}: 未找到本地版本号")
  142. except Exception as e:
  143. print(f" {config_file.name}: 读取失败 - {e}")
  144. print("=" * 60)
  145. # 返回程序版本的更新状态
  146. if remote_version:
  147. need_update = _parse_version(__version__) < _parse_version(remote_version)
  148. return need_update, remote_version if need_update else None
  149. return False, None
  150. # === 主分析器 ===
  151. class NewsAnalyzer:
  152. """新闻分析器"""
  153. # 模式策略定义
  154. MODE_STRATEGIES = {
  155. "incremental": {
  156. "mode_name": "增量模式",
  157. "description": "增量模式(只关注新增新闻,无新增时不推送)",
  158. "report_type": "增量分析",
  159. "should_send_notification": True,
  160. },
  161. "current": {
  162. "mode_name": "当前榜单模式",
  163. "description": "当前榜单模式(当前榜单匹配新闻 + 新增新闻区域 + 按时推送)",
  164. "report_type": "当前榜单",
  165. "should_send_notification": True,
  166. },
  167. "daily": {
  168. "mode_name": "全天汇总模式",
  169. "description": "全天汇总模式(所有匹配新闻 + 新增新闻区域 + 按时推送)",
  170. "report_type": "全天汇总",
  171. "should_send_notification": True,
  172. },
  173. }
  174. def __init__(self, config: Optional[Dict] = None):
  175. # 使用传入的配置或加载新配置
  176. if config is None:
  177. print("正在加载配置...")
  178. config = load_config()
  179. print(f"TrendRadar v{__version__} 配置加载完成")
  180. print(f"监控平台数量: {len(config['PLATFORMS'])}")
  181. print(f"时区: {config.get('TIMEZONE', DEFAULT_TIMEZONE)}")
  182. # 创建应用上下文
  183. self.ctx = AppContext(config)
  184. self.request_interval = self.ctx.config["REQUEST_INTERVAL"]
  185. self.report_mode = self.ctx.config["REPORT_MODE"]
  186. self.rank_threshold = self.ctx.rank_threshold
  187. self.is_github_actions = os.environ.get("GITHUB_ACTIONS") == "true"
  188. self.is_docker_container = self._detect_docker_environment()
  189. self.update_info = None
  190. self.proxy_url = None
  191. self._setup_proxy()
  192. self.data_fetcher = DataFetcher(self.proxy_url)
  193. # 初始化存储管理器(使用 AppContext)
  194. self._init_storage_manager()
  195. # 注意:update_info 由 main() 函数设置,避免重复请求远程版本
  196. def _init_storage_manager(self) -> None:
  197. """初始化存储管理器(使用 AppContext)"""
  198. # 获取数据保留天数(支持环境变量覆盖)
  199. env_retention = os.environ.get("STORAGE_RETENTION_DAYS", "").strip()
  200. if env_retention:
  201. # 环境变量覆盖配置
  202. self.ctx.config["STORAGE"]["RETENTION_DAYS"] = int(env_retention)
  203. self.storage_manager = self.ctx.get_storage_manager()
  204. print(f"存储后端: {self.storage_manager.backend_name}")
  205. retention_days = self.ctx.config.get("STORAGE", {}).get("RETENTION_DAYS", 0)
  206. if retention_days > 0:
  207. print(f"数据保留天数: {retention_days} 天")
  208. def _detect_docker_environment(self) -> bool:
  209. """检测是否运行在 Docker 容器中"""
  210. try:
  211. if os.environ.get("DOCKER_CONTAINER") == "true":
  212. return True
  213. if os.path.exists("/.dockerenv"):
  214. return True
  215. return False
  216. except Exception:
  217. return False
  218. def _should_open_browser(self) -> bool:
  219. """判断是否应该打开浏览器"""
  220. return not self.is_github_actions and not self.is_docker_container
  221. def _setup_proxy(self) -> None:
  222. """设置代理配置"""
  223. if not self.is_github_actions and self.ctx.config["USE_PROXY"]:
  224. self.proxy_url = self.ctx.config["DEFAULT_PROXY"]
  225. print("本地环境,使用代理")
  226. elif not self.is_github_actions and not self.ctx.config["USE_PROXY"]:
  227. print("本地环境,未启用代理")
  228. else:
  229. print("GitHub Actions环境,不使用代理")
  230. def _set_update_info_from_config(self) -> None:
  231. """从已缓存的远程版本设置更新信息(不再重复请求)"""
  232. try:
  233. version_url = self.ctx.config.get("VERSION_CHECK_URL", "")
  234. if not version_url:
  235. return
  236. remote_version = _fetch_remote_version(version_url, self.proxy_url)
  237. if remote_version:
  238. need_update = _parse_version(__version__) < _parse_version(remote_version)
  239. if need_update:
  240. self.update_info = {
  241. "current_version": __version__,
  242. "remote_version": remote_version,
  243. }
  244. except Exception as e:
  245. print(f"版本检查出错: {e}")
  246. def _get_mode_strategy(self) -> Dict:
  247. """获取当前模式的策略配置"""
  248. return self.MODE_STRATEGIES.get(self.report_mode, self.MODE_STRATEGIES["daily"])
  249. def _has_notification_configured(self) -> bool:
  250. """检查是否配置了任何通知渠道"""
  251. cfg = self.ctx.config
  252. return any(
  253. [
  254. cfg["FEISHU_WEBHOOK_URL"],
  255. cfg["DINGTALK_WEBHOOK_URL"],
  256. cfg["WEWORK_WEBHOOK_URL"],
  257. (cfg["TELEGRAM_BOT_TOKEN"] and cfg["TELEGRAM_CHAT_ID"]),
  258. (
  259. cfg["EMAIL_FROM"]
  260. and cfg["EMAIL_PASSWORD"]
  261. and cfg["EMAIL_TO"]
  262. ),
  263. (cfg["NTFY_SERVER_URL"] and cfg["NTFY_TOPIC"]),
  264. cfg["BARK_URL"],
  265. cfg["SLACK_WEBHOOK_URL"],
  266. cfg["GENERIC_WEBHOOK_URL"],
  267. ]
  268. )
  269. def _has_valid_content(
  270. self, stats: List[Dict], new_titles: Optional[Dict] = None
  271. ) -> bool:
  272. """检查是否有有效的新闻内容"""
  273. if self.report_mode == "incremental":
  274. # 增量模式:只要有匹配的新闻就推送
  275. # count_word_frequency 已经确保只处理新增的新闻(包括当天第一次爬取的情况)
  276. has_matched_news = any(stat["count"] > 0 for stat in stats)
  277. return has_matched_news
  278. elif self.report_mode == "current":
  279. # current模式:只要stats有内容就说明有匹配的新闻
  280. return any(stat["count"] > 0 for stat in stats)
  281. else:
  282. # 当日汇总模式下,检查是否有匹配的频率词新闻或新增新闻
  283. has_matched_news = any(stat["count"] > 0 for stat in stats)
  284. has_new_news = bool(
  285. new_titles and any(len(titles) > 0 for titles in new_titles.values())
  286. )
  287. return has_matched_news or has_new_news
  288. def _prepare_ai_analysis_data(
  289. self,
  290. ai_mode: str,
  291. current_results: Optional[Dict] = None,
  292. current_id_to_name: Optional[Dict] = None,
  293. ) -> Tuple[List[Dict], Optional[Dict]]:
  294. """
  295. 为 AI 分析准备指定模式的数据
  296. Args:
  297. ai_mode: AI 分析模式 (daily/current/incremental)
  298. current_results: 当前抓取的结果(用于 incremental 模式)
  299. current_id_to_name: 当前的平台映射(用于 incremental 模式)
  300. Returns:
  301. Tuple[stats, id_to_name]: 统计数据和平台映射
  302. """
  303. try:
  304. word_groups, filter_words, global_filters = self.ctx.load_frequency_words()
  305. if ai_mode == "incremental":
  306. # incremental 模式:使用当前抓取的数据
  307. if not current_results or not current_id_to_name:
  308. print("[AI] incremental 模式需要当前抓取数据,但未提供")
  309. return [], None
  310. # 准备当前时间信息
  311. time_info = self.ctx.format_time()
  312. title_info = self._prepare_current_title_info(current_results, time_info)
  313. # 检测新增标题
  314. new_titles = self.ctx.detect_new_titles(list(current_results.keys()))
  315. # 统计计算
  316. stats, _ = self.ctx.count_frequency(
  317. current_results,
  318. word_groups,
  319. filter_words,
  320. current_id_to_name,
  321. title_info,
  322. new_titles,
  323. mode="incremental",
  324. global_filters=global_filters,
  325. quiet=True,
  326. )
  327. # 如果是 platform 模式,转换数据结构
  328. if self.ctx.display_mode == "platform" and stats:
  329. stats = convert_keyword_stats_to_platform_stats(
  330. stats,
  331. self.ctx.weight_config,
  332. self.ctx.rank_threshold,
  333. )
  334. return stats, current_id_to_name
  335. elif ai_mode in ["daily", "current"]:
  336. # 加载历史数据
  337. analysis_data = self._load_analysis_data(quiet=True)
  338. if not analysis_data:
  339. print(f"[AI] 无法加载历史数据用于 {ai_mode} 模式分析")
  340. return [], None
  341. (
  342. all_results,
  343. id_to_name,
  344. title_info,
  345. new_titles,
  346. _,
  347. _,
  348. _,
  349. ) = analysis_data
  350. # 统计计算
  351. stats, _ = self.ctx.count_frequency(
  352. all_results,
  353. word_groups,
  354. filter_words,
  355. id_to_name,
  356. title_info,
  357. new_titles,
  358. mode=ai_mode,
  359. global_filters=global_filters,
  360. quiet=True,
  361. )
  362. # 如果是 platform 模式,转换数据结构
  363. if self.ctx.display_mode == "platform" and stats:
  364. stats = convert_keyword_stats_to_platform_stats(
  365. stats,
  366. self.ctx.weight_config,
  367. self.ctx.rank_threshold,
  368. )
  369. return stats, id_to_name
  370. else:
  371. print(f"[AI] 未知的 AI 模式: {ai_mode}")
  372. return [], None
  373. except Exception as e:
  374. print(f"[AI] 准备 {ai_mode} 模式数据时出错: {e}")
  375. if self.ctx.config.get("DEBUG", False):
  376. import traceback
  377. traceback.print_exc()
  378. return [], None
  379. def _run_ai_analysis(
  380. self,
  381. stats: List[Dict],
  382. rss_items: Optional[List[Dict]],
  383. mode: str,
  384. report_type: str,
  385. id_to_name: Optional[Dict],
  386. current_results: Optional[Dict] = None,
  387. schedule: ResolvedSchedule = None,
  388. standalone_data: Optional[Dict] = None,
  389. ) -> Optional[AIAnalysisResult]:
  390. """执行 AI 分析"""
  391. analysis_config = self.ctx.config.get("AI_ANALYSIS", {})
  392. if not analysis_config.get("ENABLED", False):
  393. return None
  394. # 调度系统决策
  395. if not schedule.analyze:
  396. print("[AI] 调度器: 当前时间段不执行 AI 分析")
  397. return None
  398. if schedule.once_analyze and schedule.period_key:
  399. scheduler = self.ctx.create_scheduler()
  400. date_str = self.ctx.format_date()
  401. if scheduler.already_executed(schedule.period_key, "analyze", date_str):
  402. print(f"[AI] 调度器: 时间段 {schedule.period_name or schedule.period_key} 今天已分析过,跳过")
  403. return None
  404. else:
  405. print(f"[AI] 调度器: 时间段 {schedule.period_name or schedule.period_key} 今天首次分析")
  406. print("[AI] 正在进行 AI 分析...")
  407. try:
  408. ai_config = self.ctx.config.get("AI", {})
  409. debug_mode = self.ctx.config.get("DEBUG", False)
  410. analyzer = AIAnalyzer(ai_config, analysis_config, self.ctx.get_time, debug=debug_mode)
  411. # 确定 AI 分析使用的模式
  412. ai_mode_config = analysis_config.get("MODE", "follow_report")
  413. if ai_mode_config == "follow_report":
  414. # 跟随推送报告模式
  415. ai_mode = mode
  416. ai_stats = stats
  417. ai_id_to_name = id_to_name
  418. elif ai_mode_config in ["daily", "current", "incremental"]:
  419. # 使用独立配置的模式,需要重新准备数据
  420. ai_mode = ai_mode_config
  421. if ai_mode != mode:
  422. print(f"[AI] 使用独立分析模式: {ai_mode} (推送模式: {mode})")
  423. print(f"[AI] 正在准备 {ai_mode} 模式的数据...")
  424. # 根据 AI 模式重新准备数据
  425. ai_stats, ai_id_to_name = self._prepare_ai_analysis_data(
  426. ai_mode, current_results, id_to_name
  427. )
  428. if not ai_stats:
  429. print(f"[AI] 警告: 无法准备 {ai_mode} 模式的数据,回退到推送模式数据")
  430. ai_stats = stats
  431. ai_id_to_name = id_to_name
  432. ai_mode = mode
  433. else:
  434. ai_stats = stats
  435. ai_id_to_name = id_to_name
  436. else:
  437. # 配置错误,回退到跟随模式
  438. print(f"[AI] 警告: 无效的 ai_analysis.mode 配置 '{ai_mode_config}',使用推送模式 '{mode}'")
  439. ai_mode = mode
  440. ai_stats = stats
  441. ai_id_to_name = id_to_name
  442. # 提取平台列表
  443. platforms = list(ai_id_to_name.values()) if ai_id_to_name else []
  444. # 提取关键词列表
  445. keywords = [s.get("word", "") for s in ai_stats if s.get("word")] if ai_stats else []
  446. # 确定报告类型
  447. if ai_mode != mode:
  448. # 根据 AI 模式确定报告类型
  449. ai_report_type = {
  450. "daily": "当日汇总",
  451. "current": "当前榜单",
  452. "incremental": "增量更新"
  453. }.get(ai_mode, report_type)
  454. else:
  455. ai_report_type = report_type
  456. result = analyzer.analyze(
  457. stats=ai_stats,
  458. rss_stats=rss_items,
  459. report_mode=ai_mode,
  460. report_type=ai_report_type,
  461. platforms=platforms,
  462. keywords=keywords,
  463. standalone_data=standalone_data,
  464. )
  465. # 设置 AI 分析使用的模式
  466. if result.success:
  467. result.ai_mode = ai_mode
  468. if result.error:
  469. # 成功但有警告(如 JSON 解析问题但使用了原始文本)
  470. print(f"[AI] 分析完成(有警告: {result.error})")
  471. else:
  472. print("[AI] 分析完成")
  473. # 记录 AI 分析
  474. if schedule.once_analyze and schedule.period_key:
  475. scheduler = self.ctx.create_scheduler()
  476. date_str = self.ctx.format_date()
  477. scheduler.record_execution(schedule.period_key, "analyze", date_str)
  478. else:
  479. print(f"[AI] 分析失败: {result.error}")
  480. return result
  481. except Exception as e:
  482. import traceback
  483. error_type = type(e).__name__
  484. error_msg = str(e)
  485. # 截断过长的错误消息
  486. if len(error_msg) > 200:
  487. error_msg = error_msg[:200] + "..."
  488. print(f"[AI] 分析出错 ({error_type}): {error_msg}")
  489. # 详细错误日志到 stderr
  490. import sys
  491. print(f"[AI] 详细错误堆栈:", file=sys.stderr)
  492. traceback.print_exc(file=sys.stderr)
  493. return AIAnalysisResult(success=False, error=f"{error_type}: {error_msg}")
  494. def _load_analysis_data(
  495. self,
  496. quiet: bool = False,
  497. ) -> Optional[Tuple[Dict, Dict, Dict, Dict, List, List]]:
  498. """统一的数据加载和预处理,使用当前监控平台列表过滤历史数据"""
  499. try:
  500. # 获取当前配置的监控平台ID列表
  501. current_platform_ids = self.ctx.platform_ids
  502. if not quiet:
  503. print(f"当前监控平台: {current_platform_ids}")
  504. all_results, id_to_name, title_info = self.ctx.read_today_titles(
  505. current_platform_ids, quiet=quiet
  506. )
  507. if not all_results:
  508. print("没有找到当天的数据")
  509. return None
  510. total_titles = sum(len(titles) for titles in all_results.values())
  511. if not quiet:
  512. print(f"读取到 {total_titles} 个标题(已按当前监控平台过滤)")
  513. new_titles = self.ctx.detect_new_titles(current_platform_ids, quiet=quiet)
  514. word_groups, filter_words, global_filters = self.ctx.load_frequency_words()
  515. return (
  516. all_results,
  517. id_to_name,
  518. title_info,
  519. new_titles,
  520. word_groups,
  521. filter_words,
  522. global_filters,
  523. )
  524. except Exception as e:
  525. print(f"数据加载失败: {e}")
  526. return None
  527. def _prepare_current_title_info(self, results: Dict, time_info: str) -> Dict:
  528. """从当前抓取结果构建标题信息"""
  529. title_info = {}
  530. for source_id, titles_data in results.items():
  531. title_info[source_id] = {}
  532. for title, title_data in titles_data.items():
  533. ranks = title_data.get("ranks", [])
  534. url = title_data.get("url", "")
  535. mobile_url = title_data.get("mobileUrl", "")
  536. title_info[source_id][title] = {
  537. "first_time": time_info,
  538. "last_time": time_info,
  539. "count": 1,
  540. "ranks": ranks,
  541. "url": url,
  542. "mobileUrl": mobile_url,
  543. }
  544. return title_info
  545. def _prepare_standalone_data(
  546. self,
  547. results: Dict,
  548. id_to_name: Dict,
  549. title_info: Optional[Dict] = None,
  550. rss_items: Optional[List[Dict]] = None,
  551. ) -> Optional[Dict]:
  552. """
  553. 从原始数据中提取独立展示区数据
  554. 纯数据准备方法,不检查 display.regions.standalone 开关。
  555. 各消费者自行决定是否使用:
  556. - AI 分析:由 ai.include_standalone 控制
  557. - 通知推送:由 display.regions.standalone 控制(在 dispatcher 层门控)
  558. - HTML 报告:始终包含(如果有数据)
  559. Args:
  560. results: 原始爬取结果 {platform_id: {title: title_data}}
  561. id_to_name: 平台 ID 到名称的映射
  562. title_info: 标题元信息(含排名历史、时间等)
  563. rss_items: RSS 条目列表
  564. Returns:
  565. 独立展示数据字典,如果未配置数据源返回 None
  566. """
  567. display_config = self.ctx.config.get("DISPLAY", {})
  568. standalone_config = display_config.get("STANDALONE", {})
  569. platform_ids = standalone_config.get("PLATFORMS", [])
  570. rss_feed_ids = standalone_config.get("RSS_FEEDS", [])
  571. max_items = standalone_config.get("MAX_ITEMS", 20)
  572. if not platform_ids and not rss_feed_ids:
  573. return None
  574. standalone_data = {
  575. "platforms": [],
  576. "rss_feeds": [],
  577. }
  578. # 找出最新批次时间(类似 current 模式的过滤逻辑)
  579. latest_time = None
  580. if title_info:
  581. for source_titles in title_info.values():
  582. for title_data in source_titles.values():
  583. last_time = title_data.get("last_time", "")
  584. if last_time:
  585. if latest_time is None or last_time > latest_time:
  586. latest_time = last_time
  587. # 提取热榜平台数据
  588. for platform_id in platform_ids:
  589. if platform_id not in results:
  590. continue
  591. platform_name = id_to_name.get(platform_id, platform_id)
  592. platform_titles = results[platform_id]
  593. items = []
  594. for title, title_data in platform_titles.items():
  595. # 获取元信息(如果有 title_info)
  596. meta = {}
  597. if title_info and platform_id in title_info and title in title_info[platform_id]:
  598. meta = title_info[platform_id][title]
  599. # 只保留当前在榜的话题(last_time 等于最新时间)
  600. if latest_time and meta:
  601. if meta.get("last_time") != latest_time:
  602. continue
  603. # 使用当前热榜的排名数据(title_data)进行排序
  604. # title_data 包含的是爬虫返回的当前排名,用于保证独立展示区的顺序与热榜一致
  605. current_ranks = title_data.get("ranks", [])
  606. current_rank = current_ranks[-1] if current_ranks else 0
  607. # 用于显示的排名范围:合并历史排名和当前排名
  608. historical_ranks = meta.get("ranks", []) if meta else []
  609. # 合并去重,保持顺序
  610. all_ranks = historical_ranks.copy()
  611. for rank in current_ranks:
  612. if rank not in all_ranks:
  613. all_ranks.append(rank)
  614. display_ranks = all_ranks if all_ranks else current_ranks
  615. item = {
  616. "title": title,
  617. "url": title_data.get("url", ""),
  618. "mobileUrl": title_data.get("mobileUrl", ""),
  619. "rank": current_rank, # 用于排序的当前排名
  620. "ranks": display_ranks, # 用于显示的排名范围(历史+当前)
  621. "first_time": meta.get("first_time", ""),
  622. "last_time": meta.get("last_time", ""),
  623. "count": meta.get("count", 1),
  624. "rank_timeline": meta.get("rank_timeline", []),
  625. }
  626. items.append(item)
  627. # 按当前排名排序
  628. items.sort(key=lambda x: x["rank"] if x["rank"] > 0 else 9999)
  629. # 限制条数
  630. if max_items > 0:
  631. items = items[:max_items]
  632. if items:
  633. standalone_data["platforms"].append({
  634. "id": platform_id,
  635. "name": platform_name,
  636. "items": items,
  637. })
  638. # 提取 RSS 数据
  639. if rss_items and rss_feed_ids:
  640. # 按 feed_id 分组
  641. feed_items_map = {}
  642. for item in rss_items:
  643. feed_id = item.get("feed_id", "")
  644. if feed_id in rss_feed_ids:
  645. if feed_id not in feed_items_map:
  646. feed_items_map[feed_id] = {
  647. "name": item.get("feed_name", feed_id),
  648. "items": [],
  649. }
  650. feed_items_map[feed_id]["items"].append({
  651. "title": item.get("title", ""),
  652. "url": item.get("url", ""),
  653. "published_at": item.get("published_at", ""),
  654. "author": item.get("author", ""),
  655. })
  656. # 限制条数并添加到结果
  657. for feed_id in rss_feed_ids:
  658. if feed_id in feed_items_map:
  659. feed_data = feed_items_map[feed_id]
  660. items = feed_data["items"]
  661. if max_items > 0:
  662. items = items[:max_items]
  663. if items:
  664. standalone_data["rss_feeds"].append({
  665. "id": feed_id,
  666. "name": feed_data["name"],
  667. "items": items,
  668. })
  669. # 如果没有任何数据,返回 None
  670. if not standalone_data["platforms"] and not standalone_data["rss_feeds"]:
  671. return None
  672. return standalone_data
  673. def _run_analysis_pipeline(
  674. self,
  675. data_source: Dict,
  676. mode: str,
  677. title_info: Dict,
  678. new_titles: Dict,
  679. word_groups: List[Dict],
  680. filter_words: List[str],
  681. id_to_name: Dict,
  682. failed_ids: Optional[List] = None,
  683. global_filters: Optional[List[str]] = None,
  684. quiet: bool = False,
  685. rss_items: Optional[List[Dict]] = None,
  686. rss_new_items: Optional[List[Dict]] = None,
  687. standalone_data: Optional[Dict] = None,
  688. schedule: ResolvedSchedule = None,
  689. ) -> Tuple[List[Dict], Optional[str], Optional[AIAnalysisResult]]:
  690. """统一的分析流水线:数据处理 → 统计计算 → AI分析 → HTML生成"""
  691. # 统计计算(使用 AppContext)
  692. stats, total_titles = self.ctx.count_frequency(
  693. data_source,
  694. word_groups,
  695. filter_words,
  696. id_to_name,
  697. title_info,
  698. new_titles,
  699. mode=mode,
  700. global_filters=global_filters,
  701. quiet=quiet,
  702. )
  703. # 如果是 platform 模式,转换数据结构
  704. if self.ctx.display_mode == "platform" and stats:
  705. stats = convert_keyword_stats_to_platform_stats(
  706. stats,
  707. self.ctx.weight_config,
  708. self.ctx.rank_threshold,
  709. )
  710. # AI 分析(如果启用,用于 HTML 报告)
  711. ai_result = None
  712. ai_config = self.ctx.config.get("AI_ANALYSIS", {})
  713. if ai_config.get("ENABLED", False) and stats:
  714. # 获取模式策略来确定报告类型
  715. mode_strategy = self._get_mode_strategy()
  716. report_type = mode_strategy["report_type"]
  717. ai_result = self._run_ai_analysis(
  718. stats, rss_items, mode, report_type, id_to_name,
  719. current_results=data_source, schedule=schedule,
  720. standalone_data=standalone_data
  721. )
  722. # HTML生成(如果启用)
  723. html_file = None
  724. if self.ctx.config["STORAGE"]["FORMATS"]["HTML"]:
  725. html_file = self.ctx.generate_html(
  726. stats,
  727. total_titles,
  728. failed_ids=failed_ids,
  729. new_titles=new_titles,
  730. id_to_name=id_to_name,
  731. mode=mode,
  732. update_info=self.update_info if self.ctx.config["SHOW_VERSION_UPDATE"] else None,
  733. rss_items=rss_items,
  734. rss_new_items=rss_new_items,
  735. ai_analysis=ai_result,
  736. standalone_data=standalone_data,
  737. )
  738. return stats, html_file, ai_result
  739. def _send_notification_if_needed(
  740. self,
  741. stats: List[Dict],
  742. report_type: str,
  743. mode: str,
  744. failed_ids: Optional[List] = None,
  745. new_titles: Optional[Dict] = None,
  746. id_to_name: Optional[Dict] = None,
  747. html_file_path: Optional[str] = None,
  748. rss_items: Optional[List[Dict]] = None,
  749. rss_new_items: Optional[List[Dict]] = None,
  750. standalone_data: Optional[Dict] = None,
  751. ai_result: Optional[AIAnalysisResult] = None,
  752. current_results: Optional[Dict] = None,
  753. schedule: ResolvedSchedule = None,
  754. ) -> bool:
  755. """统一的通知发送逻辑,包含所有判断条件,支持热榜+RSS合并推送+AI分析+独立展示区"""
  756. has_notification = self._has_notification_configured()
  757. cfg = self.ctx.config
  758. # 检查是否有有效内容(热榜或RSS)
  759. has_news_content = self._has_valid_content(stats, new_titles)
  760. has_rss_content = bool(rss_items and len(rss_items) > 0)
  761. has_any_content = has_news_content or has_rss_content
  762. # 计算热榜匹配条数
  763. news_count = sum(len(stat.get("titles", [])) for stat in stats) if stats else 0
  764. rss_count = sum(stat.get("count", 0) for stat in rss_items) if rss_items else 0
  765. if (
  766. cfg["ENABLE_NOTIFICATION"]
  767. and has_notification
  768. and has_any_content
  769. ):
  770. # 输出推送内容统计
  771. content_parts = []
  772. if news_count > 0:
  773. content_parts.append(f"热榜 {news_count} 条")
  774. if rss_count > 0:
  775. content_parts.append(f"RSS {rss_count} 条")
  776. total_count = news_count + rss_count
  777. print(f"[推送] 准备发送:{' + '.join(content_parts)},合计 {total_count} 条")
  778. # 调度系统决策
  779. if not schedule.push:
  780. print("[推送] 调度器: 当前时间段不执行推送")
  781. return False
  782. if schedule.once_push and schedule.period_key:
  783. scheduler = self.ctx.create_scheduler()
  784. date_str = self.ctx.format_date()
  785. if scheduler.already_executed(schedule.period_key, "push", date_str):
  786. print(f"[推送] 调度器: 时间段 {schedule.period_name or schedule.period_key} 今天已推送过,跳过")
  787. return False
  788. else:
  789. print(f"[推送] 调度器: 时间段 {schedule.period_name or schedule.period_key} 今天首次推送")
  790. # AI 分析:优先使用传入的结果,避免重复分析
  791. if ai_result is None:
  792. ai_config = cfg.get("AI_ANALYSIS", {})
  793. if ai_config.get("ENABLED", False):
  794. ai_result = self._run_ai_analysis(
  795. stats, rss_items, mode, report_type, id_to_name,
  796. current_results=current_results, schedule=schedule
  797. )
  798. # 准备报告数据
  799. report_data = self.ctx.prepare_report(stats, failed_ids, new_titles, id_to_name, mode)
  800. # 是否发送版本更新信息
  801. update_info_to_send = self.update_info if cfg["SHOW_VERSION_UPDATE"] else None
  802. # 使用 NotificationDispatcher 发送到所有渠道
  803. dispatcher = self.ctx.create_notification_dispatcher()
  804. results = dispatcher.dispatch_all(
  805. report_data=report_data,
  806. report_type=report_type,
  807. update_info=update_info_to_send,
  808. proxy_url=self.proxy_url,
  809. mode=mode,
  810. html_file_path=html_file_path,
  811. rss_items=rss_items,
  812. rss_new_items=rss_new_items,
  813. ai_analysis=ai_result,
  814. standalone_data=standalone_data,
  815. )
  816. if not results:
  817. print("未配置任何通知渠道,跳过通知发送")
  818. return False
  819. # 记录推送成功
  820. if any(results.values()):
  821. if schedule.once_push and schedule.period_key:
  822. scheduler = self.ctx.create_scheduler()
  823. date_str = self.ctx.format_date()
  824. scheduler.record_execution(schedule.period_key, "push", date_str)
  825. return True
  826. elif cfg["ENABLE_NOTIFICATION"] and not has_notification:
  827. print("⚠️ 警告:通知功能已启用但未配置任何通知渠道,将跳过通知发送")
  828. elif not cfg["ENABLE_NOTIFICATION"]:
  829. print(f"跳过{report_type}通知:通知功能已禁用")
  830. elif (
  831. cfg["ENABLE_NOTIFICATION"]
  832. and has_notification
  833. and not has_any_content
  834. ):
  835. mode_strategy = self._get_mode_strategy()
  836. if self.report_mode == "incremental":
  837. if not has_rss_content:
  838. print("跳过通知:增量模式下未检测到匹配的新闻和RSS")
  839. else:
  840. print("跳过通知:增量模式下新闻未匹配到关键词")
  841. else:
  842. print(
  843. f"跳过通知:{mode_strategy['mode_name']}下未检测到匹配的新闻"
  844. )
  845. return False
  846. def _initialize_and_check_config(self) -> None:
  847. """通用初始化和配置检查"""
  848. now = self.ctx.get_time()
  849. print(f"当前北京时间: {now.strftime('%Y-%m-%d %H:%M:%S')}")
  850. if not self.ctx.config["ENABLE_CRAWLER"]:
  851. print("爬虫功能已禁用(ENABLE_CRAWLER=False),程序退出")
  852. return
  853. has_notification = self._has_notification_configured()
  854. if not self.ctx.config["ENABLE_NOTIFICATION"]:
  855. print("通知功能已禁用(ENABLE_NOTIFICATION=False),将只进行数据抓取")
  856. elif not has_notification:
  857. print("未配置任何通知渠道,将只进行数据抓取,不发送通知")
  858. else:
  859. print("通知功能已启用,将发送通知")
  860. mode_strategy = self._get_mode_strategy()
  861. print(f"报告模式: {self.report_mode}")
  862. print(f"运行模式: {mode_strategy['description']}")
  863. def _crawl_data(self) -> Tuple[Dict, Dict, List]:
  864. """执行数据爬取"""
  865. ids = []
  866. for platform in self.ctx.platforms:
  867. if "name" in platform:
  868. ids.append((platform["id"], platform["name"]))
  869. else:
  870. ids.append(platform["id"])
  871. print(
  872. f"配置的监控平台: {[p.get('name', p['id']) for p in self.ctx.platforms]}"
  873. )
  874. print(f"开始爬取数据,请求间隔 {self.request_interval} 毫秒")
  875. Path("output").mkdir(parents=True, exist_ok=True)
  876. results, id_to_name, failed_ids = self.data_fetcher.crawl_websites(
  877. ids, self.request_interval
  878. )
  879. # 转换为 NewsData 格式并保存到存储后端
  880. crawl_time = self.ctx.format_time()
  881. crawl_date = self.ctx.format_date()
  882. news_data = convert_crawl_results_to_news_data(
  883. results, id_to_name, failed_ids, crawl_time, crawl_date
  884. )
  885. # 保存到存储后端(SQLite)
  886. if self.storage_manager.save_news_data(news_data):
  887. print(f"数据已保存到存储后端: {self.storage_manager.backend_name}")
  888. # 保存 TXT 快照(如果启用)
  889. txt_file = self.storage_manager.save_txt_snapshot(news_data)
  890. if txt_file:
  891. print(f"TXT 快照已保存: {txt_file}")
  892. return results, id_to_name, failed_ids
  893. def _crawl_rss_data(self) -> Tuple[Optional[List[Dict]], Optional[List[Dict]], Optional[List[Dict]]]:
  894. """
  895. 执行 RSS 数据抓取
  896. Returns:
  897. (rss_items, rss_new_items, raw_rss_items) 元组:
  898. - rss_items: 统计条目列表(按模式处理,用于统计区块)
  899. - rss_new_items: 新增条目列表(用于新增区块)
  900. - raw_rss_items: 原始 RSS 条目列表(用于独立展示区)
  901. 如果未启用或失败返回 (None, None, None)
  902. """
  903. if not self.ctx.rss_enabled:
  904. return None, None, None
  905. rss_feeds = self.ctx.rss_feeds
  906. if not rss_feeds:
  907. print("[RSS] 未配置任何 RSS 源")
  908. return None, None, None
  909. try:
  910. from trendradar.crawler.rss import RSSFetcher, RSSFeedConfig
  911. # 构建 RSS 源配置
  912. feeds = []
  913. for feed_config in rss_feeds:
  914. # 读取并验证单个 feed 的 max_age_days(可选)
  915. max_age_days_raw = feed_config.get("max_age_days")
  916. max_age_days = None
  917. if max_age_days_raw is not None:
  918. try:
  919. max_age_days = int(max_age_days_raw)
  920. if max_age_days < 0:
  921. feed_id = feed_config.get("id", "unknown")
  922. print(f"[警告] RSS feed '{feed_id}' 的 max_age_days 为负数,将使用全局默认值")
  923. max_age_days = None
  924. except (ValueError, TypeError):
  925. feed_id = feed_config.get("id", "unknown")
  926. print(f"[警告] RSS feed '{feed_id}' 的 max_age_days 格式错误:{max_age_days_raw}")
  927. max_age_days = None
  928. feed = RSSFeedConfig(
  929. id=feed_config.get("id", ""),
  930. name=feed_config.get("name", ""),
  931. url=feed_config.get("url", ""),
  932. max_items=feed_config.get("max_items", 50),
  933. enabled=feed_config.get("enabled", True),
  934. max_age_days=max_age_days, # None=使用全局,0=禁用,>0=覆盖
  935. )
  936. if feed.id and feed.url and feed.enabled:
  937. feeds.append(feed)
  938. if not feeds:
  939. print("[RSS] 没有启用的 RSS 源")
  940. return None, None, None
  941. # 创建抓取器
  942. rss_config = self.ctx.rss_config
  943. # RSS 代理:优先使用 RSS 专属代理,否则使用爬虫默认代理
  944. rss_proxy_url = rss_config.get("PROXY_URL", "") or self.proxy_url or ""
  945. # 获取配置的时区
  946. timezone = self.ctx.config.get("TIMEZONE", DEFAULT_TIMEZONE)
  947. # 获取新鲜度过滤配置
  948. freshness_config = rss_config.get("FRESHNESS_FILTER", {})
  949. freshness_enabled = freshness_config.get("ENABLED", True)
  950. default_max_age_days = freshness_config.get("MAX_AGE_DAYS", 3)
  951. fetcher = RSSFetcher(
  952. feeds=feeds,
  953. request_interval=rss_config.get("REQUEST_INTERVAL", 2000),
  954. timeout=rss_config.get("TIMEOUT", 15),
  955. use_proxy=rss_config.get("USE_PROXY", False),
  956. proxy_url=rss_proxy_url,
  957. timezone=timezone,
  958. freshness_enabled=freshness_enabled,
  959. default_max_age_days=default_max_age_days,
  960. )
  961. # 抓取数据
  962. rss_data = fetcher.fetch_all()
  963. # 保存到存储后端
  964. if self.storage_manager.save_rss_data(rss_data):
  965. print(f"[RSS] 数据已保存到存储后端")
  966. # 处理 RSS 数据(按模式过滤)并返回用于合并推送
  967. return self._process_rss_data_by_mode(rss_data)
  968. else:
  969. print(f"[RSS] 数据保存失败")
  970. return None, None, None
  971. except ImportError as e:
  972. print(f"[RSS] 缺少依赖: {e}")
  973. print("[RSS] 请安装 feedparser: pip install feedparser")
  974. return None, None, None
  975. except Exception as e:
  976. print(f"[RSS] 抓取失败: {e}")
  977. return None, None, None
  978. def _process_rss_data_by_mode(self, rss_data) -> Tuple[Optional[List[Dict]], Optional[List[Dict]], Optional[List[Dict]]]:
  979. """
  980. 按报告模式处理 RSS 数据,返回与热榜相同格式的统计结构
  981. 三种模式:
  982. - daily: 当日汇总,统计=当天所有条目,新增=本次新增条目
  983. - current: 当前榜单,统计=当前榜单条目,新增=本次新增条目
  984. - incremental: 增量模式,统计=新增条目,新增=无
  985. Args:
  986. rss_data: 当前抓取的 RSSData 对象
  987. Returns:
  988. (rss_stats, rss_new_stats, raw_rss_items) 元组:
  989. - rss_stats: RSS 关键词统计列表(与热榜 stats 格式一致)
  990. - rss_new_stats: RSS 新增关键词统计列表(与热榜 stats 格式一致)
  991. - raw_rss_items: 原始 RSS 条目列表(用于独立展示区)
  992. """
  993. from trendradar.core.analyzer import count_rss_frequency
  994. # 从 display.regions.rss 统一控制 RSS 分析和展示
  995. rss_display_enabled = self.ctx.config.get("DISPLAY", {}).get("REGIONS", {}).get("RSS", True)
  996. # 加载关键词配置
  997. try:
  998. word_groups, filter_words, global_filters = self.ctx.load_frequency_words()
  999. except FileNotFoundError:
  1000. word_groups, filter_words, global_filters = [], [], []
  1001. timezone = self.ctx.timezone
  1002. max_news_per_keyword = self.ctx.config.get("MAX_NEWS_PER_KEYWORD", 0)
  1003. sort_by_position_first = self.ctx.config.get("SORT_BY_POSITION_FIRST", False)
  1004. rss_stats = None
  1005. rss_new_stats = None
  1006. raw_rss_items = None # 原始 RSS 条目列表(用于独立展示区)
  1007. # 1. 首先获取原始条目(用于独立展示区,不受 display.regions.rss 影响)
  1008. # 根据模式获取原始条目
  1009. if self.report_mode == "incremental":
  1010. new_items_dict = self.storage_manager.detect_new_rss_items(rss_data)
  1011. if new_items_dict:
  1012. raw_rss_items = self._convert_rss_items_to_list(new_items_dict, rss_data.id_to_name)
  1013. elif self.report_mode == "current":
  1014. latest_data = self.storage_manager.get_latest_rss_data(rss_data.date)
  1015. if latest_data:
  1016. raw_rss_items = self._convert_rss_items_to_list(latest_data.items, latest_data.id_to_name)
  1017. else: # daily
  1018. all_data = self.storage_manager.get_rss_data(rss_data.date)
  1019. if all_data:
  1020. raw_rss_items = self._convert_rss_items_to_list(all_data.items, all_data.id_to_name)
  1021. # 如果 RSS 展示未启用,跳过关键词分析,只返回原始条目用于独立展示区
  1022. if not rss_display_enabled:
  1023. return None, None, raw_rss_items
  1024. # 2. 获取新增条目(用于统计)
  1025. new_items_dict = self.storage_manager.detect_new_rss_items(rss_data)
  1026. new_items_list = None
  1027. if new_items_dict:
  1028. new_items_list = self._convert_rss_items_to_list(new_items_dict, rss_data.id_to_name)
  1029. if new_items_list:
  1030. print(f"[RSS] 检测到 {len(new_items_list)} 条新增")
  1031. # 3. 根据模式获取统计条目
  1032. if self.report_mode == "incremental":
  1033. # 增量模式:统计条目就是新增条目
  1034. if not new_items_list:
  1035. print("[RSS] 增量模式:没有新增 RSS 条目")
  1036. return None, None, raw_rss_items
  1037. rss_stats, total = count_rss_frequency(
  1038. rss_items=new_items_list,
  1039. word_groups=word_groups,
  1040. filter_words=filter_words,
  1041. global_filters=global_filters,
  1042. new_items=new_items_list, # 增量模式所有都是新增
  1043. max_news_per_keyword=max_news_per_keyword,
  1044. sort_by_position_first=sort_by_position_first,
  1045. timezone=timezone,
  1046. rank_threshold=self.rank_threshold,
  1047. quiet=False,
  1048. )
  1049. if not rss_stats:
  1050. print("[RSS] 增量模式:关键词匹配后没有内容")
  1051. # 即使关键词匹配为空,也返回原始条目用于独立展示区
  1052. return None, None, raw_rss_items
  1053. elif self.report_mode == "current":
  1054. # 当前榜单模式:统计=当前榜单所有条目
  1055. # raw_rss_items 已在前面获取
  1056. if not raw_rss_items:
  1057. print("[RSS] 当前榜单模式:没有 RSS 数据")
  1058. return None, None, None
  1059. rss_stats, total = count_rss_frequency(
  1060. rss_items=raw_rss_items,
  1061. word_groups=word_groups,
  1062. filter_words=filter_words,
  1063. global_filters=global_filters,
  1064. new_items=new_items_list, # 标记新增
  1065. max_news_per_keyword=max_news_per_keyword,
  1066. sort_by_position_first=sort_by_position_first,
  1067. timezone=timezone,
  1068. rank_threshold=self.rank_threshold,
  1069. quiet=False,
  1070. )
  1071. if not rss_stats:
  1072. print("[RSS] 当前榜单模式:关键词匹配后没有内容")
  1073. # 即使关键词匹配为空,也返回原始条目用于独立展示区
  1074. return None, None, raw_rss_items
  1075. # 生成新增统计
  1076. if new_items_list:
  1077. rss_new_stats, _ = count_rss_frequency(
  1078. rss_items=new_items_list,
  1079. word_groups=word_groups,
  1080. filter_words=filter_words,
  1081. global_filters=global_filters,
  1082. new_items=new_items_list,
  1083. max_news_per_keyword=max_news_per_keyword,
  1084. sort_by_position_first=sort_by_position_first,
  1085. timezone=timezone,
  1086. rank_threshold=self.rank_threshold,
  1087. quiet=True,
  1088. )
  1089. else:
  1090. # daily 模式:统计=当天所有条目
  1091. # raw_rss_items 已在前面获取
  1092. if not raw_rss_items:
  1093. print("[RSS] 当日汇总模式:没有 RSS 数据")
  1094. return None, None, None
  1095. rss_stats, total = count_rss_frequency(
  1096. rss_items=raw_rss_items,
  1097. word_groups=word_groups,
  1098. filter_words=filter_words,
  1099. global_filters=global_filters,
  1100. new_items=new_items_list, # 标记新增
  1101. max_news_per_keyword=max_news_per_keyword,
  1102. sort_by_position_first=sort_by_position_first,
  1103. timezone=timezone,
  1104. rank_threshold=self.rank_threshold,
  1105. quiet=False,
  1106. )
  1107. if not rss_stats:
  1108. print("[RSS] 当日汇总模式:关键词匹配后没有内容")
  1109. # 即使关键词匹配为空,也返回原始条目用于独立展示区
  1110. return None, None, raw_rss_items
  1111. # 生成新增统计
  1112. if new_items_list:
  1113. rss_new_stats, _ = count_rss_frequency(
  1114. rss_items=new_items_list,
  1115. word_groups=word_groups,
  1116. filter_words=filter_words,
  1117. global_filters=global_filters,
  1118. new_items=new_items_list,
  1119. max_news_per_keyword=max_news_per_keyword,
  1120. sort_by_position_first=sort_by_position_first,
  1121. timezone=timezone,
  1122. rank_threshold=self.rank_threshold,
  1123. quiet=True,
  1124. )
  1125. return rss_stats, rss_new_stats, raw_rss_items
  1126. def _convert_rss_items_to_list(self, items_dict: Dict, id_to_name: Dict) -> List[Dict]:
  1127. """将 RSS 条目字典转换为列表格式,并应用新鲜度过滤(用于推送)"""
  1128. rss_items = []
  1129. filtered_count = 0
  1130. filtered_details = [] # 用于 DEBUG 模式下的详细日志
  1131. # 获取新鲜度过滤配置
  1132. rss_config = self.ctx.rss_config
  1133. freshness_config = rss_config.get("FRESHNESS_FILTER", {})
  1134. freshness_enabled = freshness_config.get("ENABLED", True)
  1135. default_max_age_days = freshness_config.get("MAX_AGE_DAYS", 3)
  1136. timezone = self.ctx.config.get("TIMEZONE", DEFAULT_TIMEZONE)
  1137. debug_mode = self.ctx.config.get("DEBUG", False)
  1138. # 构建 feed_id -> max_age_days 的映射
  1139. feed_max_age_map = {}
  1140. for feed_cfg in self.ctx.rss_feeds:
  1141. feed_id = feed_cfg.get("id", "")
  1142. max_age = feed_cfg.get("max_age_days")
  1143. if max_age is not None:
  1144. try:
  1145. feed_max_age_map[feed_id] = int(max_age)
  1146. except (ValueError, TypeError):
  1147. pass
  1148. for feed_id, items in items_dict.items():
  1149. # 确定此 feed 的 max_age_days
  1150. max_days = feed_max_age_map.get(feed_id)
  1151. if max_days is None:
  1152. max_days = default_max_age_days
  1153. for item in items:
  1154. # 应用新鲜度过滤(仅在启用时)
  1155. if freshness_enabled and max_days > 0:
  1156. if item.published_at and not is_within_days(item.published_at, max_days, timezone):
  1157. filtered_count += 1
  1158. # 记录详细信息用于 DEBUG 模式
  1159. if debug_mode:
  1160. days_old = calculate_days_old(item.published_at, timezone)
  1161. feed_name = id_to_name.get(feed_id, feed_id)
  1162. filtered_details.append({
  1163. "title": item.title[:50] + "..." if len(item.title) > 50 else item.title,
  1164. "feed": feed_name,
  1165. "days_old": days_old,
  1166. "max_days": max_days,
  1167. })
  1168. continue # 跳过超过指定天数的文章
  1169. rss_items.append({
  1170. "title": item.title,
  1171. "feed_id": feed_id,
  1172. "feed_name": id_to_name.get(feed_id, feed_id),
  1173. "url": item.url,
  1174. "published_at": item.published_at,
  1175. "summary": item.summary,
  1176. "author": item.author,
  1177. })
  1178. # 输出过滤统计
  1179. if filtered_count > 0:
  1180. print(f"[RSS] 新鲜度过滤:跳过 {filtered_count} 篇超过指定天数的旧文章(仍保留在数据库中)")
  1181. # DEBUG 模式下显示详细信息
  1182. if debug_mode and filtered_details:
  1183. print(f"[RSS] 被过滤的文章详情(共 {len(filtered_details)} 篇):")
  1184. for detail in filtered_details[:10]: # 最多显示 10 条
  1185. days_str = f"{detail['days_old']:.1f}" if detail['days_old'] else "未知"
  1186. print(f" - [{days_str}天前] [{detail['feed']}] {detail['title']} (限制: {detail['max_days']}天)")
  1187. if len(filtered_details) > 10:
  1188. print(f" ... 还有 {len(filtered_details) - 10} 篇被过滤")
  1189. return rss_items
  1190. def _filter_rss_by_keywords(self, rss_items: List[Dict]) -> List[Dict]:
  1191. """使用 frequency_words.txt 过滤 RSS 条目"""
  1192. try:
  1193. word_groups, filter_words, global_filters = self.ctx.load_frequency_words()
  1194. if word_groups or filter_words or global_filters:
  1195. from trendradar.core.frequency import matches_word_groups
  1196. filtered_items = []
  1197. for item in rss_items:
  1198. title = item.get("title", "")
  1199. if matches_word_groups(title, word_groups, filter_words, global_filters):
  1200. filtered_items.append(item)
  1201. original_count = len(rss_items)
  1202. rss_items = filtered_items
  1203. print(f"[RSS] 关键词过滤后剩余 {len(rss_items)}/{original_count} 条")
  1204. if not rss_items:
  1205. print("[RSS] 关键词过滤后没有匹配内容")
  1206. return []
  1207. except FileNotFoundError:
  1208. # frequency_words.txt 不存在时跳过过滤
  1209. pass
  1210. return rss_items
  1211. def _generate_rss_html_report(self, rss_items: list, feeds_info: dict) -> str:
  1212. """生成 RSS HTML 报告"""
  1213. try:
  1214. from trendradar.report.rss_html import render_rss_html_content
  1215. from pathlib import Path
  1216. html_content = render_rss_html_content(
  1217. rss_items=rss_items,
  1218. total_count=len(rss_items),
  1219. feeds_info=feeds_info,
  1220. get_time_func=self.ctx.get_time,
  1221. )
  1222. # 保存 HTML 文件(扁平化结构:output/html/日期/)
  1223. date_folder = self.ctx.format_date()
  1224. time_filename = self.ctx.format_time()
  1225. output_dir = Path("output") / "html" / date_folder
  1226. output_dir.mkdir(parents=True, exist_ok=True)
  1227. file_path = output_dir / f"rss_{time_filename}.html"
  1228. with open(file_path, "w", encoding="utf-8") as f:
  1229. f.write(html_content)
  1230. print(f"[RSS] HTML 报告已生成: {file_path}")
  1231. return str(file_path)
  1232. except Exception as e:
  1233. print(f"[RSS] 生成 HTML 报告失败: {e}")
  1234. return None
  1235. def _execute_mode_strategy(
  1236. self, mode_strategy: Dict, results: Dict, id_to_name: Dict, failed_ids: List,
  1237. rss_items: Optional[List[Dict]] = None,
  1238. rss_new_items: Optional[List[Dict]] = None,
  1239. raw_rss_items: Optional[List[Dict]] = None,
  1240. ) -> Optional[str]:
  1241. """执行模式特定逻辑,支持热榜+RSS合并推送
  1242. 简化后的逻辑:
  1243. - 每次运行都生成 HTML 报告(时间戳快照 + latest/{mode}.html + index.html)
  1244. - 根据模式发送通知
  1245. """
  1246. # 调度系统
  1247. scheduler = self.ctx.create_scheduler()
  1248. schedule = scheduler.resolve()
  1249. # 使用 schedule 决定的 report_mode 覆盖全局配置
  1250. effective_mode = schedule.report_mode
  1251. if effective_mode != self.report_mode:
  1252. print(f"[调度] 报告模式覆盖: {self.report_mode} -> {effective_mode}")
  1253. self.report_mode = effective_mode
  1254. # 如果调度器说不采集,则直接跳过
  1255. if not schedule.collect:
  1256. print("[调度] 当前时间段不执行数据采集,跳过分析流水线")
  1257. return None
  1258. # 获取当前监控平台ID列表
  1259. current_platform_ids = self.ctx.platform_ids
  1260. new_titles = self.ctx.detect_new_titles(current_platform_ids)
  1261. time_info = self.ctx.format_time()
  1262. word_groups, filter_words, global_filters = self.ctx.load_frequency_words()
  1263. html_file = None
  1264. stats = []
  1265. ai_result = None
  1266. title_info = None
  1267. # current 模式需要使用完整的历史数据
  1268. if self.report_mode == "current":
  1269. analysis_data = self._load_analysis_data()
  1270. if analysis_data:
  1271. (
  1272. all_results,
  1273. historical_id_to_name,
  1274. historical_title_info,
  1275. historical_new_titles,
  1276. _,
  1277. _,
  1278. _,
  1279. ) = analysis_data
  1280. print(
  1281. f"current模式:使用过滤后的历史数据,包含平台:{list(all_results.keys())}"
  1282. )
  1283. # 使用历史数据准备独立展示区数据(包含完整的 title_info)
  1284. standalone_data = self._prepare_standalone_data(
  1285. all_results, historical_id_to_name, historical_title_info, raw_rss_items
  1286. )
  1287. stats, html_file, ai_result = self._run_analysis_pipeline(
  1288. all_results,
  1289. self.report_mode,
  1290. historical_title_info,
  1291. historical_new_titles,
  1292. word_groups,
  1293. filter_words,
  1294. historical_id_to_name,
  1295. failed_ids=failed_ids,
  1296. global_filters=global_filters,
  1297. rss_items=rss_items,
  1298. rss_new_items=rss_new_items,
  1299. standalone_data=standalone_data,
  1300. schedule=schedule,
  1301. )
  1302. combined_id_to_name = {**historical_id_to_name, **id_to_name}
  1303. new_titles = historical_new_titles
  1304. id_to_name = combined_id_to_name
  1305. title_info = historical_title_info
  1306. results = all_results
  1307. else:
  1308. print("❌ 严重错误:无法读取刚保存的数据文件")
  1309. raise RuntimeError("数据一致性检查失败:保存后立即读取失败")
  1310. elif self.report_mode == "daily":
  1311. # daily 模式:使用全天累计数据
  1312. analysis_data = self._load_analysis_data()
  1313. if analysis_data:
  1314. (
  1315. all_results,
  1316. historical_id_to_name,
  1317. historical_title_info,
  1318. historical_new_titles,
  1319. _,
  1320. _,
  1321. _,
  1322. ) = analysis_data
  1323. # 使用历史数据准备独立展示区数据(包含完整的 title_info)
  1324. standalone_data = self._prepare_standalone_data(
  1325. all_results, historical_id_to_name, historical_title_info, raw_rss_items
  1326. )
  1327. stats, html_file, ai_result = self._run_analysis_pipeline(
  1328. all_results,
  1329. self.report_mode,
  1330. historical_title_info,
  1331. historical_new_titles,
  1332. word_groups,
  1333. filter_words,
  1334. historical_id_to_name,
  1335. failed_ids=failed_ids,
  1336. global_filters=global_filters,
  1337. rss_items=rss_items,
  1338. rss_new_items=rss_new_items,
  1339. standalone_data=standalone_data,
  1340. schedule=schedule,
  1341. )
  1342. combined_id_to_name = {**historical_id_to_name, **id_to_name}
  1343. new_titles = historical_new_titles
  1344. id_to_name = combined_id_to_name
  1345. title_info = historical_title_info
  1346. results = all_results
  1347. else:
  1348. # 没有历史数据时使用当前数据
  1349. title_info = self._prepare_current_title_info(results, time_info)
  1350. standalone_data = self._prepare_standalone_data(
  1351. results, id_to_name, title_info, raw_rss_items
  1352. )
  1353. stats, html_file, ai_result = self._run_analysis_pipeline(
  1354. results,
  1355. self.report_mode,
  1356. title_info,
  1357. new_titles,
  1358. word_groups,
  1359. filter_words,
  1360. id_to_name,
  1361. failed_ids=failed_ids,
  1362. global_filters=global_filters,
  1363. rss_items=rss_items,
  1364. rss_new_items=rss_new_items,
  1365. standalone_data=standalone_data,
  1366. schedule=schedule,
  1367. )
  1368. else:
  1369. # incremental 模式:只使用当前抓取的数据
  1370. title_info = self._prepare_current_title_info(results, time_info)
  1371. standalone_data = self._prepare_standalone_data(
  1372. results, id_to_name, title_info, raw_rss_items
  1373. )
  1374. stats, html_file, ai_result = self._run_analysis_pipeline(
  1375. results,
  1376. self.report_mode,
  1377. title_info,
  1378. new_titles,
  1379. word_groups,
  1380. filter_words,
  1381. id_to_name,
  1382. failed_ids=failed_ids,
  1383. global_filters=global_filters,
  1384. rss_items=rss_items,
  1385. rss_new_items=rss_new_items,
  1386. standalone_data=standalone_data,
  1387. schedule=schedule,
  1388. )
  1389. if html_file:
  1390. print(f"HTML报告已生成: {html_file}")
  1391. print(f"最新报告已更新: output/html/latest/{self.report_mode}.html")
  1392. # 发送通知
  1393. if mode_strategy["should_send_notification"]:
  1394. standalone_data = self._prepare_standalone_data(
  1395. results, id_to_name, title_info, raw_rss_items
  1396. )
  1397. self._send_notification_if_needed(
  1398. stats,
  1399. mode_strategy["report_type"],
  1400. self.report_mode,
  1401. failed_ids=failed_ids,
  1402. new_titles=new_titles,
  1403. id_to_name=id_to_name,
  1404. html_file_path=html_file,
  1405. rss_items=rss_items,
  1406. rss_new_items=rss_new_items,
  1407. standalone_data=standalone_data,
  1408. ai_result=ai_result,
  1409. current_results=results,
  1410. schedule=schedule,
  1411. )
  1412. # 打开浏览器(仅在非容器环境)
  1413. if self._should_open_browser() and html_file:
  1414. file_url = "file://" + str(Path(html_file).resolve())
  1415. print(f"正在打开HTML报告: {file_url}")
  1416. webbrowser.open(file_url)
  1417. elif self.is_docker_container and html_file:
  1418. print(f"HTML报告已生成(Docker环境): {html_file}")
  1419. return html_file
  1420. def run(self) -> None:
  1421. """执行分析流程"""
  1422. try:
  1423. self._initialize_and_check_config()
  1424. mode_strategy = self._get_mode_strategy()
  1425. # 抓取热榜数据
  1426. results, id_to_name, failed_ids = self._crawl_data()
  1427. # 抓取 RSS 数据(如果启用),返回统计条目、新增条目和原始条目
  1428. rss_items, rss_new_items, raw_rss_items = self._crawl_rss_data()
  1429. # 执行模式策略,传递 RSS 数据用于合并推送
  1430. self._execute_mode_strategy(
  1431. mode_strategy, results, id_to_name, failed_ids,
  1432. rss_items=rss_items, rss_new_items=rss_new_items,
  1433. raw_rss_items=raw_rss_items
  1434. )
  1435. except Exception as e:
  1436. print(f"分析流程执行出错: {e}")
  1437. if self.ctx.config.get("DEBUG", False):
  1438. raise
  1439. finally:
  1440. # 清理资源(包括过期数据清理和数据库连接关闭)
  1441. self.ctx.cleanup()
  1442. def main():
  1443. """主程序入口"""
  1444. # 解析命令行参数
  1445. parser = argparse.ArgumentParser(
  1446. description="TrendRadar - 热点新闻聚合与分析工具",
  1447. formatter_class=argparse.RawDescriptionHelpFormatter,
  1448. epilog="""
  1449. 调度状态命令:
  1450. --show-schedule 显示当前调度状态(时间段、行为开关)
  1451. 示例:
  1452. python -m trendradar # 正常运行
  1453. python -m trendradar --show-schedule # 查看当前调度状态
  1454. """
  1455. )
  1456. parser.add_argument(
  1457. "--show-schedule",
  1458. action="store_true",
  1459. help="显示当前调度状态"
  1460. )
  1461. args = parser.parse_args()
  1462. debug_mode = False
  1463. try:
  1464. # 先加载配置
  1465. config = load_config()
  1466. # 处理状态查看命令
  1467. if args.show_schedule:
  1468. _handle_status_commands(config, args)
  1469. return
  1470. version_url = config.get("VERSION_CHECK_URL", "")
  1471. configs_version_url = config.get("CONFIGS_VERSION_CHECK_URL", "")
  1472. # 统一版本检查(程序版本 + 配置文件版本,只请求一次远程)
  1473. need_update = False
  1474. remote_version = None
  1475. if version_url:
  1476. need_update, remote_version = check_all_versions(version_url, configs_version_url)
  1477. # 复用已加载的配置,避免重复加载
  1478. analyzer = NewsAnalyzer(config=config)
  1479. # 设置更新信息(复用已获取的远程版本,不再重复请求)
  1480. if analyzer.is_github_actions and need_update and remote_version:
  1481. analyzer.update_info = {
  1482. "current_version": __version__,
  1483. "remote_version": remote_version,
  1484. }
  1485. # 获取 debug 配置
  1486. debug_mode = analyzer.ctx.config.get("DEBUG", False)
  1487. analyzer.run()
  1488. except FileNotFoundError as e:
  1489. print(f"❌ 配置文件错误: {e}")
  1490. print("\n请确保以下文件存在:")
  1491. print(" • config/config.yaml")
  1492. print(" • config/frequency_words.txt")
  1493. print("\n参考项目文档进行正确配置")
  1494. except Exception as e:
  1495. print(f"❌ 程序运行错误: {e}")
  1496. if debug_mode:
  1497. raise
  1498. def _handle_status_commands(config: Dict, args) -> None:
  1499. """处理状态查看命令 - 显示当前调度状态"""
  1500. from trendradar.context import AppContext
  1501. ctx = AppContext(config)
  1502. print("=" * 60)
  1503. print(f"TrendRadar v{__version__} 调度状态")
  1504. print("=" * 60)
  1505. try:
  1506. scheduler = ctx.create_scheduler()
  1507. schedule = scheduler.resolve()
  1508. now = ctx.get_time()
  1509. date_str = ctx.format_date()
  1510. print(f"\n⏰ 当前时间: {now.strftime('%Y-%m-%d %H:%M:%S')} ({ctx.timezone})")
  1511. print(f"📅 当前日期: {date_str}")
  1512. print(f"\n📋 调度信息:")
  1513. print(f" 日计划: {schedule.day_plan}")
  1514. if schedule.period_key:
  1515. print(f" 当前时间段: {schedule.period_name or schedule.period_key} ({schedule.period_key})")
  1516. else:
  1517. print(f" 当前时间段: 无(使用默认配置)")
  1518. print(f"\n🔧 行为开关:")
  1519. print(f" 采集数据: {'✅ 是' if schedule.collect else '❌ 否'}")
  1520. print(f" AI 分析: {'✅ 是' if schedule.analyze else '❌ 否'}")
  1521. print(f" 推送通知: {'✅ 是' if schedule.push else '❌ 否'}")
  1522. print(f" 报告模式: {schedule.report_mode}")
  1523. print(f" AI 模式: {schedule.ai_mode}")
  1524. if schedule.period_key:
  1525. print(f"\n🔁 一次性控制:")
  1526. if schedule.once_analyze:
  1527. already_analyzed = scheduler.already_executed(schedule.period_key, "analyze", date_str)
  1528. print(f" AI 分析: 仅一次 {'(今日已执行 ⚠️)' if already_analyzed else '(今日未执行 ✅)'}")
  1529. else:
  1530. print(f" AI 分析: 不限次数")
  1531. if schedule.once_push:
  1532. already_pushed = scheduler.already_executed(schedule.period_key, "push", date_str)
  1533. print(f" 推送通知: 仅一次 {'(今日已执行 ⚠️)' if already_pushed else '(今日未执行 ✅)'}")
  1534. else:
  1535. print(f" 推送通知: 不限次数")
  1536. except Exception as e:
  1537. print(f"\n❌ 获取调度状态失败: {e}")
  1538. print("\n" + "=" * 60)
  1539. # 清理资源
  1540. ctx.cleanup()
  1541. if __name__ == "__main__":
  1542. main()