__main__.py 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364
  1. # coding=utf-8
  2. """
  3. TrendRadar 主程序
  4. 热点新闻聚合与分析工具
  5. 支持: python -m trendradar
  6. """
  7. import os
  8. import webbrowser
  9. from pathlib import Path
  10. from typing import Dict, List, Tuple, Optional
  11. import requests
  12. from trendradar.context import AppContext
  13. from trendradar import __version__
  14. from trendradar.core import load_config
  15. from trendradar.core.analyzer import convert_keyword_stats_to_platform_stats
  16. from trendradar.crawler import DataFetcher
  17. from trendradar.storage import convert_crawl_results_to_news_data
  18. from trendradar.utils.time import is_within_days
  19. from trendradar.ai import AIAnalyzer, AIAnalysisResult
  20. def check_version_update(
  21. current_version: str, version_url: str, proxy_url: Optional[str] = None
  22. ) -> Tuple[bool, Optional[str]]:
  23. """检查版本更新"""
  24. try:
  25. proxies = None
  26. if proxy_url:
  27. proxies = {"http": proxy_url, "https": proxy_url}
  28. headers = {
  29. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
  30. "Accept": "text/plain, */*",
  31. "Cache-Control": "no-cache",
  32. }
  33. response = requests.get(
  34. version_url, proxies=proxies, headers=headers, timeout=10
  35. )
  36. response.raise_for_status()
  37. remote_version = response.text.strip()
  38. print(f"当前版本: {current_version}, 远程版本: {remote_version}")
  39. # 比较版本
  40. def parse_version(version_str):
  41. try:
  42. parts = version_str.strip().split(".")
  43. if len(parts) != 3:
  44. raise ValueError("版本号格式不正确")
  45. return int(parts[0]), int(parts[1]), int(parts[2])
  46. except:
  47. return 0, 0, 0
  48. current_tuple = parse_version(current_version)
  49. remote_tuple = parse_version(remote_version)
  50. need_update = current_tuple < remote_tuple
  51. return need_update, remote_version if need_update else None
  52. except Exception as e:
  53. print(f"版本检查失败: {e}")
  54. return False, None
  55. # === 主分析器 ===
  56. class NewsAnalyzer:
  57. """新闻分析器"""
  58. # 模式策略定义
  59. MODE_STRATEGIES = {
  60. "incremental": {
  61. "mode_name": "增量模式",
  62. "description": "增量模式(只关注新增新闻,无新增时不推送)",
  63. "report_type": "增量分析",
  64. "should_send_notification": True,
  65. },
  66. "current": {
  67. "mode_name": "当前榜单模式",
  68. "description": "当前榜单模式(当前榜单匹配新闻 + 新增新闻区域 + 按时推送)",
  69. "report_type": "当前榜单",
  70. "should_send_notification": True,
  71. },
  72. "daily": {
  73. "mode_name": "全天汇总模式",
  74. "description": "全天汇总模式(所有匹配新闻 + 新增新闻区域 + 按时推送)",
  75. "report_type": "全天汇总",
  76. "should_send_notification": True,
  77. },
  78. }
  79. def __init__(self):
  80. # 加载配置
  81. print("正在加载配置...")
  82. config = load_config()
  83. print(f"TrendRadar v{__version__} 配置加载完成")
  84. print(f"监控平台数量: {len(config['PLATFORMS'])}")
  85. print(f"时区: {config.get('TIMEZONE', 'Asia/Shanghai')}")
  86. # 创建应用上下文
  87. self.ctx = AppContext(config)
  88. self.request_interval = self.ctx.config["REQUEST_INTERVAL"]
  89. self.report_mode = self.ctx.config["REPORT_MODE"]
  90. self.rank_threshold = self.ctx.rank_threshold
  91. self.is_github_actions = os.environ.get("GITHUB_ACTIONS") == "true"
  92. self.is_docker_container = self._detect_docker_environment()
  93. self.update_info = None
  94. self.proxy_url = None
  95. self._setup_proxy()
  96. self.data_fetcher = DataFetcher(self.proxy_url)
  97. # 初始化存储管理器(使用 AppContext)
  98. self._init_storage_manager()
  99. if self.is_github_actions:
  100. self._check_version_update()
  101. def _init_storage_manager(self) -> None:
  102. """初始化存储管理器(使用 AppContext)"""
  103. # 获取数据保留天数(支持环境变量覆盖)
  104. env_retention = os.environ.get("STORAGE_RETENTION_DAYS", "").strip()
  105. if env_retention:
  106. # 环境变量覆盖配置
  107. self.ctx.config["STORAGE"]["RETENTION_DAYS"] = int(env_retention)
  108. self.storage_manager = self.ctx.get_storage_manager()
  109. print(f"存储后端: {self.storage_manager.backend_name}")
  110. retention_days = self.ctx.config.get("STORAGE", {}).get("RETENTION_DAYS", 0)
  111. if retention_days > 0:
  112. print(f"数据保留天数: {retention_days} 天")
  113. def _detect_docker_environment(self) -> bool:
  114. """检测是否运行在 Docker 容器中"""
  115. try:
  116. if os.environ.get("DOCKER_CONTAINER") == "true":
  117. return True
  118. if os.path.exists("/.dockerenv"):
  119. return True
  120. return False
  121. except Exception:
  122. return False
  123. def _should_open_browser(self) -> bool:
  124. """判断是否应该打开浏览器"""
  125. return not self.is_github_actions and not self.is_docker_container
  126. def _setup_proxy(self) -> None:
  127. """设置代理配置"""
  128. if not self.is_github_actions and self.ctx.config["USE_PROXY"]:
  129. self.proxy_url = self.ctx.config["DEFAULT_PROXY"]
  130. print("本地环境,使用代理")
  131. elif not self.is_github_actions and not self.ctx.config["USE_PROXY"]:
  132. print("本地环境,未启用代理")
  133. else:
  134. print("GitHub Actions环境,不使用代理")
  135. def _check_version_update(self) -> None:
  136. """检查版本更新"""
  137. try:
  138. need_update, remote_version = check_version_update(
  139. __version__, self.ctx.config["VERSION_CHECK_URL"], self.proxy_url
  140. )
  141. if need_update and remote_version:
  142. self.update_info = {
  143. "current_version": __version__,
  144. "remote_version": remote_version,
  145. }
  146. print(f"发现新版本: {remote_version} (当前: {__version__})")
  147. else:
  148. print("版本检查完成,当前为最新版本")
  149. except Exception as e:
  150. print(f"版本检查出错: {e}")
  151. def _get_mode_strategy(self) -> Dict:
  152. """获取当前模式的策略配置"""
  153. return self.MODE_STRATEGIES.get(self.report_mode, self.MODE_STRATEGIES["daily"])
  154. def _has_notification_configured(self) -> bool:
  155. """检查是否配置了任何通知渠道"""
  156. cfg = self.ctx.config
  157. return any(
  158. [
  159. cfg["FEISHU_WEBHOOK_URL"],
  160. cfg["DINGTALK_WEBHOOK_URL"],
  161. cfg["WEWORK_WEBHOOK_URL"],
  162. (cfg["TELEGRAM_BOT_TOKEN"] and cfg["TELEGRAM_CHAT_ID"]),
  163. (
  164. cfg["EMAIL_FROM"]
  165. and cfg["EMAIL_PASSWORD"]
  166. and cfg["EMAIL_TO"]
  167. ),
  168. (cfg["NTFY_SERVER_URL"] and cfg["NTFY_TOPIC"]),
  169. cfg["BARK_URL"],
  170. cfg["SLACK_WEBHOOK_URL"],
  171. cfg["GENERIC_WEBHOOK_URL"],
  172. ]
  173. )
  174. def _has_valid_content(
  175. self, stats: List[Dict], new_titles: Optional[Dict] = None
  176. ) -> bool:
  177. """检查是否有有效的新闻内容"""
  178. if self.report_mode == "incremental":
  179. # 增量模式:必须有新增标题且匹配了关键词才推送
  180. has_new_titles = bool(
  181. new_titles and any(len(titles) > 0 for titles in new_titles.values())
  182. )
  183. has_matched_news = any(stat["count"] > 0 for stat in stats)
  184. return has_new_titles and has_matched_news
  185. elif self.report_mode == "current":
  186. # current模式:只要stats有内容就说明有匹配的新闻
  187. return any(stat["count"] > 0 for stat in stats)
  188. else:
  189. # 当日汇总模式下,检查是否有匹配的频率词新闻或新增新闻
  190. has_matched_news = any(stat["count"] > 0 for stat in stats)
  191. has_new_news = bool(
  192. new_titles and any(len(titles) > 0 for titles in new_titles.values())
  193. )
  194. return has_matched_news or has_new_news
  195. def _run_ai_analysis(
  196. self,
  197. stats: List[Dict],
  198. rss_items: Optional[List[Dict]],
  199. mode: str,
  200. report_type: str,
  201. id_to_name: Optional[Dict],
  202. ) -> Optional[AIAnalysisResult]:
  203. """执行 AI 分析"""
  204. analysis_config = self.ctx.config.get("AI_ANALYSIS", {})
  205. if not analysis_config.get("ENABLED", False):
  206. return None
  207. print("[AI] 正在进行 AI 分析...")
  208. try:
  209. ai_config = self.ctx.config.get("AI", {})
  210. debug_mode = self.ctx.config.get("DEBUG", False)
  211. analyzer = AIAnalyzer(ai_config, analysis_config, self.ctx.get_time, debug=debug_mode)
  212. # 提取平台列表
  213. platforms = list(id_to_name.values()) if id_to_name else []
  214. # 提取关键词列表
  215. keywords = [s.get("word", "") for s in stats if s.get("word")] if stats else []
  216. result = analyzer.analyze(
  217. stats=stats,
  218. rss_stats=rss_items,
  219. report_mode=mode,
  220. report_type=report_type,
  221. platforms=platforms,
  222. keywords=keywords,
  223. )
  224. if result.success:
  225. if result.error:
  226. # 成功但有警告(如 JSON 解析问题但使用了原始文本)
  227. print(f"[AI] 分析完成(有警告: {result.error})")
  228. else:
  229. print("[AI] 分析完成")
  230. else:
  231. print(f"[AI] 分析失败: {result.error}")
  232. return result
  233. except Exception as e:
  234. import traceback
  235. error_type = type(e).__name__
  236. error_msg = str(e)
  237. # 截断过长的错误消息
  238. if len(error_msg) > 200:
  239. error_msg = error_msg[:200] + "..."
  240. print(f"[AI] 分析出错 ({error_type}): {error_msg}")
  241. # 详细错误日志到 stderr
  242. import sys
  243. print(f"[AI] 详细错误堆栈:", file=sys.stderr)
  244. traceback.print_exc(file=sys.stderr)
  245. return AIAnalysisResult(success=False, error=f"{error_type}: {error_msg}")
  246. def _load_analysis_data(
  247. self,
  248. quiet: bool = False,
  249. ) -> Optional[Tuple[Dict, Dict, Dict, Dict, List, List]]:
  250. """统一的数据加载和预处理,使用当前监控平台列表过滤历史数据"""
  251. try:
  252. # 获取当前配置的监控平台ID列表
  253. current_platform_ids = self.ctx.platform_ids
  254. if not quiet:
  255. print(f"当前监控平台: {current_platform_ids}")
  256. all_results, id_to_name, title_info = self.ctx.read_today_titles(
  257. current_platform_ids, quiet=quiet
  258. )
  259. if not all_results:
  260. print("没有找到当天的数据")
  261. return None
  262. total_titles = sum(len(titles) for titles in all_results.values())
  263. if not quiet:
  264. print(f"读取到 {total_titles} 个标题(已按当前监控平台过滤)")
  265. new_titles = self.ctx.detect_new_titles(current_platform_ids, quiet=quiet)
  266. word_groups, filter_words, global_filters = self.ctx.load_frequency_words()
  267. return (
  268. all_results,
  269. id_to_name,
  270. title_info,
  271. new_titles,
  272. word_groups,
  273. filter_words,
  274. global_filters,
  275. )
  276. except Exception as e:
  277. print(f"数据加载失败: {e}")
  278. return None
  279. def _prepare_current_title_info(self, results: Dict, time_info: str) -> Dict:
  280. """从当前抓取结果构建标题信息"""
  281. title_info = {}
  282. for source_id, titles_data in results.items():
  283. title_info[source_id] = {}
  284. for title, title_data in titles_data.items():
  285. ranks = title_data.get("ranks", [])
  286. url = title_data.get("url", "")
  287. mobile_url = title_data.get("mobileUrl", "")
  288. title_info[source_id][title] = {
  289. "first_time": time_info,
  290. "last_time": time_info,
  291. "count": 1,
  292. "ranks": ranks,
  293. "url": url,
  294. "mobileUrl": mobile_url,
  295. }
  296. return title_info
  297. def _prepare_standalone_data(
  298. self,
  299. results: Dict,
  300. id_to_name: Dict,
  301. title_info: Optional[Dict] = None,
  302. rss_items: Optional[List[Dict]] = None,
  303. ) -> Optional[Dict]:
  304. """
  305. 从原始数据中提取独立展示区数据
  306. Args:
  307. results: 原始爬取结果 {platform_id: {title: title_data}}
  308. id_to_name: 平台 ID 到名称的映射
  309. title_info: 标题元信息(含排名历史、时间等)
  310. rss_items: RSS 条目列表
  311. Returns:
  312. 独立展示数据字典,如果未启用返回 None
  313. """
  314. display_config = self.ctx.config.get("DISPLAY", {})
  315. regions = display_config.get("REGIONS", {})
  316. standalone_config = display_config.get("STANDALONE", {})
  317. if not regions.get("STANDALONE", False):
  318. return None
  319. platform_ids = standalone_config.get("PLATFORMS", [])
  320. rss_feed_ids = standalone_config.get("RSS_FEEDS", [])
  321. max_items = standalone_config.get("MAX_ITEMS", 20)
  322. if not platform_ids and not rss_feed_ids:
  323. return None
  324. standalone_data = {
  325. "platforms": [],
  326. "rss_feeds": [],
  327. }
  328. # 找出最新批次时间(类似 current 模式的过滤逻辑)
  329. latest_time = None
  330. if title_info:
  331. for source_titles in title_info.values():
  332. for title_data in source_titles.values():
  333. last_time = title_data.get("last_time", "")
  334. if last_time:
  335. if latest_time is None or last_time > latest_time:
  336. latest_time = last_time
  337. # 提取热榜平台数据
  338. for platform_id in platform_ids:
  339. if platform_id not in results:
  340. continue
  341. platform_name = id_to_name.get(platform_id, platform_id)
  342. platform_titles = results[platform_id]
  343. items = []
  344. for title, title_data in platform_titles.items():
  345. # 获取元信息(如果有 title_info)
  346. meta = {}
  347. if title_info and platform_id in title_info and title in title_info[platform_id]:
  348. meta = title_info[platform_id][title]
  349. # 只保留当前在榜的话题(last_time 等于最新时间)
  350. if latest_time and meta:
  351. if meta.get("last_time") != latest_time:
  352. continue
  353. # 使用当前热榜的排名数据(title_data)进行排序
  354. # title_data 包含的是爬虫返回的当前排名,用于保证独立展示区的顺序与热榜一致
  355. current_ranks = title_data.get("ranks", [])
  356. current_rank = current_ranks[-1] if current_ranks else 0
  357. # 用于显示的排名范围:合并历史排名和当前排名
  358. historical_ranks = meta.get("ranks", []) if meta else []
  359. # 合并去重,保持顺序
  360. all_ranks = historical_ranks.copy()
  361. for rank in current_ranks:
  362. if rank not in all_ranks:
  363. all_ranks.append(rank)
  364. display_ranks = all_ranks if all_ranks else current_ranks
  365. item = {
  366. "title": title,
  367. "url": title_data.get("url", ""),
  368. "mobileUrl": title_data.get("mobileUrl", ""),
  369. "rank": current_rank, # 用于排序的当前排名
  370. "ranks": display_ranks, # 用于显示的排名范围(历史+当前)
  371. "first_time": meta.get("first_time", ""),
  372. "last_time": meta.get("last_time", ""),
  373. "count": meta.get("count", 1),
  374. }
  375. items.append(item)
  376. # 按当前排名排序
  377. items.sort(key=lambda x: x["rank"] if x["rank"] > 0 else 9999)
  378. # 限制条数
  379. if max_items > 0:
  380. items = items[:max_items]
  381. if items:
  382. standalone_data["platforms"].append({
  383. "id": platform_id,
  384. "name": platform_name,
  385. "items": items,
  386. })
  387. # 提取 RSS 数据
  388. if rss_items and rss_feed_ids:
  389. # 按 feed_id 分组
  390. feed_items_map = {}
  391. for item in rss_items:
  392. feed_id = item.get("feed_id", "")
  393. if feed_id in rss_feed_ids:
  394. if feed_id not in feed_items_map:
  395. feed_items_map[feed_id] = {
  396. "name": item.get("feed_name", feed_id),
  397. "items": [],
  398. }
  399. feed_items_map[feed_id]["items"].append({
  400. "title": item.get("title", ""),
  401. "url": item.get("url", ""),
  402. "published_at": item.get("published_at", ""),
  403. "author": item.get("author", ""),
  404. })
  405. # 限制条数并添加到结果
  406. for feed_id in rss_feed_ids:
  407. if feed_id in feed_items_map:
  408. feed_data = feed_items_map[feed_id]
  409. items = feed_data["items"]
  410. if max_items > 0:
  411. items = items[:max_items]
  412. if items:
  413. standalone_data["rss_feeds"].append({
  414. "id": feed_id,
  415. "name": feed_data["name"],
  416. "items": items,
  417. })
  418. # 如果没有任何数据,返回 None
  419. if not standalone_data["platforms"] and not standalone_data["rss_feeds"]:
  420. return None
  421. return standalone_data
  422. def _run_analysis_pipeline(
  423. self,
  424. data_source: Dict,
  425. mode: str,
  426. title_info: Dict,
  427. new_titles: Dict,
  428. word_groups: List[Dict],
  429. filter_words: List[str],
  430. id_to_name: Dict,
  431. failed_ids: Optional[List] = None,
  432. global_filters: Optional[List[str]] = None,
  433. quiet: bool = False,
  434. rss_items: Optional[List[Dict]] = None,
  435. rss_new_items: Optional[List[Dict]] = None,
  436. standalone_data: Optional[Dict] = None,
  437. ) -> Tuple[List[Dict], Optional[str], Optional[AIAnalysisResult]]:
  438. """统一的分析流水线:数据处理 → 统计计算 → AI分析 → HTML生成"""
  439. # 统计计算(使用 AppContext)
  440. stats, total_titles = self.ctx.count_frequency(
  441. data_source,
  442. word_groups,
  443. filter_words,
  444. id_to_name,
  445. title_info,
  446. new_titles,
  447. mode=mode,
  448. global_filters=global_filters,
  449. quiet=quiet,
  450. )
  451. # 如果是 platform 模式,转换数据结构
  452. if self.ctx.display_mode == "platform" and stats:
  453. stats = convert_keyword_stats_to_platform_stats(
  454. stats,
  455. self.ctx.weight_config,
  456. self.ctx.rank_threshold,
  457. )
  458. # AI 分析(如果启用,用于 HTML 报告)
  459. ai_result = None
  460. ai_config = self.ctx.config.get("AI_ANALYSIS", {})
  461. if ai_config.get("ENABLED", False) and stats:
  462. # 获取模式策略来确定报告类型
  463. mode_strategy = self._get_mode_strategy()
  464. report_type = mode_strategy["report_type"]
  465. ai_result = self._run_ai_analysis(
  466. stats, rss_items, mode, report_type, id_to_name
  467. )
  468. # HTML生成(如果启用)
  469. html_file = None
  470. if self.ctx.config["STORAGE"]["FORMATS"]["HTML"]:
  471. html_file = self.ctx.generate_html(
  472. stats,
  473. total_titles,
  474. failed_ids=failed_ids,
  475. new_titles=new_titles,
  476. id_to_name=id_to_name,
  477. mode=mode,
  478. update_info=self.update_info if self.ctx.config["SHOW_VERSION_UPDATE"] else None,
  479. rss_items=rss_items,
  480. rss_new_items=rss_new_items,
  481. ai_analysis=ai_result,
  482. standalone_data=standalone_data,
  483. )
  484. return stats, html_file, ai_result
  485. def _send_notification_if_needed(
  486. self,
  487. stats: List[Dict],
  488. report_type: str,
  489. mode: str,
  490. failed_ids: Optional[List] = None,
  491. new_titles: Optional[Dict] = None,
  492. id_to_name: Optional[Dict] = None,
  493. html_file_path: Optional[str] = None,
  494. rss_items: Optional[List[Dict]] = None,
  495. rss_new_items: Optional[List[Dict]] = None,
  496. standalone_data: Optional[Dict] = None,
  497. ai_result: Optional[AIAnalysisResult] = None,
  498. ) -> bool:
  499. """统一的通知发送逻辑,包含所有判断条件,支持热榜+RSS合并推送+AI分析+独立展示区"""
  500. has_notification = self._has_notification_configured()
  501. cfg = self.ctx.config
  502. # 检查是否有有效内容(热榜或RSS)
  503. has_news_content = self._has_valid_content(stats, new_titles)
  504. has_rss_content = bool(rss_items and len(rss_items) > 0)
  505. has_any_content = has_news_content or has_rss_content
  506. # 计算热榜匹配条数
  507. news_count = sum(len(stat.get("titles", [])) for stat in stats) if stats else 0
  508. # rss_items 是统计列表 [{"word": "xx", "count": 5, ...}],需累加 count
  509. rss_count = sum(stat.get("count", 0) for stat in rss_items) if rss_items else 0
  510. if (
  511. cfg["ENABLE_NOTIFICATION"]
  512. and has_notification
  513. and has_any_content
  514. ):
  515. # 输出推送内容统计
  516. content_parts = []
  517. if news_count > 0:
  518. content_parts.append(f"热榜 {news_count} 条")
  519. if rss_count > 0:
  520. content_parts.append(f"RSS {rss_count} 条")
  521. total_count = news_count + rss_count
  522. print(f"[推送] 准备发送:{' + '.join(content_parts)},合计 {total_count} 条")
  523. # 推送窗口控制
  524. if cfg["PUSH_WINDOW"]["ENABLED"]:
  525. push_manager = self.ctx.create_push_manager()
  526. time_range_start = cfg["PUSH_WINDOW"]["TIME_RANGE"]["START"]
  527. time_range_end = cfg["PUSH_WINDOW"]["TIME_RANGE"]["END"]
  528. if not push_manager.is_in_time_range(time_range_start, time_range_end):
  529. now = self.ctx.get_time()
  530. print(
  531. f"推送窗口控制:当前时间 {now.strftime('%H:%M')} 不在推送时间窗口 {time_range_start}-{time_range_end} 内,跳过推送"
  532. )
  533. return False
  534. if cfg["PUSH_WINDOW"]["ONCE_PER_DAY"]:
  535. if push_manager.has_pushed_today():
  536. print(f"推送窗口控制:今天已推送过,跳过本次推送")
  537. return False
  538. else:
  539. print(f"推送窗口控制:今天首次推送")
  540. # AI 分析:优先使用传入的结果,避免重复分析
  541. if ai_result is None:
  542. ai_config = cfg.get("AI_ANALYSIS", {})
  543. if ai_config.get("ENABLED", False):
  544. ai_result = self._run_ai_analysis(
  545. stats, rss_items, mode, report_type, id_to_name
  546. )
  547. # 准备报告数据
  548. report_data = self.ctx.prepare_report(stats, failed_ids, new_titles, id_to_name, mode)
  549. # 是否发送版本更新信息
  550. update_info_to_send = self.update_info if cfg["SHOW_VERSION_UPDATE"] else None
  551. # 使用 NotificationDispatcher 发送到所有渠道(合并热榜+RSS+AI分析+独立展示区)
  552. dispatcher = self.ctx.create_notification_dispatcher()
  553. results = dispatcher.dispatch_all(
  554. report_data=report_data,
  555. report_type=report_type,
  556. update_info=update_info_to_send,
  557. proxy_url=self.proxy_url,
  558. mode=mode,
  559. html_file_path=html_file_path,
  560. rss_items=rss_items,
  561. rss_new_items=rss_new_items,
  562. ai_analysis=ai_result,
  563. standalone_data=standalone_data,
  564. )
  565. if not results:
  566. print("未配置任何通知渠道,跳过通知发送")
  567. return False
  568. # 如果成功发送了任何通知,且启用了每天只推一次,则记录推送
  569. if (
  570. cfg["PUSH_WINDOW"]["ENABLED"]
  571. and cfg["PUSH_WINDOW"]["ONCE_PER_DAY"]
  572. and any(results.values())
  573. ):
  574. push_manager = self.ctx.create_push_manager()
  575. push_manager.record_push(report_type)
  576. return True
  577. elif cfg["ENABLE_NOTIFICATION"] and not has_notification:
  578. print("⚠️ 警告:通知功能已启用但未配置任何通知渠道,将跳过通知发送")
  579. elif not cfg["ENABLE_NOTIFICATION"]:
  580. print(f"跳过{report_type}通知:通知功能已禁用")
  581. elif (
  582. cfg["ENABLE_NOTIFICATION"]
  583. and has_notification
  584. and not has_any_content
  585. ):
  586. mode_strategy = self._get_mode_strategy()
  587. if self.report_mode == "incremental":
  588. has_new = bool(
  589. new_titles and any(len(titles) > 0 for titles in new_titles.values())
  590. )
  591. if not has_new and not has_rss_content:
  592. print("跳过通知:增量模式下未检测到新增的新闻和RSS")
  593. elif not has_new:
  594. print("跳过通知:增量模式下新增新闻未匹配到关键词")
  595. else:
  596. print(
  597. f"跳过通知:{mode_strategy['mode_name']}下未检测到匹配的新闻"
  598. )
  599. return False
  600. def _initialize_and_check_config(self) -> None:
  601. """通用初始化和配置检查"""
  602. now = self.ctx.get_time()
  603. print(f"当前北京时间: {now.strftime('%Y-%m-%d %H:%M:%S')}")
  604. if not self.ctx.config["ENABLE_CRAWLER"]:
  605. print("爬虫功能已禁用(ENABLE_CRAWLER=False),程序退出")
  606. return
  607. has_notification = self._has_notification_configured()
  608. if not self.ctx.config["ENABLE_NOTIFICATION"]:
  609. print("通知功能已禁用(ENABLE_NOTIFICATION=False),将只进行数据抓取")
  610. elif not has_notification:
  611. print("未配置任何通知渠道,将只进行数据抓取,不发送通知")
  612. else:
  613. print("通知功能已启用,将发送通知")
  614. mode_strategy = self._get_mode_strategy()
  615. print(f"报告模式: {self.report_mode}")
  616. print(f"运行模式: {mode_strategy['description']}")
  617. def _crawl_data(self) -> Tuple[Dict, Dict, List]:
  618. """执行数据爬取"""
  619. ids = []
  620. for platform in self.ctx.platforms:
  621. if "name" in platform:
  622. ids.append((platform["id"], platform["name"]))
  623. else:
  624. ids.append(platform["id"])
  625. print(
  626. f"配置的监控平台: {[p.get('name', p['id']) for p in self.ctx.platforms]}"
  627. )
  628. print(f"开始爬取数据,请求间隔 {self.request_interval} 毫秒")
  629. Path("output").mkdir(parents=True, exist_ok=True)
  630. results, id_to_name, failed_ids = self.data_fetcher.crawl_websites(
  631. ids, self.request_interval
  632. )
  633. # 转换为 NewsData 格式并保存到存储后端
  634. crawl_time = self.ctx.format_time()
  635. crawl_date = self.ctx.format_date()
  636. news_data = convert_crawl_results_to_news_data(
  637. results, id_to_name, failed_ids, crawl_time, crawl_date
  638. )
  639. # 保存到存储后端(SQLite)
  640. if self.storage_manager.save_news_data(news_data):
  641. print(f"数据已保存到存储后端: {self.storage_manager.backend_name}")
  642. # 保存 TXT 快照(如果启用)
  643. txt_file = self.storage_manager.save_txt_snapshot(news_data)
  644. if txt_file:
  645. print(f"TXT 快照已保存: {txt_file}")
  646. # 兼容:同时保存到原有 TXT 格式(确保向后兼容)
  647. if self.ctx.config["STORAGE"]["FORMATS"]["TXT"]:
  648. title_file = self.ctx.save_titles(results, id_to_name, failed_ids)
  649. print(f"标题已保存到: {title_file}")
  650. return results, id_to_name, failed_ids
  651. def _crawl_rss_data(self) -> Tuple[Optional[List[Dict]], Optional[List[Dict]], Optional[List[Dict]]]:
  652. """
  653. 执行 RSS 数据抓取
  654. Returns:
  655. (rss_items, rss_new_items, raw_rss_items) 元组:
  656. - rss_items: 统计条目列表(按模式处理,用于统计区块)
  657. - rss_new_items: 新增条目列表(用于新增区块)
  658. - raw_rss_items: 原始 RSS 条目列表(用于独立展示区)
  659. 如果未启用或失败返回 (None, None, None)
  660. """
  661. if not self.ctx.rss_enabled:
  662. return None, None, None
  663. rss_feeds = self.ctx.rss_feeds
  664. if not rss_feeds:
  665. print("[RSS] 未配置任何 RSS 源")
  666. return None, None, None
  667. try:
  668. from trendradar.crawler.rss import RSSFetcher, RSSFeedConfig
  669. # 构建 RSS 源配置
  670. feeds = []
  671. for feed_config in rss_feeds:
  672. # 读取并验证单个 feed 的 max_age_days(可选)
  673. max_age_days_raw = feed_config.get("max_age_days")
  674. max_age_days = None
  675. if max_age_days_raw is not None:
  676. try:
  677. max_age_days = int(max_age_days_raw)
  678. if max_age_days < 0:
  679. feed_id = feed_config.get("id", "unknown")
  680. print(f"[警告] RSS feed '{feed_id}' 的 max_age_days 为负数,将使用全局默认值")
  681. max_age_days = None
  682. except (ValueError, TypeError):
  683. feed_id = feed_config.get("id", "unknown")
  684. print(f"[警告] RSS feed '{feed_id}' 的 max_age_days 格式错误:{max_age_days_raw}")
  685. max_age_days = None
  686. feed = RSSFeedConfig(
  687. id=feed_config.get("id", ""),
  688. name=feed_config.get("name", ""),
  689. url=feed_config.get("url", ""),
  690. max_items=feed_config.get("max_items", 50),
  691. enabled=feed_config.get("enabled", True),
  692. max_age_days=max_age_days, # None=使用全局,0=禁用,>0=覆盖
  693. )
  694. if feed.id and feed.url and feed.enabled:
  695. feeds.append(feed)
  696. if not feeds:
  697. print("[RSS] 没有启用的 RSS 源")
  698. return None, None, None
  699. # 创建抓取器
  700. rss_config = self.ctx.rss_config
  701. # RSS 代理:优先使用 RSS 专属代理,否则使用爬虫默认代理
  702. rss_proxy_url = rss_config.get("PROXY_URL", "") or self.proxy_url or ""
  703. # 获取配置的时区
  704. timezone = self.ctx.config.get("TIMEZONE", "Asia/Shanghai")
  705. # 获取新鲜度过滤配置
  706. freshness_config = rss_config.get("FRESHNESS_FILTER", {})
  707. freshness_enabled = freshness_config.get("ENABLED", True)
  708. default_max_age_days = freshness_config.get("MAX_AGE_DAYS", 3)
  709. fetcher = RSSFetcher(
  710. feeds=feeds,
  711. request_interval=rss_config.get("REQUEST_INTERVAL", 2000),
  712. timeout=rss_config.get("TIMEOUT", 15),
  713. use_proxy=rss_config.get("USE_PROXY", False),
  714. proxy_url=rss_proxy_url,
  715. timezone=timezone,
  716. freshness_enabled=freshness_enabled,
  717. default_max_age_days=default_max_age_days,
  718. )
  719. # 抓取数据
  720. rss_data = fetcher.fetch_all()
  721. # 保存到存储后端
  722. if self.storage_manager.save_rss_data(rss_data):
  723. print(f"[RSS] 数据已保存到存储后端")
  724. # 处理 RSS 数据(按模式过滤)并返回用于合并推送
  725. return self._process_rss_data_by_mode(rss_data)
  726. else:
  727. print(f"[RSS] 数据保存失败")
  728. return None, None, None
  729. except ImportError as e:
  730. print(f"[RSS] 缺少依赖: {e}")
  731. print("[RSS] 请安装 feedparser: pip install feedparser")
  732. return None, None, None
  733. except Exception as e:
  734. print(f"[RSS] 抓取失败: {e}")
  735. return None, None, None
  736. def _process_rss_data_by_mode(self, rss_data) -> Tuple[Optional[List[Dict]], Optional[List[Dict]], Optional[List[Dict]]]:
  737. """
  738. 按报告模式处理 RSS 数据,返回与热榜相同格式的统计结构
  739. 三种模式:
  740. - daily: 当日汇总,统计=当天所有条目,新增=本次新增条目
  741. - current: 当前榜单,统计=当前榜单条目,新增=本次新增条目
  742. - incremental: 增量模式,统计=新增条目,新增=无
  743. Args:
  744. rss_data: 当前抓取的 RSSData 对象
  745. Returns:
  746. (rss_stats, rss_new_stats, raw_rss_items) 元组:
  747. - rss_stats: RSS 关键词统计列表(与热榜 stats 格式一致)
  748. - rss_new_stats: RSS 新增关键词统计列表(与热榜 stats 格式一致)
  749. - raw_rss_items: 原始 RSS 条目列表(用于独立展示区)
  750. """
  751. from trendradar.core.analyzer import count_rss_frequency
  752. # 从 display.regions.rss 统一控制 RSS 分析和展示
  753. rss_display_enabled = self.ctx.config.get("DISPLAY", {}).get("REGIONS", {}).get("RSS", True)
  754. # 加载关键词配置
  755. try:
  756. word_groups, filter_words, global_filters = self.ctx.load_frequency_words()
  757. except FileNotFoundError:
  758. word_groups, filter_words, global_filters = [], [], []
  759. timezone = self.ctx.timezone
  760. max_news_per_keyword = self.ctx.config.get("MAX_NEWS_PER_KEYWORD", 0)
  761. sort_by_position_first = self.ctx.config.get("SORT_BY_POSITION_FIRST", False)
  762. rss_stats = None
  763. rss_new_stats = None
  764. raw_rss_items = None # 原始 RSS 条目列表(用于独立展示区)
  765. # 1. 首先获取原始条目(用于独立展示区,不受 display.regions.rss 影响)
  766. # 根据模式获取原始条目
  767. if self.report_mode == "incremental":
  768. new_items_dict = self.storage_manager.detect_new_rss_items(rss_data)
  769. if new_items_dict:
  770. raw_rss_items = self._convert_rss_items_to_list(new_items_dict, rss_data.id_to_name)
  771. elif self.report_mode == "current":
  772. latest_data = self.storage_manager.get_latest_rss_data(rss_data.date)
  773. if latest_data:
  774. raw_rss_items = self._convert_rss_items_to_list(latest_data.items, latest_data.id_to_name)
  775. else: # daily
  776. all_data = self.storage_manager.get_rss_data(rss_data.date)
  777. if all_data:
  778. raw_rss_items = self._convert_rss_items_to_list(all_data.items, all_data.id_to_name)
  779. # 如果 RSS 展示未启用,跳过关键词分析,只返回原始条目用于独立展示区
  780. if not rss_display_enabled:
  781. return None, None, raw_rss_items
  782. # 2. 获取新增条目(用于统计)
  783. new_items_dict = self.storage_manager.detect_new_rss_items(rss_data)
  784. new_items_list = None
  785. if new_items_dict:
  786. new_items_list = self._convert_rss_items_to_list(new_items_dict, rss_data.id_to_name)
  787. if new_items_list:
  788. print(f"[RSS] 检测到 {len(new_items_list)} 条新增")
  789. # 3. 根据模式获取统计条目
  790. if self.report_mode == "incremental":
  791. # 增量模式:统计条目就是新增条目
  792. if not new_items_list:
  793. print("[RSS] 增量模式:没有新增 RSS 条目")
  794. return None, None, raw_rss_items
  795. rss_stats, total = count_rss_frequency(
  796. rss_items=new_items_list,
  797. word_groups=word_groups,
  798. filter_words=filter_words,
  799. global_filters=global_filters,
  800. new_items=new_items_list, # 增量模式所有都是新增
  801. max_news_per_keyword=max_news_per_keyword,
  802. sort_by_position_first=sort_by_position_first,
  803. timezone=timezone,
  804. rank_threshold=self.rank_threshold,
  805. quiet=False,
  806. )
  807. if not rss_stats:
  808. print("[RSS] 增量模式:关键词匹配后没有内容")
  809. # 即使关键词匹配为空,也返回原始条目用于独立展示区
  810. return None, None, raw_rss_items
  811. elif self.report_mode == "current":
  812. # 当前榜单模式:统计=当前榜单所有条目
  813. # raw_rss_items 已在前面获取
  814. if not raw_rss_items:
  815. print("[RSS] 当前榜单模式:没有 RSS 数据")
  816. return None, None, None
  817. rss_stats, total = count_rss_frequency(
  818. rss_items=raw_rss_items,
  819. word_groups=word_groups,
  820. filter_words=filter_words,
  821. global_filters=global_filters,
  822. new_items=new_items_list, # 标记新增
  823. max_news_per_keyword=max_news_per_keyword,
  824. sort_by_position_first=sort_by_position_first,
  825. timezone=timezone,
  826. rank_threshold=self.rank_threshold,
  827. quiet=False,
  828. )
  829. if not rss_stats:
  830. print("[RSS] 当前榜单模式:关键词匹配后没有内容")
  831. # 即使关键词匹配为空,也返回原始条目用于独立展示区
  832. return None, None, raw_rss_items
  833. # 生成新增统计
  834. if new_items_list:
  835. rss_new_stats, _ = count_rss_frequency(
  836. rss_items=new_items_list,
  837. word_groups=word_groups,
  838. filter_words=filter_words,
  839. global_filters=global_filters,
  840. new_items=new_items_list,
  841. max_news_per_keyword=max_news_per_keyword,
  842. sort_by_position_first=sort_by_position_first,
  843. timezone=timezone,
  844. rank_threshold=self.rank_threshold,
  845. quiet=True,
  846. )
  847. else:
  848. # daily 模式:统计=当天所有条目
  849. # raw_rss_items 已在前面获取
  850. if not raw_rss_items:
  851. print("[RSS] 当日汇总模式:没有 RSS 数据")
  852. return None, None, None
  853. rss_stats, total = count_rss_frequency(
  854. rss_items=raw_rss_items,
  855. word_groups=word_groups,
  856. filter_words=filter_words,
  857. global_filters=global_filters,
  858. new_items=new_items_list, # 标记新增
  859. max_news_per_keyword=max_news_per_keyword,
  860. sort_by_position_first=sort_by_position_first,
  861. timezone=timezone,
  862. rank_threshold=self.rank_threshold,
  863. quiet=False,
  864. )
  865. if not rss_stats:
  866. print("[RSS] 当日汇总模式:关键词匹配后没有内容")
  867. # 即使关键词匹配为空,也返回原始条目用于独立展示区
  868. return None, None, raw_rss_items
  869. # 生成新增统计
  870. if new_items_list:
  871. rss_new_stats, _ = count_rss_frequency(
  872. rss_items=new_items_list,
  873. word_groups=word_groups,
  874. filter_words=filter_words,
  875. global_filters=global_filters,
  876. new_items=new_items_list,
  877. max_news_per_keyword=max_news_per_keyword,
  878. sort_by_position_first=sort_by_position_first,
  879. timezone=timezone,
  880. rank_threshold=self.rank_threshold,
  881. quiet=True,
  882. )
  883. return rss_stats, rss_new_stats, raw_rss_items
  884. def _convert_rss_items_to_list(self, items_dict: Dict, id_to_name: Dict) -> List[Dict]:
  885. """将 RSS 条目字典转换为列表格式,并应用新鲜度过滤(用于推送)"""
  886. rss_items = []
  887. filtered_count = 0
  888. # 获取新鲜度过滤配置
  889. rss_config = self.ctx.rss_config
  890. freshness_config = rss_config.get("FRESHNESS_FILTER", {})
  891. freshness_enabled = freshness_config.get("ENABLED", True)
  892. default_max_age_days = freshness_config.get("MAX_AGE_DAYS", 3)
  893. timezone = self.ctx.config.get("TIMEZONE", "Asia/Shanghai")
  894. # 构建 feed_id -> max_age_days 的映射
  895. feed_max_age_map = {}
  896. for feed_cfg in self.ctx.rss_feeds:
  897. feed_id = feed_cfg.get("id", "")
  898. max_age = feed_cfg.get("max_age_days")
  899. if max_age is not None:
  900. try:
  901. feed_max_age_map[feed_id] = int(max_age)
  902. except (ValueError, TypeError):
  903. pass
  904. for feed_id, items in items_dict.items():
  905. # 确定此 feed 的 max_age_days
  906. max_days = feed_max_age_map.get(feed_id)
  907. if max_days is None:
  908. max_days = default_max_age_days
  909. for item in items:
  910. # 应用新鲜度过滤(仅在启用时)
  911. if freshness_enabled and max_days > 0:
  912. if item.published_at and not is_within_days(item.published_at, max_days, timezone):
  913. filtered_count += 1
  914. continue # 跳过超过指定天数的文章
  915. rss_items.append({
  916. "title": item.title,
  917. "feed_id": feed_id,
  918. "feed_name": id_to_name.get(feed_id, feed_id),
  919. "url": item.url,
  920. "published_at": item.published_at,
  921. "summary": item.summary,
  922. "author": item.author,
  923. })
  924. # 输出过滤统计
  925. if filtered_count > 0:
  926. print(f"[RSS] 新鲜度过滤:跳过 {filtered_count} 篇超过指定天数的旧文章(仍保留在数据库中)")
  927. return rss_items
  928. def _filter_rss_by_keywords(self, rss_items: List[Dict]) -> List[Dict]:
  929. """使用 frequency_words.txt 过滤 RSS 条目"""
  930. try:
  931. word_groups, filter_words, global_filters = self.ctx.load_frequency_words()
  932. if word_groups or filter_words or global_filters:
  933. from trendradar.core.frequency import matches_word_groups
  934. filtered_items = []
  935. for item in rss_items:
  936. title = item.get("title", "")
  937. if matches_word_groups(title, word_groups, filter_words, global_filters):
  938. filtered_items.append(item)
  939. original_count = len(rss_items)
  940. rss_items = filtered_items
  941. print(f"[RSS] 关键词过滤后剩余 {len(rss_items)}/{original_count} 条")
  942. if not rss_items:
  943. print("[RSS] 关键词过滤后没有匹配内容")
  944. return []
  945. except FileNotFoundError:
  946. # frequency_words.txt 不存在时跳过过滤
  947. pass
  948. return rss_items
  949. def _generate_rss_html_report(self, rss_items: list, feeds_info: dict) -> str:
  950. """生成 RSS HTML 报告"""
  951. try:
  952. from trendradar.report.rss_html import render_rss_html_content
  953. from pathlib import Path
  954. html_content = render_rss_html_content(
  955. rss_items=rss_items,
  956. total_count=len(rss_items),
  957. feeds_info=feeds_info,
  958. get_time_func=self.ctx.get_time,
  959. )
  960. # 保存 HTML 文件(扁平化结构:output/html/日期/)
  961. date_folder = self.ctx.format_date()
  962. time_filename = self.ctx.format_time()
  963. output_dir = Path("output") / "html" / date_folder
  964. output_dir.mkdir(parents=True, exist_ok=True)
  965. file_path = output_dir / f"rss_{time_filename}.html"
  966. with open(file_path, "w", encoding="utf-8") as f:
  967. f.write(html_content)
  968. print(f"[RSS] HTML 报告已生成: {file_path}")
  969. return str(file_path)
  970. except Exception as e:
  971. print(f"[RSS] 生成 HTML 报告失败: {e}")
  972. return None
  973. def _execute_mode_strategy(
  974. self, mode_strategy: Dict, results: Dict, id_to_name: Dict, failed_ids: List,
  975. rss_items: Optional[List[Dict]] = None,
  976. rss_new_items: Optional[List[Dict]] = None,
  977. raw_rss_items: Optional[List[Dict]] = None,
  978. ) -> Optional[str]:
  979. """执行模式特定逻辑,支持热榜+RSS合并推送
  980. 简化后的逻辑:
  981. - 每次运行都生成 HTML 报告(时间戳快照 + latest/{mode}.html + index.html)
  982. - 根据模式发送通知
  983. """
  984. # 获取当前监控平台ID列表
  985. current_platform_ids = self.ctx.platform_ids
  986. new_titles = self.ctx.detect_new_titles(current_platform_ids)
  987. time_info = self.ctx.format_time()
  988. if self.ctx.config["STORAGE"]["FORMATS"]["TXT"]:
  989. self.ctx.save_titles(results, id_to_name, failed_ids)
  990. word_groups, filter_words, global_filters = self.ctx.load_frequency_words()
  991. html_file = None
  992. stats = []
  993. ai_result = None
  994. title_info = None
  995. # current 模式需要使用完整的历史数据
  996. if self.report_mode == "current":
  997. analysis_data = self._load_analysis_data()
  998. if analysis_data:
  999. (
  1000. all_results,
  1001. historical_id_to_name,
  1002. historical_title_info,
  1003. historical_new_titles,
  1004. _,
  1005. _,
  1006. _,
  1007. ) = analysis_data
  1008. print(
  1009. f"current模式:使用过滤后的历史数据,包含平台:{list(all_results.keys())}"
  1010. )
  1011. # 使用历史数据准备独立展示区数据(包含完整的 title_info)
  1012. standalone_data = self._prepare_standalone_data(
  1013. all_results, historical_id_to_name, historical_title_info, raw_rss_items
  1014. )
  1015. stats, html_file, ai_result = self._run_analysis_pipeline(
  1016. all_results,
  1017. self.report_mode,
  1018. historical_title_info,
  1019. historical_new_titles,
  1020. word_groups,
  1021. filter_words,
  1022. historical_id_to_name,
  1023. failed_ids=failed_ids,
  1024. global_filters=global_filters,
  1025. rss_items=rss_items,
  1026. rss_new_items=rss_new_items,
  1027. standalone_data=standalone_data,
  1028. )
  1029. combined_id_to_name = {**historical_id_to_name, **id_to_name}
  1030. new_titles = historical_new_titles
  1031. id_to_name = combined_id_to_name
  1032. title_info = historical_title_info
  1033. results = all_results
  1034. else:
  1035. print("❌ 严重错误:无法读取刚保存的数据文件")
  1036. raise RuntimeError("数据一致性检查失败:保存后立即读取失败")
  1037. elif self.report_mode == "daily":
  1038. # daily 模式:使用全天累计数据
  1039. analysis_data = self._load_analysis_data()
  1040. if analysis_data:
  1041. (
  1042. all_results,
  1043. historical_id_to_name,
  1044. historical_title_info,
  1045. historical_new_titles,
  1046. _,
  1047. _,
  1048. _,
  1049. ) = analysis_data
  1050. # 使用历史数据准备独立展示区数据(包含完整的 title_info)
  1051. standalone_data = self._prepare_standalone_data(
  1052. all_results, historical_id_to_name, historical_title_info, raw_rss_items
  1053. )
  1054. stats, html_file, ai_result = self._run_analysis_pipeline(
  1055. all_results,
  1056. self.report_mode,
  1057. historical_title_info,
  1058. historical_new_titles,
  1059. word_groups,
  1060. filter_words,
  1061. historical_id_to_name,
  1062. failed_ids=failed_ids,
  1063. global_filters=global_filters,
  1064. rss_items=rss_items,
  1065. rss_new_items=rss_new_items,
  1066. standalone_data=standalone_data,
  1067. )
  1068. combined_id_to_name = {**historical_id_to_name, **id_to_name}
  1069. new_titles = historical_new_titles
  1070. id_to_name = combined_id_to_name
  1071. title_info = historical_title_info
  1072. results = all_results
  1073. else:
  1074. # 没有历史数据时使用当前数据
  1075. title_info = self._prepare_current_title_info(results, time_info)
  1076. standalone_data = self._prepare_standalone_data(
  1077. results, id_to_name, title_info, raw_rss_items
  1078. )
  1079. stats, html_file, ai_result = self._run_analysis_pipeline(
  1080. results,
  1081. self.report_mode,
  1082. title_info,
  1083. new_titles,
  1084. word_groups,
  1085. filter_words,
  1086. id_to_name,
  1087. failed_ids=failed_ids,
  1088. global_filters=global_filters,
  1089. rss_items=rss_items,
  1090. rss_new_items=rss_new_items,
  1091. standalone_data=standalone_data,
  1092. )
  1093. else:
  1094. # incremental 模式:只使用当前抓取的数据
  1095. title_info = self._prepare_current_title_info(results, time_info)
  1096. standalone_data = self._prepare_standalone_data(
  1097. results, id_to_name, title_info, raw_rss_items
  1098. )
  1099. stats, html_file, ai_result = self._run_analysis_pipeline(
  1100. results,
  1101. self.report_mode,
  1102. title_info,
  1103. new_titles,
  1104. word_groups,
  1105. filter_words,
  1106. id_to_name,
  1107. failed_ids=failed_ids,
  1108. global_filters=global_filters,
  1109. rss_items=rss_items,
  1110. rss_new_items=rss_new_items,
  1111. standalone_data=standalone_data,
  1112. )
  1113. if html_file:
  1114. print(f"HTML报告已生成: {html_file}")
  1115. print(f"最新报告已更新: output/html/latest/{self.report_mode}.html")
  1116. # 发送通知
  1117. if mode_strategy["should_send_notification"]:
  1118. standalone_data = self._prepare_standalone_data(
  1119. results, id_to_name, title_info, raw_rss_items
  1120. )
  1121. self._send_notification_if_needed(
  1122. stats,
  1123. mode_strategy["report_type"],
  1124. self.report_mode,
  1125. failed_ids=failed_ids,
  1126. new_titles=new_titles,
  1127. id_to_name=id_to_name,
  1128. html_file_path=html_file,
  1129. rss_items=rss_items,
  1130. rss_new_items=rss_new_items,
  1131. standalone_data=standalone_data,
  1132. ai_result=ai_result,
  1133. )
  1134. # 打开浏览器(仅在非容器环境)
  1135. if self._should_open_browser() and html_file:
  1136. file_url = "file://" + str(Path(html_file).resolve())
  1137. print(f"正在打开HTML报告: {file_url}")
  1138. webbrowser.open(file_url)
  1139. elif self.is_docker_container and html_file:
  1140. print(f"HTML报告已生成(Docker环境): {html_file}")
  1141. return html_file
  1142. def run(self) -> None:
  1143. """执行分析流程"""
  1144. try:
  1145. self._initialize_and_check_config()
  1146. mode_strategy = self._get_mode_strategy()
  1147. # 抓取热榜数据
  1148. results, id_to_name, failed_ids = self._crawl_data()
  1149. # 抓取 RSS 数据(如果启用),返回统计条目、新增条目和原始条目
  1150. rss_items, rss_new_items, raw_rss_items = self._crawl_rss_data()
  1151. # 执行模式策略,传递 RSS 数据用于合并推送
  1152. self._execute_mode_strategy(
  1153. mode_strategy, results, id_to_name, failed_ids,
  1154. rss_items=rss_items, rss_new_items=rss_new_items,
  1155. raw_rss_items=raw_rss_items
  1156. )
  1157. except Exception as e:
  1158. print(f"分析流程执行出错: {e}")
  1159. if self.ctx.config.get("DEBUG", False):
  1160. raise
  1161. finally:
  1162. # 清理资源(包括过期数据清理和数据库连接关闭)
  1163. self.ctx.cleanup()
  1164. def main():
  1165. """主程序入口"""
  1166. debug_mode = False
  1167. try:
  1168. analyzer = NewsAnalyzer()
  1169. # 获取 debug 配置
  1170. debug_mode = analyzer.ctx.config.get("DEBUG", False)
  1171. analyzer.run()
  1172. except FileNotFoundError as e:
  1173. print(f"❌ 配置文件错误: {e}")
  1174. print("\n请确保以下文件存在:")
  1175. print(" • config/config.yaml")
  1176. print(" • config/frequency_words.txt")
  1177. print("\n参考项目文档进行正确配置")
  1178. except Exception as e:
  1179. print(f"❌ 程序运行错误: {e}")
  1180. if debug_mode:
  1181. raise
  1182. if __name__ == "__main__":
  1183. main()