data_service.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. """
  2. 数据访问服务
  3. 提供统一的数据查询接口,封装数据访问逻辑。
  4. """
  5. import re
  6. from collections import Counter
  7. from datetime import datetime, timedelta
  8. from typing import Dict, List, Optional, Tuple
  9. from .cache_service import get_cache
  10. from .parser_service import ParserService
  11. from ..utils.errors import DataNotFoundError
  12. class DataService:
  13. """数据访问服务类"""
  14. def __init__(self, project_root: str = None):
  15. """
  16. 初始化数据服务
  17. Args:
  18. project_root: 项目根目录
  19. """
  20. self.parser = ParserService(project_root)
  21. self.cache = get_cache()
  22. def get_latest_news(
  23. self,
  24. platforms: Optional[List[str]] = None,
  25. limit: int = 50,
  26. include_url: bool = False
  27. ) -> List[Dict]:
  28. """
  29. 获取最新一批爬取的新闻数据
  30. Args:
  31. platforms: 平台ID列表,None表示所有平台
  32. limit: 返回条数限制
  33. include_url: 是否包含URL链接,默认False(节省token)
  34. Returns:
  35. 新闻列表
  36. Raises:
  37. DataNotFoundError: 数据不存在
  38. """
  39. # 尝试从缓存获取
  40. cache_key = f"latest_news:{','.join(platforms or [])}:{limit}:{include_url}"
  41. cached = self.cache.get(cache_key, ttl=900) # 15分钟缓存
  42. if cached:
  43. return cached
  44. # 读取今天的数据
  45. all_titles, id_to_name, timestamps = self.parser.read_all_titles_for_date(
  46. date=None,
  47. platform_ids=platforms
  48. )
  49. # 获取最新的文件时间
  50. if timestamps:
  51. latest_timestamp = max(timestamps.values())
  52. fetch_time = datetime.fromtimestamp(latest_timestamp)
  53. else:
  54. fetch_time = datetime.now()
  55. # 转换为新闻列表
  56. news_list = []
  57. for platform_id, titles in all_titles.items():
  58. platform_name = id_to_name.get(platform_id, platform_id)
  59. for title, info in titles.items():
  60. # 取第一个排名
  61. rank = info["ranks"][0] if info["ranks"] else 0
  62. news_item = {
  63. "title": title,
  64. "platform": platform_id,
  65. "platform_name": platform_name,
  66. "rank": rank,
  67. "timestamp": fetch_time.strftime("%Y-%m-%d %H:%M:%S")
  68. }
  69. # 条件性添加 URL 字段
  70. if include_url:
  71. news_item["url"] = info.get("url", "")
  72. news_item["mobileUrl"] = info.get("mobileUrl", "")
  73. news_list.append(news_item)
  74. # 按排名排序
  75. news_list.sort(key=lambda x: x["rank"])
  76. # 限制返回数量
  77. result = news_list[:limit]
  78. # 缓存结果
  79. self.cache.set(cache_key, result)
  80. return result
  81. def get_news_by_date(
  82. self,
  83. target_date: datetime,
  84. platforms: Optional[List[str]] = None,
  85. limit: int = 50,
  86. include_url: bool = False
  87. ) -> List[Dict]:
  88. """
  89. 按指定日期获取新闻
  90. Args:
  91. target_date: 目标日期
  92. platforms: 平台ID列表,None表示所有平台
  93. limit: 返回条数限制
  94. include_url: 是否包含URL链接,默认False(节省token)
  95. Returns:
  96. 新闻列表
  97. Raises:
  98. DataNotFoundError: 数据不存在
  99. Examples:
  100. >>> service = DataService()
  101. >>> news = service.get_news_by_date(
  102. ... target_date=datetime(2025, 10, 10),
  103. ... platforms=['zhihu'],
  104. ... limit=20
  105. ... )
  106. """
  107. # 尝试从缓存获取
  108. date_str = target_date.strftime("%Y-%m-%d")
  109. cache_key = f"news_by_date:{date_str}:{','.join(platforms or [])}:{limit}:{include_url}"
  110. cached = self.cache.get(cache_key, ttl=1800) # 30分钟缓存
  111. if cached:
  112. return cached
  113. # 读取指定日期的数据
  114. all_titles, id_to_name, timestamps = self.parser.read_all_titles_for_date(
  115. date=target_date,
  116. platform_ids=platforms
  117. )
  118. # 转换为新闻列表
  119. news_list = []
  120. for platform_id, titles in all_titles.items():
  121. platform_name = id_to_name.get(platform_id, platform_id)
  122. for title, info in titles.items():
  123. # 计算平均排名
  124. avg_rank = sum(info["ranks"]) / len(info["ranks"]) if info["ranks"] else 0
  125. news_item = {
  126. "title": title,
  127. "platform": platform_id,
  128. "platform_name": platform_name,
  129. "rank": info["ranks"][0] if info["ranks"] else 0,
  130. "avg_rank": round(avg_rank, 2),
  131. "count": len(info["ranks"]),
  132. "date": date_str
  133. }
  134. # 条件性添加 URL 字段
  135. if include_url:
  136. news_item["url"] = info.get("url", "")
  137. news_item["mobileUrl"] = info.get("mobileUrl", "")
  138. news_list.append(news_item)
  139. # 按排名排序
  140. news_list.sort(key=lambda x: x["rank"])
  141. # 限制返回数量
  142. result = news_list[:limit]
  143. # 缓存结果(历史数据缓存更久)
  144. self.cache.set(cache_key, result)
  145. return result
  146. def search_news_by_keyword(
  147. self,
  148. keyword: str,
  149. date_range: Optional[Tuple[datetime, datetime]] = None,
  150. platforms: Optional[List[str]] = None,
  151. limit: Optional[int] = None
  152. ) -> Dict:
  153. """
  154. 按关键词搜索新闻
  155. Args:
  156. keyword: 搜索关键词
  157. date_range: 日期范围 (start_date, end_date)
  158. platforms: 平台过滤列表
  159. limit: 返回条数限制(可选)
  160. Returns:
  161. 搜索结果字典
  162. Raises:
  163. DataNotFoundError: 数据不存在
  164. """
  165. # 确定搜索日期范围
  166. if date_range:
  167. start_date, end_date = date_range
  168. else:
  169. # 默认搜索今天
  170. start_date = end_date = datetime.now()
  171. # 收集所有匹配的新闻
  172. results = []
  173. platform_distribution = Counter()
  174. # 遍历日期范围
  175. current_date = start_date
  176. while current_date <= end_date:
  177. try:
  178. all_titles, id_to_name, _ = self.parser.read_all_titles_for_date(
  179. date=current_date,
  180. platform_ids=platforms
  181. )
  182. # 搜索包含关键词的标题
  183. for platform_id, titles in all_titles.items():
  184. platform_name = id_to_name.get(platform_id, platform_id)
  185. for title, info in titles.items():
  186. if keyword.lower() in title.lower():
  187. # 计算平均排名
  188. avg_rank = sum(info["ranks"]) / len(info["ranks"]) if info["ranks"] else 0
  189. results.append({
  190. "title": title,
  191. "platform": platform_id,
  192. "platform_name": platform_name,
  193. "ranks": info["ranks"],
  194. "count": len(info["ranks"]),
  195. "avg_rank": round(avg_rank, 2),
  196. "url": info.get("url", ""),
  197. "mobileUrl": info.get("mobileUrl", ""),
  198. "date": current_date.strftime("%Y-%m-%d")
  199. })
  200. platform_distribution[platform_id] += 1
  201. except DataNotFoundError:
  202. # 该日期没有数据,继续下一天
  203. pass
  204. # 下一天
  205. current_date += timedelta(days=1)
  206. if not results:
  207. raise DataNotFoundError(
  208. f"未找到包含关键词 '{keyword}' 的新闻",
  209. suggestion="请尝试其他关键词或扩大日期范围"
  210. )
  211. # 计算统计信息
  212. total_ranks = []
  213. for item in results:
  214. total_ranks.extend(item["ranks"])
  215. avg_rank = sum(total_ranks) / len(total_ranks) if total_ranks else 0
  216. # 限制返回数量(如果指定)
  217. total_found = len(results)
  218. if limit is not None and limit > 0:
  219. results = results[:limit]
  220. return {
  221. "results": results,
  222. "total": len(results),
  223. "total_found": total_found,
  224. "statistics": {
  225. "platform_distribution": dict(platform_distribution),
  226. "avg_rank": round(avg_rank, 2),
  227. "keyword": keyword
  228. }
  229. }
  230. def get_trending_topics(
  231. self,
  232. top_n: int = 10,
  233. mode: str = "current"
  234. ) -> Dict:
  235. """
  236. 获取个人关注词的新闻出现频率统计
  237. 注意:本工具基于 config/frequency_words.txt 中的个人关注词列表进行统计,
  238. 而不是自动从新闻中提取热点话题。用户可以自定义这个关注词列表。
  239. Args:
  240. top_n: 返回TOP N关注词
  241. mode: 模式 - daily(当日累计), current(最新一批)
  242. Returns:
  243. 关注词频率统计字典
  244. Raises:
  245. DataNotFoundError: 数据不存在
  246. """
  247. # 尝试从缓存获取
  248. cache_key = f"trending_topics:{top_n}:{mode}"
  249. cached = self.cache.get(cache_key, ttl=1800) # 30分钟缓存
  250. if cached:
  251. return cached
  252. # 读取今天的数据
  253. all_titles, id_to_name, timestamps = self.parser.read_all_titles_for_date()
  254. if not all_titles:
  255. raise DataNotFoundError(
  256. "未找到今天的新闻数据",
  257. suggestion="请确保爬虫已经运行并生成了数据"
  258. )
  259. # 加载关键词配置
  260. word_groups = self.parser.parse_frequency_words()
  261. # 根据mode选择要处理的标题数据
  262. titles_to_process = {}
  263. if mode == "daily":
  264. # daily模式:处理当天所有累计数据
  265. titles_to_process = all_titles
  266. elif mode == "current":
  267. # current模式:只处理最新一批数据(最新时间戳的文件)
  268. if timestamps:
  269. # 找出最新的时间戳
  270. latest_timestamp = max(timestamps.values())
  271. # 重新读取,只获取最新时间的数据
  272. # 这里我们通过timestamps字典反查找最新文件对应的平台
  273. latest_titles, _, _ = self.parser.read_all_titles_for_date()
  274. # 由于read_all_titles_for_date返回所有文件的合并数据,
  275. # 我们需要通过timestamps来过滤出最新批次
  276. # 简化实现:使用当前所有数据作为最新批次
  277. # (更精确的实现需要解析服务支持按时间过滤)
  278. titles_to_process = latest_titles
  279. else:
  280. titles_to_process = all_titles
  281. else:
  282. raise ValueError(
  283. f"不支持的模式: {mode}。支持的模式: daily, current"
  284. )
  285. # 统计词频
  286. word_frequency = Counter()
  287. keyword_to_news = {}
  288. # 遍历要处理的标题
  289. for platform_id, titles in titles_to_process.items():
  290. for title in titles.keys():
  291. # 对每个关键词组进行匹配
  292. for group in word_groups:
  293. all_words = group.get("required", []) + group.get("normal", [])
  294. for word in all_words:
  295. if word and word in title:
  296. word_frequency[word] += 1
  297. if word not in keyword_to_news:
  298. keyword_to_news[word] = []
  299. keyword_to_news[word].append(title)
  300. # 获取TOP N关键词
  301. top_keywords = word_frequency.most_common(top_n)
  302. # 构建话题列表
  303. topics = []
  304. for keyword, frequency in top_keywords:
  305. matched_news = keyword_to_news.get(keyword, [])
  306. topics.append({
  307. "keyword": keyword,
  308. "frequency": frequency,
  309. "matched_news": len(set(matched_news)), # 去重后的新闻数量
  310. "trend": "stable", # TODO: 需要历史数据来计算趋势
  311. "weight_score": 0.0 # TODO: 需要实现权重计算
  312. })
  313. # 构建结果
  314. result = {
  315. "topics": topics,
  316. "generated_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
  317. "mode": mode,
  318. "total_keywords": len(word_frequency),
  319. "description": self._get_mode_description(mode)
  320. }
  321. # 缓存结果
  322. self.cache.set(cache_key, result)
  323. return result
  324. def _get_mode_description(self, mode: str) -> str:
  325. """获取模式描述"""
  326. descriptions = {
  327. "daily": "当日累计统计",
  328. "current": "最新一批统计"
  329. }
  330. return descriptions.get(mode, "未知模式")
  331. def get_current_config(self, section: str = "all") -> Dict:
  332. """
  333. 获取当前系统配置
  334. Args:
  335. section: 配置节 - all/crawler/push/keywords/weights
  336. Returns:
  337. 配置字典
  338. Raises:
  339. FileParseError: 配置文件解析错误
  340. """
  341. # 尝试从缓存获取
  342. cache_key = f"config:{section}"
  343. cached = self.cache.get(cache_key, ttl=3600) # 1小时缓存
  344. if cached:
  345. return cached
  346. # 解析配置文件
  347. config_data = self.parser.parse_yaml_config()
  348. word_groups = self.parser.parse_frequency_words()
  349. # 根据section返回对应配置
  350. if section == "all" or section == "crawler":
  351. crawler_config = {
  352. "enable_crawler": config_data.get("crawler", {}).get("enable_crawler", True),
  353. "use_proxy": config_data.get("crawler", {}).get("use_proxy", False),
  354. "request_interval": config_data.get("crawler", {}).get("request_interval", 1),
  355. "retry_times": 3,
  356. "platforms": [p["id"] for p in config_data.get("platforms", [])]
  357. }
  358. if section == "all" or section == "push":
  359. push_config = {
  360. "enable_notification": config_data.get("notification", {}).get("enable_notification", True),
  361. "enabled_channels": [],
  362. "message_batch_size": config_data.get("notification", {}).get("message_batch_size", 20),
  363. "push_window": config_data.get("notification", {}).get("push_window", {})
  364. }
  365. # 检测已配置的通知渠道
  366. webhooks = config_data.get("notification", {}).get("webhooks", {})
  367. if webhooks.get("feishu_url"):
  368. push_config["enabled_channels"].append("feishu")
  369. if webhooks.get("dingtalk_url"):
  370. push_config["enabled_channels"].append("dingtalk")
  371. if webhooks.get("wework_url"):
  372. push_config["enabled_channels"].append("wework")
  373. if section == "all" or section == "keywords":
  374. keywords_config = {
  375. "word_groups": word_groups,
  376. "total_groups": len(word_groups)
  377. }
  378. if section == "all" or section == "weights":
  379. weights_config = {
  380. "rank_weight": config_data.get("weight", {}).get("rank_weight", 0.6),
  381. "frequency_weight": config_data.get("weight", {}).get("frequency_weight", 0.3),
  382. "hotness_weight": config_data.get("weight", {}).get("hotness_weight", 0.1)
  383. }
  384. # 组装结果
  385. if section == "all":
  386. result = {
  387. "crawler": crawler_config,
  388. "push": push_config,
  389. "keywords": keywords_config,
  390. "weights": weights_config
  391. }
  392. elif section == "crawler":
  393. result = crawler_config
  394. elif section == "push":
  395. result = push_config
  396. elif section == "keywords":
  397. result = keywords_config
  398. elif section == "weights":
  399. result = weights_config
  400. else:
  401. result = {}
  402. # 缓存结果
  403. self.cache.set(cache_key, result)
  404. return result
  405. def get_available_date_range(self) -> Tuple[Optional[datetime], Optional[datetime]]:
  406. """
  407. 扫描 output 目录,返回实际可用的日期范围
  408. Returns:
  409. (最早日期, 最新日期) 元组,如果没有数据则返回 (None, None)
  410. Examples:
  411. >>> service = DataService()
  412. >>> earliest, latest = service.get_available_date_range()
  413. >>> print(f"可用日期范围:{earliest} 至 {latest}")
  414. """
  415. output_dir = self.parser.project_root / "output"
  416. if not output_dir.exists():
  417. return (None, None)
  418. available_dates = []
  419. # 遍历日期文件夹
  420. for date_folder in output_dir.iterdir():
  421. if date_folder.is_dir() and not date_folder.name.startswith('.'):
  422. # 解析日期(格式: YYYY年MM月DD日)
  423. try:
  424. date_match = re.match(r'(\d{4})年(\d{2})月(\d{2})日', date_folder.name)
  425. if date_match:
  426. folder_date = datetime(
  427. int(date_match.group(1)),
  428. int(date_match.group(2)),
  429. int(date_match.group(3))
  430. )
  431. available_dates.append(folder_date)
  432. except Exception:
  433. pass
  434. if not available_dates:
  435. return (None, None)
  436. return (min(available_dates), max(available_dates))
  437. def get_system_status(self) -> Dict:
  438. """
  439. 获取系统运行状态
  440. Returns:
  441. 系统状态字典
  442. """
  443. # 获取数据统计
  444. output_dir = self.parser.project_root / "output"
  445. total_storage = 0
  446. oldest_record = None
  447. latest_record = None
  448. total_news = 0
  449. if output_dir.exists():
  450. # 遍历日期文件夹
  451. for date_folder in output_dir.iterdir():
  452. if date_folder.is_dir():
  453. # 解析日期
  454. try:
  455. date_str = date_folder.name
  456. # 格式: YYYY年MM月DD日
  457. date_match = re.match(r'(\d{4})年(\d{2})月(\d{2})日', date_str)
  458. if date_match:
  459. folder_date = datetime(
  460. int(date_match.group(1)),
  461. int(date_match.group(2)),
  462. int(date_match.group(3))
  463. )
  464. if oldest_record is None or folder_date < oldest_record:
  465. oldest_record = folder_date
  466. if latest_record is None or folder_date > latest_record:
  467. latest_record = folder_date
  468. except:
  469. pass
  470. # 计算存储大小
  471. for item in date_folder.rglob("*"):
  472. if item.is_file():
  473. total_storage += item.stat().st_size
  474. # 读取版本信息
  475. version_file = self.parser.project_root / "version"
  476. version = "unknown"
  477. if version_file.exists():
  478. try:
  479. with open(version_file, "r") as f:
  480. version = f.read().strip()
  481. except:
  482. pass
  483. return {
  484. "system": {
  485. "version": version,
  486. "project_root": str(self.parser.project_root)
  487. },
  488. "data": {
  489. "total_storage": f"{total_storage / 1024 / 1024:.2f} MB",
  490. "oldest_record": oldest_record.strftime("%Y-%m-%d") if oldest_record else None,
  491. "latest_record": latest_record.strftime("%Y-%m-%d") if latest_record else None,
  492. },
  493. "cache": self.cache.get_stats(),
  494. "health": "healthy"
  495. }