File size: 28,139 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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
#!/usr/bin/env python3
"""Deterministic PPTX structural metrics for academic posters.

- Ove: mean IoU over valid PPTX shape pairs, excluding empty rectangle
  containers and containment pairs.
- Ali: six-axis nearest-anchor alignment loss over valid PPTX shapes.
- Ofl: total area outside the slide canvas, normalized by canvas area.

The script intentionally does not depend on VLM/LLM parsing. It operates
directly on PPTX geometry.
"""

import argparse
import csv
import json
import math
import re
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
from statistics import mean

from pptx import Presentation


DEFAULT_VALID_VISIBLE_THRESHOLD = 0.001
DEFAULT_CONTAINMENT_THRESHOLD = 0.9
DEFAULT_WORKERS = 8
AXES = ("L", "C", "R", "T", "M", "B")


def normalize_key(text):
    return re.sub(r"[^a-z0-9]+", "", text.lower())


def extract_key(name, pattern):
    if pattern:
        match = re.search(pattern, name)
        if match:
            return match.groupdict().get("key") or match.group(1)
    if re.fullmatch(r"\d+", name):
        return name
    return normalize_key(name)


def should_ignore_dir(name, patterns):
    for pattern in patterns or []:
        if re.search(pattern, name):
            return True
    return False


def choose_pptx(dir_path, pptx_filename):
    if pptx_filename:
        candidate = dir_path / pptx_filename
        if candidate.exists():
            return candidate

    pptx_files = sorted(
        p for p in dir_path.glob("*.pptx") if not p.name.startswith("~$")
    )
    if not pptx_files:
        return None

    priority = {"poster.pptx": 0, "paper.pptx": 1}
    return sorted(pptx_files, key=lambda p: (priority.get(p.name, 9), p.name))[0]


def discover_method(spec):
    root = Path(spec["root"]).expanduser()
    key_regex = spec.get("key_regex")
    pptx_filename = spec.get("pptx_filename")
    ignore_dir_regex = spec.get("ignore_dir_regex", [r"^_", r"^\.", r"^__pycache__$"])

    mapping = {}
    missing_pptx = []
    duplicates = []
    ignored_dirs = []
    all_dirs = []

    if not root.exists():
        return {
            "root_exists": False,
            "mapping": mapping,
            "missing_pptx": missing_pptx,
            "duplicates": duplicates,
            "ignored_dirs": ignored_dirs,
            "all_dirs": all_dirs,
        }

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

        all_dirs.append(child.name)
        key = extract_key(child.name, key_regex)
        pptx_path = choose_pptx(child, pptx_filename)

        if pptx_path is None:
            missing_pptx.append({"dir_name": child.name, "key": key})
            continue

        if key in mapping:
            duplicates.append(
                {
                    "key": key,
                    "kept_dir": mapping[key]["dir_name"],
                    "duplicate_dir": child.name,
                }
            )
            continue

        mapping[key] = {"dir_name": child.name, "pptx_path": pptx_path}

    return {
        "root_exists": True,
        "mapping": mapping,
        "missing_pptx": missing_pptx,
        "duplicates": duplicates,
        "ignored_dirs": ignored_dirs,
        "all_dirs": all_dirs,
    }


def shape_text(shape):
    if not getattr(shape, "has_text_frame", False):
        return ""
    try:
        return shape.text_frame.text or ""
    except Exception:
        return ""


def is_container_rectangle(shape):
    """Return True for empty background/container rectangles excluded from Ove."""
    name = getattr(shape, "name", "") or ""
    if shape_text(shape).strip():
        return False
    return name.startswith("Rectangle") or name.startswith("Rounded Rectangle")


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_shapes(pptx_path):
    prs = Presentation(str(pptx_path))
    slide = prs.slides[0]
    canvas_w = float(prs.slide_width)
    canvas_h = float(prs.slide_height)

    records = []
    for index, shape in enumerate(iter_shapes(slide.shapes)):
        if not all(hasattr(shape, attr) for attr in ("left", "top", "width", "height")):
            continue
        try:
            x = float(shape.left)
            y = float(shape.top)
            w = float(shape.width)
            h = float(shape.height)
        except Exception:
            continue
        if w <= 0 or h <= 0:
            continue

        records.append(
            {
                "index": index,
                "x": x,
                "y": y,
                "w": w,
                "h": h,
                "name": getattr(shape, "name", "") or "",
                "has_text": bool(shape_text(shape).strip()),
                "is_container_rectangle": is_container_rectangle(shape),
            }
        )

    return records, canvas_w, canvas_h


