main.py 102 KB

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