Files
syops/backend/edkb_system/skills/doc_to_pdf.py
T

72 lines
2.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.
"""
backend/edkb_system/skills/doc_to_pdf.py
文件用途:将 Word 文档转换为 PDF,供后续 PDF 解析链路使用
说明:
- Windows 优先走 Word COM(word_bridge);
- Linux/容器环境走 LibreOffice,转换超时由 soffice_util 统一控制。
"""
from __future__ import annotations
import os
from pathlib import Path
from edkb_system.contracts import Context
from edkb_system.skills.soffice_util import convert_with_soffice, find_soffice
from edkb_system.skills.word_bridge import convert_with_word
def _convert_with_word(path: Path, out_dir: Path) -> Path:
output = out_dir / f"{path.stem}.pdf"
return convert_with_word(path.resolve(), output.resolve(), 17)
def _convert_with_soffice(path: Path, out_dir: Path, soffice: str) -> Path:
"""通过 soffice 转 PDF;超时抛出 RuntimeError。"""
output = out_dir / f"{path.stem}.pdf"
proc = convert_with_soffice(
soffice,
convert_to="pdf",
source_path=path,
out_dir=out_dir,
)
if proc.returncode != 0:
stderr = (proc.stderr or "").strip() or "no stderr"
raise RuntimeError(
f"soffice conversion failed (code={proc.returncode}): {stderr}"
)
if not output.exists():
raise RuntimeError(f"soffice conversion produced no output: {output}")
return output
def run(input_data: dict, context: Context) -> dict:
file_path = Path(input_data["file_path"])
work_dir = Path(input_data["work_dir"])
out_dir = work_dir / "flow_pdf"
out_dir.mkdir(parents=True, exist_ok=True)
errors: list[str] = []
if os.name == "nt":
try:
pdf = _convert_with_word(file_path, out_dir)
return {"pdf_path": str(pdf), "converter": "word"}
except Exception as exc:
errors.append(f"word: {exc}")
soffice = find_soffice()
if soffice:
try:
pdf = _convert_with_soffice(file_path, out_dir, soffice)
return {"pdf_path": str(pdf), "converter": "soffice"}
except Exception as exc:
errors.append(f"soffice: {exc}")
else:
errors.append("soffice: not found")
context.warnings.append(
"doc->pdf conversion unavailable; fallback to docx text parser"
)
context.warnings.append("doc->pdf details: " + "; ".join(errors))
return {"pdf_path": None, "converter": None}