def bbox_area(box):
    return max(0.0, box["w"]) * max(0.0, box["h"])


def intersection_area(a, b):
    x1 = max(a["x"], b["x"])
    y1 = max(a["y"], b["y"])
    x2 = min(a["x"] + a["w"], b["x"] + b["w"])
    y2 = min(a["y"] + a["h"], b["y"] + b["h"])
    if x2 <= x1 or y2 <= y1:
        return 0.0
    return (x2 - x1) * (y2 - y1)


def visible_area(box, canvas_w, canvas_h):
    canvas = {"x": 0.0, "y": 0.0, "w": canvas_w, "h": canvas_h}
    return intersection_area(box, canvas)


def is_valid_visible(box, canvas_w, canvas_h, threshold):
    canvas_area = canvas_w * canvas_h
    if canvas_area <= 0:
        return False
    return visible_area(box, canvas_w, canvas_h) / canvas_area > threshold


def compute_iou(a, b):
    inter = intersection_area(a, b)
    if inter <= 0:
        return 0.0
    union = bbox_area(a) + bbox_area(b) - inter
    if union <= 0:
        return 0.0
    return inter / union


def is_containment(a, b, threshold):
    inter = intersection_area(a, b)
    if inter <= 0:
        return False
    area_a = bbox_area(a)
    area_b = bbox_area(b)
    if area_a <= 0 or area_b <= 0:
        return False
    return inter / area_a >= threshold or inter / area_b >= threshold


def compute_ove(valid_shapes, containment_threshold):
    shapes = [s for s in valid_shapes if not s["is_container_rectangle"]]
    dropped = len(valid_shapes) - len(shapes)

    if len(shapes) < 2:
        return 0.0, {
            "ove_elements": len(shapes),
            "container_rectangles_dropped_for_ove": dropped,
            "ove_pairs": 0,
            "ove_overlapping_pairs": 0,
            "ove_skipped_containment": 0,
            "ove_max_iou": 0.0,
        }

    total_iou = 0.0
    pairs = 0
    overlapping_pairs = 0
    skipped_containment = 0
    max_iou = 0.0

    for i in range(len(shapes)):
        for j in range(i + 1, len(shapes)):
            if is_containment(shapes[i], shapes[j], containment_threshold):
                skipped_containment += 1
                continue

            iou = compute_iou(shapes[i], shapes[j])
            total_iou += iou
            pairs += 1
            if iou > 0:
                overlapping_pairs += 1
                max_iou = max(max_iou, iou)

    if pairs == 0:
        score = 0.0
    else:
        score = total_iou / pairs

    return score, {
        "ove_elements": len(shapes),
        "container_rectangles_dropped_for_ove": dropped,
        "ove_pairs": pairs,
        "ove_overlapping_pairs": overlapping_pairs,
        "ove_skipped_containment": skipped_containment,
        "ove_max_iou": max_iou,
    }


def anchor_attrs(box, canvas_w, canvas_h):
    return {
        "L": box["x"] / canvas_w if canvas_w > 0 else 0.0,
        "C": (box["x"] + box["w"] / 2.0) / canvas_w if canvas_w > 0 else 0.0,
        "R": (box["x"] + box["w"]) / canvas_w if canvas_w > 0 else 0.0,
        "T": box["y"] / canvas_h if canvas_h > 0 else 0.0,
        "M": (box["y"] + box["h"] / 2.0) / canvas_h if canvas_h > 0 else 0.0,
        "B": (box["y"] + box["h"]) / canvas_h if canvas_h > 0 else 0.0,
    }


def compute_ali(valid_shapes, canvas_w, canvas_h):
    if len(valid_shapes) < 2:
        return 0.0, {"ali_elements": len(valid_shapes)}

    attrs = [anchor_attrs(box, canvas_w, canvas_h) for box in valid_shapes]
    scores = []
    axis_counts = {axis: 0 for axis in AXES}

    for i, attrs_i in enumerate(attrs):
        min_per_axis = {}
        for axis in AXES:
            min_per_axis[axis] = min(
                abs(attrs_i[axis] - attrs_j[axis])
                for j, attrs_j in enumerate(attrs)
                if i != j
            )
        best_axis = min(min_per_axis, key=lambda axis: min_per_axis[axis])
        scores.append(min_per_axis[best_axis])
        axis_counts[best_axis] += 1

    return mean(scores), {
        "ali_elements": len(valid_shapes),
        "ali_min": min(scores),
        "ali_max": max(scores),
        "ali_axis_counts": axis_counts,
    }


