document_parser.py 13.9 KB
import os
import shutil
import subprocess
import tempfile
import time
import logging
from pathlib import Path

logger = logging.getLogger(__name__)

def is_presentation_file(file_path: str) -> bool:
    return os.path.splitext(file_path)[1].lower() in {".ppt", ".pptx"}

def extract_text_from_file(
    file_path: str,
    preview_file_id: str | None = None,
    preview_dir: str | None = None,
) -> str:
    """
    根据文件后缀提取文档中的纯文本内容。
    支持的格式: .txt, .md, .json, .pdf, .docx, .pptx, .ppt, .xlsx, .xls
    如果遇到不支持的格式,将尝试作为纯文本读取。
    """
    if not os.path.exists(file_path):
        raise FileNotFoundError(f"未找到文件,请检查路径是否正确: {file_path}")

    # 获取文件后缀名并统一转换为小写,以进行格式路由
    ext = os.path.splitext(file_path)[1].lower()

    try:
        # 基于常见文本格式进行路由
        if ext in ['.txt', '.md', '.json', '.xml', '.csv']:
            return _extract_text_plain(file_path)
        # 路由到 PDF 解析器
        elif ext == '.pdf':
            return _extract_text_pdf(file_path)
        # 路由到 Word 文档解析器
        elif ext == '.docx':
            return _extract_text_docx(file_path)
        # 路由到 PPT 演示文稿解析器:先转 PDF,再复用 PDF VLM 路径
        elif is_presentation_file(file_path):
            return _extract_text_presentation(file_path, preview_file_id=preview_file_id, preview_dir=preview_dir)
        # 路由到 Excel 表格解析器
        elif ext in ['.xlsx', '.xls']:
            return _extract_text_excel(file_path)
        else:
            # 对于未明确支持的文件后缀(例如 .log, .conf 等),
            # 默认作为纯文本文件尝试读取,充当降级(Fallback)方案
            return _extract_text_plain(file_path)
    except Exception as e:
        # 将底层解析错误包装为 RuntimeError 向上抛出,方便上层捕获和记录
        raise RuntimeError(f"从文件 {file_path} 提取文本时发生错误: {str(e)}")

def _extract_text_plain(file_path: str) -> str:
    """
    读取纯文本文件的内容,内置自动探测编码机制。
    
    参数:
        file_path (str): 文本文件路径
        
    返回:
        str: 文本文件内容
    """
    # 尝试使用多种常见编码顺序读取,以兼容不同来源的文本文件(特别是 Windows 默认的 gbk)
    for enc in ['utf-8', 'gbk', 'latin-1']:
        try:
            with open(file_path, 'r', encoding=enc) as f:
                return f.read()
        except UnicodeDecodeError:
            # 如果当前编码解码失败,静默捕获并尝试列表中的下一种编码
            continue
            
    # 如果所有常见编码都失败,最后作为兜底方案(Fallback)
    # 强制使用 utf-8 读取,并且遇到无法解码的字符时使用 'replace'(替换为 ),防止程序直接崩溃
    with open(file_path, 'r', encoding='utf-8', errors='replace') as f:
        return f.read()

def _extract_text_pdf(file_path: str) -> str:
    """
    解析 PDF 文档并提取每一页的文本。
    
    参数:
        file_path (str): PDF 文件路径
        
    返回:
        str: 合并后的 PDF 文本内容
    """
    blocks = _load_pdf_blocks(file_path)
    return _blocks_to_markdown(blocks)

def _load_pdf_blocks(file_path: str):
    """复用 RAG 的 PDF VLM 解析器,保持 qwen-vl-max 等配置统一。"""
    from src.rag.loaders.pdf_loader import _load_pdf

    return _load_pdf(file_path)

def _blocks_to_markdown(blocks) -> str:
    """将 RAG DocumentBlock 列表拼接成摄入 Agent 可读的 Markdown。"""
    sorted_blocks = sorted(
        blocks,
        key=lambda block: (
            getattr(block, "page_number", None) or 0,
            getattr(block, "source_offset", None) or 0,
        ),
    )
    if not sorted_blocks:
        raise RuntimeError("PDF 未提取到可用内容")

    text_content = []
    current_page = object()
    for block in sorted_blocks:
        page_number = getattr(block, "page_number", None)
        if page_number is not None and page_number != current_page:
            if text_content:
                text_content.append("")
            text_content.append(f"## Page {page_number}")
            current_page = page_number

        title_path = getattr(block, "title_path", "") or ""
        block_text = (getattr(block, "text", "") or "").strip()
        if not block_text:
            continue
        if title_path:
            text_content.append(f"<!-- section: {title_path} -->")
        text_content.append(block_text)

    result = "\n\n".join(part for part in text_content if part is not None).strip()
    if not result:
        raise RuntimeError("PDF 未提取到可用内容")
    return result

