File size: 7,409 Bytes
ec21fa4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
#!/usr/bin/env python3
"""Create a PPTX copy with text-frame autofit geometry materialized.

This helper is optional. It copies the source tree, sets text frames to
SHAPE_TO_FIT_TEXT, and uses LibreOffice to materialize the resulting geometry.
The source root is never edited in place.
"""

import argparse
import json
import shutil
import subprocess
from pathlib import Path

from pptx import Presentation
from pptx.enum.text import MSO_AUTO_SIZE


def iter_shapes(shapes):
    for shape in shapes:
        yield shape
        if hasattr(shape, "shapes"):
            try:
                for sub_shape in iter_shapes(shape.shapes):
                    yield sub_shape
            except Exception:
                pass


def collect_pptx_paths(root, pptx_name):
    paths = []
    skipped = []

    for child in sorted(root.iterdir(), key=lambda p: p.name):
        if not child.is_dir():
            continue

        if pptx_name:
            pptx = child / pptx_name
            if pptx.exists():
                paths.append(pptx)
            else:
                skipped.append({"dir_name": child.name, "reason": "missing_pptx"})
            continue

        matches = sorted(
            p for p in child.glob("*.pptx") if not p.name.startswith("~$")
        )
        if len(matches) == 1:
            paths.append(matches[0])
        elif not matches:
            skipped.append({"dir_name": child.name, "reason": "missing_pptx"})
        else:
            skipped.append({"dir_name": child.name, "reason": "multiple_pptx"})

    return paths, skipped


def apply_text_autofit(pptx_path):
    prs = Presentation(str(pptx_path))
    if len(prs.slides) == 0:
        return {
            "total_text_shapes": 0,
            "nonempty_text_shapes": 0,
            "changed_shapes": 0,
        }

    slide = prs.slides[0]
    changed = 0
    total_text_shapes = 0
    nonempty_text_shapes = 0

    for shape in iter_shapes(slide.shapes):
        if not getattr(shape, "has_text_frame", False):
            continue
        total_text_shapes += 1
        text = (shape.text or "").strip()
        if text:
            nonempty_text_shapes += 1
        text_frame = shape.text_frame
        text_frame.word_wrap = True
        if text_frame.auto_size != MSO_AUTO_SIZE.SHAPE_TO_FIT_TEXT:
            text_frame.auto_size = MSO_AUTO_SIZE.SHAPE_TO_FIT_TEXT
            changed += 1

    prs.save(str(pptx_path))
    return {
        "total_text_shapes": total_text_shapes,
        "nonempty_text_shapes": nonempty_text_shapes,
        "changed_shapes": changed,
    }


def libreoffice_roundtrip(pptx_path, tmp_dir, libreoffice_bin):
    tmp_dir.mkdir(parents=True, exist_ok=True)
    out_path = tmp_dir / pptx_path.name
    if out_path.exists():
        out_path.unlink()

    subprocess.run(
        [
            libreoffice_bin,
            "--headless",
            "--convert-to",
            "pptx",
            "--outdir",
            str(tmp_dir),
            str(pptx_path),
        ],
        check=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        text=True,
    )

    if not out_path.exists():
        raise FileNotFoundError("LibreOffice did not produce: {}".format(out_path))
    shutil.move(str(out_path), str(pptx_path))


def relpath(path, root):
    try:
        return str(path.relative_to(root))
    except ValueError:
        return path.name


def parse_args():
    parser = argparse.ArgumentParser(
        description="Copy a PPTX tree and materialize text-frame autofit geometry."
    )
    parser.add_argument("--src-root", required=True, help="Source benchmark root.")
    parser.add_argument("--dst-root", required=True, help="Destination benchmark root.")
    parser.add_argument(
        "--pptx-name",
        default=None,
        help="Per-poster PPTX filename. Omit to auto-detect one PPTX per directory.",
    )
    parser.add_argument(
        "--tmp-dir",
        default=None,
        help="Temporary LibreOffice output directory. Defaults to <dst-root>/_lo_tmp.",
    )
    parser.add_argument(
        "--libreoffice-bin",
        default="libreoffice",
        help="LibreOffice or soffice executable name/path.",
    )
    parser.add_argument(
        "--skip-libreoffice-roundtrip",
        action="store_true",
        help="Only set PPTX auto-size flags; do not materialize geometry with LibreOffice.",
    )
    parser.add_argument(
        "--include-paths",
        action="store_true",
        help="Include absolute source/output paths in the summary JSON.",
    )
    return parser.parse_args()


def main():
    args = parse_args()
    src_root = Path(args.src_root).expanduser().resolve()
    dst_root = Path(args.dst_root).expanduser().resolve()
    tmp_dir = (
        Path(args.tmp_dir).expanduser().resolve()
        if args.tmp_dir
        else dst_root / "_lo_tmp"
    )

    if not src_root.exists():
        raise SystemExit("Source root does not exist: {}".format(src_root))
    if dst_root.exists():
        raise SystemExit("Destination already exists: {}".format(dst_root))

    shutil.copytree(src_root, dst_root)
    pptx_paths, skipped = collect_pptx_paths(dst_root, args.pptx_name)

    records = []
    failed = []
    for index, pptx_path in enumerate(pptx_paths, start=1):
        try:
            info = apply_text_autofit(pptx_path)
            if not args.skip_libreoffice_roundtrip:
                libreoffice_roundtrip(pptx_path, tmp_dir, args.libreoffice_bin)
            record = {
                "index": index,
                "dir_name": pptx_path.parent.name,
                "pptx_relpath": relpath(pptx_path, dst_root),
                **info,
            }
            if args.include_paths:
                record["pptx_path"] = str(pptx_path)
            records.append(record)
        except Exception as exc:
            failed_record = {
                "index": index,
                "dir_name": pptx_path.parent.name,
                "pptx_relpath": relpath(pptx_path, dst_root),
                "error": repr(exc),
            }
            if args.include_paths:
                failed_record["pptx_path"] = str(pptx_path)
            failed.append(failed_record)

        if index % 10 == 0 or index == len(pptx_paths):
            print("[{}/{}] {}".format(index, len(pptx_paths), pptx_path.parent.name))

    summary = {
        "protocol": "text_frame_autofit"
        + (" only" if args.skip_libreoffice_roundtrip else " + LibreOffice roundtrip"),
        "pptx_name": args.pptx_name,
        "processed_count": len(records),
        "failed_count": len(failed),
        "skipped_count": len(skipped),
        "records": records,
        "failed": failed,
        "skipped": skipped,
    }
    if args.include_paths:
        summary.update(
            {
                "source_root": str(src_root),
                "target_root": str(dst_root),
                "tmp_dir": str(tmp_dir),
            }
        )
    else:
        summary.update(
            {
                "source_root_name": src_root.name,
                "target_root_name": dst_root.name,
            }
        )

    summary_path = dst_root / "_pptx_autofit_summary.json"
    summary_path.write_text(
        json.dumps(summary, ensure_ascii=False, indent=2) + "\n",
        encoding="utf-8",
    )
    print("Summary written to: {}".format(summary_path))


if __name__ == "__main__":
    main()