Files
ragservice/app/core/document_processor.py
T
2026-09-09 12:45:26 +08:00

140 lines
5.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import chardet
import hashlib
import re
from dataclasses import dataclass
from typing import List
from langchain_text_splitters import RecursiveCharacterTextSplitter
import logging
from app.config import settings
logger = logging.getLogger(__name__)
@dataclass
class FaqEntry:
"""FAQ 原子条目:问题 + 答案 + 去重分组 ID"""
question: str
answer: str
group_id: str
# 全角标点 → 半角(D5 归一化规则 2)。
# 注意:str.maketrans 要求两串等长,成对的全角引号(""'')无法 1:1 映射,
# 故引号用 replace 单独处理(审查 B1 修正)。
_FULL_TO_HALF = str.maketrans(",。!?;:()", ",.!?;:()")
def normalize_answer(text: str) -> str:
"""归一化答案(D5):去全部空白 → 全角标点转半角 → 小写。"""
text = re.sub(r"\s+", "", text) # 去全部空白(含全角空格、\n、\t)
text = text.translate(_FULL_TO_HALF) # 全角标点转半角(8 个可 1:1 映射的)
text = text.replace("\u201c", '"').replace("\u201d", '"') # 全角双引号 → 半角
text = text.replace("\u2018", "'").replace("\u2019", "'") # 全角单引号 → 半角
return text.lower()
class DocumentProcessor:
"""文档解析与分块处理"""
SUPPORTED_TYPES = {".txt", ".md"}
def __init__(self):
self.splitter = RecursiveCharacterTextSplitter(
chunk_size=settings.rag_chunk_size,
chunk_overlap=settings.rag_chunk_overlap,
separators=["\n\n", "\n", "。", "!", "?", ";", " ", ""]
)
def clean(self, text: str) -> str:
import re
text = text.replace('\ufeff', '') #去除BOM
text = re.sub(r'[\u200b\u200c\u200d\u2060\uFEFF]', '', text) # 零宽字符
text = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]', '', text) # 控制字符(保留\n \t)
text = re.sub(r'\n{3,}', '\n\n', text) # 多余空行
text = re.sub(r'[ \t]+', ' ', text) # 压缩多余空格
text = re.sub(r'^[ \t]+|[ \t]+$', '', text, flags=re.MULTILINE) # 行首尾多余空格
text = re.sub(r'[ \t]+\n', '\n', text) # 行尾空格
return text.strip()
def parse(self, file_path: str, file_type: str) -> str:
"""解析文档返回纯文本"""
file_type = file_type.lower()
if file_type in (".txt", ".md"):
return self._parse_txt(file_path)
else:
raise ValueError(f"Unsupported file type: {file_type}")
def _parse_txt(self, file_path: str) -> str:
"""解析文本文件,自动检测编码"""
with open(file_path, "rb") as f:
raw = f.read()
encoding = chardet.detect(raw)["encoding"] or "utf-8"
return raw.decode(encoding, errors="ignore")
def chunk(self, text: str) -> List[str]:
"""将文本分块"""
if not text.strip():
return []
return self.splitter.split_text(text)
def process_file(self, file_path: str, file_type: str) -> List[str]:
"""完整处理流程:解析 -> 分块"""
text = self.parse(file_path, file_type)
text = self.clean(text)
chunks = self.chunk(text)
logger.info(f"Processed {file_path}: {len(chunks)} chunks")
return chunks
def parse_faq(self, text: str) -> List[FaqEntry]:
"""解析 FAQ 文本为原子 Q&A 条目列表。
规则:
- 先经 self.clean() 前置清洗(BOM/零宽/控制字符/多余空行);
- 按行首 `问:` / `答:` 标记切分,每个 Q&A 对独立成条目;
- 多行答案:答案延续到下一个 `问:` / `答:` 或 EOF;
- 畸形对(缺问或缺答):跳过 + logger.warning;
- group_id = md5(normalize_answer(answer))(D5,确定性、幂等)。
"""
text = self.clean(text)
entries: List[FaqEntry] = []
lines = text.splitlines()
current_q: str | None = None
answer_parts: List[str] = []
def flush() -> None:
nonlocal current_q, answer_parts
if current_q is not None and answer_parts:
answer = "\n".join(answer_parts).strip()
group_id = hashlib.md5(normalize_answer(answer).encode("utf-8")).hexdigest()
entries.append(FaqEntry(question=current_q.strip(), answer=answer, group_id=group_id))
elif current_q is not None or answer_parts:
logger.warning(
f"parse_faq: 畸形 Q&A 对跳过(缺问或缺答): q={current_q!r}, answer_lines={len(answer_parts)}"
)
current_q = None
answer_parts = []
for line in lines:
stripped = line.strip()
if stripped.startswith("问:"):
flush()
current_q = stripped[2:].strip()
elif stripped.startswith("答:"):
answer_text = stripped[2:].strip()
if answer_text: # 过滤空答案行,避免空答案条目入库(审查 M3)
answer_parts.append(answer_text)
elif current_q is not None:
# 多行答案:延续到下一个标记
answer_parts.append(stripped)
flush()
return entries
# 单例实例
document_processor = DocumentProcessor()