def compute_ofl(all_shapes, canvas_w, canvas_h):
    canvas_area = canvas_w * canvas_h
    if canvas_area <= 0:
        return 0.0, {
            "ofl_total_elements": len(all_shapes),
            "ofl_overflow_elements": 0,
            "ofl_max_element_overflow_ratio": 0.0,
        }

    total_overflow = 0.0
    overflow_elements = 0
    max_element_overflow_ratio = 0.0

    for box in all_shapes:
        area = bbox_area(box)
        overflow = max(0.0, area - visible_area(box, canvas_w, canvas_h))
        if overflow > 0:
            total_overflow += overflow
            overflow_elements += 1
            max_element_overflow_ratio = max(
                max_element_overflow_ratio, overflow / canvas_area
            )

    return total_overflow / canvas_area, {
        "ofl_total_elements": len(all_shapes),
        "ofl_overflow_elements": overflow_elements,
        "ofl_max_element_overflow_ratio": max_element_overflow_ratio,
    }


def relative_pptx_path(pptx_path, root):
    try:
        return str(pptx_path.relative_to(root))
    except ValueError:
        return pptx_path.name


def evaluate_one(
    dataset_name,
    method_name,
    method_spec,
    key,
    item,
    valid_visible_threshold,
    containment_threshold,
    include_paths,
):
    root = Path(method_spec["root"]).expanduser()
    pptx_path = item["pptx_path"]

    row = {
        "dataset": dataset_name,
        "method": method_name,
        "key": key,
        "dir_name": item["dir_name"],
        "variant": method_spec.get("variant", ""),
        "pptx_relpath": relative_pptx_path(pptx_path, root),
        "error": "",
    }
    if include_paths:
        row["pptx_path"] = str(pptx_path)

    try:
        all_shapes, canvas_w, canvas_h = collect_shapes(pptx_path)
        valid_shapes = [
            shape
            for shape in all_shapes
            if is_valid_visible(shape, canvas_w, canvas_h, valid_visible_threshold)
        ]

        ove, ove_details = compute_ove(valid_shapes, containment_threshold)
        ali, ali_details = compute_ali(valid_shapes, canvas_w, canvas_h)
        ofl, ofl_details = compute_ofl(all_shapes, canvas_w, canvas_h)

        row.update(
            {
                "ove": ove,
                "ali": ali,
                "ofl": ofl,
                "all_shapes": len(all_shapes),
                "valid_shapes": len(valid_shapes),
                "container_rectangles_valid": sum(
                    1 for shape in valid_shapes if shape["is_container_rectangle"]
                ),
            }
        )
        row.update(ove_details)
        row.update(ali_details)
        row.update(ofl_details)
    except Exception as exc:
        row.update(
            {
                "ove": math.nan,
                "ali": math.nan,
                "ofl": math.nan,
                "all_shapes": 0,
                "valid_shapes": 0,
                "container_rectangles_valid": 0,
                "ove_elements": 0,
                "container_rectangles_dropped_for_ove": 0,
                "ove_pairs": 0,
                "ove_overlapping_pairs": 0,
                "ove_skipped_containment": 0,
                "ove_max_iou": 0.0,
                "ali_elements": 0,
                "ofl_total_elements": 0,
                "ofl_overflow_elements": 0,
                "ofl_max_element_overflow_ratio": 0.0,
                "error": repr(exc),
            }
        )

    return row


def non_nan_values(rows, field):
    values = []
    for row in rows:
        value = row.get(field)
        if isinstance(value, float) and math.isnan(value):
            continue
        if value is None:
            continue
        values.append(value)
    return values


def average(rows, field):
    values = non_nan_values(rows, field)
    return mean(values) if values else None


