""" backend/edkb_system/skills/soffice_util.py 文件用途:LibreOffice(soffice)转换统一封装 说明: - 为 loader_docx / doc_to_pdf / loader_excel / loader_pptx 等技能提供带超时的 soffice 调用; - 避免单个 Office 文档转换卡死导致 kb-worker 长期阻塞; - 超时阈值通过环境变量 EDKB_SOFFICE_TIMEOUT_SEC 配置(默认 120 秒)。 """ from __future__ import annotations import os import subprocess from pathlib import Path import shutil import tempfile def soffice_timeout_sec() -> int: """读取 soffice 子进程超时秒数,最小 10 秒。""" raw = str(os.environ.get("EDKB_SOFFICE_TIMEOUT_SEC", "120")).strip() try: value = int(raw) except ValueError: value = 120 return max(value, 10) def soffice_candidates() -> list[str]: """返回 soffice 可执行文件候选路径(环境变量优先,其次 Windows 默认安装路径)。""" return [ os.environ.get("EDKB_SOFFICE", "").strip(), r"C:\Program Files\LibreOffice\program\soffice.exe", r"C:\Program Files (x86)\LibreOffice\program\soffice.exe", "soffice", ] def find_soffice() -> str | None: """返回第一个可用的 soffice 路径;PATH 中的 `soffice` 不做存在性探测。""" for candidate in soffice_candidates(): if not candidate: continue if candidate == "soffice": return candidate if Path(candidate).exists(): return candidate return None def use_isolated_soffice_profile() -> bool: raw = str(os.environ.get("EDKB_SOFFICE_ISOLATED_PROFILE", "1")).strip().lower() return raw not in {"0", "false", "no"} def _new_soffice_profile_dir() -> Path: return Path(tempfile.mkdtemp(prefix="lo-profile-")).resolve() def run_soffice(cmd: list[str]) -> subprocess.CompletedProcess[str]: """ 执行 soffice 命令并强制超时。 超时时抛出 RuntimeError,供上层清洗任务识别为失败而非无限等待。 """ timeout = soffice_timeout_sec() try: return subprocess.run( cmd, capture_output=True, text=True, timeout=timeout, ) except subprocess.TimeoutExpired as exc: label = Path(cmd[-2]).name if len(cmd) >= 2 else "soffice" raise RuntimeError( f"soffice timed out after {timeout}s: {label}" ) from exc def convert_with_soffice( soffice: str, *, convert_to: str, source_path: Path, out_dir: Path, ) -> subprocess.CompletedProcess[str]: """ 以 headless 模式调用 soffice 做格式转换。 :param convert_to: 目标格式,如 docx / pdf / xlsx / pptx """ out_dir.mkdir(parents=True, exist_ok=True) profile_dir: Path | None = None profile_arg: str | None = None if use_isolated_soffice_profile(): profile_dir = _new_soffice_profile_dir() profile_arg = f"-env:UserInstallation={profile_dir.as_uri()}" cmd = [ soffice, *( [profile_arg] if profile_arg else [] ), "--headless", "--convert-to", convert_to, str(source_path), "--outdir", str(out_dir), ] try: return run_soffice(cmd) finally: if profile_dir is not None: shutil.rmtree(profile_dir, ignore_errors=True)