#!/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()