def summarize_rows(rows):
    ok_rows = [row for row in rows if not row.get("error")]
    return {
        "n": len(ok_rows),
        "ove": average(ok_rows, "ove"),
        "ali": average(ok_rows, "ali"),
        "ofl": average(ok_rows, "ofl"),
        "mean_all_shapes": average(ok_rows, "all_shapes"),
        "mean_valid_shapes": average(ok_rows, "valid_shapes"),
        "errors": [
            {"key": row["key"], "dir_name": row["dir_name"], "error": row["error"]}
            for row in rows
            if row.get("error")
        ],
    }


def clean_json(obj):
    if isinstance(obj, float):
        if math.isnan(obj) or math.isinf(obj):
            return None
        return obj
    if isinstance(obj, dict):
        return {key: clean_json(value) for key, value in obj.items()}
    if isinstance(obj, list):
        return [clean_json(value) for value in obj]
    return obj


def build_prefix_aliases(keys, min_chars):
    """Map truncated/full title keys to a shared representative.

    Some benchmark roots use truncated paper-title directory names while others
    keep the full title. If one normalized key is a long prefix of another, this
    helper treats them as the same paper for common-intersection reporting.
    """
    if not min_chars:
        return {key: key for key in keys}

    keys = sorted(set(keys))
    parent = {key: key for key in keys}

    def find(key):
        while parent[key] != key:
            parent[key] = parent[parent[key]]
            key = parent[key]
        return key

    def union(a, b):
        root_a = find(a)
        root_b = find(b)
        if root_a != root_b:
            parent[root_b] = root_a

    for i, key_a in enumerate(keys):
        for key_b in keys[i + 1 :]:
            if min(len(key_a), len(key_b)) < min_chars:
                continue
            if key_a.startswith(key_b) or key_b.startswith(key_a):
                union(key_a, key_b)

    groups = {}
    for key in keys:
        groups.setdefault(find(key), []).append(key)

    aliases = {}
    for group_keys in groups.values():
        representative = max(group_keys, key=lambda key: (len(key), key))
        for key in group_keys:
            aliases[key] = representative
    return aliases


def fmt(value):
    if value is None:
        return "NA"
    return "{:.6f}".format(value)


def write_markdown(summary, path):
    lines = []
    lines.append("# PosterEval Structural PPTX Results")
    lines.append("")
    lines.append("Protocol: " + summary["protocol"])
    lines.append("")

    for dataset_name, dataset_summary in summary["datasets"].items():
        lines.append("## " + dataset_name)
        lines.append("")
        lines.append("### Full available PPTX")
        lines.append("| Method | Variant | N | PPTX/Dirs | Ove | Ali | Ofl | Missing PPTX | Errors |")
        lines.append("|---|---:|---:|---:|---:|---:|---:|---:|---:|")
        for method_name in summary["method_order"]:
            if method_name not in dataset_summary["full_available"]:
                continue
            stats = dataset_summary["full_available"][method_name]
            lines.append(
                "| {method} | {variant} | {n} | {pptx}/{dirs} | {ove} | {ali} | {ofl} | {missing} | {errors} |".format(
                    method=method_name,
                    variant=stats.get("variant", ""),
                    n=stats["n"],
                    pptx=stats["n_pptx"],
                    dirs=stats["n_dirs"],
                    ove=fmt(stats["ove"]),
                    ali=fmt(stats["ali"]),
                    ofl=fmt(stats["ofl"]),
                    missing=len(stats.get("missing_pptx", [])),
                    errors=len(stats.get("errors", [])),
                )
            )
        lines.append("")

        common = dataset_summary["common_intersection"]
        lines.append("### Common intersection")
        lines.append("| Method | N_common | Ove | Ali | Ofl |")
        lines.append("|---|---:|---:|---:|---:|")
        for method_name in summary["method_order"]:
            if method_name not in common["by_method"]:
                continue
            stats = common["by_method"][method_name]
            lines.append(
                "| {method} | {n} | {ove} | {ali} | {ofl} |".format(
                    method=method_name,
                    n=stats["n"],
                    ove=fmt(stats["ove"]),
                    ali=fmt(stats["ali"]),
                    ofl=fmt(stats["ofl"]),
                )
            )
        lines.append("")

    if len(summary["datasets"]) > 1:
        lines.append("## Combined Full Available")
        lines.append("")
        lines.append("| Method | N | Ove | Ali | Ofl |")
        lines.append("|---|---:|---:|---:|---:|")
        for method_name in summary["method_order"]:
            stats = summary["combined_full_available"].get(method_name)
            if not stats:
                continue
            lines.append(
                "| {method} | {n} | {ove} | {ali} | {ofl} |".format(
                    method=method_name,
                    n=stats["n"],
                    ove=fmt(stats["ove"]),
                    ali=fmt(stats["ali"]),
                    ofl=fmt(stats["ofl"]),
                )
            )
        lines.append("")

    path.write_text("\n".join(lines).rstrip() + "\n", encoding="utf-8")


