__main__.py 73 KB

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