def _extract_text_docx(file_path: str) -> str:
    """
    解析 Word (.docx) 文档,提取所有段落以及表格内的文本。
    
    参数:
        file_path (str): Word 文件路径
        
    返回:
        str: 拼接好的 Word 文本和表格内容
    """
    import docx
    doc = docx.Document(file_path)
    text_content = []
    
    # 1. 遍历文档中的所有常规段落
    for para in doc.paragraphs:
        if para.text.strip():
            text_content.append(para.text)
            
    # 2. 遍历文档中所有的表格,将表格数据扁平化提取
    for table in doc.tables:
        for row in table.rows:
            # 将同一行内的各个单元格文本通过 ' | ' 拼接,模拟 Markdown 表格格式
            row_data = [cell.text.strip() for cell in row.cells if cell.text.strip()]
            if row_data:
                text_content.append(" | ".join(row_data))
                
    # 使用单换行符连接所有段落和表格行
    return "\n".join(text_content)

def _extract_text_presentation(
    file_path: str,
    preview_file_id: str | None = None,
    preview_dir: str | None = None,
) -> str:
    """
    解析 PPT/PPTX 演示文稿:使用 LibreOffice headless 转 PDF,再复用 PDF VLM。
    
    参数:
        file_path (str): PPT 文件路径
        
    返回:
        str: 经 PDF VLM 解析后的 Markdown 文本
    """
    if preview_file_id:
        pdf_path = get_or_create_office_preview_pdf(file_path, preview_file_id, preview_dir)
        return _extract_text_pdf(pdf_path)

    with tempfile.TemporaryDirectory(prefix="wiki_presentation_pdf_") as tmp_dir:
        pdf_path = _convert_presentation_to_pdf(file_path, tmp_dir)
        return _extract_text_pdf(pdf_path)

def _office_preview_root(preview_dir: str | None = None) -> Path:
    if preview_dir is None:
        return Path(__file__).resolve().parents[2] / "ware" / "preview" / "pdf"
    return Path(preview_dir)

def get_office_preview_pdf_path(file_path: str, file_id: str, preview_dir: str | None = None) -> Path:
    source_path = Path(file_path)
    return _office_preview_root(preview_dir) / f"{source_path.stem}_{file_id}.pdf"

def delete_office_preview_pdf(file_path: str, file_id: str, preview_dir: str | None = None) -> str | None:
    cache_path = get_office_preview_pdf_path(file_path, file_id, preview_dir)
    if not cache_path.exists():
        return None

    cache_path.unlink()
    logger.info(
        "[Preview] Deleted PPT/PPTX PDF cache: file_id=%s, cache_path=%s",
        file_id,
        cache_path,
    )
    return str(cache_path)

def get_existing_office_preview_pdf(file_path: str, file_id: str, preview_dir: str | None = None) -> str | None:
    """Return a fresh cached PPT/PPTX preview PDF path without creating it."""
    source_path = Path(file_path)
    if not source_path.exists():
        raise FileNotFoundError(f"File not found: {file_path}")

    cache_path = get_office_preview_pdf_path(file_path, file_id, preview_dir)
    if not cache_path.exists():
        return None

    if cache_path.stat().st_mtime < source_path.stat().st_mtime:
        return None

    return str(cache_path)

def get_or_create_office_preview_pdf(file_path: str, file_id: str, preview_dir: str | None = None) -> str:
    """Create or reuse a cached PDF preview for PPT/PPTX files without running VLM parsing."""
    source_path = Path(file_path)
    if not source_path.exists():
        raise FileNotFoundError(f"File not found: {file_path}")

    preview_root = _office_preview_root(preview_dir)
    preview_root.mkdir(parents=True, exist_ok=True)

    cache_path = get_office_preview_pdf_path(file_path, file_id, preview_dir)
    source_mtime = source_path.stat().st_mtime
    cache_mtime = cache_path.stat().st_mtime if cache_path.exists() else None

    if cache_mtime is not None and cache_mtime >= source_mtime:
        logger.info(
            "[Preview] PPT/PPTX PDF cache hit: file_id=%s, cache_path=%s",
            file_id,
            cache_path,
        )
        return str(cache_path)

    if cache_mtime is None:
        logger.info(
            "[Preview] PPT/PPTX PDF cache missing: file_id=%s, source_mtime=%s, cache_path=%s",
            file_id,
            source_mtime,
            cache_path,
        )
    else:
        logger.info(
            "[Preview] PPT/PPTX PDF cache stale: file_id=%s, source_mtime=%s, cache_mtime=%s, cache_path=%s",
            file_id,
            source_mtime,
            cache_mtime,
            cache_path,
        )

    soffice = _resolve_soffice_path()
    if not soffice:
        logger.error(
            "[Preview] LibreOffice not found for PPT/PPTX preview: file_id=%s, source_path=%s",
            file_id,
            source_path,
        )
        raise RuntimeError("PPT/PPTX preview requires LibreOffice and soffice in PATH")

    start = time.perf_counter()
    logger.info(
        "[Preview] Starting LibreOffice PPT/PPTX preview conversion: file_id=%s, soffice=%s, output_cache=%s",
        file_id,
        soffice,
        cache_path,
    )
    try:
        with tempfile.TemporaryDirectory(prefix="wiki_office_preview_pdf_") as tmp_dir:
            converted_pdf = Path(_convert_presentation_to_pdf_with_soffice(str(source_path), tmp_dir, soffice))
            shutil.move(str(converted_pdf), str(cache_path))
    except Exception as exc:
        logger.error(
            "[Preview] LibreOffice PPT/PPTX preview conversion failed: file_id=%s, source_path=%s, cache_path=%s, error=%s",
            file_id,
            source_path,
            cache_path,
            exc,
            exc_info=True,
        )
        raise

    duration_ms = int((time.perf_counter() - start) * 1000)
    logger.info(
        "[Preview] LibreOffice PPT/PPTX preview conversion succeeded: file_id=%s, cache_path=%s, duration_ms=%s",
        file_id,
        cache_path,
        duration_ms,
    )
    return str(cache_path)