def combine_method_stats(dataset_summaries, method_order, section):
    combined = {}
    for method_name in method_order:
        rows = []
        for dataset_summary in dataset_summaries.values():
            if section == "full_available":
                rows.extend(dataset_summary["rows_by_method"].get(method_name, []))
            else:
                common_keys = set(dataset_summary["common_intersection"]["keys"])
                rows.extend(
                    row
                    for row in dataset_summary["rows_by_method"].get(method_name, [])
                    if row["match_key"] in common_keys and not row.get("error")
                )
        if rows:
            combined[method_name] = summarize_rows(rows)
    return combined


def run(config, output_dir, workers, include_paths):
    method_order = config.get("method_order")
    if not method_order:
        first_dataset = config["datasets"][0]
        method_order = list(first_dataset["methods"].keys())

    valid_visible_threshold = config.get(
        "valid_visible_threshold", DEFAULT_VALID_VISIBLE_THRESHOLD
    )
    containment_threshold = config.get(
        "containment_threshold", DEFAULT_CONTAINMENT_THRESHOLD
    )

    all_rows = []
    summary = {
        "run_name": config.get("run_name", "postereval_structural_pptx"),
        "protocol": (
            "direct PPTX geometry; valid visible area > {visible}; Ove drops empty "
            "Rectangle/Rounded Rectangle containers and skips containment pairs >= {containment}"
        ).format(visible=valid_visible_threshold, containment=containment_threshold),
        "method_order": method_order,
        "datasets": {},
    }

    internal_dataset_summaries = {}

    for dataset in config["datasets"]:
        dataset_name = dataset["name"]
        rows_by_method = {}
        discoveries = {}

        for method_name in method_order:
            if method_name not in dataset["methods"]:
                continue
            method_spec = dataset["methods"][method_name]
            discovery = discover_method(method_spec)
            discoveries[method_name] = discovery

            futures = []
            rows = []
            with ThreadPoolExecutor(max_workers=workers) as executor:
                for key, item in sorted(discovery["mapping"].items()):
                    futures.append(
                        executor.submit(
                            evaluate_one,
                            dataset_name,
                            method_name,
                            method_spec,
                            key,
                            item,
                            valid_visible_threshold,
                            containment_threshold,
                            include_paths,
                        )
                    )
                for future in as_completed(futures):
                    rows.append(future.result())

            rows.sort(key=lambda row: (row["key"], row["dir_name"]))
            rows_by_method[method_name] = rows
            all_rows.extend(rows)

        all_dataset_keys = [
            row["key"] for rows in rows_by_method.values() for row in rows
        ]
        aliases = build_prefix_aliases(
            all_dataset_keys, dataset.get("prefix_alias_min_chars")
        )
        for rows in rows_by_method.values():
            for row in rows:
                row["match_key"] = aliases.get(row["key"], row["key"])

        success_key_sets = []
        for method_name in method_order:
            if method_name in rows_by_method:
                success_key_sets.append(
                    {
                        row["match_key"]
                        for row in rows_by_method[method_name]
                        if not row.get("error")
                    }
                )
        common_keys = sorted(set.intersection(*success_key_sets)) if success_key_sets else []

        full_available = {}
        common_by_method = {}
        for method_name in method_order:
            if method_name not in rows_by_method:
                continue
            method_spec = dataset["methods"][method_name]
            discovery = discoveries[method_name]

            full_stats = summarize_rows(rows_by_method[method_name])
            full_stats.update(
                {
                    "variant": method_spec.get("variant", ""),
                    "root_exists": discovery["root_exists"],
                    "n_dirs": len(discovery["all_dirs"]),
                    "n_pptx": len(discovery["mapping"]),
                    "missing_pptx": discovery["missing_pptx"],
                    "duplicates": discovery["duplicates"],
                    "ignored_dirs": discovery["ignored_dirs"],
                }
            )
            if include_paths:
                full_stats["root"] = str(Path(method_spec["root"]).expanduser())

            full_available[method_name] = full_stats
            common_rows = [
                row
                for row in rows_by_method[method_name]
                if row["match_key"] in common_keys and not row.get("error")
            ]
            common_by_method[method_name] = summarize_rows(common_rows)

        dataset_summary = {
            "full_available": full_available,
            "common_intersection": {
                "n_common": len(common_keys),
                "keys": common_keys,
                "by_method": common_by_method,
            },
        }
        summary["datasets"][dataset_name] = dataset_summary
        internal_dataset_summaries[dataset_name] = {
            "rows_by_method": rows_by_method,
            "common_intersection": dataset_summary["common_intersection"],
        }

    summary["combined_full_available"] = combine_method_stats(
        internal_dataset_summaries, method_order, "full_available"
    )
    summary["combined_common_intersection"] = combine_method_stats(
        internal_dataset_summaries, method_order, "common_intersection"
    )

    output_dir.mkdir(parents=True, exist_ok=True)

    json_path = output_dir / "summary.json"
    json_path.write_text(
        json.dumps(clean_json(summary), ensure_ascii=False, indent=2) + "\n",
        encoding="utf-8",
    )
    write_markdown(clean_json(summary), output_dir / "summary.md")

    fieldnames = sorted({key for row in all_rows for key in row.keys()})
    with (output_dir / "per_paper.csv").open("w", encoding="utf-8", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=fieldnames)
        writer.writeheader()
        for row in sorted(all_rows, key=lambda r: (r["dataset"], r["method"], r["key"])):
            writer.writerow(row)

    (output_dir / "per_paper.json").write_text(
        json.dumps(
            clean_json(sorted(all_rows, key=lambda r: (r["dataset"], r["method"], r["key"]))),
            ensure_ascii=False,
            indent=2,
        )
        + "\n",
        encoding="utf-8",
    )


