main.py 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680
  1. # coding=utf-8
  2. import json
  3. import time
  4. import random
  5. from datetime import datetime
  6. import webbrowser
  7. from typing import Dict, List, Tuple, Optional, Union
  8. from pathlib import Path
  9. import os
  10. import requests
  11. import pytz
  12. CONFIG = {
  13. "VERSION": "1.1.0",
  14. "VERSION_CHECK_URL": "https://raw.githubusercontent.com/sansan0/TrendRadar/refs/heads/master/version",
  15. "FEISHU_SHOW_VERSION_UPDATE": True, # 控制显示版本更新提示,改成 False 将不接受新版本提示
  16. "FEISHU_SEPARATOR": "━━━━━━━━━━━━━━━━━━━", # 飞书消息分割线,注意,其它类型的分割线可能会被飞书过滤而不显示
  17. "REQUEST_INTERVAL": 1000, # 请求间隔(毫秒)
  18. "FEISHU_REPORT_TYPE": "daily", # 飞书报告类型: "current"|"daily"|"both"
  19. "RANK_THRESHOLD": 5, # 排名高亮阈值
  20. "USE_PROXY": True, # 是否启用代理
  21. "DEFAULT_PROXY": "http://127.0.0.1:10086",
  22. "CONTINUE_WITHOUT_FEISHU": True, # 控制在没有飞书 webhook URL 时是否继续执行爬虫, 如果 True ,会依然进行爬虫行为,并在 github 上持续的生成爬取的新闻数据
  23. "FEISHU_WEBHOOK_URL": "", # 飞书机器人的 webhook URL,大概长这样:https://www.feishu.cn/flow/api/trigger-webhook/xxxx, 默认为空,推荐通过GitHub Secrets设置
  24. # 用于让关注度更高的新闻在更前面显示,这里是权重排序配置,合起来是 1就行(你可以微调,虽然我不建议动嘿嘿)
  25. "WEIGHT_CONFIG": {
  26. "RANK_WEIGHT": 0.6, # 排名
  27. "FREQUENCY_WEIGHT": 0.3, # 频次
  28. "HOTNESS_WEIGHT": 0.1, # 热度
  29. },
  30. }
  31. class TimeHelper:
  32. """时间处理工具"""
  33. @staticmethod
  34. def get_beijing_time() -> datetime:
  35. return datetime.now(pytz.timezone("Asia/Shanghai"))
  36. @staticmethod
  37. def format_date_folder() -> str:
  38. return TimeHelper.get_beijing_time().strftime("%Y年%m月%d日")
  39. @staticmethod
  40. def format_time_filename() -> str:
  41. return TimeHelper.get_beijing_time().strftime("%H时%M分")
  42. class VersionChecker:
  43. """版本检查工具"""
  44. @staticmethod
  45. def parse_version(version_str: str) -> Tuple[int, int, int]:
  46. """解析版本号字符串为元组"""
  47. try:
  48. parts = version_str.strip().split(".")
  49. if len(parts) != 3:
  50. raise ValueError("版本号格式不正确")
  51. return tuple(int(part) for part in parts)
  52. except (ValueError, AttributeError):
  53. print(f"无法解析版本号: {version_str}")
  54. return (0, 0, 0)
  55. @staticmethod
  56. def compare_versions(current: str, remote: str) -> int:
  57. """比较版本号"""
  58. current_tuple = VersionChecker.parse_version(current)
  59. remote_tuple = VersionChecker.parse_version(remote)
  60. if current_tuple < remote_tuple:
  61. return -1 # 需要更新
  62. elif current_tuple > remote_tuple:
  63. return 1 # 当前版本更新
  64. else:
  65. return 0 # 版本相同
  66. @staticmethod
  67. def check_for_updates(
  68. current_version: str,
  69. version_url: str,
  70. proxy_url: Optional[str] = None,
  71. timeout: int = 10,
  72. ) -> Tuple[bool, Optional[str]]:
  73. """检查是否有新版本"""
  74. try:
  75. proxies = None
  76. if proxy_url:
  77. proxies = {"http": proxy_url, "https": proxy_url}
  78. headers = {
  79. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
  80. "Accept": "text/plain, */*",
  81. "Cache-Control": "no-cache",
  82. }
  83. response = requests.get(
  84. version_url, proxies=proxies, headers=headers, timeout=timeout
  85. )
  86. response.raise_for_status()
  87. remote_version = response.text.strip()
  88. print(f"当前版本: {current_version}, 远程版本: {remote_version}")
  89. comparison = VersionChecker.compare_versions(
  90. current_version, remote_version
  91. )
  92. need_update = comparison == -1
  93. return need_update, remote_version if need_update else None
  94. except Exception as e:
  95. print(f"版本检查失败: {e}")
  96. return False, None
  97. class FileHelper:
  98. """文件操作工具"""
  99. @staticmethod
  100. def ensure_directory_exists(directory: str) -> None:
  101. Path(directory).mkdir(parents=True, exist_ok=True)
  102. @staticmethod
  103. def get_output_path(subfolder: str, filename: str) -> str:
  104. date_folder = TimeHelper.format_date_folder()
  105. output_dir = Path("output") / date_folder / subfolder
  106. FileHelper.ensure_directory_exists(str(output_dir))
  107. return str(output_dir / filename)
  108. class DataFetcher:
  109. """数据获取器"""
  110. def __init__(self, proxy_url: Optional[str] = None):
  111. self.proxy_url = proxy_url
  112. def fetch_data(
  113. self,
  114. id_info: Union[str, Tuple[str, str]],
  115. max_retries: int = 2,
  116. min_retry_wait: int = 3,
  117. max_retry_wait: int = 5,
  118. ) -> Tuple[Optional[str], str, str]:
  119. """获取指定ID数据,支持重试"""
  120. if isinstance(id_info, tuple):
  121. id_value, alias = id_info
  122. else:
  123. id_value = id_info
  124. alias = id_value
  125. url = f"https://newsnow.busiyi.world/api/s?id={id_value}&latest"
  126. proxies = None
  127. if self.proxy_url:
  128. proxies = {"http": self.proxy_url, "https": self.proxy_url}
  129. headers = {
  130. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
  131. "Accept": "application/json, text/plain, */*",
  132. "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
  133. "Connection": "keep-alive",
  134. "Cache-Control": "no-cache",
  135. }
  136. retries = 0
  137. while retries <= max_retries:
  138. try:
  139. response = requests.get(
  140. url, proxies=proxies, headers=headers, timeout=10
  141. )
  142. response.raise_for_status()
  143. data_text = response.text
  144. data_json = json.loads(data_text)
  145. status = data_json.get("status", "未知")
  146. if status not in ["success", "cache"]:
  147. raise ValueError(f"响应状态异常: {status}")
  148. status_info = "最新数据" if status == "success" else "缓存数据"
  149. print(f"获取 {id_value} 成功({status_info})")
  150. return data_text, id_value, alias
  151. except Exception as e:
  152. retries += 1
  153. if retries <= max_retries:
  154. base_wait = random.uniform(min_retry_wait, max_retry_wait)
  155. additional_wait = (retries - 1) * random.uniform(1, 2)
  156. wait_time = base_wait + additional_wait
  157. print(f"请求 {id_value} 失败: {e}. {wait_time:.2f}秒后重试...")
  158. time.sleep(wait_time)
  159. else:
  160. print(f"请求 {id_value} 失败: {e}")
  161. return None, id_value, alias
  162. return None, id_value, alias
  163. def crawl_websites(
  164. self,
  165. ids_list: List[Union[str, Tuple[str, str]]],
  166. request_interval: int = CONFIG["REQUEST_INTERVAL"],
  167. ) -> Tuple[Dict, Dict, List]:
  168. """爬取多个网站数据"""
  169. results = {}
  170. id_to_alias = {}
  171. failed_ids = []
  172. for i, id_info in enumerate(ids_list):
  173. if isinstance(id_info, tuple):
  174. id_value, alias = id_info
  175. else:
  176. id_value = id_info
  177. alias = id_value
  178. id_to_alias[id_value] = alias
  179. response, _, _ = self.fetch_data(id_info)
  180. if response:
  181. try:
  182. data = json.loads(response)
  183. results[id_value] = {}
  184. for index, item in enumerate(data.get("items", []), 1):
  185. title = item["title"]
  186. url = item.get("url", "")
  187. mobile_url = item.get("mobileUrl", "")
  188. if title in results[id_value]:
  189. results[id_value][title]["ranks"].append(index)
  190. else:
  191. results[id_value][title] = {
  192. "ranks": [index],
  193. "url": url,
  194. "mobileUrl": mobile_url,
  195. }
  196. except json.JSONDecodeError:
  197. print(f"解析 {id_value} 响应失败")
  198. failed_ids.append(id_value)
  199. except Exception as e:
  200. print(f"处理 {id_value} 数据出错: {e}")
  201. failed_ids.append(id_value)
  202. else:
  203. failed_ids.append(id_value)
  204. if i < len(ids_list) - 1:
  205. actual_interval = request_interval + random.randint(-10, 20)
  206. actual_interval = max(50, actual_interval)
  207. time.sleep(actual_interval / 1000)
  208. print(f"成功: {list(results.keys())}, 失败: {failed_ids}")
  209. return results, id_to_alias, failed_ids
  210. class DataProcessor:
  211. """数据处理器"""
  212. @staticmethod
  213. def detect_latest_new_titles(id_to_alias: Dict) -> Dict:
  214. """检测当日最新批次的新增标题"""
  215. date_folder = TimeHelper.format_date_folder()
  216. txt_dir = Path("output") / date_folder / "txt"
  217. if not txt_dir.exists():
  218. return {}
  219. files = sorted([f for f in txt_dir.iterdir() if f.suffix == ".txt"])
  220. if len(files) < 2:
  221. if len(files) == 1:
  222. return DataProcessor._parse_file_titles(files[0])
  223. return {}
  224. latest_file = files[-1]
  225. latest_titles = DataProcessor._parse_file_titles(latest_file)
  226. # 汇总历史标题
  227. historical_titles = {}
  228. for file_path in files[:-1]:
  229. historical_data = DataProcessor._parse_file_titles(file_path)
  230. for source_name, titles_data in historical_data.items():
  231. if source_name not in historical_titles:
  232. historical_titles[source_name] = set()
  233. for title in titles_data.keys():
  234. historical_titles[source_name].add(title)
  235. # 找出新增标题
  236. new_titles = {}
  237. for source_name, latest_source_titles in latest_titles.items():
  238. historical_set = historical_titles.get(source_name, set())
  239. source_new_titles = {}
  240. for title, title_data in latest_source_titles.items():
  241. if title not in historical_set:
  242. source_new_titles[title] = title_data
  243. if source_new_titles:
  244. source_id = None
  245. for id_val, alias in id_to_alias.items():
  246. if alias == source_name:
  247. source_id = id_val
  248. break
  249. if source_id:
  250. new_titles[source_id] = source_new_titles
  251. return new_titles
  252. @staticmethod
  253. def _parse_file_titles(file_path: Path) -> Dict:
  254. """解析单个txt文件的标题数据"""
  255. titles_by_source = {}
  256. with open(file_path, "r", encoding="utf-8") as f:
  257. content = f.read()
  258. sections = content.split("\n\n")
  259. for section in sections:
  260. if not section.strip() or "==== 以下ID请求失败 ====" in section:
  261. continue
  262. lines = section.strip().split("\n")
  263. if len(lines) < 2:
  264. continue
  265. source_name = lines[0].strip()
  266. titles_by_source[source_name] = {}
  267. for line in lines[1:]:
  268. if line.strip():
  269. try:
  270. title_part = line.strip()
  271. rank = None
  272. # 提取排名
  273. if (
  274. ". " in title_part
  275. and title_part.split(". ")[0].isdigit()
  276. ):
  277. rank_str, title_part = title_part.split(". ", 1)
  278. rank = int(rank_str)
  279. # 提取MOBILE URL
  280. mobile_url = ""
  281. if " [MOBILE:" in title_part:
  282. title_part, mobile_part = title_part.rsplit(
  283. " [MOBILE:", 1
  284. )
  285. if mobile_part.endswith("]"):
  286. mobile_url = mobile_part[:-1]
  287. # 提取URL
  288. url = ""
  289. if " [URL:" in title_part:
  290. title_part, url_part = title_part.rsplit(" [URL:", 1)
  291. if url_part.endswith("]"):
  292. url = url_part[:-1]
  293. title = title_part.strip()
  294. ranks = [rank] if rank is not None else [1]
  295. titles_by_source[source_name][title] = {
  296. "ranks": ranks,
  297. "url": url,
  298. "mobileUrl": mobile_url,
  299. }
  300. except Exception as e:
  301. print(f"解析标题行出错: {line}, 错误: {e}")
  302. return titles_by_source
  303. @staticmethod
  304. def save_titles_to_file(results: Dict, id_to_alias: Dict, failed_ids: List) -> str:
  305. """保存标题到文件"""
  306. file_path = FileHelper.get_output_path(
  307. "txt", f"{TimeHelper.format_time_filename()}.txt"
  308. )
  309. with open(file_path, "w", encoding="utf-8") as f:
  310. for id_value, title_data in results.items():
  311. display_name = id_to_alias.get(id_value, id_value)
  312. f.write(f"{display_name}\n")
  313. # 按排名排序标题
  314. sorted_titles = []
  315. for title, info in title_data.items():
  316. if isinstance(info, dict):
  317. ranks = info.get("ranks", [])
  318. url = info.get("url", "")
  319. mobile_url = info.get("mobileUrl", "")
  320. else:
  321. ranks = info if isinstance(info, list) else []
  322. url = ""
  323. mobile_url = ""
  324. rank = ranks[0] if ranks else 1
  325. sorted_titles.append((rank, title, url, mobile_url))
  326. sorted_titles.sort(key=lambda x: x[0])
  327. for rank, title, url, mobile_url in sorted_titles:
  328. line = f"{rank}. {title}"
  329. if url:
  330. line += f" [URL:{url}]"
  331. if mobile_url:
  332. line += f" [MOBILE:{mobile_url}]"
  333. f.write(line + "\n")
  334. f.write("\n")
  335. if failed_ids:
  336. f.write("==== 以下ID请求失败 ====\n")
  337. for id_value in failed_ids:
  338. display_name = id_to_alias.get(id_value, id_value)
  339. f.write(f"{display_name} (ID: {id_value})\n")
  340. return file_path
  341. @staticmethod
  342. def load_frequency_words(
  343. frequency_file: str = "frequency_words.txt",
  344. ) -> Tuple[List[Dict], List[str]]:
  345. """加载频率词配置"""
  346. frequency_path = Path(frequency_file)
  347. if not frequency_path.exists():
  348. print(f"频率词文件 {frequency_file} 不存在")
  349. return [], []
  350. with open(frequency_path, "r", encoding="utf-8") as f:
  351. content = f.read()
  352. word_groups = [
  353. group.strip() for group in content.split("\n\n") if group.strip()
  354. ]
  355. processed_groups = []
  356. filter_words = []
  357. for group in word_groups:
  358. words = [word.strip() for word in group.split("\n") if word.strip()]
  359. group_required_words = []
  360. group_normal_words = []
  361. group_filter_words = []
  362. for word in words:
  363. if word.startswith("!"):
  364. filter_words.append(word[1:])
  365. group_filter_words.append(word[1:])
  366. elif word.startswith("+"):
  367. group_required_words.append(word[1:])
  368. else:
  369. group_normal_words.append(word)
  370. if group_required_words or group_normal_words:
  371. if group_normal_words:
  372. group_key = " ".join(group_normal_words)
  373. else:
  374. group_key = " ".join(group_required_words)
  375. processed_groups.append(
  376. {
  377. "required": group_required_words,
  378. "normal": group_normal_words,
  379. "group_key": group_key,
  380. }
  381. )
  382. return processed_groups, filter_words
  383. @staticmethod
  384. def read_all_today_titles() -> Tuple[Dict, Dict, Dict]:
  385. """读取当天所有标题文件"""
  386. date_folder = TimeHelper.format_date_folder()
  387. txt_dir = Path("output") / date_folder / "txt"
  388. if not txt_dir.exists():
  389. return {}, {}, {}
  390. all_results = {}
  391. id_to_alias = {}
  392. title_info = {}
  393. files = sorted([f for f in txt_dir.iterdir() if f.suffix == ".txt"])
  394. for file_path in files:
  395. time_info = file_path.stem
  396. with open(file_path, "r", encoding="utf-8") as f:
  397. content = f.read()
  398. sections = content.split("\n\n")
  399. for section in sections:
  400. if not section.strip() or "==== 以下ID请求失败 ====" in section:
  401. continue
  402. lines = section.strip().split("\n")
  403. if len(lines) < 2:
  404. continue
  405. source_name = lines[0].strip()
  406. title_data = {}
  407. for line in lines[1:]:
  408. if line.strip():
  409. try:
  410. rank = None
  411. title_part = line.strip()
  412. # 提取行首的排名数字
  413. if (
  414. ". " in title_part
  415. and title_part.split(". ")[0].isdigit()
  416. ):
  417. parts = title_part.split(". ", 1)
  418. rank = int(parts[0])
  419. title_part = parts[1]
  420. # 提取 MOBILE URL
  421. mobile_url = ""
  422. if " [MOBILE:" in title_part:
  423. title_part, mobile_part = title_part.rsplit(
  424. " [MOBILE:", 1
  425. )
  426. if mobile_part.endswith("]"):
  427. mobile_url = mobile_part[:-1]
  428. # 提取 URL
  429. url = ""
  430. if " [URL:" in title_part:
  431. title_part, url_part = title_part.rsplit(
  432. " [URL:", 1
  433. )
  434. if url_part.endswith("]"):
  435. url = url_part[:-1]
  436. title = title_part.strip()
  437. ranks = [rank] if rank is not None else [1]
  438. title_data[title] = {
  439. "ranks": ranks,
  440. "url": url,
  441. "mobileUrl": mobile_url,
  442. }
  443. except Exception as e:
  444. print(f"解析标题行出错: {line}, 错误: {e}")
  445. DataProcessor._process_source_data(
  446. source_name,
  447. title_data,
  448. time_info,
  449. all_results,
  450. title_info,
  451. id_to_alias,
  452. )
  453. # 转换为ID格式
  454. id_results = {}
  455. id_title_info = {}
  456. for name, titles in all_results.items():
  457. for id_value, alias in id_to_alias.items():
  458. if alias == name:
  459. id_results[id_value] = titles
  460. id_title_info[id_value] = title_info[name]
  461. break
  462. return id_results, id_to_alias, id_title_info
  463. @staticmethod
  464. def _process_source_data(
  465. source_name: str,
  466. title_data: Dict,
  467. time_info: str,
  468. all_results: Dict,
  469. title_info: Dict,
  470. id_to_alias: Dict,
  471. ) -> None:
  472. """处理来源数据,合并重复标题"""
  473. if source_name not in all_results:
  474. all_results[source_name] = title_data
  475. if source_name not in title_info:
  476. title_info[source_name] = {}
  477. for title, data in title_data.items():
  478. ranks = data.get("ranks", [])
  479. url = data.get("url", "")
  480. mobile_url = data.get("mobileUrl", "")
  481. title_info[source_name][title] = {
  482. "first_time": time_info,
  483. "last_time": time_info,
  484. "count": 1,
  485. "ranks": ranks,
  486. "url": url,
  487. "mobileUrl": mobile_url,
  488. }
  489. reversed_id = source_name.lower().replace(" ", "-")
  490. id_to_alias[reversed_id] = source_name
  491. else:
  492. for title, data in title_data.items():
  493. ranks = data.get("ranks", [])
  494. url = data.get("url", "")
  495. mobile_url = data.get("mobileUrl", "")
  496. if title not in all_results[source_name]:
  497. all_results[source_name][title] = {
  498. "ranks": ranks,
  499. "url": url,
  500. "mobileUrl": mobile_url,
  501. }
  502. title_info[source_name][title] = {
  503. "first_time": time_info,
  504. "last_time": time_info,
  505. "count": 1,
  506. "ranks": ranks,
  507. "url": url,
  508. "mobileUrl": mobile_url,
  509. }
  510. else:
  511. existing_data = all_results[source_name][title]
  512. existing_ranks = existing_data.get("ranks", [])
  513. existing_url = existing_data.get("url", "")
  514. existing_mobile_url = existing_data.get("mobileUrl", "")
  515. merged_ranks = existing_ranks.copy()
  516. for rank in ranks:
  517. if rank not in merged_ranks:
  518. merged_ranks.append(rank)
  519. all_results[source_name][title] = {
  520. "ranks": merged_ranks,
  521. "url": existing_url or url,
  522. "mobileUrl": existing_mobile_url or mobile_url,
  523. }
  524. title_info[source_name][title]["last_time"] = time_info
  525. title_info[source_name][title]["ranks"] = merged_ranks
  526. title_info[source_name][title]["count"] += 1
  527. if not title_info[source_name][title].get("url"):
  528. title_info[source_name][title]["url"] = url
  529. if not title_info[source_name][title].get("mobileUrl"):
  530. title_info[source_name][title]["mobileUrl"] = mobile_url
  531. class StatisticsCalculator:
  532. """统计计算器"""
  533. @staticmethod
  534. def calculate_news_weight(
  535. title_data: Dict, rank_threshold: int = CONFIG["RANK_THRESHOLD"]
  536. ) -> float:
  537. """计算新闻权重,用于排序"""
  538. ranks = title_data.get("ranks", [])
  539. if not ranks:
  540. return 0.0
  541. count = title_data.get("count", len(ranks))
  542. weight_config = CONFIG["WEIGHT_CONFIG"]
  543. # 排名权重:Σ(11 - min(rank, 10)) / 出现次数
  544. rank_scores = []
  545. for rank in ranks:
  546. score = 11 - min(rank, 10)
  547. rank_scores.append(score)
  548. rank_weight = sum(rank_scores) / len(ranks) if ranks else 0
  549. # 频次权重:min(出现次数, 10) × 10
  550. frequency_weight = min(count, 10) * 10
  551. # 热度加成:高排名次数 / 总出现次数 × 100
  552. high_rank_count = sum(1 for rank in ranks if rank <= rank_threshold)
  553. hotness_ratio = high_rank_count / len(ranks) if ranks else 0
  554. hotness_weight = hotness_ratio * 100
  555. # 综合权重计算
  556. total_weight = (
  557. rank_weight * weight_config["RANK_WEIGHT"]
  558. + frequency_weight * weight_config["FREQUENCY_WEIGHT"]
  559. + hotness_weight * weight_config["HOTNESS_WEIGHT"]
  560. )
  561. return total_weight
  562. @staticmethod
  563. def sort_titles_by_weight(
  564. titles_list: List[Dict], rank_threshold: int = CONFIG["RANK_THRESHOLD"]
  565. ) -> List[Dict]:
  566. """按权重对新闻标题列表进行排序"""
  567. def get_sort_key(title_data):
  568. weight = StatisticsCalculator.calculate_news_weight(
  569. title_data, rank_threshold
  570. )
  571. ranks = title_data.get("ranks", [])
  572. count = title_data.get("count", 1)
  573. # 主要按权重排序,权重相同时按最高排名排序,再相同时按出现次数排序
  574. min_rank = min(ranks) if ranks else 999
  575. return (-weight, min_rank, -count)
  576. return sorted(titles_list, key=get_sort_key)
  577. @staticmethod
  578. def _matches_word_groups(
  579. title: str, word_groups: List[Dict], filter_words: List[str]
  580. ) -> bool:
  581. """检查标题是否匹配词组规则"""
  582. title_lower = title.lower()
  583. # 过滤词检查
  584. if any(filter_word.lower() in title_lower for filter_word in filter_words):
  585. return False
  586. # 词组匹配检查
  587. for group in word_groups:
  588. required_words = group["required"]
  589. normal_words = group["normal"]
  590. # 必须词检查
  591. if required_words:
  592. all_required_present = all(
  593. req_word.lower() in title_lower for req_word in required_words
  594. )
  595. if not all_required_present:
  596. continue
  597. # 普通词检查
  598. if normal_words:
  599. any_normal_present = any(
  600. normal_word.lower() in title_lower for normal_word in normal_words
  601. )
  602. if not any_normal_present:
  603. continue
  604. return True
  605. return False
  606. @staticmethod
  607. def count_word_frequency(
  608. results: Dict,
  609. word_groups: List[Dict],
  610. filter_words: List[str],
  611. id_to_alias: Dict,
  612. title_info: Optional[Dict] = None,
  613. rank_threshold: int = CONFIG["RANK_THRESHOLD"],
  614. new_titles: Optional[Dict] = None,
  615. ) -> Tuple[List[Dict], int]:
  616. """统计词频,支持必须词、频率词、过滤词,并标记新增标题"""
  617. word_stats = {}
  618. total_titles = 0
  619. processed_titles = {}
  620. if title_info is None:
  621. title_info = {}
  622. if new_titles is None:
  623. new_titles = {}
  624. for group in word_groups:
  625. group_key = group["group_key"]
  626. word_stats[group_key] = {"count": 0, "titles": {}}
  627. for source_id, titles_data in results.items():
  628. total_titles += len(titles_data)
  629. if source_id not in processed_titles:
  630. processed_titles[source_id] = {}
  631. for title, title_data in titles_data.items():
  632. if title in processed_titles.get(source_id, {}):
  633. continue
  634. # 使用统一的匹配逻辑
  635. if not StatisticsCalculator._matches_word_groups(
  636. title, word_groups, filter_words
  637. ):
  638. continue
  639. source_ranks = title_data.get("ranks", [])
  640. source_url = title_data.get("url", "")
  641. source_mobile_url = title_data.get("mobileUrl", "")
  642. # 找到匹配的词组
  643. title_lower = title.lower()
  644. for group in word_groups:
  645. required_words = group["required"]
  646. normal_words = group["normal"]
  647. # 再次检查匹配
  648. if required_words:
  649. all_required_present = all(
  650. req_word.lower() in title_lower
  651. for req_word in required_words
  652. )
  653. if not all_required_present:
  654. continue
  655. if normal_words:
  656. any_normal_present = any(
  657. normal_word.lower() in title_lower
  658. for normal_word in normal_words
  659. )
  660. if not any_normal_present:
  661. continue
  662. group_key = group["group_key"]
  663. word_stats[group_key]["count"] += 1
  664. if source_id not in word_stats[group_key]["titles"]:
  665. word_stats[group_key]["titles"][source_id] = []
  666. first_time = ""
  667. last_time = ""
  668. count_info = 1
  669. ranks = source_ranks if source_ranks else []
  670. url = source_url
  671. mobile_url = source_mobile_url
  672. if (
  673. title_info
  674. and source_id in title_info
  675. and title in title_info[source_id]
  676. ):
  677. info = title_info[source_id][title]
  678. first_time = info.get("first_time", "")
  679. last_time = info.get("last_time", "")
  680. count_info = info.get("count", 1)
  681. if "ranks" in info and info["ranks"]:
  682. ranks = info["ranks"]
  683. url = info.get("url", source_url)
  684. mobile_url = info.get("mobileUrl", source_mobile_url)
  685. if not ranks:
  686. ranks = [99]
  687. time_display = StatisticsCalculator._format_time_display(
  688. first_time, last_time
  689. )
  690. source_alias = id_to_alias.get(source_id, source_id)
  691. is_new = source_id in new_titles and title in new_titles[source_id]
  692. word_stats[group_key]["titles"][source_id].append(
  693. {
  694. "title": title,
  695. "source_alias": source_alias,
  696. "first_time": first_time,
  697. "last_time": last_time,
  698. "time_display": time_display,
  699. "count": count_info,
  700. "ranks": ranks,
  701. "rank_threshold": rank_threshold,
  702. "url": url,
  703. "mobileUrl": mobile_url,
  704. "is_new": is_new,
  705. }
  706. )
  707. if source_id not in processed_titles:
  708. processed_titles[source_id] = {}
  709. processed_titles[source_id][title] = True
  710. break
  711. stats = []
  712. for group_key, data in word_stats.items():
  713. all_titles = []
  714. for source_id, title_list in data["titles"].items():
  715. all_titles.extend(title_list)
  716. # 按权重排序标题
  717. sorted_titles = StatisticsCalculator.sort_titles_by_weight(
  718. all_titles, rank_threshold
  719. )
  720. stats.append(
  721. {
  722. "word": group_key,
  723. "count": data["count"],
  724. "titles": sorted_titles,
  725. "percentage": (
  726. round(data["count"] / total_titles * 100, 2)
  727. if total_titles > 0
  728. else 0
  729. ),
  730. }
  731. )
  732. stats.sort(key=lambda x: x["count"], reverse=True)
  733. return stats, total_titles
  734. @staticmethod
  735. def _format_rank_base(
  736. ranks: List[int], rank_threshold: int = 5, format_type: str = "html"
  737. ) -> str:
  738. """基础排名格式化方法"""
  739. if not ranks:
  740. return ""
  741. unique_ranks = sorted(set(ranks))
  742. min_rank = unique_ranks[0]
  743. max_rank = unique_ranks[-1]
  744. # 根据格式类型选择不同的标记方式
  745. if format_type == "html":
  746. highlight_start = "<font color='red'><strong>"
  747. highlight_end = "</strong></font>"
  748. else: # feishu
  749. highlight_start = "<font color='red'>**"
  750. highlight_end = "**</font>"
  751. # 格式化排名显示
  752. if min_rank <= rank_threshold:
  753. if min_rank == max_rank:
  754. return f"{highlight_start}[{min_rank}]{highlight_end}"
  755. else:
  756. return f"{highlight_start}[{min_rank} - {max_rank}]{highlight_end}"
  757. else:
  758. if min_rank == max_rank:
  759. return f"[{min_rank}]"
  760. else:
  761. return f"[{min_rank} - {max_rank}]"
  762. @staticmethod
  763. def _format_rank_for_html(ranks: List[int], rank_threshold: int = 5) -> str:
  764. """格式化HTML排名显示"""
  765. return StatisticsCalculator._format_rank_base(ranks, rank_threshold, "html")
  766. @staticmethod
  767. def _format_rank_for_feishu(ranks: List[int], rank_threshold: int = 5) -> str:
  768. """格式化飞书排名显示"""
  769. return StatisticsCalculator._format_rank_base(ranks, rank_threshold, "feishu")
  770. @staticmethod
  771. def _format_time_display(first_time: str, last_time: str) -> str:
  772. """格式化时间显示"""
  773. if not first_time:
  774. return ""
  775. if first_time == last_time or not last_time:
  776. return first_time
  777. else:
  778. return f"[{first_time} ~ {last_time}]"
  779. class ReportGenerator:
  780. """报告生成器"""
  781. @staticmethod
  782. def generate_html_report(
  783. stats: List[Dict],
  784. total_titles: int,
  785. failed_ids: Optional[List] = None,
  786. is_daily: bool = False,
  787. new_titles: Optional[Dict] = None,
  788. id_to_alias: Optional[Dict] = None,
  789. ) -> str:
  790. """生成HTML报告"""
  791. if is_daily:
  792. filename = "当日统计.html"
  793. else:
  794. filename = f"{TimeHelper.format_time_filename()}.html"
  795. file_path = FileHelper.get_output_path("html", filename)
  796. # 数据处理层
  797. report_data = ReportGenerator._prepare_report_data(
  798. stats, failed_ids, new_titles, id_to_alias
  799. )
  800. # 渲染层
  801. html_content = ReportGenerator._render_html_content(
  802. report_data, total_titles, is_daily
  803. )
  804. with open(file_path, "w", encoding="utf-8") as f:
  805. f.write(html_content)
  806. if is_daily:
  807. root_file_path = Path("index.html")
  808. with open(root_file_path, "w", encoding="utf-8") as f:
  809. f.write(html_content)
  810. return file_path
  811. @staticmethod
  812. def _prepare_report_data(
  813. stats: List[Dict],
  814. failed_ids: Optional[List] = None,
  815. new_titles: Optional[Dict] = None,
  816. id_to_alias: Optional[Dict] = None,
  817. ) -> Dict:
  818. """准备报告数据"""
  819. filtered_new_titles = {}
  820. if new_titles and id_to_alias:
  821. word_groups, filter_words = DataProcessor.load_frequency_words()
  822. for source_id, titles_data in new_titles.items():
  823. filtered_titles = ReportGenerator._apply_frequency_filter(
  824. titles_data, word_groups, filter_words
  825. )
  826. if filtered_titles:
  827. filtered_new_titles[source_id] = filtered_titles
  828. processed_stats = []
  829. for stat in stats:
  830. if stat["count"] <= 0:
  831. continue
  832. processed_titles = []
  833. for title_data in stat["titles"]:
  834. processed_title = {
  835. "title": title_data["title"],
  836. "source_alias": title_data["source_alias"],
  837. "time_display": title_data["time_display"],
  838. "count": title_data["count"],
  839. "ranks": title_data["ranks"],
  840. "rank_threshold": title_data["rank_threshold"],
  841. "url": title_data.get("url", ""),
  842. "mobile_url": title_data.get("mobileUrl", ""),
  843. "is_new": title_data.get("is_new", False),
  844. }
  845. processed_titles.append(processed_title)
  846. processed_stats.append(
  847. {
  848. "word": stat["word"],
  849. "count": stat["count"],
  850. "percentage": stat.get("percentage", 0),
  851. "titles": processed_titles,
  852. }
  853. )
  854. processed_new_titles = []
  855. if filtered_new_titles and id_to_alias:
  856. for source_id, titles_data in filtered_new_titles.items():
  857. source_alias = id_to_alias.get(source_id, source_id)
  858. source_titles = []
  859. for title, title_data in titles_data.items():
  860. url, mobile_url, ranks = ReportGenerator._extract_title_data_fields(
  861. title_data
  862. )
  863. processed_title = {
  864. "title": title,
  865. "source_alias": source_alias,
  866. "time_display": "",
  867. "count": 1,
  868. "ranks": ranks,
  869. "rank_threshold": CONFIG["RANK_THRESHOLD"],
  870. "url": url,
  871. "mobile_url": mobile_url,
  872. "is_new": True,
  873. }
  874. source_titles.append(processed_title)
  875. if source_titles:
  876. processed_new_titles.append(
  877. {
  878. "source_id": source_id,
  879. "source_alias": source_alias,
  880. "titles": source_titles,
  881. }
  882. )
  883. return {
  884. "stats": processed_stats,
  885. "new_titles": processed_new_titles,
  886. "failed_ids": failed_ids or [],
  887. "total_new_count": sum(
  888. len(source["titles"]) for source in processed_new_titles
  889. ),
  890. }
  891. @staticmethod
  892. def _extract_title_data_fields(title_data) -> Tuple[str, str, List[int]]:
  893. """提取标题数据的通用字段"""
  894. url = title_data.get("url", "")
  895. mobile_url = title_data.get("mobileUrl", "")
  896. ranks = title_data.get("ranks", [])
  897. return url, mobile_url, ranks
  898. @staticmethod
  899. def _apply_frequency_filter(
  900. titles_data: Dict, word_groups: List[Dict], filter_words: List[str]
  901. ) -> Dict:
  902. """应用频率词过滤逻辑"""
  903. filtered_titles = {}
  904. for title, title_data in titles_data.items():
  905. if StatisticsCalculator._matches_word_groups(
  906. title, word_groups, filter_words
  907. ):
  908. filtered_titles[title] = title_data
  909. return filtered_titles
  910. @staticmethod
  911. def _html_escape(text: str) -> str:
  912. """HTML转义"""
  913. if not isinstance(text, str):
  914. text = str(text)
  915. return (
  916. text.replace("&", "&amp;")
  917. .replace("<", "&lt;")
  918. .replace(">", "&gt;")
  919. .replace('"', "&quot;")
  920. .replace("'", "&#x27;")
  921. )
  922. @staticmethod
  923. def _format_title_html(title_data: Dict) -> str:
  924. """格式化HTML标题显示"""
  925. rank_display = StatisticsCalculator._format_rank_for_html(
  926. title_data["ranks"], title_data["rank_threshold"]
  927. )
  928. link_url = title_data["mobile_url"] or title_data["url"]
  929. escaped_title = ReportGenerator._html_escape(title_data["title"])
  930. escaped_source_alias = ReportGenerator._html_escape(title_data["source_alias"])
  931. if link_url:
  932. escaped_url = ReportGenerator._html_escape(link_url)
  933. formatted_title = f'[{escaped_source_alias}] <a href="{escaped_url}" target="_blank" class="news-link">{escaped_title}</a>'
  934. else:
  935. formatted_title = (
  936. f'[{escaped_source_alias}] <span class="no-link">{escaped_title}</span>'
  937. )
  938. if rank_display:
  939. formatted_title += f" {rank_display}"
  940. if title_data["time_display"]:
  941. escaped_time = ReportGenerator._html_escape(title_data["time_display"])
  942. formatted_title += f" <font color='grey'>- {escaped_time}</font>"
  943. if title_data["count"] > 1:
  944. formatted_title += f" <font color='green'>({title_data['count']}次)</font>"
  945. if title_data["is_new"]:
  946. formatted_title = f"<div class='new-title'>🆕 {formatted_title}</div>"
  947. return formatted_title
  948. @staticmethod
  949. def _render_html_content(
  950. report_data: Dict, total_titles: int, is_daily: bool = False
  951. ) -> str:
  952. """渲染HTML内容"""
  953. html = """
  954. <!DOCTYPE html>
  955. <html>
  956. <head>
  957. <meta charset="UTF-8">
  958. <title>频率词统计报告</title>
  959. <style>
  960. body { font-family: Arial, sans-serif; margin: 20px; }
  961. h1, h2 { color: #333; }
  962. table { border-collapse: collapse; width: 100%; margin-top: 20px; }
  963. th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
  964. th { background-color: #f2f2f2; }
  965. tr:nth-child(even) { background-color: #f9f9f9; }
  966. .word { font-weight: bold; }
  967. .count { text-align: center; }
  968. .percentage { text-align: center; }
  969. .titles { max-width: 500px; }
  970. .source { color: #666; font-style: italic; }
  971. .error { color: #d9534f; }
  972. .news-link {
  973. color: #007bff;
  974. text-decoration: none;
  975. border-bottom: 1px dotted #007bff;
  976. }
  977. .news-link:hover {
  978. color: #0056b3;
  979. text-decoration: underline;
  980. }
  981. .news-link:visited {
  982. color: #6f42c1;
  983. }
  984. .no-link {
  985. color: #333;
  986. }
  987. .new-title {
  988. background-color: #fff3cd;
  989. border: 1px solid #ffc107;
  990. border-radius: 3px;
  991. padding: 2px 6px;
  992. margin: 2px 0;
  993. }
  994. .new-section {
  995. background-color: #d1ecf1;
  996. border: 1px solid #bee5eb;
  997. border-radius: 5px;
  998. padding: 10px;
  999. margin-top: 10px;
  1000. }
  1001. .new-section h3 {
  1002. color: #0c5460;
  1003. margin-top: 0;
  1004. }
  1005. </style>
  1006. </head>
  1007. <body>
  1008. <h1>频率词统计报告</h1>
  1009. """
  1010. if is_daily:
  1011. html += "<p>报告类型: 当日汇总</p>"
  1012. now = TimeHelper.get_beijing_time()
  1013. html += f"<p>总标题数: {total_titles}</p>"
  1014. html += f"<p>生成时间: {now.strftime('%Y-%m-%d %H:%M:%S')}</p>"
  1015. # 渲染失败平台
  1016. if report_data["failed_ids"]:
  1017. html += """
  1018. <div class="error">
  1019. <h2>请求失败的平台</h2>
  1020. <ul>
  1021. """
  1022. for id_value in report_data["failed_ids"]:
  1023. html += f"<li>{ReportGenerator._html_escape(id_value)}</li>"
  1024. html += """
  1025. </ul>
  1026. </div>
  1027. """
  1028. # 渲染统计表格
  1029. html += """
  1030. <table>
  1031. <tr>
  1032. <th>排名</th>
  1033. <th>频率词</th>
  1034. <th>出现次数</th>
  1035. <th>占比</th>
  1036. <th>相关标题</th>
  1037. </tr>
  1038. """
  1039. for i, stat in enumerate(report_data["stats"], 1):
  1040. formatted_titles = []
  1041. for title_data in stat["titles"]:
  1042. formatted_title = ReportGenerator._format_title_html(title_data)
  1043. formatted_titles.append(formatted_title)
  1044. escaped_word = ReportGenerator._html_escape(stat["word"])
  1045. html += f"""
  1046. <tr>
  1047. <td>{i}</td>
  1048. <td class="word">{escaped_word}</td>
  1049. <td class="count">{stat['count']}</td>
  1050. <td class="percentage">{stat.get('percentage', 0)}%</td>
  1051. <td class="titles">{"<br>".join(formatted_titles)}</td>
  1052. </tr>
  1053. """
  1054. html += """
  1055. </table>
  1056. """
  1057. # 渲染新增新闻部分
  1058. if report_data["new_titles"]:
  1059. html += f"""
  1060. <div class="new-section">
  1061. <h3>🆕 本次新增热点新闻 (共 {report_data['total_new_count']} 条)</h3>
  1062. """
  1063. for source_data in report_data["new_titles"]:
  1064. escaped_source = ReportGenerator._html_escape(
  1065. source_data["source_alias"]
  1066. )
  1067. html += (
  1068. f"<h4>{escaped_source} ({len(source_data['titles'])} 条)</h4><ul>"
  1069. )
  1070. for title_data in source_data["titles"]:
  1071. title_data_copy = title_data.copy()
  1072. title_data_copy["is_new"] = False
  1073. formatted_title = ReportGenerator._format_title_html(
  1074. title_data_copy
  1075. )
  1076. # 移除来源标签
  1077. if "] " in formatted_title:
  1078. formatted_title = formatted_title.split("] ", 1)[1]
  1079. html += f"<li>{formatted_title}</li>"
  1080. html += "</ul>"
  1081. html += "</div>"
  1082. html += """
  1083. </body>
  1084. </html>
  1085. """
  1086. return html
  1087. @staticmethod
  1088. def _format_title_feishu(title_data: Dict, show_source: bool = True) -> str:
  1089. """格式化飞书标题显示"""
  1090. rank_display = StatisticsCalculator._format_rank_for_feishu(
  1091. title_data["ranks"], title_data["rank_threshold"]
  1092. )
  1093. link_url = title_data["mobile_url"] or title_data["url"]
  1094. if link_url:
  1095. formatted_title = f"[{title_data['title']}]({link_url})"
  1096. else:
  1097. formatted_title = title_data["title"]
  1098. title_prefix = "🆕 " if title_data["is_new"] else ""
  1099. if show_source:
  1100. result = f"<font color='grey'>[{title_data['source_alias']}]</font> {title_prefix}{formatted_title}"
  1101. else:
  1102. result = f"{title_prefix}{formatted_title}"
  1103. if rank_display:
  1104. result += f" {rank_display}"
  1105. if title_data["time_display"]:
  1106. result += f" <font color='grey'>- {title_data['time_display']}</font>"
  1107. if title_data["count"] > 1:
  1108. result += f" <font color='green'>({title_data['count']}次)</font>"
  1109. return result
  1110. @staticmethod
  1111. def _render_feishu_content(
  1112. report_data: Dict, update_info: Optional[Dict] = None
  1113. ) -> str:
  1114. """渲染飞书内容"""
  1115. text_content = ""
  1116. # 渲染热点词汇统计
  1117. if report_data["stats"]:
  1118. text_content += "📊 **热点词汇统计**\n\n"
  1119. total_count = len(report_data["stats"])
  1120. for i, stat in enumerate(report_data["stats"]):
  1121. word = stat["word"]
  1122. count = stat["count"]
  1123. sequence_display = f"<font color='grey'>[{i + 1}/{total_count}]</font>"
  1124. if count >= 10:
  1125. text_content += f"🔥 {sequence_display} **{word}** : <font color='red'>{count}</font> 条\n\n"
  1126. elif count >= 5:
  1127. text_content += f"📈 {sequence_display} **{word}** : <font color='orange'>{count}</font> 条\n\n"
  1128. else:
  1129. text_content += f"📌 {sequence_display} **{word}** : {count} 条\n\n"
  1130. for j, title_data in enumerate(stat["titles"], 1):
  1131. formatted_title = ReportGenerator._format_title_feishu(
  1132. title_data, show_source=True
  1133. )
  1134. text_content += f" {j}. {formatted_title}\n"
  1135. if j < len(stat["titles"]):
  1136. text_content += "\n"
  1137. if i < len(report_data["stats"]) - 1:
  1138. text_content += f"\n{CONFIG['FEISHU_SEPARATOR']}\n\n"
  1139. if not text_content:
  1140. text_content = "📭 暂无匹配的热点词汇\n\n"
  1141. # 渲染新增新闻部分
  1142. if report_data["new_titles"]:
  1143. if text_content and "暂无匹配" not in text_content:
  1144. text_content += f"\n{CONFIG['FEISHU_SEPARATOR']}\n\n"
  1145. text_content += (
  1146. f"🆕 **本次新增热点新闻** (共 {report_data['total_new_count']} 条)\n\n"
  1147. )
  1148. for source_data in report_data["new_titles"]:
  1149. text_content += f"**{source_data['source_alias']}** ({len(source_data['titles'])} 条):\n"
  1150. for j, title_data in enumerate(source_data["titles"], 1):
  1151. title_data_copy = title_data.copy()
  1152. title_data_copy["is_new"] = False
  1153. formatted_title = ReportGenerator._format_title_feishu(
  1154. title_data_copy, show_source=False
  1155. )
  1156. text_content += f" {j}. {formatted_title}\n"
  1157. text_content += "\n"
  1158. # 渲染失败平台
  1159. if report_data["failed_ids"]:
  1160. if text_content and "暂无匹配" not in text_content:
  1161. text_content += f"\n{CONFIG['FEISHU_SEPARATOR']}\n\n"
  1162. text_content += "⚠️ **数据获取失败的平台:**\n\n"
  1163. for i, id_value in enumerate(report_data["failed_ids"], 1):
  1164. text_content += f" • <font color='red'>{id_value}</font>\n"
  1165. # 添加时间戳
  1166. now = TimeHelper.get_beijing_time()
  1167. text_content += f"\n\n<font color='grey'>更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}</font>"
  1168. # 版本更新提示
  1169. if update_info:
  1170. text_content += f"\n<font color='grey'>TrendRadar 发现新版本 {update_info['remote_version']},当前 {update_info['current_version']}</font>"
  1171. return text_content
  1172. @staticmethod
  1173. def send_to_feishu(
  1174. stats: List[Dict],
  1175. failed_ids: Optional[List] = None,
  1176. report_type: str = "单次爬取",
  1177. new_titles: Optional[Dict] = None,
  1178. id_to_alias: Optional[Dict] = None,
  1179. update_info: Optional[Dict] = None,
  1180. ) -> bool:
  1181. """发送数据到飞书"""
  1182. webhook_url = os.environ.get("FEISHU_WEBHOOK_URL", CONFIG["FEISHU_WEBHOOK_URL"])
  1183. if not webhook_url:
  1184. print(f"FEISHU_WEBHOOK_URL未设置,跳过飞书通知")
  1185. return False
  1186. headers = {"Content-Type": "application/json"}
  1187. total_titles = sum(len(stat["titles"]) for stat in stats if stat["count"] > 0)
  1188. # 数据处理层
  1189. report_data = ReportGenerator._prepare_report_data(
  1190. stats, failed_ids, new_titles, id_to_alias
  1191. )
  1192. # 渲染层
  1193. text_content = ReportGenerator._render_feishu_content(report_data, update_info)
  1194. now = TimeHelper.get_beijing_time()
  1195. payload = {
  1196. "msg_type": "text",
  1197. "content": {
  1198. "total_titles": total_titles,
  1199. "timestamp": now.strftime("%Y-%m-%d %H:%M:%S"),
  1200. "report_type": report_type,
  1201. "text": text_content,
  1202. },
  1203. }
  1204. try:
  1205. response = requests.post(webhook_url, headers=headers, json=payload)
  1206. if response.status_code == 200:
  1207. print(f"飞书通知发送成功 [{report_type}]")
  1208. return True
  1209. else:
  1210. print(
  1211. f"飞书通知发送失败 [{report_type}],状态码:{response.status_code}"
  1212. )
  1213. return False
  1214. except Exception as e:
  1215. print(f"飞书通知发送出错 [{report_type}]:{e}")
  1216. return False
  1217. class NewsAnalyzer:
  1218. """新闻分析器"""
  1219. def __init__(
  1220. self,
  1221. request_interval: int = CONFIG["REQUEST_INTERVAL"],
  1222. feishu_report_type: str = CONFIG["FEISHU_REPORT_TYPE"],
  1223. rank_threshold: int = CONFIG["RANK_THRESHOLD"],
  1224. ):
  1225. self.request_interval = request_interval
  1226. self.feishu_report_type = feishu_report_type
  1227. self.rank_threshold = rank_threshold
  1228. self.is_github_actions = os.environ.get("GITHUB_ACTIONS") == "true"
  1229. self.update_info = None
  1230. self.proxy_url = None
  1231. if not self.is_github_actions and CONFIG["USE_PROXY"]:
  1232. self.proxy_url = CONFIG["DEFAULT_PROXY"]
  1233. print("本地环境,使用代理")
  1234. elif not self.is_github_actions and not CONFIG["USE_PROXY"]:
  1235. print("本地环境,未启用代理")
  1236. else:
  1237. print("GitHub Actions环境,不使用代理")
  1238. self.data_fetcher = DataFetcher(self.proxy_url)
  1239. if self.is_github_actions:
  1240. self._check_version_update()
  1241. def _check_version_update(self) -> None:
  1242. """检查版本更新"""
  1243. try:
  1244. need_update, remote_version = VersionChecker.check_for_updates(
  1245. CONFIG["VERSION"], CONFIG["VERSION_CHECK_URL"], self.proxy_url
  1246. )
  1247. if need_update and remote_version:
  1248. self.update_info = {
  1249. "current_version": CONFIG["VERSION"],
  1250. "remote_version": remote_version,
  1251. }
  1252. print(f"发现新版本: {remote_version} (当前: {CONFIG['VERSION']})")
  1253. else:
  1254. print("版本检查完成,当前为最新版本")
  1255. except Exception as e:
  1256. print(f"版本检查出错: {e}")
  1257. def generate_daily_summary(self) -> Optional[str]:
  1258. """生成当日统计报告"""
  1259. print("生成当日统计报告...")
  1260. all_results, id_to_alias, title_info = DataProcessor.read_all_today_titles()
  1261. if not all_results:
  1262. print("没有找到当天的数据")
  1263. return None
  1264. total_titles = sum(len(titles) for titles in all_results.values())
  1265. print(f"读取到 {total_titles} 个标题")
  1266. latest_new_titles = DataProcessor.detect_latest_new_titles(id_to_alias)
  1267. if latest_new_titles:
  1268. total_new_count = sum(len(titles) for titles in latest_new_titles.values())
  1269. print(f"检测到 {total_new_count} 条最新新增新闻")
  1270. word_groups, filter_words = DataProcessor.load_frequency_words()
  1271. stats, total_titles = StatisticsCalculator.count_word_frequency(
  1272. all_results,
  1273. word_groups,
  1274. filter_words,
  1275. id_to_alias,
  1276. title_info,
  1277. self.rank_threshold,
  1278. latest_new_titles,
  1279. )
  1280. html_file = ReportGenerator.generate_html_report(
  1281. stats,
  1282. total_titles,
  1283. is_daily=True,
  1284. new_titles=latest_new_titles,
  1285. id_to_alias=id_to_alias,
  1286. )
  1287. print(f"当日HTML统计报告已生成: {html_file}")
  1288. if self.feishu_report_type in ["daily", "both"]:
  1289. update_info_for_feishu = (
  1290. self.update_info if CONFIG["FEISHU_SHOW_VERSION_UPDATE"] else None
  1291. )
  1292. ReportGenerator.send_to_feishu(
  1293. stats,
  1294. [],
  1295. "当日汇总",
  1296. latest_new_titles,
  1297. id_to_alias,
  1298. update_info_for_feishu,
  1299. )
  1300. return html_file
  1301. def run(self) -> None:
  1302. """执行分析流程"""
  1303. now = TimeHelper.get_beijing_time()
  1304. print(f"当前北京时间: {now.strftime('%Y-%m-%d %H:%M:%S')}")
  1305. webhook_url = os.environ.get("FEISHU_WEBHOOK_URL", CONFIG["FEISHU_WEBHOOK_URL"])
  1306. if not webhook_url and not CONFIG["CONTINUE_WITHOUT_FEISHU"]:
  1307. print(
  1308. "错误: FEISHU_WEBHOOK_URL未设置且CONTINUE_WITHOUT_FEISHU为False,程序退出"
  1309. )
  1310. return
  1311. if not webhook_url:
  1312. print("FEISHU_WEBHOOK_URL未设置,将继续执行爬虫但不发送飞书通知")
  1313. print(f"飞书报告类型: {self.feishu_report_type}")
  1314. ids = [
  1315. ("toutiao", "今日头条"),
  1316. ("baidu", "百度热搜"),
  1317. ("wallstreetcn-hot", "华尔街见闻"),
  1318. ("thepaper", "澎湃新闻"),
  1319. ("bilibili-hot-search", "bilibili 热搜"),
  1320. ("cls-hot", "财联社热门"),
  1321. ("ifeng", "凤凰网"),
  1322. "tieba",
  1323. "weibo",
  1324. "douyin",
  1325. "zhihu",
  1326. ]
  1327. print(f"开始爬取数据,请求间隔 {self.request_interval} 毫秒")
  1328. FileHelper.ensure_directory_exists("output")
  1329. results, id_to_alias, failed_ids = self.data_fetcher.crawl_websites(
  1330. ids, self.request_interval
  1331. )
  1332. title_file = DataProcessor.save_titles_to_file(results, id_to_alias, failed_ids)
  1333. print(f"标题已保存到: {title_file}")
  1334. new_titles = DataProcessor.detect_latest_new_titles(id_to_alias)
  1335. # 构建标题信息
  1336. time_info = Path(title_file).stem
  1337. title_info = {}
  1338. for source_id, titles_data in results.items():
  1339. title_info[source_id] = {}
  1340. for title, title_data in titles_data.items():
  1341. ranks = title_data.get("ranks", [])
  1342. url = title_data.get("url", "")
  1343. mobile_url = title_data.get("mobileUrl", "")
  1344. title_info[source_id][title] = {
  1345. "first_time": time_info,
  1346. "last_time": time_info,
  1347. "count": 1,
  1348. "ranks": ranks,
  1349. "url": url,
  1350. "mobileUrl": mobile_url,
  1351. }
  1352. word_groups, filter_words = DataProcessor.load_frequency_words()
  1353. stats, total_titles = StatisticsCalculator.count_word_frequency(
  1354. results,
  1355. word_groups,
  1356. filter_words,
  1357. id_to_alias,
  1358. title_info,
  1359. self.rank_threshold,
  1360. new_titles,
  1361. )
  1362. if self.feishu_report_type in ["current", "both"]:
  1363. update_info_for_feishu = (
  1364. self.update_info if CONFIG["FEISHU_SHOW_VERSION_UPDATE"] else None
  1365. )
  1366. ReportGenerator.send_to_feishu(
  1367. stats,
  1368. failed_ids,
  1369. "单次爬取",
  1370. new_titles,
  1371. id_to_alias,
  1372. update_info_for_feishu,
  1373. )
  1374. html_file = ReportGenerator.generate_html_report(
  1375. stats, total_titles, failed_ids, False, new_titles, id_to_alias
  1376. )
  1377. print(f"HTML报告已生成: {html_file}")
  1378. daily_html = self.generate_daily_summary()
  1379. if not self.is_github_actions and html_file:
  1380. file_url = "file://" + str(Path(html_file).resolve())
  1381. print(f"正在打开HTML报告: {file_url}")
  1382. webbrowser.open(file_url)
  1383. if daily_html:
  1384. daily_url = "file://" + str(Path(daily_html).resolve())
  1385. print(f"正在打开当日统计报告: {daily_url}")
  1386. webbrowser.open(daily_url)
  1387. def main():
  1388. analyzer = NewsAnalyzer(
  1389. request_interval=CONFIG["REQUEST_INTERVAL"],
  1390. feishu_report_type=CONFIG["FEISHU_REPORT_TYPE"],
  1391. rank_threshold=CONFIG["RANK_THRESHOLD"],
  1392. )
  1393. analyzer.run()
  1394. if __name__ == "__main__":
  1395. main()