def _convert_presentation_to_pdf(file_path: str, output_dir: str) -> str:
    soffice = _resolve_soffice_path()
    if not soffice:
        raise RuntimeError("PPT/PPTX 多模态解析需要安装 LibreOffice,并确保 soffice 在 PATH 中")

    return _convert_presentation_to_pdf_with_soffice(file_path, output_dir, soffice)

def _convert_presentation_to_pdf_with_soffice(file_path: str, output_dir: str, soffice: str) -> str:
    timeout = int(os.environ.get("LIBREOFFICE_CONVERT_TIMEOUT", "120"))
    try:
        with tempfile.TemporaryDirectory(prefix="wiki_libreoffice_profile_") as profile_dir:
            cmd = [
                soffice,
                "--headless",
                "--nologo",
                "--nofirststartwizard",
                "--nolockcheck",
                "--nodefault",
                "--norestore",
                f"-env:UserInstallation={Path(profile_dir).as_uri()}",
                "--convert-to",
                "pdf",
                "--outdir",
                output_dir,
                file_path,
            ]
            subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, check=True)
    except subprocess.TimeoutExpired as exc:
        raise RuntimeError(f"LibreOffice 转换 PPT/PPTX 超时: {exc}") from exc
    except subprocess.CalledProcessError as exc:
        detail = "\n".join(part for part in [exc.stdout, exc.stderr] if part).strip()
        raise RuntimeError(f"LibreOffice 转换 PPT/PPTX 失败: {detail or exc}") from exc

    expected_pdf = Path(output_dir) / f"{Path(file_path).stem}.pdf"
    if expected_pdf.exists():
        return str(expected_pdf)

    pdf_candidates = sorted(Path(output_dir).glob("*.pdf"))
    if pdf_candidates:
        return str(pdf_candidates[0])

    raise RuntimeError("LibreOffice 转换 PPT/PPTX 失败: 未生成 PDF 文件")

def _resolve_soffice_path() -> str | None:
    configured_path = os.environ.get("LIBREOFFICE_PATH")
    if configured_path and Path(configured_path).exists():
        return configured_path

    soffice = shutil.which("soffice")
    if soffice:
        return soffice

    for candidate in (
        Path(r"C:\Program Files\LibreOffice\program\soffice.exe"),
        Path(r"C:\Program Files (x86)\LibreOffice\program\soffice.exe"),
    ):
        if candidate.exists():
            return str(candidate)

    return None

def _extract_text_excel(file_path: str) -> str:
    """
    解析 Excel 表格 (.xlsx, .xls) 数据。
    利用 Pandas 框架一次性读取所有 Sheet,并转化为纯文本表现形式。
    
    参数:
        file_path (str): Excel 文件路径
        
    返回:
        str: 包含所有 Sheet 数据的纯文本格式
    """
    import pandas as pd
    text_content = []
    
    # sheet_name=None 表示读取工作簿中的所有工作表 (Sheets),返回结果为一个字典
    # 键为 Sheet 名称,值为对应的 DataFrame 对象
    df_dict = pd.read_excel(file_path, sheet_name=None)
    
    for sheet_name, df in df_dict.items():
        # 添加 Sheet 标题作为明显的分隔符
        text_content.append(f"--- Sheet: {sheet_name} ---")
        
        # 将 DataFrame 转换为字符串格式
        # index=False 意味着不输出行号索引,使结果更接近纯数据表格
        text_content.append(df.to_string(index=False))
        
    return "\n\n".join(text_content)