File size: 3,344 Bytes
fdfe81a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
"""
lo_runner.py — soffice subprocess wrapper with timeout and isolated UserInstallation.

Each call generates a UUID and uses -env:UserInstallation=file:///tmp/lo_<uuid>
to avoid lock-file collisions when multiple render_deck() calls run concurrently.
"""
from __future__ import annotations

import logging
import os
import shutil
import signal
import subprocess
import uuid
from pathlib import Path

logger = logging.getLogger(__name__)

SOFFICE_TIMEOUT_SECONDS = 60


def soffice_available() -> bool:
    """Return True if soffice is on $PATH."""
    return shutil.which("soffice") is not None


def convert_pptx_to_pdf(pptx_path: Path, out_dir: Path) -> Path:
    """
    Convert a .pptx file to a single PDF using LibreOffice headless.

    Each invocation creates an isolated UserInstallation directory at
    /tmp/lo_<uuid> to prevent concurrent lock-file collisions.

    Parameters
    ----------
    pptx_path : Path
        Absolute path to the source .pptx file.
    out_dir : Path
        Directory where LibreOffice will write the output PDF.

    Returns
    -------
    Path
        Path to the generated PDF file.

    Raises
    ------
    RuntimeError
        If soffice is not available, the process times out, or conversion fails.
    """
    if not soffice_available():
        raise RuntimeError("soffice is not available on $PATH")

    run_id = uuid.uuid4().hex
    lo_user_dir = Path(f"/tmp/lo_{run_id}")
    lo_user_dir.mkdir(parents=True, exist_ok=True)

    cmd = [
        "soffice",
        "--headless",
        f"-env:UserInstallation=file://{lo_user_dir}",
        "--convert-to",
        "pdf",
        "--outdir",
        str(out_dir),
        str(pptx_path),
    ]

    logger.debug("Running soffice: %s", " ".join(cmd))

    try:
        proc = subprocess.Popen(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            # Start in a new process group so we can kill the whole group on timeout
            preexec_fn=os.setsid,
        )

        try:
            stdout, stderr = proc.communicate(timeout=SOFFICE_TIMEOUT_SECONDS)
        except subprocess.TimeoutExpired:
            # Kill the entire process group
            try:
                os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
            except ProcessLookupError:
                pass
            proc.wait()
            raise RuntimeError(
                f"soffice timed out after {SOFFICE_TIMEOUT_SECONDS}s converting "
                f"{pptx_path.name}"
            )

        if proc.returncode != 0:
            stderr_text = stderr.decode("utf-8", errors="replace").strip()
            raise RuntimeError(
                f"soffice exited with code {proc.returncode} for {pptx_path.name}: "
                f"{stderr_text}"
            )

        # LibreOffice names the output <stem>.pdf in out_dir
        pdf_path = out_dir / (pptx_path.stem + ".pdf")
        if not pdf_path.exists():
            raise RuntimeError(
                f"soffice succeeded but expected PDF not found: {pdf_path}"
            )

        logger.debug("soffice produced: %s", pdf_path)
        return pdf_path

    finally:
        # Always clean up the isolated UserInstallation dir
        try:
            shutil.rmtree(lo_user_dir, ignore_errors=True)
        except Exception:
            pass