Fix SSE route dependency and align architecture docs

This commit is contained in:
ash66
2026-05-18 16:32:42 +08:00
parent 86b9ac806a
commit 3f69cad404
149 changed files with 4786 additions and 5957 deletions

View File

@@ -1,4 +1,4 @@
"""PDF文档解析 - 使用PyMuPDF基础解析"""
"""Provide service-layer logic for pdf parser."""
import fitz # PyMuPDF
from typing import List, Dict, Optional, Tuple
@@ -9,17 +9,17 @@ import re
@dataclass
class PDFPageContent:
"""PDF页面内容"""
"""Represent the P D F Page Content type."""
page_number: int
text: str
tables: List[str] = field(default_factory=list)
images: List[str] = field(default_factory=list) # 图片路径列表
images: List[str] = field(default_factory=list) # Keep service responsibilities explicit so downstream behavior stays predictable.
blocks: List[Dict] = field(default_factory=list)
@dataclass
class PDFDocumentContent:
"""PDF文档完整内容"""
"""Represent the P D F Document Content type."""
file_path: str
total_pages: int
pages: List[PDFPageContent]
@@ -28,23 +28,14 @@ class PDFDocumentContent:
class PDFParser:
"""PDF文档解析器 - 基于PyMuPDF"""
"""Provide the P D F Parser parser."""
def __init__(self):
"""Initialize the P D F Parser instance."""
self.pdf = None
def parse(self, file_path: str, extract_tables: bool = True, extract_images: bool = False) -> PDFDocumentContent:
"""
解析PDF文档
Args:
file_path: PDF文件路径
extract_tables: 是否提取表格
extract_images: 是否提取图片
Returns:
PDFDocumentContent: 解析后的文档内容
"""
"""Handle parse for the P D F Parser instance."""
logger.info(f"开始解析PDF文档: {file_path}")
try:
@@ -55,16 +46,16 @@ class PDFParser:
pages=[]
)
# 提取文档元数据
# Keep service responsibilities explicit so downstream behavior stays predictable.
doc_content.metadata = self._extract_metadata()
# 逐页解析
# Keep service responsibilities explicit so downstream behavior stays predictable.
for page_num in range(self.pdf.page_count):
page = self.pdf[page_num]
page_content = self._parse_page(page, page_num + 1, extract_tables, extract_images)
doc_content.pages.append(page_content)
# 生成Markdown格式文本
# Keep service responsibilities explicit so downstream behavior stays predictable.
doc_content.markdown_text = self._generate_markdown(doc_content)
self.pdf.close()
@@ -77,7 +68,7 @@ class PDFParser:
raise
def _extract_metadata(self) -> Dict[str, str]:
"""提取PDF元数据"""
"""Handle extract metadata for this module for the P D F Parser instance."""
metadata = {}
try:
meta = self.pdf.metadata
@@ -97,23 +88,23 @@ class PDFParser:
def _parse_page(self, page: fitz.Page, page_num: int,
extract_tables: bool, extract_images: bool) -> PDFPageContent:
"""解析单页内容"""
"""Handle parse page for this module for the P D F Parser instance."""
page_content = PDFPageContent(page_number=page_num, text="")
# 提取文本块(保留结构)
# Keep service responsibilities explicit so downstream behavior stays predictable.
blocks = page.get_text("dict", flags=fitz.TEXT_PRESERVE_WHITESPACE)["blocks"]
page_content.blocks = blocks
# 提取纯文本
# Keep service responsibilities explicit so downstream behavior stays predictable.
text = page.get_text("text", flags=fitz.TEXT_PRESERVE_WHITESPACE)
page_content.text = text.strip()
# 提取表格使用PyMuPDF的表格提取功能
# Keep service responsibilities explicit so downstream behavior stays predictable.
if extract_tables:
tables = self._extract_tables_from_page(page)
page_content.tables = tables
# 提取图片
# Keep service responsibilities explicit so downstream behavior stays predictable.
if extract_images:
images = self._extract_images_from_page(page, page_num)
page_content.images = images
@@ -121,25 +112,22 @@ class PDFParser:
return page_content
def _extract_tables_from_page(self, page: fitz.Page) -> List[str]:
"""
从页面提取表格(基于文本块分析)
注意PyMuPDF基础版表格提取能力有限复杂表格建议使用MinerU
"""
"""Handle extract tables from page for this module for the P D F Parser instance."""
tables = []
try:
# 使用PyMuPDF的表格提取方法2.4+版本)
# 对于更复杂的表格需要在mineru_parser中使用更高级的方法
# Keep service responsibilities explicit so downstream behavior stays predictable.
# Keep service responsibilities explicit so downstream behavior stays predictable.
tabs = page.find_tables()
if tabs:
for tab in tabs:
table_text = tab.extract()
# 将表格转换为Markdown格式
# Keep service responsibilities explicit so downstream behavior stays predictable.
markdown_table = self._table_to_markdown(table_text)
tables.append(markdown_table)
except AttributeError:
# 旧版本PyMuPDF没有表格提取功能
# Keep service responsibilities explicit so downstream behavior stays predictable.
logger.warning("PyMuPDF版本不支持表格提取请升级到2.4+版本")
except Exception as e:
logger.warning(f"表格提取失败: {e}")
@@ -147,28 +135,28 @@ class PDFParser:
return tables
def _table_to_markdown(self, table_data: List[List[str]]) -> str:
"""将表格数据转换为Markdown格式"""
"""Handle table to markdown for this module for the P D F Parser instance."""
if not table_data or len(table_data) < 1:
return ""
lines = []
# 表头
# Keep service responsibilities explicit so downstream behavior stays predictable.
if len(table_data) >= 1:
header = table_data[0]
lines.append("| " + " | ".join(str(cell).strip() for cell in header) + " |")
lines.append("| " + " | ".join("---" for _ in header) + " |")
# 数据行
# Keep service responsibilities explicit so downstream behavior stays predictable.
for row in table_data[1:]:
lines.append("| " + " | ".join(str(cell).strip() for cell in row) + " |")
return "\n".join(lines)
def _extract_images_from_page(self, page: fitz.Page, page_num: int) -> List[str]:
"""提取页面图片"""
"""Handle extract images from page for this module for the P D F Parser instance."""
images = []
# 图片提取功能(可选实现)
# 这里仅记录图片信息,实际图片需要额外保存
# Keep service responsibilities explicit so downstream behavior stays predictable.
# Keep service responsibilities explicit so downstream behavior stays predictable.
try:
image_list = page.get_images()
for img_index, img in enumerate(image_list):
@@ -179,52 +167,52 @@ class PDFParser:
return images
def _generate_markdown(self, doc_content: PDFDocumentContent) -> str:
"""生成Markdown格式文本"""
"""Handle generate markdown for this module for the P D F Parser instance."""
lines = []
# 文档标题
# Keep service responsibilities explicit so downstream behavior stays predictable.
title = doc_content.metadata.get("title", "")
if title:
lines.append(f"# {title}\n")
else:
lines.append(f"# {doc_content.file_path}\n")
# 元数据信息
# Keep service responsibilities explicit so downstream behavior stays predictable.
lines.append("\n## 文档信息\n")
for key, value in doc_content.metadata.items():
if value and key in ["author", "subject", "keywords", "creation_date"]:
lines.append(f"- **{key}**: {value}")
# 正文内容
# Keep service responsibilities explicit so downstream behavior stays predictable.
lines.append("\n## 正文\n")
for page in doc_content.pages:
# 页码标记
# Keep service responsibilities explicit so downstream behavior stays predictable.
lines.append(f"\n---\n**第 {page.page_number} 页**\n")
# 处理文本内容,识别标题结构
# Keep service responsibilities explicit so downstream behavior stays predictable.
text = self._process_page_text(page.text, page.blocks)
lines.append(text)
# 添加表格
# Keep service responsibilities explicit so downstream behavior stays predictable.
for table in page.tables:
lines.append("\n" + table + "\n")
return "\n".join(lines)
def _process_page_text(self, text: str, blocks: List[Dict]) -> str:
"""处理页面文本,识别标题结构"""
# 基于字体大小识别标题
"""Handle process page text for this module for the P D F Parser instance."""
# Keep service responsibilities explicit so downstream behavior stays predictable.
processed_text = text
# 尝试识别标题(基于字号)
# 法规文档通常有明确的层级结构:章、节、条
# Keep service responsibilities explicit so downstream behavior stays predictable.
# Keep service responsibilities explicit so downstream behavior stays predictable.
processed_text = self._detect_headers(text, blocks)
return processed_text
def _detect_headers(self, text: str, blocks: List[Dict]) -> str:
"""检测并标记标题(基于字号或内容模式)"""
"""Handle detect headers for this module for the P D F Parser instance."""
lines = text.split("\n")
processed_lines = []
@@ -233,8 +221,8 @@ class PDFParser:
if not line:
continue
# 法规标题模式检测
# 第一章、第X章、第X节、第X条等
# Keep service responsibilities explicit so downstream behavior stays predictable.
# Keep service responsibilities explicit so downstream behavior stays predictable.
if re.match(r'^第[一二三四五六七八九十百]+章\s', line):
processed_lines.append(f"\n## {line}\n")
elif re.match(r'^第[一二三四五六七八九十百]+节\s', line):
@@ -242,7 +230,7 @@ class PDFParser:
elif re.match(r'^第[一二三四五六七八九十百]+条\s', line):
processed_lines.append(f"\n#### {line}\n")
elif re.match(r'^[一二三四五六七八九十]+\s*[、.]', line):
# 条款子项
# Keep service responsibilities explicit so downstream behavior stays predictable.
processed_lines.append(f"- {line}")
else:
processed_lines.append(line)
@@ -250,18 +238,18 @@ class PDFParser:
return "\n".join(processed_lines)
def parse_to_markdown(self, file_path: str) -> str:
"""直接解析并返回Markdown文本"""
"""Parse to markdown for the P D F Parser instance."""
doc_content = self.parse(file_path)
return doc_content.markdown_text
def parse_pdf(file_path: str, **kwargs) -> PDFDocumentContent:
"""便捷函数解析PDF文档"""
"""Parse pdf."""
parser = PDFParser()
return parser.parse(file_path, **kwargs)
def parse_pdf_to_markdown(file_path: str) -> str:
"""便捷函数解析PDF并返回Markdown"""
"""Parse pdf to markdown."""
parser = PDFParser()
return parser.parse_to_markdown(file_path)