main.py 94 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549
  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.3.0",
  14. "VERSION_CHECK_URL": "https://raw.githubusercontent.com/sansan0/TrendRadar/refs/heads/master/version",
  15. "SHOW_VERSION_UPDATE": True, # 控制显示版本更新提示,改成 False 将不接受新版本提示
  16. "FEISHU_MESSAGE_SEPARATOR": "━━━━━━━━━━━━━━━━━━━", # feishu消息分割线
  17. "REQUEST_INTERVAL": 1000, # 请求间隔(毫秒)
  18. "REPORT_TYPE": "daily", # 报告类型: "current"|"daily"|"both"
  19. "RANK_THRESHOLD": 5, # 排名高亮阈值
  20. "USE_PROXY": True, # 是否启用代理
  21. "DEFAULT_PROXY": "http://127.0.0.1:10086",
  22. "ENABLE_CRAWLER": True, # 是否启用爬取新闻功能,False时直接停止程序
  23. "ENABLE_NOTIFICATION": True, # 是否启用通知功能,False时不发送手机通知
  24. "MESSAGE_BATCH_SIZE": 4000, # 消息分批大小(字节)
  25. "BATCH_SEND_INTERVAL": 1, # 批次发送间隔(秒)
  26. # 飞书机器人的 webhook URL
  27. "FEISHU_WEBHOOK_URL": "",
  28. # 钉钉机器人的 webhook URL
  29. "DINGTALK_WEBHOOK_URL": "",
  30. # 企业微信机器人的 webhook URL
  31. "WEWORK_WEBHOOK_URL": "",
  32. # Telegram 要填两个
  33. "TELEGRAM_BOT_TOKEN": "",
  34. "TELEGRAM_CHAT_ID": "",
  35. # 用于让关注度更高的新闻在更前面显示,这里是权重排序配置,合起来是 1 就行
  36. "WEIGHT_CONFIG": {
  37. "RANK_WEIGHT": 0.6, # 排名
  38. "FREQUENCY_WEIGHT": 0.3, # 频次
  39. "HOTNESS_WEIGHT": 0.1, # 热度
  40. },
  41. }
  42. class TimeHelper:
  43. """时间处理工具"""
  44. @staticmethod
  45. def get_beijing_time() -> datetime:
  46. return datetime.now(pytz.timezone("Asia/Shanghai"))
  47. @staticmethod
  48. def format_date_folder() -> str:
  49. return TimeHelper.get_beijing_time().strftime("%Y年%m月%d日")
  50. @staticmethod
  51. def format_time_filename() -> str:
  52. return TimeHelper.get_beijing_time().strftime("%H时%M分")
  53. class VersionChecker:
  54. """版本检查工具"""
  55. @staticmethod
  56. def parse_version(version_str: str) -> Tuple[int, int, int]:
  57. """解析版本号字符串为元组"""
  58. try:
  59. parts = version_str.strip().split(".")
  60. if len(parts) != 3:
  61. raise ValueError("版本号格式不正确")
  62. return tuple(int(part) for part in parts)
  63. except (ValueError, AttributeError):
  64. print(f"无法解析版本号: {version_str}")
  65. return (0, 0, 0)
  66. @staticmethod
  67. def compare_versions(current: str, remote: str) -> int:
  68. """比较版本号"""
  69. current_tuple = VersionChecker.parse_version(current)
  70. remote_tuple = VersionChecker.parse_version(remote)
  71. if current_tuple < remote_tuple:
  72. return -1 # 需要更新
  73. elif current_tuple > remote_tuple:
  74. return 1 # 当前版本更新
  75. else:
  76. return 0 # 版本相同
  77. @staticmethod
  78. def check_for_updates(
  79. current_version: str,
  80. version_url: str,
  81. proxy_url: Optional[str] = None,
  82. timeout: int = 10,
  83. ) -> Tuple[bool, Optional[str]]:
  84. """检查是否有新版本"""
  85. try:
  86. proxies = None
  87. if proxy_url:
  88. proxies = {"http": proxy_url, "https": proxy_url}
  89. headers = {
  90. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
  91. "Accept": "text/plain, */*",
  92. "Cache-Control": "no-cache",
  93. }
  94. response = requests.get(
  95. version_url, proxies=proxies, headers=headers, timeout=timeout
  96. )
  97. response.raise_for_status()
  98. remote_version = response.text.strip()
  99. print(f"当前版本: {current_version}, 远程版本: {remote_version}")
  100. comparison = VersionChecker.compare_versions(
  101. current_version, remote_version
  102. )
  103. need_update = comparison == -1
  104. return need_update, remote_version if need_update else None
  105. except Exception as e:
  106. print(f"版本检查失败: {e}")
  107. return False, None
  108. class FileHelper:
  109. """文件操作工具"""
  110. @staticmethod
  111. def ensure_directory_exists(directory: str) -> None:
  112. Path(directory).mkdir(parents=True, exist_ok=True)
  113. @staticmethod
  114. def get_output_path(subfolder: str, filename: str) -> str:
  115. date_folder = TimeHelper.format_date_folder()
  116. output_dir = Path("output") / date_folder / subfolder
  117. FileHelper.ensure_directory_exists(str(output_dir))
  118. return str(output_dir / filename)
  119. class DataFetcher:
  120. """数据获取器"""
  121. def __init__(self, proxy_url: Optional[str] = None):
  122. self.proxy_url = proxy_url
  123. def fetch_data(
  124. self,
  125. id_info: Union[str, Tuple[str, str]],
  126. max_retries: int = 2,
  127. min_retry_wait: int = 3,
  128. max_retry_wait: int = 5,
  129. ) -> Tuple[Optional[str], str, str]:
  130. """获取指定ID数据,支持重试"""
  131. if isinstance(id_info, tuple):
  132. id_value, alias = id_info
  133. else:
  134. id_value = id_info
  135. alias = id_value
  136. url = f"https://newsnow.busiyi.world/api/s?id={id_value}&latest"
  137. proxies = None
  138. if self.proxy_url:
  139. proxies = {"http": self.proxy_url, "https": self.proxy_url}
  140. headers = {
  141. "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",
  142. "Accept": "application/json, text/plain, */*",
  143. "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
  144. "Connection": "keep-alive",
  145. "Cache-Control": "no-cache",
  146. }
  147. retries = 0
  148. while retries <= max_retries:
  149. try:
  150. response = requests.get(
  151. url, proxies=proxies, headers=headers, timeout=10
  152. )
  153. response.raise_for_status()
  154. data_text = response.text
  155. data_json = json.loads(data_text)
  156. status = data_json.get("status", "未知")
  157. if status not in ["success", "cache"]:
  158. raise ValueError(f"响应状态异常: {status}")
  159. status_info = "最新数据" if status == "success" else "缓存数据"
  160. print(f"获取 {id_value} 成功({status_info})")
  161. return data_text, id_value, alias
  162. except Exception as e:
  163. retries += 1
  164. if retries <= max_retries:
  165. base_wait = random.uniform(min_retry_wait, max_retry_wait)
  166. additional_wait = (retries - 1) * random.uniform(1, 2)
  167. wait_time = base_wait + additional_wait
  168. print(f"请求 {id_value} 失败: {e}. {wait_time:.2f}秒后重试...")
  169. time.sleep(wait_time)
  170. else:
  171. print(f"请求 {id_value} 失败: {e}")
  172. return None, id_value, alias
  173. return None, id_value, alias
  174. def crawl_websites(
  175. self,
  176. ids_list: List[Union[str, Tuple[str, str]]],
  177. request_interval: int = CONFIG["REQUEST_INTERVAL"],
  178. ) -> Tuple[Dict, Dict, List]:
  179. """爬取多个网站数据"""
  180. results = {}
  181. id_to_alias = {}
  182. failed_ids = []
  183. for i, id_info in enumerate(ids_list):
  184. if isinstance(id_info, tuple):
  185. id_value, alias = id_info
  186. else:
  187. id_value = id_info
  188. alias = id_value
  189. id_to_alias[id_value] = alias
  190. response, _, _ = self.fetch_data(id_info)
  191. if response:
  192. try:
  193. data = json.loads(response)
  194. results[id_value] = {}
  195. for index, item in enumerate(data.get("items", []), 1):
  196. title = item["title"]
  197. url = item.get("url", "")
  198. mobile_url = item.get("mobileUrl", "")
  199. if title in results[id_value]:
  200. results[id_value][title]["ranks"].append(index)
  201. else:
  202. results[id_value][title] = {
  203. "ranks": [index],
  204. "url": url,
  205. "mobileUrl": mobile_url,
  206. }
  207. except json.JSONDecodeError:
  208. print(f"解析 {id_value} 响应失败")
  209. failed_ids.append(id_value)
  210. except Exception as e:
  211. print(f"处理 {id_value} 数据出错: {e}")
  212. failed_ids.append(id_value)
  213. else:
  214. failed_ids.append(id_value)
  215. if i < len(ids_list) - 1:
  216. actual_interval = request_interval + random.randint(-10, 20)
  217. actual_interval = max(50, actual_interval)
  218. time.sleep(actual_interval / 1000)
  219. print(f"成功: {list(results.keys())}, 失败: {failed_ids}")
  220. return results, id_to_alias, failed_ids
  221. class DataProcessor:
  222. """数据处理器"""
  223. @staticmethod
  224. def detect_latest_new_titles(id_to_alias: Dict) -> Dict:
  225. """检测当日最新批次的新增标题"""
  226. date_folder = TimeHelper.format_date_folder()
  227. txt_dir = Path("output") / date_folder / "txt"
  228. if not txt_dir.exists():
  229. return {}
  230. files = sorted([f for f in txt_dir.iterdir() if f.suffix == ".txt"])
  231. if len(files) < 2:
  232. # 如果只有一个文件(第一次爬取),没有"新增"的概念,返回空字典
  233. return {}
  234. latest_file = files[-1]
  235. latest_titles = DataProcessor._parse_file_titles(latest_file)
  236. # 汇总历史标题
  237. historical_titles = {}
  238. for file_path in files[:-1]:
  239. historical_data = DataProcessor._parse_file_titles(file_path)
  240. for source_name, titles_data in historical_data.items():
  241. if source_name not in historical_titles:
  242. historical_titles[source_name] = set()
  243. for title in titles_data.keys():
  244. historical_titles[source_name].add(title)
  245. # 找出新增标题
  246. new_titles = {}
  247. for source_name, latest_source_titles in latest_titles.items():
  248. historical_set = historical_titles.get(source_name, set())
  249. source_new_titles = {}
  250. for title, title_data in latest_source_titles.items():
  251. if title not in historical_set:
  252. source_new_titles[title] = title_data
  253. if source_new_titles:
  254. source_id = None
  255. for id_val, alias in id_to_alias.items():
  256. if alias == source_name:
  257. source_id = id_val
  258. break
  259. if source_id:
  260. new_titles[source_id] = source_new_titles
  261. return new_titles
  262. @staticmethod
  263. def _parse_file_titles(file_path: Path) -> Dict:
  264. """解析单个txt文件的标题数据"""
  265. titles_by_source = {}
  266. with open(file_path, "r", encoding="utf-8") as f:
  267. content = f.read()
  268. sections = content.split("\n\n")
  269. for section in sections:
  270. if not section.strip() or "==== 以下ID请求失败 ====" in section:
  271. continue
  272. lines = section.strip().split("\n")
  273. if len(lines) < 2:
  274. continue
  275. source_name = lines[0].strip()
  276. titles_by_source[source_name] = {}
  277. for line in lines[1:]:
  278. if line.strip():
  279. try:
  280. title_part = line.strip()
  281. rank = None
  282. # 提取排名
  283. if (
  284. ". " in title_part
  285. and title_part.split(". ")[0].isdigit()
  286. ):
  287. rank_str, title_part = title_part.split(". ", 1)
  288. rank = int(rank_str)
  289. # 提取MOBILE URL
  290. mobile_url = ""
  291. if " [MOBILE:" in title_part:
  292. title_part, mobile_part = title_part.rsplit(
  293. " [MOBILE:", 1
  294. )
  295. if mobile_part.endswith("]"):
  296. mobile_url = mobile_part[:-1]
  297. # 提取URL
  298. url = ""
  299. if " [URL:" in title_part:
  300. title_part, url_part = title_part.rsplit(" [URL:", 1)
  301. if url_part.endswith("]"):
  302. url = url_part[:-1]
  303. title = title_part.strip()
  304. ranks = [rank] if rank is not None else [1]
  305. titles_by_source[source_name][title] = {
  306. "ranks": ranks,
  307. "url": url,
  308. "mobileUrl": mobile_url,
  309. }
  310. except Exception as e:
  311. print(f"解析标题行出错: {line}, 错误: {e}")
  312. return titles_by_source
  313. @staticmethod
  314. def save_titles_to_file(results: Dict, id_to_alias: Dict, failed_ids: List) -> str:
  315. """保存标题到文件"""
  316. file_path = FileHelper.get_output_path(
  317. "txt", f"{TimeHelper.format_time_filename()}.txt"
  318. )
  319. with open(file_path, "w", encoding="utf-8") as f:
  320. for id_value, title_data in results.items():
  321. display_name = id_to_alias.get(id_value, id_value)
  322. f.write(f"{display_name}\n")
  323. # 按排名排序标题
  324. sorted_titles = []
  325. for title, info in title_data.items():
  326. if isinstance(info, dict):
  327. ranks = info.get("ranks", [])
  328. url = info.get("url", "")
  329. mobile_url = info.get("mobileUrl", "")
  330. else:
  331. ranks = info if isinstance(info, list) else []
  332. url = ""
  333. mobile_url = ""
  334. rank = ranks[0] if ranks else 1
  335. sorted_titles.append((rank, title, url, mobile_url))
  336. sorted_titles.sort(key=lambda x: x[0])
  337. for rank, title, url, mobile_url in sorted_titles:
  338. line = f"{rank}. {title}"
  339. if url:
  340. line += f" [URL:{url}]"
  341. if mobile_url:
  342. line += f" [MOBILE:{mobile_url}]"
  343. f.write(line + "\n")
  344. f.write("\n")
  345. if failed_ids:
  346. f.write("==== 以下ID请求失败 ====\n")
  347. for id_value in failed_ids:
  348. display_name = id_to_alias.get(id_value, id_value)
  349. f.write(f"{display_name} (ID: {id_value})\n")
  350. return file_path
  351. @staticmethod
  352. def load_frequency_words(
  353. frequency_file: str = "frequency_words.txt",
  354. ) -> Tuple[List[Dict], List[str]]:
  355. """加载频率词配置"""
  356. frequency_path = Path(frequency_file)
  357. if not frequency_path.exists():
  358. print(f"频率词文件 {frequency_file} 不存在")
  359. return [], []
  360. with open(frequency_path, "r", encoding="utf-8") as f:
  361. content = f.read()
  362. word_groups = [
  363. group.strip() for group in content.split("\n\n") if group.strip()
  364. ]
  365. processed_groups = []
  366. filter_words = []
  367. for group in word_groups:
  368. words = [word.strip() for word in group.split("\n") if word.strip()]
  369. group_required_words = []
  370. group_normal_words = []
  371. group_filter_words = []
  372. for word in words:
  373. if word.startswith("!"):
  374. filter_words.append(word[1:])
  375. group_filter_words.append(word[1:])
  376. elif word.startswith("+"):
  377. group_required_words.append(word[1:])
  378. else:
  379. group_normal_words.append(word)
  380. if group_required_words or group_normal_words:
  381. if group_normal_words:
  382. group_key = " ".join(group_normal_words)
  383. else:
  384. group_key = " ".join(group_required_words)
  385. processed_groups.append(
  386. {
  387. "required": group_required_words,
  388. "normal": group_normal_words,
  389. "group_key": group_key,
  390. }
  391. )
  392. return processed_groups, filter_words
  393. @staticmethod
  394. def read_all_today_titles() -> Tuple[Dict, Dict, Dict]:
  395. """读取当天所有标题文件"""
  396. date_folder = TimeHelper.format_date_folder()
  397. txt_dir = Path("output") / date_folder / "txt"
  398. if not txt_dir.exists():
  399. return {}, {}, {}
  400. all_results = {}
  401. id_to_alias = {}
  402. title_info = {}
  403. files = sorted([f for f in txt_dir.iterdir() if f.suffix == ".txt"])
  404. for file_path in files:
  405. time_info = file_path.stem
  406. with open(file_path, "r", encoding="utf-8") as f:
  407. content = f.read()
  408. sections = content.split("\n\n")
  409. for section in sections:
  410. if not section.strip() or "==== 以下ID请求失败 ====" in section:
  411. continue
  412. lines = section.strip().split("\n")
  413. if len(lines) < 2:
  414. continue
  415. source_name = lines[0].strip()
  416. title_data = {}
  417. for line in lines[1:]:
  418. if line.strip():
  419. try:
  420. rank = None
  421. title_part = line.strip()
  422. # 提取行首的排名数字
  423. if (
  424. ". " in title_part
  425. and title_part.split(". ")[0].isdigit()
  426. ):
  427. parts = title_part.split(". ", 1)
  428. rank = int(parts[0])
  429. title_part = parts[1]
  430. # 提取 MOBILE URL
  431. mobile_url = ""
  432. if " [MOBILE:" in title_part:
  433. title_part, mobile_part = title_part.rsplit(
  434. " [MOBILE:", 1
  435. )
  436. if mobile_part.endswith("]"):
  437. mobile_url = mobile_part[:-1]
  438. # 提取 URL
  439. url = ""
  440. if " [URL:" in title_part:
  441. title_part, url_part = title_part.rsplit(
  442. " [URL:", 1
  443. )
  444. if url_part.endswith("]"):
  445. url = url_part[:-1]
  446. title = title_part.strip()
  447. ranks = [rank] if rank is not None else [1]
  448. title_data[title] = {
  449. "ranks": ranks,
  450. "url": url,
  451. "mobileUrl": mobile_url,
  452. }
  453. except Exception as e:
  454. print(f"解析标题行出错: {line}, 错误: {e}")
  455. DataProcessor._process_source_data(
  456. source_name,
  457. title_data,
  458. time_info,
  459. all_results,
  460. title_info,
  461. id_to_alias,
  462. )
  463. # 转换为ID格式
  464. id_results = {}
  465. id_title_info = {}
  466. for name, titles in all_results.items():
  467. for id_value, alias in id_to_alias.items():
  468. if alias == name:
  469. id_results[id_value] = titles
  470. id_title_info[id_value] = title_info[name]
  471. break
  472. return id_results, id_to_alias, id_title_info
  473. @staticmethod
  474. def _process_source_data(
  475. source_name: str,
  476. title_data: Dict,
  477. time_info: str,
  478. all_results: Dict,
  479. title_info: Dict,
  480. id_to_alias: Dict,
  481. ) -> None:
  482. """处理来源数据,合并重复标题"""
  483. if source_name not in all_results:
  484. all_results[source_name] = title_data
  485. if source_name not in title_info:
  486. title_info[source_name] = {}
  487. for title, data in title_data.items():
  488. ranks = data.get("ranks", [])
  489. url = data.get("url", "")
  490. mobile_url = data.get("mobileUrl", "")
  491. title_info[source_name][title] = {
  492. "first_time": time_info,
  493. "last_time": time_info,
  494. "count": 1,
  495. "ranks": ranks,
  496. "url": url,
  497. "mobileUrl": mobile_url,
  498. }
  499. reversed_id = source_name.lower().replace(" ", "-")
  500. id_to_alias[reversed_id] = source_name
  501. else:
  502. for title, data in title_data.items():
  503. ranks = data.get("ranks", [])
  504. url = data.get("url", "")
  505. mobile_url = data.get("mobileUrl", "")
  506. if title not in all_results[source_name]:
  507. all_results[source_name][title] = {
  508. "ranks": ranks,
  509. "url": url,
  510. "mobileUrl": mobile_url,
  511. }
  512. title_info[source_name][title] = {
  513. "first_time": time_info,
  514. "last_time": time_info,
  515. "count": 1,
  516. "ranks": ranks,
  517. "url": url,
  518. "mobileUrl": mobile_url,
  519. }
  520. else:
  521. existing_data = all_results[source_name][title]
  522. existing_ranks = existing_data.get("ranks", [])
  523. existing_url = existing_data.get("url", "")
  524. existing_mobile_url = existing_data.get("mobileUrl", "")
  525. merged_ranks = existing_ranks.copy()
  526. for rank in ranks:
  527. if rank not in merged_ranks:
  528. merged_ranks.append(rank)
  529. all_results[source_name][title] = {
  530. "ranks": merged_ranks,
  531. "url": existing_url or url,
  532. "mobileUrl": existing_mobile_url or mobile_url,
  533. }
  534. title_info[source_name][title]["last_time"] = time_info
  535. title_info[source_name][title]["ranks"] = merged_ranks
  536. title_info[source_name][title]["count"] += 1
  537. if not title_info[source_name][title].get("url"):
  538. title_info[source_name][title]["url"] = url
  539. if not title_info[source_name][title].get("mobileUrl"):
  540. title_info[source_name][title]["mobileUrl"] = mobile_url
  541. class StatisticsCalculator:
  542. """统计计算器"""
  543. @staticmethod
  544. def calculate_news_weight(
  545. title_data: Dict, rank_threshold: int = CONFIG["RANK_THRESHOLD"]
  546. ) -> float:
  547. """计算新闻权重,用于排序"""
  548. ranks = title_data.get("ranks", [])
  549. if not ranks:
  550. return 0.0
  551. count = title_data.get("count", len(ranks))
  552. weight_config = CONFIG["WEIGHT_CONFIG"]
  553. # 排名权重:Σ(11 - min(rank, 10)) / 出现次数
  554. rank_scores = []
  555. for rank in ranks:
  556. score = 11 - min(rank, 10)
  557. rank_scores.append(score)
  558. rank_weight = sum(rank_scores) / len(ranks) if ranks else 0
  559. # 频次权重:min(出现次数, 10) × 10
  560. frequency_weight = min(count, 10) * 10
  561. # 热度加成:高排名次数 / 总出现次数 × 100
  562. high_rank_count = sum(1 for rank in ranks if rank <= rank_threshold)
  563. hotness_ratio = high_rank_count / len(ranks) if ranks else 0
  564. hotness_weight = hotness_ratio * 100
  565. # 综合权重计算
  566. total_weight = (
  567. rank_weight * weight_config["RANK_WEIGHT"]
  568. + frequency_weight * weight_config["FREQUENCY_WEIGHT"]
  569. + hotness_weight * weight_config["HOTNESS_WEIGHT"]
  570. )
  571. return total_weight
  572. @staticmethod
  573. def sort_titles_by_weight(
  574. titles_list: List[Dict], rank_threshold: int = CONFIG["RANK_THRESHOLD"]
  575. ) -> List[Dict]:
  576. """按权重对新闻标题列表进行排序"""
  577. def get_sort_key(title_data):
  578. weight = StatisticsCalculator.calculate_news_weight(
  579. title_data, rank_threshold
  580. )
  581. ranks = title_data.get("ranks", [])
  582. count = title_data.get("count", 1)
  583. # 主要按权重排序,权重相同时按最高排名排序,再相同时按出现次数排序
  584. min_rank = min(ranks) if ranks else 999
  585. return (-weight, min_rank, -count)
  586. return sorted(titles_list, key=get_sort_key)
  587. @staticmethod
  588. def _matches_word_groups(
  589. title: str, word_groups: List[Dict], filter_words: List[str]
  590. ) -> bool:
  591. """检查标题是否匹配词组规则"""
  592. title_lower = title.lower()
  593. # 过滤词检查
  594. if any(filter_word.lower() in title_lower for filter_word in filter_words):
  595. return False
  596. # 词组匹配检查
  597. for group in word_groups:
  598. required_words = group["required"]
  599. normal_words = group["normal"]
  600. # 必须词检查
  601. if required_words:
  602. all_required_present = all(
  603. req_word.lower() in title_lower for req_word in required_words
  604. )
  605. if not all_required_present:
  606. continue
  607. # 普通词检查
  608. if normal_words:
  609. any_normal_present = any(
  610. normal_word.lower() in title_lower for normal_word in normal_words
  611. )
  612. if not any_normal_present:
  613. continue
  614. return True
  615. return False
  616. @staticmethod
  617. def count_word_frequency(
  618. results: Dict,
  619. word_groups: List[Dict],
  620. filter_words: List[str],
  621. id_to_alias: Dict,
  622. title_info: Optional[Dict] = None,
  623. rank_threshold: int = CONFIG["RANK_THRESHOLD"],
  624. new_titles: Optional[Dict] = None,
  625. ) -> Tuple[List[Dict], int]:
  626. """统计词频,支持必须词、频率词、过滤词,并标记新增标题"""
  627. word_stats = {}
  628. total_titles = 0
  629. processed_titles = {}
  630. if title_info is None:
  631. title_info = {}
  632. if new_titles is None:
  633. new_titles = {}
  634. for group in word_groups:
  635. group_key = group["group_key"]
  636. word_stats[group_key] = {"count": 0, "titles": {}}
  637. for source_id, titles_data in results.items():
  638. total_titles += len(titles_data)
  639. if source_id not in processed_titles:
  640. processed_titles[source_id] = {}
  641. for title, title_data in titles_data.items():
  642. if title in processed_titles.get(source_id, {}):
  643. continue
  644. # 使用统一的匹配逻辑
  645. if not StatisticsCalculator._matches_word_groups(
  646. title, word_groups, filter_words
  647. ):
  648. continue
  649. source_ranks = title_data.get("ranks", [])
  650. source_url = title_data.get("url", "")
  651. source_mobile_url = title_data.get("mobileUrl", "")
  652. # 找到匹配的词组
  653. title_lower = title.lower()
  654. for group in word_groups:
  655. required_words = group["required"]
  656. normal_words = group["normal"]
  657. # 再次检查匹配
  658. if required_words:
  659. all_required_present = all(
  660. req_word.lower() in title_lower
  661. for req_word in required_words
  662. )
  663. if not all_required_present:
  664. continue
  665. if normal_words:
  666. any_normal_present = any(
  667. normal_word.lower() in title_lower
  668. for normal_word in normal_words
  669. )
  670. if not any_normal_present:
  671. continue
  672. group_key = group["group_key"]
  673. word_stats[group_key]["count"] += 1
  674. if source_id not in word_stats[group_key]["titles"]:
  675. word_stats[group_key]["titles"][source_id] = []
  676. first_time = ""
  677. last_time = ""
  678. count_info = 1
  679. ranks = source_ranks if source_ranks else []
  680. url = source_url
  681. mobile_url = source_mobile_url
  682. if (
  683. title_info
  684. and source_id in title_info
  685. and title in title_info[source_id]
  686. ):
  687. info = title_info[source_id][title]
  688. first_time = info.get("first_time", "")
  689. last_time = info.get("last_time", "")
  690. count_info = info.get("count", 1)
  691. if "ranks" in info and info["ranks"]:
  692. ranks = info["ranks"]
  693. url = info.get("url", source_url)
  694. mobile_url = info.get("mobileUrl", source_mobile_url)
  695. if not ranks:
  696. ranks = [99]
  697. time_display = StatisticsCalculator._format_time_display(
  698. first_time, last_time
  699. )
  700. source_alias = id_to_alias.get(source_id, source_id)
  701. # 修复is_new判断逻辑,添加容错处理
  702. is_new = False
  703. if new_titles and source_id in new_titles:
  704. new_titles_for_source = new_titles[source_id]
  705. if title in new_titles_for_source:
  706. is_new = True
  707. else:
  708. # 如果直接匹配失败,尝试去除首尾空格后匹配
  709. title_stripped = title.strip()
  710. for new_title in new_titles_for_source.keys():
  711. if title_stripped == new_title.strip():
  712. is_new = True
  713. break
  714. word_stats[group_key]["titles"][source_id].append(
  715. {
  716. "title": title,
  717. "source_alias": source_alias,
  718. "first_time": first_time,
  719. "last_time": last_time,
  720. "time_display": time_display,
  721. "count": count_info,
  722. "ranks": ranks,
  723. "rank_threshold": rank_threshold,
  724. "url": url,
  725. "mobileUrl": mobile_url,
  726. "is_new": is_new,
  727. }
  728. )
  729. if source_id not in processed_titles:
  730. processed_titles[source_id] = {}
  731. processed_titles[source_id][title] = True
  732. break
  733. stats = []
  734. for group_key, data in word_stats.items():
  735. all_titles = []
  736. for source_id, title_list in data["titles"].items():
  737. all_titles.extend(title_list)
  738. # 按权重排序标题
  739. sorted_titles = StatisticsCalculator.sort_titles_by_weight(
  740. all_titles, rank_threshold
  741. )
  742. stats.append(
  743. {
  744. "word": group_key,
  745. "count": data["count"],
  746. "titles": sorted_titles,
  747. "percentage": (
  748. round(data["count"] / total_titles * 100, 2)
  749. if total_titles > 0
  750. else 0
  751. ),
  752. }
  753. )
  754. stats.sort(key=lambda x: x["count"], reverse=True)
  755. return stats, total_titles
  756. @staticmethod
  757. def _format_rank_base(
  758. ranks: List[int], rank_threshold: int = 5, format_type: str = "html"
  759. ) -> str:
  760. """基础排名格式化方法"""
  761. if not ranks:
  762. return ""
  763. unique_ranks = sorted(set(ranks))
  764. min_rank = unique_ranks[0]
  765. max_rank = unique_ranks[-1]
  766. # 根据格式类型选择不同的标记方式
  767. if format_type == "html":
  768. highlight_start = "<font color='red'><strong>"
  769. highlight_end = "</strong></font>"
  770. elif format_type == "feishu":
  771. highlight_start = "<font color='red'>**"
  772. highlight_end = "**</font>"
  773. elif format_type == "dingtalk":
  774. highlight_start = "**"
  775. highlight_end = "**"
  776. elif format_type == "wework":
  777. highlight_start = "**"
  778. highlight_end = "**"
  779. elif format_type == "telegram":
  780. highlight_start = "<b>"
  781. highlight_end = "</b>"
  782. else:
  783. highlight_start = "**"
  784. highlight_end = "**"
  785. # 格式化排名显示
  786. if min_rank <= rank_threshold:
  787. if min_rank == max_rank:
  788. return f"{highlight_start}[{min_rank}]{highlight_end}"
  789. else:
  790. return f"{highlight_start}[{min_rank} - {max_rank}]{highlight_end}"
  791. else:
  792. if min_rank == max_rank:
  793. return f"[{min_rank}]"
  794. else:
  795. return f"[{min_rank} - {max_rank}]"
  796. @staticmethod
  797. def _format_rank_for_html(ranks: List[int], rank_threshold: int = 5) -> str:
  798. """格式化HTML排名显示"""
  799. return StatisticsCalculator._format_rank_base(ranks, rank_threshold, "html")
  800. @staticmethod
  801. def _format_rank_for_feishu(ranks: List[int], rank_threshold: int = 5) -> str:
  802. """格式化飞书排名显示"""
  803. return StatisticsCalculator._format_rank_base(ranks, rank_threshold, "feishu")
  804. @staticmethod
  805. def _format_rank_for_dingtalk(ranks: List[int], rank_threshold: int = 5) -> str:
  806. """格式化钉钉排名显示"""
  807. return StatisticsCalculator._format_rank_base(ranks, rank_threshold, "dingtalk")
  808. @staticmethod
  809. def _format_rank_for_wework(ranks: List[int], rank_threshold: int = 5) -> str:
  810. """格式化企业微信排名显示"""
  811. return StatisticsCalculator._format_rank_base(ranks, rank_threshold, "wework")
  812. @staticmethod
  813. def _format_rank_for_telegram(ranks: List[int], rank_threshold: int = 5) -> str:
  814. """格式化Telegram排名显示"""
  815. return StatisticsCalculator._format_rank_base(ranks, rank_threshold, "telegram")
  816. @staticmethod
  817. def _format_time_display(first_time: str, last_time: str) -> str:
  818. """格式化时间显示"""
  819. if not first_time:
  820. return ""
  821. if first_time == last_time or not last_time:
  822. return first_time
  823. else:
  824. return f"[{first_time} ~ {last_time}]"
  825. class ReportGenerator:
  826. """报告生成器"""
  827. @staticmethod
  828. def generate_html_report(
  829. stats: List[Dict],
  830. total_titles: int,
  831. failed_ids: Optional[List] = None,
  832. is_daily: bool = False,
  833. new_titles: Optional[Dict] = None,
  834. id_to_alias: Optional[Dict] = None,
  835. ) -> str:
  836. """生成HTML报告"""
  837. if is_daily:
  838. filename = "当日统计.html"
  839. else:
  840. filename = f"{TimeHelper.format_time_filename()}.html"
  841. file_path = FileHelper.get_output_path("html", filename)
  842. # 数据处理层
  843. report_data = ReportGenerator._prepare_report_data(
  844. stats, failed_ids, new_titles, id_to_alias
  845. )
  846. # 渲染层
  847. html_content = ReportGenerator._render_html_content(
  848. report_data, total_titles, is_daily
  849. )
  850. with open(file_path, "w", encoding="utf-8") as f:
  851. f.write(html_content)
  852. if is_daily:
  853. root_file_path = Path("index.html")
  854. with open(root_file_path, "w", encoding="utf-8") as f:
  855. f.write(html_content)
  856. return file_path
  857. @staticmethod
  858. def _prepare_report_data(
  859. stats: List[Dict],
  860. failed_ids: Optional[List] = None,
  861. new_titles: Optional[Dict] = None,
  862. id_to_alias: Optional[Dict] = None,
  863. ) -> Dict:
  864. """准备报告数据"""
  865. filtered_new_titles = {}
  866. if new_titles and id_to_alias:
  867. word_groups, filter_words = DataProcessor.load_frequency_words()
  868. for source_id, titles_data in new_titles.items():
  869. filtered_titles = ReportGenerator._apply_frequency_filter(
  870. titles_data, word_groups, filter_words
  871. )
  872. if filtered_titles:
  873. filtered_new_titles[source_id] = filtered_titles
  874. processed_stats = []
  875. for stat in stats:
  876. if stat["count"] <= 0:
  877. continue
  878. processed_titles = []
  879. for title_data in stat["titles"]:
  880. processed_title = {
  881. "title": title_data["title"],
  882. "source_alias": title_data["source_alias"],
  883. "time_display": title_data["time_display"],
  884. "count": title_data["count"],
  885. "ranks": title_data["ranks"],
  886. "rank_threshold": title_data["rank_threshold"],
  887. "url": title_data.get("url", ""),
  888. "mobile_url": title_data.get("mobileUrl", ""),
  889. "is_new": title_data.get("is_new", False),
  890. }
  891. processed_titles.append(processed_title)
  892. processed_stats.append(
  893. {
  894. "word": stat["word"],
  895. "count": stat["count"],
  896. "percentage": stat.get("percentage", 0),
  897. "titles": processed_titles,
  898. }
  899. )
  900. processed_new_titles = []
  901. if filtered_new_titles and id_to_alias:
  902. for source_id, titles_data in filtered_new_titles.items():
  903. source_alias = id_to_alias.get(source_id, source_id)
  904. source_titles = []
  905. for title, title_data in titles_data.items():
  906. url, mobile_url, ranks = ReportGenerator._extract_title_data_fields(
  907. title_data
  908. )
  909. processed_title = {
  910. "title": title,
  911. "source_alias": source_alias,
  912. "time_display": "",
  913. "count": 1,
  914. "ranks": ranks,
  915. "rank_threshold": CONFIG["RANK_THRESHOLD"],
  916. "url": url,
  917. "mobile_url": mobile_url,
  918. "is_new": True,
  919. }
  920. source_titles.append(processed_title)
  921. if source_titles:
  922. processed_new_titles.append(
  923. {
  924. "source_id": source_id,
  925. "source_alias": source_alias,
  926. "titles": source_titles,
  927. }
  928. )
  929. return {
  930. "stats": processed_stats,
  931. "new_titles": processed_new_titles,
  932. "failed_ids": failed_ids or [],
  933. "total_new_count": sum(
  934. len(source["titles"]) for source in processed_new_titles
  935. ),
  936. }
  937. @staticmethod
  938. def _extract_title_data_fields(title_data) -> Tuple[str, str, List[int]]:
  939. """提取标题数据的通用字段"""
  940. url = title_data.get("url", "")
  941. mobile_url = title_data.get("mobileUrl", "")
  942. ranks = title_data.get("ranks", [])
  943. return url, mobile_url, ranks
  944. @staticmethod
  945. def _apply_frequency_filter(
  946. titles_data: Dict, word_groups: List[Dict], filter_words: List[str]
  947. ) -> Dict:
  948. """应用频率词过滤逻辑"""
  949. filtered_titles = {}
  950. for title, title_data in titles_data.items():
  951. if StatisticsCalculator._matches_word_groups(
  952. title, word_groups, filter_words
  953. ):
  954. filtered_titles[title] = title_data
  955. return filtered_titles
  956. @staticmethod
  957. def _html_escape(text: str) -> str:
  958. """HTML转义"""
  959. if not isinstance(text, str):
  960. text = str(text)
  961. return (
  962. text.replace("&", "&amp;")
  963. .replace("<", "&lt;")
  964. .replace(">", "&gt;")
  965. .replace('"', "&quot;")
  966. .replace("'", "&#x27;")
  967. )
  968. @staticmethod
  969. def _format_title_html(title_data: Dict) -> str:
  970. """格式化HTML标题显示"""
  971. rank_display = StatisticsCalculator._format_rank_for_html(
  972. title_data["ranks"], title_data["rank_threshold"]
  973. )
  974. link_url = title_data["mobile_url"] or title_data["url"]
  975. escaped_title = ReportGenerator._html_escape(title_data["title"])
  976. escaped_source_alias = ReportGenerator._html_escape(title_data["source_alias"])
  977. if link_url:
  978. escaped_url = ReportGenerator._html_escape(link_url)
  979. formatted_title = f'[{escaped_source_alias}] <a href="{escaped_url}" target="_blank" class="news-link">{escaped_title}</a>'
  980. else:
  981. formatted_title = (
  982. f'[{escaped_source_alias}] <span class="no-link">{escaped_title}</span>'
  983. )
  984. if rank_display:
  985. formatted_title += f" {rank_display}"
  986. if title_data["time_display"]:
  987. escaped_time = ReportGenerator._html_escape(title_data["time_display"])
  988. formatted_title += f" <font color='grey'>- {escaped_time}</font>"
  989. if title_data["count"] > 1:
  990. formatted_title += f" <font color='green'>({title_data['count']}次)</font>"
  991. if title_data["is_new"]:
  992. formatted_title = f"<div class='new-title'>🆕 {formatted_title}</div>"
  993. return formatted_title
  994. @staticmethod
  995. def _render_html_content(
  996. report_data: Dict, total_titles: int, is_daily: bool = False
  997. ) -> str:
  998. """渲染HTML内容"""
  999. html = """
  1000. <!DOCTYPE html>
  1001. <html>
  1002. <head>
  1003. <meta charset="UTF-8">
  1004. <title>频率词统计报告</title>
  1005. <style>
  1006. body { font-family: Arial, sans-serif; margin: 20px; }
  1007. h1, h2 { color: #333; }
  1008. table { border-collapse: collapse; width: 100%; margin-top: 20px; }
  1009. th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
  1010. th { background-color: #f2f2f2; }
  1011. tr:nth-child(even) { background-color: #f9f9f9; }
  1012. .word { font-weight: bold; }
  1013. .count { text-align: center; }
  1014. .percentage { text-align: center; }
  1015. .titles { max-width: 500px; }
  1016. .source { color: #666; font-style: italic; }
  1017. .error { color: #d9534f; }
  1018. .news-link {
  1019. color: #007bff;
  1020. text-decoration: none;
  1021. border-bottom: 1px dotted #007bff;
  1022. }
  1023. .news-link:hover {
  1024. color: #0056b3;
  1025. text-decoration: underline;
  1026. }
  1027. .news-link:visited {
  1028. color: #6f42c1;
  1029. }
  1030. .no-link {
  1031. color: #333;
  1032. }
  1033. .new-title {
  1034. background-color: #fff3cd;
  1035. border: 1px solid #ffc107;
  1036. border-radius: 3px;
  1037. padding: 2px 6px;
  1038. margin: 2px 0;
  1039. }
  1040. .new-section {
  1041. background-color: #d1ecf1;
  1042. border: 1px solid #bee5eb;
  1043. border-radius: 5px;
  1044. padding: 10px;
  1045. margin-top: 10px;
  1046. }
  1047. .new-section h3 {
  1048. color: #0c5460;
  1049. margin-top: 0;
  1050. }
  1051. </style>
  1052. </head>
  1053. <body>
  1054. <h1>频率词统计报告</h1>
  1055. """
  1056. if is_daily:
  1057. html += "<p>报告类型: 当日汇总</p>"
  1058. now = TimeHelper.get_beijing_time()
  1059. html += f"<p>总标题数: {total_titles}</p>"
  1060. html += f"<p>生成时间: {now.strftime('%Y-%m-%d %H:%M:%S')}</p>"
  1061. # 渲染失败平台
  1062. if report_data["failed_ids"]:
  1063. html += """
  1064. <div class="error">
  1065. <h2>请求失败的平台</h2>
  1066. <ul>
  1067. """
  1068. for id_value in report_data["failed_ids"]:
  1069. html += f"<li>{ReportGenerator._html_escape(id_value)}</li>"
  1070. html += """
  1071. </ul>
  1072. </div>
  1073. """
  1074. # 渲染统计表格
  1075. html += """
  1076. <table>
  1077. <tr>
  1078. <th>排名</th>
  1079. <th>频率词</th>
  1080. <th>出现次数</th>
  1081. <th>占比</th>
  1082. <th>相关标题</th>
  1083. </tr>
  1084. """
  1085. for i, stat in enumerate(report_data["stats"], 1):
  1086. formatted_titles = []
  1087. for title_data in stat["titles"]:
  1088. formatted_title = ReportGenerator._format_title_html(title_data)
  1089. formatted_titles.append(formatted_title)
  1090. escaped_word = ReportGenerator._html_escape(stat["word"])
  1091. html += f"""
  1092. <tr>
  1093. <td>{i}</td>
  1094. <td class="word">{escaped_word}</td>
  1095. <td class="count">{stat['count']}</td>
  1096. <td class="percentage">{stat.get('percentage', 0)}%</td>
  1097. <td class="titles">{"<br>".join(formatted_titles)}</td>
  1098. </tr>
  1099. """
  1100. html += """
  1101. </table>
  1102. """
  1103. # 渲染新增新闻部分
  1104. if report_data["new_titles"]:
  1105. html += f"""
  1106. <div class="new-section">
  1107. <h3>🆕 本次新增热点新闻 (共 {report_data['total_new_count']} 条)</h3>
  1108. """
  1109. for source_data in report_data["new_titles"]:
  1110. escaped_source = ReportGenerator._html_escape(
  1111. source_data["source_alias"]
  1112. )
  1113. html += (
  1114. f"<h4>{escaped_source} ({len(source_data['titles'])} 条)</h4><ul>"
  1115. )
  1116. for title_data in source_data["titles"]:
  1117. title_data_copy = title_data.copy()
  1118. title_data_copy["is_new"] = False
  1119. formatted_title = ReportGenerator._format_title_html(
  1120. title_data_copy
  1121. )
  1122. # 移除来源标签
  1123. if "] " in formatted_title:
  1124. formatted_title = formatted_title.split("] ", 1)[1]
  1125. html += f"<li>{formatted_title}</li>"
  1126. html += "</ul>"
  1127. html += "</div>"
  1128. html += """
  1129. </body>
  1130. </html>
  1131. """
  1132. return html
  1133. @staticmethod
  1134. def _format_title_feishu(title_data: Dict, show_source: bool = True) -> str:
  1135. """格式化飞书标题显示"""
  1136. rank_display = StatisticsCalculator._format_rank_for_feishu(
  1137. title_data["ranks"], title_data["rank_threshold"]
  1138. )
  1139. link_url = title_data["mobile_url"] or title_data["url"]
  1140. if link_url:
  1141. formatted_title = f"[{title_data['title']}]({link_url})"
  1142. else:
  1143. formatted_title = title_data["title"]
  1144. title_prefix = "🆕 " if title_data["is_new"] else ""
  1145. if show_source:
  1146. result = f"<font color='grey'>[{title_data['source_alias']}]</font> {title_prefix}{formatted_title}"
  1147. else:
  1148. result = f"{title_prefix}{formatted_title}"
  1149. if rank_display:
  1150. result += f" {rank_display}"
  1151. if title_data["time_display"]:
  1152. result += f" <font color='grey'>- {title_data['time_display']}</font>"
  1153. if title_data["count"] > 1:
  1154. result += f" <font color='green'>({title_data['count']}次)</font>"
  1155. return result
  1156. @staticmethod
  1157. def _format_title_dingtalk(title_data: Dict, show_source: bool = True) -> str:
  1158. """格式化钉钉标题显示"""
  1159. rank_display = StatisticsCalculator._format_rank_for_dingtalk(
  1160. title_data["ranks"], title_data["rank_threshold"]
  1161. )
  1162. link_url = title_data["mobile_url"] or title_data["url"]
  1163. if link_url:
  1164. formatted_title = f"[{title_data['title']}]({link_url})"
  1165. else:
  1166. formatted_title = title_data["title"]
  1167. title_prefix = "🆕 " if title_data["is_new"] else ""
  1168. if show_source:
  1169. result = f"[{title_data['source_alias']}] {title_prefix}{formatted_title}"
  1170. else:
  1171. result = f"{title_prefix}{formatted_title}"
  1172. if rank_display:
  1173. result += f" {rank_display}"
  1174. if title_data["time_display"]:
  1175. result += f" - {title_data['time_display']}"
  1176. if title_data["count"] > 1:
  1177. result += f" ({title_data['count']}次)"
  1178. return result
  1179. @staticmethod
  1180. def _format_title_wework(title_data: Dict, show_source: bool = True) -> str:
  1181. """格式化企业微信标题显示"""
  1182. rank_display = StatisticsCalculator._format_rank_for_wework(
  1183. title_data["ranks"], title_data["rank_threshold"]
  1184. )
  1185. link_url = title_data["mobile_url"] or title_data["url"]
  1186. if link_url:
  1187. formatted_title = f"[{title_data['title']}]({link_url})"
  1188. else:
  1189. formatted_title = title_data["title"]
  1190. title_prefix = "🆕 " if title_data["is_new"] else ""
  1191. if show_source:
  1192. result = f"[{title_data['source_alias']}] {title_prefix}{formatted_title}"
  1193. else:
  1194. result = f"{title_prefix}{formatted_title}"
  1195. if rank_display:
  1196. result += f" {rank_display}"
  1197. if title_data["time_display"]:
  1198. result += f" - {title_data['time_display']}"
  1199. if title_data["count"] > 1:
  1200. result += f" ({title_data['count']}次)"
  1201. return result
  1202. @staticmethod
  1203. def _format_title_telegram(title_data: Dict, show_source: bool = True) -> str:
  1204. """格式化Telegram标题显示"""
  1205. rank_display = StatisticsCalculator._format_rank_for_telegram(
  1206. title_data["ranks"], title_data["rank_threshold"]
  1207. )
  1208. link_url = title_data["mobile_url"] or title_data["url"]
  1209. if link_url:
  1210. formatted_title = f'<a href="{link_url}">{ReportGenerator._html_escape(title_data["title"])}</a>'
  1211. else:
  1212. formatted_title = title_data["title"]
  1213. title_prefix = "🆕 " if title_data["is_new"] else ""
  1214. if show_source:
  1215. result = f"[{title_data['source_alias']}] {title_prefix}{formatted_title}"
  1216. else:
  1217. result = f"{title_prefix}{formatted_title}"
  1218. if rank_display:
  1219. result += f" {rank_display}"
  1220. if title_data["time_display"]:
  1221. result += f" <code>- {title_data['time_display']}</code>"
  1222. if title_data["count"] > 1:
  1223. result += f" <code>({title_data['count']}次)</code>"
  1224. return result
  1225. @staticmethod
  1226. def _render_feishu_content(
  1227. report_data: Dict, update_info: Optional[Dict] = None
  1228. ) -> str:
  1229. """渲染飞书内容"""
  1230. text_content = ""
  1231. # 渲染热点词汇统计
  1232. if report_data["stats"]:
  1233. text_content += "📊 **热点词汇统计**\n\n"
  1234. total_count = len(report_data["stats"])
  1235. for i, stat in enumerate(report_data["stats"]):
  1236. word = stat["word"]
  1237. count = stat["count"]
  1238. sequence_display = f"<font color='grey'>[{i + 1}/{total_count}]</font>"
  1239. if count >= 10:
  1240. text_content += f"🔥 {sequence_display} **{word}** : <font color='red'>{count}</font> 条\n\n"
  1241. elif count >= 5:
  1242. text_content += f"📈 {sequence_display} **{word}** : <font color='orange'>{count}</font> 条\n\n"
  1243. else:
  1244. text_content += f"📌 {sequence_display} **{word}** : {count} 条\n\n"
  1245. for j, title_data in enumerate(stat["titles"], 1):
  1246. formatted_title = ReportGenerator._format_title_feishu(
  1247. title_data, show_source=True
  1248. )
  1249. text_content += f" {j}. {formatted_title}\n"
  1250. if j < len(stat["titles"]):
  1251. text_content += "\n"
  1252. if i < len(report_data["stats"]) - 1:
  1253. text_content += f"\n{CONFIG['FEISHU_MESSAGE_SEPARATOR']}\n\n"
  1254. if not text_content:
  1255. text_content = "📭 暂无匹配的热点词汇\n\n"
  1256. # 渲染新增新闻部分
  1257. if report_data["new_titles"]:
  1258. if text_content and "暂无匹配" not in text_content:
  1259. text_content += f"\n{CONFIG['FEISHU_MESSAGE_SEPARATOR']}\n\n"
  1260. text_content += (
  1261. f"🆕 **本次新增热点新闻** (共 {report_data['total_new_count']} 条)\n\n"
  1262. )
  1263. for source_data in report_data["new_titles"]:
  1264. text_content += f"**{source_data['source_alias']}** ({len(source_data['titles'])} 条):\n"
  1265. for j, title_data in enumerate(source_data["titles"], 1):
  1266. title_data_copy = title_data.copy()
  1267. title_data_copy["is_new"] = False
  1268. formatted_title = ReportGenerator._format_title_feishu(
  1269. title_data_copy, show_source=False
  1270. )
  1271. text_content += f" {j}. {formatted_title}\n"
  1272. text_content += "\n"
  1273. # 渲染失败平台
  1274. if report_data["failed_ids"]:
  1275. if text_content and "暂无匹配" not in text_content:
  1276. text_content += f"\n{CONFIG['FEISHU_MESSAGE_SEPARATOR']}\n\n"
  1277. text_content += "⚠️ **数据获取失败的平台:**\n\n"
  1278. for i, id_value in enumerate(report_data["failed_ids"], 1):
  1279. text_content += f" • <font color='red'>{id_value}</font>\n"
  1280. # 添加时间戳
  1281. now = TimeHelper.get_beijing_time()
  1282. text_content += f"\n\n<font color='grey'>更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}</font>"
  1283. # 版本更新提示
  1284. if update_info:
  1285. text_content += f"\n<font color='grey'>TrendRadar 发现新版本 {update_info['remote_version']},当前 {update_info['current_version']}</font>"
  1286. return text_content
  1287. @staticmethod
  1288. def _render_dingtalk_content(
  1289. report_data: Dict, update_info: Optional[Dict] = None
  1290. ) -> str:
  1291. """渲染钉钉内容"""
  1292. text_content = ""
  1293. # 计算总标题数
  1294. total_titles = sum(
  1295. len(stat["titles"]) for stat in report_data["stats"] if stat["count"] > 0
  1296. )
  1297. now = TimeHelper.get_beijing_time()
  1298. # 顶部统计信息
  1299. text_content += f"**总新闻数:** {total_titles}\n\n"
  1300. text_content += f"**时间:** {now.strftime('%Y-%m-%d %H:%M:%S')}\n\n"
  1301. text_content += f"**类型:** 热点分析报告\n\n"
  1302. text_content += "---\n\n"
  1303. # 渲染热点词汇统计
  1304. if report_data["stats"]:
  1305. text_content += "📊 **热点词汇统计**\n\n"
  1306. total_count = len(report_data["stats"])
  1307. for i, stat in enumerate(report_data["stats"]):
  1308. word = stat["word"]
  1309. count = stat["count"]
  1310. sequence_display = f"[{i + 1}/{total_count}]"
  1311. if count >= 10:
  1312. text_content += (
  1313. f"🔥 {sequence_display} **{word}** : **{count}** 条\n\n"
  1314. )
  1315. elif count >= 5:
  1316. text_content += (
  1317. f"📈 {sequence_display} **{word}** : **{count}** 条\n\n"
  1318. )
  1319. else:
  1320. text_content += f"📌 {sequence_display} **{word}** : {count} 条\n\n"
  1321. for j, title_data in enumerate(stat["titles"], 1):
  1322. formatted_title = ReportGenerator._format_title_dingtalk(
  1323. title_data, show_source=True
  1324. )
  1325. text_content += f" {j}. {formatted_title}\n"
  1326. if j < len(stat["titles"]):
  1327. text_content += "\n"
  1328. if i < len(report_data["stats"]) - 1:
  1329. text_content += f"\n---\n\n"
  1330. if not report_data["stats"]:
  1331. text_content += "📭 暂无匹配的热点词汇\n\n"
  1332. # 渲染新增新闻部分
  1333. if report_data["new_titles"]:
  1334. if text_content and "暂无匹配" not in text_content:
  1335. text_content += f"\n---\n\n"
  1336. text_content += (
  1337. f"🆕 **本次新增热点新闻** (共 {report_data['total_new_count']} 条)\n\n"
  1338. )
  1339. for source_data in report_data["new_titles"]:
  1340. text_content += f"**{source_data['source_alias']}** ({len(source_data['titles'])} 条):\n\n"
  1341. for j, title_data in enumerate(source_data["titles"], 1):
  1342. title_data_copy = title_data.copy()
  1343. title_data_copy["is_new"] = False
  1344. formatted_title = ReportGenerator._format_title_dingtalk(
  1345. title_data_copy, show_source=False
  1346. )
  1347. text_content += f" {j}. {formatted_title}\n"
  1348. text_content += "\n"
  1349. # 渲染失败平台
  1350. if report_data["failed_ids"]:
  1351. if text_content and "暂无匹配" not in text_content:
  1352. text_content += f"\n---\n\n"
  1353. text_content += "⚠️ **数据获取失败的平台:**\n\n"
  1354. for i, id_value in enumerate(report_data["failed_ids"], 1):
  1355. text_content += f" • **{id_value}**\n"
  1356. # 添加时间戳
  1357. text_content += f"\n\n> 更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}"
  1358. # 版本更新提示
  1359. if update_info:
  1360. text_content += f"\n> TrendRadar 发现新版本 **{update_info['remote_version']}**,当前 **{update_info['current_version']}**"
  1361. return text_content
  1362. @staticmethod
  1363. def _split_content_into_batches(
  1364. report_data: Dict,
  1365. format_type: str,
  1366. update_info: Optional[Dict] = None,
  1367. max_bytes: int = CONFIG["MESSAGE_BATCH_SIZE"],
  1368. ) -> List[str]:
  1369. """分批处理消息内容,确保词组标题+至少第一条新闻的完整性"""
  1370. batches = []
  1371. # 基础信息构建
  1372. total_titles = sum(
  1373. len(stat["titles"]) for stat in report_data["stats"] if stat["count"] > 0
  1374. )
  1375. now = TimeHelper.get_beijing_time()
  1376. base_header = ""
  1377. if format_type == "wework":
  1378. base_header = f"**总新闻数:** {total_titles}\n\n\n\n"
  1379. elif format_type == "telegram":
  1380. base_header = f"总新闻数: {total_titles}\n\n"
  1381. base_footer = ""
  1382. if format_type == "wework":
  1383. base_footer = f"\n\n\n> 更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}"
  1384. if update_info:
  1385. base_footer += f"\n> TrendRadar 发现新版本 **{update_info['remote_version']}**,当前 **{update_info['current_version']}**"
  1386. elif format_type == "telegram":
  1387. base_footer = f"\n\n更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}"
  1388. if update_info:
  1389. base_footer += f"\nTrendRadar 发现新版本 {update_info['remote_version']},当前 {update_info['current_version']}"
  1390. stats_header = ""
  1391. if report_data["stats"]:
  1392. if format_type == "wework":
  1393. stats_header = "📊 **热点词汇统计**\n\n"
  1394. elif format_type == "telegram":
  1395. stats_header = "📊 热点词汇统计\n\n"
  1396. current_batch = base_header
  1397. current_batch_has_content = False
  1398. # 空内容处理
  1399. if (
  1400. not report_data["stats"]
  1401. and not report_data["new_titles"]
  1402. and not report_data["failed_ids"]
  1403. ):
  1404. simple_content = "📭 暂无匹配的热点词汇\n\n"
  1405. final_content = base_header + simple_content + base_footer
  1406. batches.append(final_content)
  1407. return batches
  1408. # 处理热点词汇统计
  1409. if report_data["stats"]:
  1410. total_count = len(report_data["stats"])
  1411. # 添加统计标题
  1412. test_content = current_batch + stats_header
  1413. if (
  1414. len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8"))
  1415. < max_bytes
  1416. ):
  1417. current_batch = test_content
  1418. current_batch_has_content = True
  1419. else:
  1420. if current_batch_has_content:
  1421. batches.append(current_batch + base_footer)
  1422. current_batch = base_header + stats_header
  1423. current_batch_has_content = True
  1424. # 逐个处理词组(确保词组标题+第一条新闻的原子性)
  1425. for i, stat in enumerate(report_data["stats"]):
  1426. word = stat["word"]
  1427. count = stat["count"]
  1428. sequence_display = f"[{i + 1}/{total_count}]"
  1429. # 构建词组标题
  1430. word_header = ""
  1431. if format_type == "wework":
  1432. if count >= 10:
  1433. word_header = (
  1434. f"🔥 {sequence_display} **{word}** : **{count}** 条\n\n"
  1435. )
  1436. elif count >= 5:
  1437. word_header = (
  1438. f"📈 {sequence_display} **{word}** : **{count}** 条\n\n"
  1439. )
  1440. else:
  1441. word_header = (
  1442. f"📌 {sequence_display} **{word}** : {count} 条\n\n"
  1443. )
  1444. elif format_type == "telegram":
  1445. if count >= 10:
  1446. word_header = f"🔥 {sequence_display} {word} : {count} 条\n\n"
  1447. elif count >= 5:
  1448. word_header = f"📈 {sequence_display} {word} : {count} 条\n\n"
  1449. else:
  1450. word_header = f"📌 {sequence_display} {word} : {count} 条\n\n"
  1451. # 构建第一条新闻
  1452. first_news_line = ""
  1453. if stat["titles"]:
  1454. first_title_data = stat["titles"][0]
  1455. if format_type == "wework":
  1456. formatted_title = ReportGenerator._format_title_wework(
  1457. first_title_data, show_source=True
  1458. )
  1459. elif format_type == "telegram":
  1460. formatted_title = ReportGenerator._format_title_telegram(
  1461. first_title_data, show_source=True
  1462. )
  1463. else:
  1464. formatted_title = f"{first_title_data['title']}"
  1465. first_news_line = f" 1. {formatted_title}\n"
  1466. if len(stat["titles"]) > 1:
  1467. first_news_line += "\n"
  1468. # 原子性检查:词组标题+第一条新闻必须一起处理
  1469. word_with_first_news = word_header + first_news_line
  1470. test_content = current_batch + word_with_first_news
  1471. if (
  1472. len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8"))
  1473. >= max_bytes
  1474. ):
  1475. # 当前批次容纳不下,开启新批次
  1476. if current_batch_has_content:
  1477. batches.append(current_batch + base_footer)
  1478. current_batch = base_header + stats_header + word_with_first_news
  1479. current_batch_has_content = True
  1480. start_index = 1
  1481. else:
  1482. current_batch = test_content
  1483. current_batch_has_content = True
  1484. start_index = 1
  1485. # 处理剩余新闻条目
  1486. for j in range(start_index, len(stat["titles"])):
  1487. title_data = stat["titles"][j]
  1488. if format_type == "wework":
  1489. formatted_title = ReportGenerator._format_title_wework(
  1490. title_data, show_source=True
  1491. )
  1492. elif format_type == "telegram":
  1493. formatted_title = ReportGenerator._format_title_telegram(
  1494. title_data, show_source=True
  1495. )
  1496. else:
  1497. formatted_title = f"{title_data['title']}"
  1498. news_line = f" {j + 1}. {formatted_title}\n"
  1499. if j < len(stat["titles"]) - 1:
  1500. news_line += "\n"
  1501. test_content = current_batch + news_line
  1502. if (
  1503. len(test_content.encode("utf-8"))
  1504. + len(base_footer.encode("utf-8"))
  1505. >= max_bytes
  1506. ):
  1507. if current_batch_has_content:
  1508. batches.append(current_batch + base_footer)
  1509. current_batch = (
  1510. base_header + stats_header + word_header + news_line
  1511. )
  1512. current_batch_has_content = True
  1513. else:
  1514. current_batch = test_content
  1515. current_batch_has_content = True
  1516. # 词组间分隔符
  1517. if i < len(report_data["stats"]) - 1:
  1518. separator = ""
  1519. if format_type == "wework":
  1520. separator = f"\n\n\n\n"
  1521. elif format_type == "telegram":
  1522. separator = f"\n\n"
  1523. test_content = current_batch + separator
  1524. if (
  1525. len(test_content.encode("utf-8"))
  1526. + len(base_footer.encode("utf-8"))
  1527. < max_bytes
  1528. ):
  1529. current_batch = test_content
  1530. # 处理新增新闻(同样确保来源标题+第一条新闻的原子性)
  1531. if report_data["new_titles"]:
  1532. new_header = ""
  1533. if format_type == "wework":
  1534. new_header = f"\n\n\n\n🆕 **本次新增热点新闻** (共 {report_data['total_new_count']} 条)\n\n"
  1535. elif format_type == "telegram":
  1536. new_header = f"\n\n🆕 本次新增热点新闻 (共 {report_data['total_new_count']} 条)\n\n"
  1537. test_content = current_batch + new_header
  1538. if (
  1539. len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8"))
  1540. >= max_bytes
  1541. ):
  1542. if current_batch_has_content:
  1543. batches.append(current_batch + base_footer)
  1544. current_batch = base_header + new_header
  1545. current_batch_has_content = True
  1546. else:
  1547. current_batch = test_content
  1548. current_batch_has_content = True
  1549. # 逐个处理新增新闻来源
  1550. for source_data in report_data["new_titles"]:
  1551. source_header = ""
  1552. if format_type == "wework":
  1553. source_header = f"**{source_data['source_alias']}** ({len(source_data['titles'])} 条):\n\n"
  1554. elif format_type == "telegram":
  1555. source_header = f"{source_data['source_alias']} ({len(source_data['titles'])} 条):\n\n"
  1556. # 构建第一条新增新闻
  1557. first_news_line = ""
  1558. if source_data["titles"]:
  1559. first_title_data = source_data["titles"][0]
  1560. title_data_copy = first_title_data.copy()
  1561. title_data_copy["is_new"] = False
  1562. if format_type == "wework":
  1563. formatted_title = ReportGenerator._format_title_wework(
  1564. title_data_copy, show_source=False
  1565. )
  1566. elif format_type == "telegram":
  1567. formatted_title = ReportGenerator._format_title_telegram(
  1568. title_data_copy, show_source=False
  1569. )
  1570. else:
  1571. formatted_title = f"{title_data_copy['title']}"
  1572. first_news_line = f" 1. {formatted_title}\n"
  1573. # 原子性检查:来源标题+第一条新闻
  1574. source_with_first_news = source_header + first_news_line
  1575. test_content = current_batch + source_with_first_news
  1576. if (
  1577. len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8"))
  1578. >= max_bytes
  1579. ):
  1580. if current_batch_has_content:
  1581. batches.append(current_batch + base_footer)
  1582. current_batch = base_header + new_header + source_with_first_news
  1583. current_batch_has_content = True
  1584. start_index = 1
  1585. else:
  1586. current_batch = test_content
  1587. current_batch_has_content = True
  1588. start_index = 1
  1589. # 处理剩余新增新闻
  1590. for j in range(start_index, len(source_data["titles"])):
  1591. title_data = source_data["titles"][j]
  1592. title_data_copy = title_data.copy()
  1593. title_data_copy["is_new"] = False
  1594. if format_type == "wework":
  1595. formatted_title = ReportGenerator._format_title_wework(
  1596. title_data_copy, show_source=False
  1597. )
  1598. elif format_type == "telegram":
  1599. formatted_title = ReportGenerator._format_title_telegram(
  1600. title_data_copy, show_source=False
  1601. )
  1602. else:
  1603. formatted_title = f"{title_data_copy['title']}"
  1604. news_line = f" {j + 1}. {formatted_title}\n"
  1605. test_content = current_batch + news_line
  1606. if (
  1607. len(test_content.encode("utf-8"))
  1608. + len(base_footer.encode("utf-8"))
  1609. >= max_bytes
  1610. ):
  1611. if current_batch_has_content:
  1612. batches.append(current_batch + base_footer)
  1613. current_batch = (
  1614. base_header + new_header + source_header + news_line
  1615. )
  1616. current_batch_has_content = True
  1617. else:
  1618. current_batch = test_content
  1619. current_batch_has_content = True
  1620. current_batch += "\n"
  1621. # 处理失败平台
  1622. if report_data["failed_ids"]:
  1623. failed_header = ""
  1624. if format_type == "wework":
  1625. failed_header = f"\n\n\n\n⚠️ **数据获取失败的平台:**\n\n"
  1626. elif format_type == "telegram":
  1627. failed_header = f"\n\n⚠️ 数据获取失败的平台:\n\n"
  1628. test_content = current_batch + failed_header
  1629. if (
  1630. len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8"))
  1631. >= max_bytes
  1632. ):
  1633. if current_batch_has_content:
  1634. batches.append(current_batch + base_footer)
  1635. current_batch = base_header + failed_header
  1636. current_batch_has_content = True
  1637. else:
  1638. current_batch = test_content
  1639. current_batch_has_content = True
  1640. for i, id_value in enumerate(report_data["failed_ids"], 1):
  1641. failed_line = f" • {id_value}\n"
  1642. test_content = current_batch + failed_line
  1643. if (
  1644. len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8"))
  1645. >= max_bytes
  1646. ):
  1647. if current_batch_has_content:
  1648. batches.append(current_batch + base_footer)
  1649. current_batch = base_header + failed_header + failed_line
  1650. current_batch_has_content = True
  1651. else:
  1652. current_batch = test_content
  1653. current_batch_has_content = True
  1654. # 完成最后批次
  1655. if current_batch_has_content:
  1656. batches.append(current_batch + base_footer)
  1657. return batches
  1658. @staticmethod
  1659. def send_to_webhooks(
  1660. stats: List[Dict],
  1661. failed_ids: Optional[List] = None,
  1662. report_type: str = "单次爬取",
  1663. new_titles: Optional[Dict] = None,
  1664. id_to_alias: Optional[Dict] = None,
  1665. update_info: Optional[Dict] = None,
  1666. proxy_url: Optional[str] = None,
  1667. ) -> Dict[str, bool]:
  1668. """发送数据到多个webhook平台"""
  1669. results = {}
  1670. # 数据处理层
  1671. report_data = ReportGenerator._prepare_report_data(
  1672. stats, failed_ids, new_titles, id_to_alias
  1673. )
  1674. # 获取环境变量中的webhook配置
  1675. feishu_url = os.environ.get("FEISHU_WEBHOOK_URL", CONFIG["FEISHU_WEBHOOK_URL"])
  1676. dingtalk_url = os.environ.get(
  1677. "DINGTALK_WEBHOOK_URL", CONFIG["DINGTALK_WEBHOOK_URL"]
  1678. )
  1679. wework_url = os.environ.get("WEWORK_WEBHOOK_URL", CONFIG["WEWORK_WEBHOOK_URL"])
  1680. telegram_token = os.environ.get(
  1681. "TELEGRAM_BOT_TOKEN", CONFIG["TELEGRAM_BOT_TOKEN"]
  1682. )
  1683. telegram_chat_id = os.environ.get(
  1684. "TELEGRAM_CHAT_ID", CONFIG["TELEGRAM_CHAT_ID"]
  1685. )
  1686. update_info_to_send = update_info if CONFIG["SHOW_VERSION_UPDATE"] else None
  1687. # 发送到飞书
  1688. if feishu_url:
  1689. results["feishu"] = ReportGenerator._send_to_feishu(
  1690. feishu_url, report_data, report_type, update_info_to_send, proxy_url
  1691. )
  1692. # 发送到钉钉
  1693. if dingtalk_url:
  1694. results["dingtalk"] = ReportGenerator._send_to_dingtalk(
  1695. dingtalk_url, report_data, report_type, update_info_to_send, proxy_url
  1696. )
  1697. # 发送到企业微信
  1698. if wework_url:
  1699. results["wework"] = ReportGenerator._send_to_wework(
  1700. wework_url, report_data, report_type, update_info_to_send, proxy_url
  1701. )
  1702. # 发送到Telegram
  1703. if telegram_token and telegram_chat_id:
  1704. results["telegram"] = ReportGenerator._send_to_telegram(
  1705. telegram_token,
  1706. telegram_chat_id,
  1707. report_data,
  1708. report_type,
  1709. update_info_to_send,
  1710. proxy_url,
  1711. )
  1712. if not results:
  1713. print("未配置任何webhook URL,跳过通知发送")
  1714. return results
  1715. @staticmethod
  1716. def _send_to_feishu(
  1717. webhook_url: str,
  1718. report_data: Dict,
  1719. report_type: str,
  1720. update_info: Optional[Dict] = None,
  1721. proxy_url: Optional[str] = None,
  1722. ) -> bool:
  1723. """发送到飞书"""
  1724. headers = {"Content-Type": "application/json"}
  1725. text_content = ReportGenerator._render_feishu_content(report_data, update_info)
  1726. total_titles = sum(
  1727. len(stat["titles"]) for stat in report_data["stats"] if stat["count"] > 0
  1728. )
  1729. now = TimeHelper.get_beijing_time()
  1730. payload = {
  1731. "msg_type": "text",
  1732. "content": {
  1733. "total_titles": total_titles,
  1734. "timestamp": now.strftime("%Y-%m-%d %H:%M:%S"),
  1735. "report_type": report_type,
  1736. "text": text_content,
  1737. },
  1738. }
  1739. proxies = None
  1740. if proxy_url:
  1741. proxies = {"http": proxy_url, "https": proxy_url}
  1742. try:
  1743. response = requests.post(
  1744. webhook_url, headers=headers, json=payload, proxies=proxies, timeout=30
  1745. )
  1746. if response.status_code == 200:
  1747. print(f"飞书通知发送成功 [{report_type}]")
  1748. return True
  1749. else:
  1750. print(
  1751. f"飞书通知发送失败 [{report_type}],状态码:{response.status_code}"
  1752. )
  1753. return False
  1754. except Exception as e:
  1755. print(f"飞书通知发送出错 [{report_type}]:{e}")
  1756. return False
  1757. @staticmethod
  1758. def _send_to_dingtalk(
  1759. webhook_url: str,
  1760. report_data: Dict,
  1761. report_type: str,
  1762. update_info: Optional[Dict] = None,
  1763. proxy_url: Optional[str] = None,
  1764. ) -> bool:
  1765. """发送到钉钉"""
  1766. headers = {"Content-Type": "application/json"}
  1767. text_content = ReportGenerator._render_dingtalk_content(
  1768. report_data, update_info
  1769. )
  1770. payload = {
  1771. "msgtype": "markdown",
  1772. "markdown": {
  1773. "title": f"TrendRadar 热点分析报告 - {report_type}",
  1774. "text": text_content,
  1775. },
  1776. }
  1777. proxies = None
  1778. if proxy_url:
  1779. proxies = {"http": proxy_url, "https": proxy_url}
  1780. try:
  1781. response = requests.post(
  1782. webhook_url, headers=headers, json=payload, proxies=proxies, timeout=30
  1783. )
  1784. if response.status_code == 200:
  1785. result = response.json()
  1786. if result.get("errcode") == 0:
  1787. print(f"钉钉通知发送成功 [{report_type}]")
  1788. return True
  1789. else:
  1790. print(
  1791. f"钉钉通知发送失败 [{report_type}],错误:{result.get('errmsg')}"
  1792. )
  1793. return False
  1794. else:
  1795. print(
  1796. f"钉钉通知发送失败 [{report_type}],状态码:{response.status_code}"
  1797. )
  1798. return False
  1799. except Exception as e:
  1800. print(f"钉钉通知发送出错 [{report_type}]:{e}")
  1801. return False
  1802. @staticmethod
  1803. def _send_to_wework(
  1804. webhook_url: str,
  1805. report_data: Dict,
  1806. report_type: str,
  1807. update_info: Optional[Dict] = None,
  1808. proxy_url: Optional[str] = None,
  1809. ) -> bool:
  1810. """发送到企业微信(支持分批发送)"""
  1811. headers = {"Content-Type": "application/json"}
  1812. proxies = None
  1813. if proxy_url:
  1814. proxies = {"http": proxy_url, "https": proxy_url}
  1815. # 获取分批内容
  1816. batches = ReportGenerator._split_content_into_batches(
  1817. report_data, "wework", update_info
  1818. )
  1819. print(f"企业微信消息分为 {len(batches)} 批次发送 [{report_type}]")
  1820. # 逐批发送
  1821. for i, batch_content in enumerate(batches, 1):
  1822. batch_size = len(batch_content.encode("utf-8"))
  1823. print(
  1824. f"发送企业微信第 {i}/{len(batches)} 批次,大小:{batch_size} 字节 [{report_type}]"
  1825. )
  1826. # 添加批次标识
  1827. if len(batches) > 1:
  1828. batch_header = f"**[第 {i}/{len(batches)} 批次]**\n\n"
  1829. batch_content = batch_header + batch_content
  1830. payload = {"msgtype": "markdown", "markdown": {"content": batch_content}}
  1831. try:
  1832. response = requests.post(
  1833. webhook_url,
  1834. headers=headers,
  1835. json=payload,
  1836. proxies=proxies,
  1837. timeout=30,
  1838. )
  1839. if response.status_code == 200:
  1840. result = response.json()
  1841. if result.get("errcode") == 0:
  1842. print(
  1843. f"企业微信第 {i}/{len(batches)} 批次发送成功 [{report_type}]"
  1844. )
  1845. # 批次间间隔
  1846. if i < len(batches):
  1847. time.sleep(CONFIG["BATCH_SEND_INTERVAL"])
  1848. else:
  1849. print(
  1850. f"企业微信第 {i}/{len(batches)} 批次发送失败 [{report_type}],错误:{result.get('errmsg')}"
  1851. )
  1852. return False
  1853. else:
  1854. print(
  1855. f"企业微信第 {i}/{len(batches)} 批次发送失败 [{report_type}],状态码:{response.status_code}"
  1856. )
  1857. return False
  1858. except Exception as e:
  1859. print(
  1860. f"企业微信第 {i}/{len(batches)} 批次发送出错 [{report_type}]:{e}"
  1861. )
  1862. return False
  1863. print(f"企业微信所有 {len(batches)} 批次发送完成 [{report_type}]")
  1864. return True
  1865. @staticmethod
  1866. def _send_to_telegram(
  1867. bot_token: str,
  1868. chat_id: str,
  1869. report_data: Dict,
  1870. report_type: str,
  1871. update_info: Optional[Dict] = None,
  1872. proxy_url: Optional[str] = None,
  1873. ) -> bool:
  1874. """发送到Telegram(支持分批发送)"""
  1875. headers = {"Content-Type": "application/json"}
  1876. url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
  1877. proxies = None
  1878. if proxy_url:
  1879. proxies = {"http": proxy_url, "https": proxy_url}
  1880. # 获取分批内容
  1881. batches = ReportGenerator._split_content_into_batches(
  1882. report_data, "telegram", update_info
  1883. )
  1884. print(f"Telegram消息分为 {len(batches)} 批次发送 [{report_type}]")
  1885. # 逐批发送
  1886. for i, batch_content in enumerate(batches, 1):
  1887. batch_size = len(batch_content.encode("utf-8"))
  1888. print(
  1889. f"发送Telegram第 {i}/{len(batches)} 批次,大小:{batch_size} 字节 [{report_type}]"
  1890. )
  1891. # 添加批次标识
  1892. if len(batches) > 1:
  1893. batch_header = f"<b>[第 {i}/{len(batches)} 批次]</b>\n\n"
  1894. batch_content = batch_header + batch_content
  1895. payload = {
  1896. "chat_id": chat_id,
  1897. "text": batch_content,
  1898. "parse_mode": "HTML",
  1899. "disable_web_page_preview": True,
  1900. }
  1901. try:
  1902. response = requests.post(
  1903. url, headers=headers, json=payload, proxies=proxies, timeout=30
  1904. )
  1905. if response.status_code == 200:
  1906. result = response.json()
  1907. if result.get("ok"):
  1908. print(
  1909. f"Telegram第 {i}/{len(batches)} 批次发送成功 [{report_type}]"
  1910. )
  1911. # 批次间间隔
  1912. if i < len(batches):
  1913. time.sleep(CONFIG["BATCH_SEND_INTERVAL"])
  1914. else:
  1915. print(
  1916. f"Telegram第 {i}/{len(batches)} 批次发送失败 [{report_type}],错误:{result.get('description')}"
  1917. )
  1918. return False
  1919. else:
  1920. print(
  1921. f"Telegram第 {i}/{len(batches)} 批次发送失败 [{report_type}],状态码:{response.status_code}"
  1922. )
  1923. return False
  1924. except Exception as e:
  1925. print(
  1926. f"Telegram第 {i}/{len(batches)} 批次发送出错 [{report_type}]:{e}"
  1927. )
  1928. return False
  1929. print(f"Telegram所有 {len(batches)} 批次发送完成 [{report_type}]")
  1930. return True
  1931. class NewsAnalyzer:
  1932. """新闻分析器"""
  1933. def __init__(
  1934. self,
  1935. request_interval: int = CONFIG["REQUEST_INTERVAL"],
  1936. report_type: str = CONFIG["REPORT_TYPE"],
  1937. rank_threshold: int = CONFIG["RANK_THRESHOLD"],
  1938. ):
  1939. self.request_interval = request_interval
  1940. self.report_type = report_type
  1941. self.rank_threshold = rank_threshold
  1942. self.is_github_actions = os.environ.get("GITHUB_ACTIONS") == "true"
  1943. self.update_info = None
  1944. self.proxy_url = None
  1945. if not self.is_github_actions and CONFIG["USE_PROXY"]:
  1946. self.proxy_url = CONFIG["DEFAULT_PROXY"]
  1947. print("本地环境,使用代理")
  1948. elif not self.is_github_actions and not CONFIG["USE_PROXY"]:
  1949. print("本地环境,未启用代理")
  1950. else:
  1951. print("GitHub Actions环境,不使用代理")
  1952. self.data_fetcher = DataFetcher(self.proxy_url)
  1953. if self.is_github_actions:
  1954. self._check_version_update()
  1955. def _check_version_update(self) -> None:
  1956. """检查版本更新"""
  1957. try:
  1958. need_update, remote_version = VersionChecker.check_for_updates(
  1959. CONFIG["VERSION"], CONFIG["VERSION_CHECK_URL"], self.proxy_url
  1960. )
  1961. if need_update and remote_version:
  1962. self.update_info = {
  1963. "current_version": CONFIG["VERSION"],
  1964. "remote_version": remote_version,
  1965. }
  1966. print(f"发现新版本: {remote_version} (当前: {CONFIG['VERSION']})")
  1967. else:
  1968. print("版本检查完成,当前为最新版本")
  1969. except Exception as e:
  1970. print(f"版本检查出错: {e}")
  1971. def generate_daily_summary(self) -> Optional[str]:
  1972. """生成当日统计报告"""
  1973. print("生成当日统计报告...")
  1974. all_results, id_to_alias, title_info = DataProcessor.read_all_today_titles()
  1975. if not all_results:
  1976. print("没有找到当天的数据")
  1977. return None
  1978. total_titles = sum(len(titles) for titles in all_results.values())
  1979. print(f"读取到 {total_titles} 个标题")
  1980. latest_new_titles = DataProcessor.detect_latest_new_titles(id_to_alias)
  1981. if latest_new_titles:
  1982. total_new_count = sum(len(titles) for titles in latest_new_titles.values())
  1983. print(f"检测到 {total_new_count} 条最新新增新闻")
  1984. word_groups, filter_words = DataProcessor.load_frequency_words()
  1985. stats, total_titles = StatisticsCalculator.count_word_frequency(
  1986. all_results,
  1987. word_groups,
  1988. filter_words,
  1989. id_to_alias,
  1990. title_info,
  1991. self.rank_threshold,
  1992. latest_new_titles,
  1993. )
  1994. html_file = ReportGenerator.generate_html_report(
  1995. stats,
  1996. total_titles,
  1997. is_daily=True,
  1998. new_titles=latest_new_titles,
  1999. id_to_alias=id_to_alias,
  2000. )
  2001. print(f"当日HTML统计报告已生成: {html_file}")
  2002. # 检查通知配置
  2003. has_webhook = any(
  2004. [
  2005. os.environ.get("FEISHU_WEBHOOK_URL", CONFIG["FEISHU_WEBHOOK_URL"]),
  2006. os.environ.get("DINGTALK_WEBHOOK_URL", CONFIG["DINGTALK_WEBHOOK_URL"]),
  2007. os.environ.get("WEWORK_WEBHOOK_URL", CONFIG["WEWORK_WEBHOOK_URL"]),
  2008. (
  2009. os.environ.get("TELEGRAM_BOT_TOKEN", CONFIG["TELEGRAM_BOT_TOKEN"])
  2010. and os.environ.get("TELEGRAM_CHAT_ID", CONFIG["TELEGRAM_CHAT_ID"])
  2011. ),
  2012. ]
  2013. )
  2014. if (
  2015. CONFIG["ENABLE_NOTIFICATION"]
  2016. and has_webhook
  2017. and self.report_type in ["daily", "both"]
  2018. ):
  2019. ReportGenerator.send_to_webhooks(
  2020. stats,
  2021. [],
  2022. "当日汇总",
  2023. latest_new_titles,
  2024. id_to_alias,
  2025. self.update_info,
  2026. self.proxy_url,
  2027. )
  2028. elif CONFIG["ENABLE_NOTIFICATION"] and not has_webhook:
  2029. print("⚠️ 警告:通知功能已启用但未配置webhook URL,将跳过通知发送")
  2030. elif not CONFIG["ENABLE_NOTIFICATION"]:
  2031. print("跳过当日汇总通知:通知功能已禁用")
  2032. return html_file
  2033. def run(self) -> None:
  2034. """执行分析流程"""
  2035. now = TimeHelper.get_beijing_time()
  2036. print(f"当前北京时间: {now.strftime('%Y-%m-%d %H:%M:%S')}")
  2037. if not CONFIG["ENABLE_CRAWLER"]:
  2038. print("爬虫功能已禁用(ENABLE_CRAWLER=False),程序退出")
  2039. return
  2040. # 检查是否配置了任何webhook URL
  2041. has_webhook = any(
  2042. [
  2043. os.environ.get("FEISHU_WEBHOOK_URL", CONFIG["FEISHU_WEBHOOK_URL"]),
  2044. os.environ.get("DINGTALK_WEBHOOK_URL", CONFIG["DINGTALK_WEBHOOK_URL"]),
  2045. os.environ.get("WEWORK_WEBHOOK_URL", CONFIG["WEWORK_WEBHOOK_URL"]),
  2046. (
  2047. os.environ.get("TELEGRAM_BOT_TOKEN", CONFIG["TELEGRAM_BOT_TOKEN"])
  2048. and os.environ.get("TELEGRAM_CHAT_ID", CONFIG["TELEGRAM_CHAT_ID"])
  2049. ),
  2050. ]
  2051. )
  2052. # 通知功能状态检查和提示
  2053. if not CONFIG["ENABLE_NOTIFICATION"]:
  2054. print("通知功能已禁用(ENABLE_NOTIFICATION=False),将只进行数据抓取")
  2055. elif not has_webhook:
  2056. print("未配置任何webhook URL,将只进行数据抓取,不发送通知")
  2057. else:
  2058. print("通知功能已启用,将发送webhook通知")
  2059. print(f"报告类型: {self.report_type}")
  2060. ids = [
  2061. ("toutiao", "今日头条"),
  2062. ("baidu", "百度热搜"),
  2063. ("wallstreetcn-hot", "华尔街见闻"),
  2064. ("thepaper", "澎湃新闻"),
  2065. ("bilibili-hot-search", "bilibili 热搜"),
  2066. ("cls-hot", "财联社热门"),
  2067. ("ifeng", "凤凰网"),
  2068. "tieba",
  2069. "weibo",
  2070. "douyin",
  2071. "zhihu",
  2072. ]
  2073. print(f"开始爬取数据,请求间隔 {self.request_interval} 毫秒")
  2074. FileHelper.ensure_directory_exists("output")
  2075. results, id_to_alias, failed_ids = self.data_fetcher.crawl_websites(
  2076. ids, self.request_interval
  2077. )
  2078. title_file = DataProcessor.save_titles_to_file(results, id_to_alias, failed_ids)
  2079. print(f"标题已保存到: {title_file}")
  2080. new_titles = DataProcessor.detect_latest_new_titles(id_to_alias)
  2081. # 构建标题信息
  2082. time_info = Path(title_file).stem
  2083. title_info = {}
  2084. for source_id, titles_data in results.items():
  2085. title_info[source_id] = {}
  2086. for title, title_data in titles_data.items():
  2087. ranks = title_data.get("ranks", [])
  2088. url = title_data.get("url", "")
  2089. mobile_url = title_data.get("mobileUrl", "")
  2090. title_info[source_id][title] = {
  2091. "first_time": time_info,
  2092. "last_time": time_info,
  2093. "count": 1,
  2094. "ranks": ranks,
  2095. "url": url,
  2096. "mobileUrl": mobile_url,
  2097. }
  2098. word_groups, filter_words = DataProcessor.load_frequency_words()
  2099. stats, total_titles = StatisticsCalculator.count_word_frequency(
  2100. results,
  2101. word_groups,
  2102. filter_words,
  2103. id_to_alias,
  2104. title_info,
  2105. self.rank_threshold,
  2106. new_titles,
  2107. )
  2108. # 只有启用通知且配置了webhook时才发送通知
  2109. if (
  2110. CONFIG["ENABLE_NOTIFICATION"]
  2111. and has_webhook
  2112. and self.report_type in ["current", "both"]
  2113. ):
  2114. ReportGenerator.send_to_webhooks(
  2115. stats,
  2116. failed_ids,
  2117. "单次爬取",
  2118. new_titles,
  2119. id_to_alias,
  2120. self.update_info,
  2121. self.proxy_url,
  2122. )
  2123. elif CONFIG["ENABLE_NOTIFICATION"] and not has_webhook:
  2124. print("⚠️ 警告:通知功能已启用但未配置webhook URL,将跳过通知发送")
  2125. elif not CONFIG["ENABLE_NOTIFICATION"]:
  2126. print("跳过单次爬取通知:通知功能已禁用")
  2127. html_file = ReportGenerator.generate_html_report(
  2128. stats, total_titles, failed_ids, False, new_titles, id_to_alias
  2129. )
  2130. print(f"HTML报告已生成: {html_file}")
  2131. daily_html = self.generate_daily_summary()
  2132. if not self.is_github_actions and html_file:
  2133. file_url = "file://" + str(Path(html_file).resolve())
  2134. print(f"正在打开HTML报告: {file_url}")
  2135. webbrowser.open(file_url)
  2136. if daily_html:
  2137. daily_url = "file://" + str(Path(daily_html).resolve())
  2138. print(f"正在打开当日统计报告: {daily_url}")
  2139. webbrowser.open(daily_url)
  2140. def main():
  2141. analyzer = NewsAnalyzer(
  2142. request_interval=CONFIG["REQUEST_INTERVAL"],
  2143. report_type=CONFIG["REPORT_TYPE"],
  2144. rank_threshold=CONFIG["RANK_THRESHOLD"],
  2145. )
  2146. analyzer.run()
  2147. if __name__ == "__main__":
  2148. main()