def build_direct_config(args):
    if not args.pptx_root:
        raise SystemExit("Either --config or --pptx-root is required.")

    method_name = args.method_name or "method"
    return {
        "run_name": args.run_name or "structural_pptx_evaluation",
        "method_order": [method_name],
        "valid_visible_threshold": args.valid_visible_threshold,
        "containment_threshold": args.containment_threshold,
        "datasets": [
            {
                "name": args.dataset_name or "dataset",
                "methods": {
                    method_name: {
                        "root": args.pptx_root,
                        "variant": args.variant or "pptx",
                        "pptx_filename": args.pptx_filename,
                        "key_regex": args.key_regex,
                    }
                },
            }
        ],
    }


def parse_args():
    parser = argparse.ArgumentParser(
        description="Compute deterministic structural metrics from generated poster PPTX files."
    )
    parser.add_argument("--config", help="Optional JSON config for multi-method runs.")
    parser.add_argument("--pptx-root", help="PPTX root for a direct single-method run.")
    parser.add_argument("--output-dir", required=True, help="Directory for result files.")
    parser.add_argument("--method-name", default="method", help="Method name for direct mode.")
    parser.add_argument("--dataset-name", default="dataset", help="Dataset name for direct mode.")
    parser.add_argument("--run-name", default="structural_pptx_evaluation")
    parser.add_argument("--pptx-filename", help="PPTX filename inside each poster directory.")
    parser.add_argument("--key-regex", help="Regex with optional named group 'key'.")
    parser.add_argument("--variant", default="pptx")
    parser.add_argument(
        "--valid-visible-threshold",
        type=float,
        default=DEFAULT_VALID_VISIBLE_THRESHOLD,
        help="Minimum visible area ratio used to keep a shape.",
    )
    parser.add_argument(
        "--containment-threshold",
        type=float,
        default=DEFAULT_CONTAINMENT_THRESHOLD,
        help="Containment threshold for skipping nested Ove pairs.",
    )
    parser.add_argument("--workers", type=int, default=DEFAULT_WORKERS)
    parser.add_argument(
        "--include-paths",
        action="store_true",
        help="Include absolute input paths in outputs. Keep this off for anonymous release artifacts.",
    )
    return parser.parse_args()


def main():
    args = parse_args()
    if args.config:
        config = json.loads(Path(args.config).read_text(encoding="utf-8"))
    else:
        config = build_direct_config(args)
    run(config, Path(args.output_dir), args.workers, args.include_paths)


if __name__ == "__main__":
    main()