parser_service.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. """
  2. 文件解析服务
  3. 提供txt格式新闻数据和YAML配置文件的解析功能。
  4. 支持从 SQLite 数据库和 TXT 文件两种数据源读取。
  5. """
  6. import json
  7. import re
  8. import sqlite3
  9. from pathlib import Path
  10. from typing import Dict, List, Tuple, Optional
  11. from datetime import datetime
  12. import yaml
  13. from ..utils.errors import FileParseError, DataNotFoundError
  14. from .cache_service import get_cache
  15. class ParserService:
  16. """文件解析服务类"""
  17. def __init__(self, project_root: str = None):
  18. """
  19. 初始化解析服务
  20. Args:
  21. project_root: 项目根目录,默认为当前目录的父目录
  22. """
  23. if project_root is None:
  24. # 获取当前文件所在目录的父目录的父目录
  25. current_file = Path(__file__)
  26. self.project_root = current_file.parent.parent.parent
  27. else:
  28. self.project_root = Path(project_root)
  29. # 初始化缓存服务
  30. self.cache = get_cache()
  31. @staticmethod
  32. def clean_title(title: str) -> str:
  33. """
  34. 清理标题文本
  35. Args:
  36. title: 原始标题
  37. Returns:
  38. 清理后的标题
  39. """
  40. # 移除多余空白
  41. title = re.sub(r'\s+', ' ', title)
  42. # 移除特殊字符
  43. title = title.strip()
  44. return title
  45. def parse_txt_file(self, file_path: Path) -> Tuple[Dict, Dict]:
  46. """
  47. 解析单个txt文件的标题数据
  48. Args:
  49. file_path: txt文件路径
  50. Returns:
  51. (titles_by_id, id_to_name) 元组
  52. - titles_by_id: {platform_id: {title: {ranks, url, mobileUrl}}}
  53. - id_to_name: {platform_id: platform_name}
  54. Raises:
  55. FileParseError: 文件解析错误
  56. """
  57. if not file_path.exists():
  58. raise FileParseError(str(file_path), "文件不存在")
  59. titles_by_id = {}
  60. id_to_name = {}
  61. try:
  62. with open(file_path, "r", encoding="utf-8") as f:
  63. content = f.read()
  64. sections = content.split("\n\n")
  65. for section in sections:
  66. if not section.strip() or "==== 以下ID请求失败 ====" in section:
  67. continue
  68. lines = section.strip().split("\n")
  69. if len(lines) < 2:
  70. continue
  71. # 解析header: id | name 或 id
  72. header_line = lines[0].strip()
  73. if " | " in header_line:
  74. parts = header_line.split(" | ", 1)
  75. source_id = parts[0].strip()
  76. name = parts[1].strip()
  77. id_to_name[source_id] = name
  78. else:
  79. source_id = header_line
  80. id_to_name[source_id] = source_id
  81. titles_by_id[source_id] = {}
  82. # 解析标题行
  83. for line in lines[1:]:
  84. if line.strip():
  85. try:
  86. title_part = line.strip()
  87. rank = None
  88. # 提取排名
  89. if ". " in title_part and title_part.split(". ")[0].isdigit():
  90. rank_str, title_part = title_part.split(". ", 1)
  91. rank = int(rank_str)
  92. # 提取 MOBILE URL
  93. mobile_url = ""
  94. if " [MOBILE:" in title_part:
  95. title_part, mobile_part = title_part.rsplit(" [MOBILE:", 1)
  96. if mobile_part.endswith("]"):
  97. mobile_url = mobile_part[:-1]
  98. # 提取 URL
  99. url = ""
  100. if " [URL:" in title_part:
  101. title_part, url_part = title_part.rsplit(" [URL:", 1)
  102. if url_part.endswith("]"):
  103. url = url_part[:-1]
  104. title = self.clean_title(title_part.strip())
  105. ranks = [rank] if rank is not None else [1]
  106. titles_by_id[source_id][title] = {
  107. "ranks": ranks,
  108. "url": url,
  109. "mobileUrl": mobile_url,
  110. }
  111. except Exception as e:
  112. # 忽略单行解析错误
  113. continue
  114. except Exception as e:
  115. raise FileParseError(str(file_path), str(e))
  116. return titles_by_id, id_to_name
  117. def get_date_folder_name(self, date: datetime = None) -> str:
  118. """
  119. 获取日期文件夹名称(兼容中文和ISO格式)
  120. Args:
  121. date: 日期对象,默认为今天
  122. Returns:
  123. 实际存在的文件夹名称,优先返回中文格式(YYYY年MM月DD日),
  124. 若不存在则返回 ISO 格式(YYYY-MM-DD)
  125. """
  126. if date is None:
  127. date = datetime.now()
  128. return self._find_date_folder(date)
  129. def _get_date_folder_name(self, date: datetime = None) -> str:
  130. """
  131. 获取日期文件夹名称(兼容中文和ISO格式)
  132. Args:
  133. date: 日期对象,默认为今天
  134. Returns:
  135. 实际存在的文件夹名称,优先返回中文格式(YYYY年MM月DD日),
  136. 若不存在则返回 ISO 格式(YYYY-MM-DD)
  137. """
  138. if date is None:
  139. date = datetime.now()
  140. return self._find_date_folder(date)
  141. def _find_date_folder(self, date: datetime) -> str:
  142. """
  143. 查找实际存在的日期文件夹
  144. 支持两种格式:
  145. - 中文格式:YYYY年MM月DD日(优先)
  146. - ISO格式:YYYY-MM-DD
  147. Args:
  148. date: 日期对象
  149. Returns:
  150. 实际存在的文件夹名称,若都不存在则返回中文格式
  151. """
  152. output_dir = self.project_root / "output"
  153. # 中文格式:YYYY年MM月DD日
  154. chinese_format = date.strftime("%Y年%m月%d日")
  155. # ISO格式:YYYY-MM-DD
  156. iso_format = date.strftime("%Y-%m-%d")
  157. # 优先检查中文格式
  158. if (output_dir / chinese_format).exists():
  159. return chinese_format
  160. # 其次检查 ISO 格式
  161. if (output_dir / iso_format).exists():
  162. return iso_format
  163. # 都不存在,返回中文格式(与项目现有风格一致)
  164. return chinese_format
  165. def _get_sqlite_db_path(self, date: datetime = None) -> Optional[Path]:
  166. """
  167. 获取 SQLite 数据库文件路径
  168. Args:
  169. date: 日期对象,默认为今天
  170. Returns:
  171. 数据库文件路径,如果不存在则返回 None
  172. """
  173. date_folder = self._get_date_folder_name(date)
  174. db_path = self.project_root / "output" / date_folder / "news.db"
  175. if db_path.exists():
  176. return db_path
  177. return None
  178. def _get_txt_folder_path(self, date: datetime = None) -> Optional[Path]:
  179. """
  180. 获取 TXT 文件夹路径
  181. Args:
  182. date: 日期对象,默认为今天
  183. Returns:
  184. TXT 文件夹路径,如果不存在则返回 None
  185. """
  186. date_folder = self._get_date_folder_name(date)
  187. txt_path = self.project_root / "output" / date_folder / "txt"
  188. if txt_path.exists() and txt_path.is_dir():
  189. return txt_path
  190. return None
  191. def _read_from_txt(
  192. self,
  193. date: datetime = None,
  194. platform_ids: Optional[List[str]] = None
  195. ) -> Optional[Tuple[Dict, Dict, Dict]]:
  196. """
  197. 从 TXT 文件夹读取新闻数据
  198. Args:
  199. date: 日期对象,默认为今天
  200. platform_ids: 平台ID列表,None表示所有平台
  201. Returns:
  202. (all_titles, id_to_name, all_timestamps) 元组,如果不存在返回 None
  203. """
  204. txt_folder = self._get_txt_folder_path(date)
  205. if txt_folder is None:
  206. return None
  207. # 获取所有 TXT 文件并按时间排序
  208. txt_files = sorted(txt_folder.glob("*.txt"))
  209. if not txt_files:
  210. return None
  211. all_titles = {}
  212. id_to_name = {}
  213. all_timestamps = {}
  214. for txt_file in txt_files:
  215. try:
  216. titles_by_id, file_id_to_name = self.parse_txt_file(txt_file)
  217. # 记录时间戳
  218. all_timestamps[txt_file.name] = txt_file.stat().st_mtime
  219. # 合并 id_to_name
  220. id_to_name.update(file_id_to_name)
  221. # 合并标题数据
  222. for source_id, titles in titles_by_id.items():
  223. # 如果指定了 platform_ids,过滤
  224. if platform_ids and source_id not in platform_ids:
  225. continue
  226. if source_id not in all_titles:
  227. all_titles[source_id] = {}
  228. for title, data in titles.items():
  229. if title not in all_titles[source_id]:
  230. # 新标题
  231. all_titles[source_id][title] = {
  232. "ranks": data.get("ranks", []),
  233. "url": data.get("url", ""),
  234. "mobileUrl": data.get("mobileUrl", ""),
  235. "first_time": txt_file.stem, # 使用文件名作为时间
  236. "last_time": txt_file.stem,
  237. "count": 1,
  238. }
  239. else:
  240. # 合并已存在的标题
  241. existing = all_titles[source_id][title]
  242. # 合并排名
  243. for rank in data.get("ranks", []):
  244. if rank not in existing["ranks"]:
  245. existing["ranks"].append(rank)
  246. # 更新 last_time
  247. existing["last_time"] = txt_file.stem
  248. existing["count"] += 1
  249. # 保留 URL
  250. if not existing["url"] and data.get("url"):
  251. existing["url"] = data["url"]
  252. if not existing["mobileUrl"] and data.get("mobileUrl"):
  253. existing["mobileUrl"] = data["mobileUrl"]
  254. except Exception as e:
  255. print(f"Warning: 解析 TXT 文件失败 {txt_file}: {e}")
  256. continue
  257. if not all_titles:
  258. return None
  259. return (all_titles, id_to_name, all_timestamps)
  260. def _read_from_sqlite(
  261. self,
  262. date: datetime = None,
  263. platform_ids: Optional[List[str]] = None
  264. ) -> Optional[Tuple[Dict, Dict, Dict]]:
  265. """
  266. 从 SQLite 数据库读取新闻数据
  267. 新表结构数据已按 URL 去重,包含:
  268. - first_crawl_time: 首次抓取时间
  269. - last_crawl_time: 最后抓取时间
  270. - crawl_count: 抓取次数
  271. Args:
  272. date: 日期对象,默认为今天
  273. platform_ids: 平台ID列表,None表示所有平台
  274. Returns:
  275. (all_titles, id_to_name, all_timestamps) 元组,如果数据库不存在返回 None
  276. """
  277. db_path = self._get_sqlite_db_path(date)
  278. if db_path is None:
  279. return None
  280. all_titles = {}
  281. id_to_name = {}
  282. all_timestamps = {}
  283. try:
  284. conn = sqlite3.connect(str(db_path))
  285. conn.row_factory = sqlite3.Row
  286. cursor = conn.cursor()
  287. # 检查表是否存在
  288. cursor.execute("""
  289. SELECT name FROM sqlite_master
  290. WHERE type='table' AND name='news_items'
  291. """)
  292. if not cursor.fetchone():
  293. conn.close()
  294. return None
  295. # 构建查询
  296. if platform_ids:
  297. placeholders = ','.join(['?' for _ in platform_ids])
  298. query = f"""
  299. SELECT n.id, n.platform_id, p.name as platform_name, n.title,
  300. n.rank, n.url, n.mobile_url,
  301. n.first_crawl_time, n.last_crawl_time, n.crawl_count
  302. FROM news_items n
  303. LEFT JOIN platforms p ON n.platform_id = p.id
  304. WHERE n.platform_id IN ({placeholders})
  305. """
  306. cursor.execute(query, platform_ids)
  307. else:
  308. cursor.execute("""
  309. SELECT n.id, n.platform_id, p.name as platform_name, n.title,
  310. n.rank, n.url, n.mobile_url,
  311. n.first_crawl_time, n.last_crawl_time, n.crawl_count
  312. FROM news_items n
  313. LEFT JOIN platforms p ON n.platform_id = p.id
  314. """)
  315. rows = cursor.fetchall()
  316. # 收集所有 news_item_id 用于查询历史排名
  317. news_ids = [row['id'] for row in rows]
  318. rank_history_map = {}
  319. if news_ids:
  320. placeholders = ",".join("?" * len(news_ids))
  321. cursor.execute(f"""
  322. SELECT news_item_id, rank FROM rank_history
  323. WHERE news_item_id IN ({placeholders})
  324. ORDER BY news_item_id, crawl_time
  325. """, news_ids)
  326. for rh_row in cursor.fetchall():
  327. news_id = rh_row['news_item_id']
  328. rank = rh_row['rank']
  329. if news_id not in rank_history_map:
  330. rank_history_map[news_id] = []
  331. rank_history_map[news_id].append(rank)
  332. for row in rows:
  333. news_id = row['id']
  334. platform_id = row['platform_id']
  335. platform_name = row['platform_name'] or platform_id
  336. title = row['title']
  337. # 更新 id_to_name
  338. if platform_id not in id_to_name:
  339. id_to_name[platform_id] = platform_name
  340. # 初始化平台字典
  341. if platform_id not in all_titles:
  342. all_titles[platform_id] = {}
  343. # 获取排名历史,如果为空则使用当前排名
  344. ranks = rank_history_map.get(news_id, [row['rank']])
  345. # 直接使用数据(已去重)
  346. all_titles[platform_id][title] = {
  347. "ranks": ranks,
  348. "url": row['url'] or "",
  349. "mobileUrl": row['mobile_url'] or "",
  350. "first_time": row['first_crawl_time'] or "",
  351. "last_time": row['last_crawl_time'] or "",
  352. "count": row['crawl_count'] or 1,
  353. }
  354. # 获取抓取时间作为 timestamps
  355. cursor.execute("""
  356. SELECT crawl_time FROM crawl_records
  357. ORDER BY crawl_time
  358. """)
  359. for row in cursor.fetchall():
  360. crawl_time = row['crawl_time']
  361. all_timestamps[f"{crawl_time}.db"] = 0 # 用虚拟时间戳
  362. conn.close()
  363. if not all_titles:
  364. return None
  365. return (all_titles, id_to_name, all_timestamps)
  366. except Exception as e:
  367. print(f"Warning: 从 SQLite 读取数据失败: {e}")
  368. return None
  369. def read_all_titles_for_date(
  370. self,
  371. date: datetime = None,
  372. platform_ids: Optional[List[str]] = None
  373. ) -> Tuple[Dict, Dict, Dict]:
  374. """
  375. 读取指定日期的所有标题(带缓存)
  376. Args:
  377. date: 日期对象,默认为今天
  378. platform_ids: 平台ID列表,None表示所有平台
  379. Returns:
  380. (all_titles, id_to_name, all_timestamps) 元组
  381. - all_titles: {platform_id: {title: {ranks, url, mobileUrl, ...}}}
  382. - id_to_name: {platform_id: platform_name}
  383. - all_timestamps: {filename: timestamp}
  384. Raises:
  385. DataNotFoundError: 数据不存在
  386. """
  387. # 生成缓存键
  388. date_str = self.get_date_folder_name(date)
  389. platform_key = ','.join(sorted(platform_ids)) if platform_ids else 'all'
  390. cache_key = f"read_all_titles:{date_str}:{platform_key}"
  391. # 尝试从缓存获取
  392. # 对于历史数据(非今天),使用更长的缓存时间(1小时)
  393. # 对于今天的数据,使用较短的缓存时间(15分钟),因为可能有新数据
  394. is_today = (date is None) or (date.date() == datetime.now().date())
  395. ttl = 900 if is_today else 3600 # 15分钟 vs 1小时
  396. cached = self.cache.get(cache_key, ttl=ttl)
  397. if cached:
  398. return cached
  399. # 优先从 SQLite 读取
  400. sqlite_result = self._read_from_sqlite(date, platform_ids)
  401. if sqlite_result:
  402. self.cache.set(cache_key, sqlite_result)
  403. return sqlite_result
  404. # SQLite 不存在,尝试从 TXT 读取
  405. txt_result = self._read_from_txt(date, platform_ids)
  406. if txt_result:
  407. self.cache.set(cache_key, txt_result)
  408. return txt_result
  409. # 两种数据源都不存在
  410. raise DataNotFoundError(
  411. f"未找到 {date_str} 的数据",
  412. suggestion="请先运行爬虫或检查日期是否正确"
  413. )
  414. def parse_yaml_config(self, config_path: str = None) -> dict:
  415. """
  416. 解析YAML配置文件
  417. Args:
  418. config_path: 配置文件路径,默认为 config/config.yaml
  419. Returns:
  420. 配置字典
  421. Raises:
  422. FileParseError: 配置文件解析错误
  423. """
  424. if config_path is None:
  425. config_path = self.project_root / "config" / "config.yaml"
  426. else:
  427. config_path = Path(config_path)
  428. if not config_path.exists():
  429. raise FileParseError(str(config_path), "配置文件不存在")
  430. try:
  431. with open(config_path, "r", encoding="utf-8") as f:
  432. config_data = yaml.safe_load(f)
  433. return config_data
  434. except Exception as e:
  435. raise FileParseError(str(config_path), str(e))
  436. def parse_frequency_words(self, words_file: str = None) -> List[Dict]:
  437. """
  438. 解析关键词配置文件
  439. Args:
  440. words_file: 关键词文件路径,默认为 config/frequency_words.txt
  441. Returns:
  442. 词组列表
  443. Raises:
  444. FileParseError: 文件解析错误
  445. """
  446. if words_file is None:
  447. words_file = self.project_root / "config" / "frequency_words.txt"
  448. else:
  449. words_file = Path(words_file)
  450. if not words_file.exists():
  451. return []
  452. word_groups = []
  453. try:
  454. with open(words_file, "r", encoding="utf-8") as f:
  455. for line in f:
  456. line = line.strip()
  457. if not line or line.startswith("#"):
  458. continue
  459. # 使用 | 分隔符
  460. parts = [p.strip() for p in line.split("|")]
  461. if not parts:
  462. continue
  463. group = {
  464. "required": [],
  465. "normal": [],
  466. "filter_words": []
  467. }
  468. for part in parts:
  469. if not part:
  470. continue
  471. words = [w.strip() for w in part.split(",")]
  472. for word in words:
  473. if not word:
  474. continue
  475. if word.endswith("+"):
  476. # 必须词
  477. group["required"].append(word[:-1])
  478. elif word.endswith("!"):
  479. # 过滤词
  480. group["filter_words"].append(word[:-1])
  481. else:
  482. # 普通词
  483. group["normal"].append(word)
  484. if group["required"] or group["normal"]:
  485. word_groups.append(group)
  486. except Exception as e:
  487. raise FileParseError(str(words_file), str(e))
  488. return word_groups