File size: 30,057 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
#!/usr/bin/env python3
"""Evaluate PosterEval semantic/content metrics from IR files.

Metric inputs:
- content IR: Order, Completeness, Claim F1.
- figure IR + poster PNG/JPEG: LTA.
"""

import argparse
import csv
import importlib
import json
import math
import re
import statistics
import sys
from pathlib import Path
from statistics import mean
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple

from PIL import Image

from openrouter_client import call_openrouter_json


PROMPT_DIR = Path(__file__).resolve().parent / "prompts"
CLAIM_PROMPT = PROMPT_DIR / "claim_pair_scoring_prompt.md"
DEFAULT_CLAIM_MODE = "strict_v2_t05_subset_numeric_one_side85"
CLAIM_VARIANT = (
    "strict_v2_pair_scoring_plus_threshold_0_5_plus_greedy_one_to_one_plus_"
    "subset_numeric_plus_one_side_high_score_waiver_0_85"
)
DEFAULT_LTA_MODEL_PATH = "models/modelscope/Qwen__Qwen3-VL-Embedding-2B"
DEFAULT_IMAGE_NAMES = (
    "poster.png",
    "paper.png",
    "poster.jpg",
    "paper.jpg",
    "poster.jpeg",
    "paper.jpeg",
)


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


def extract_key(name: str, pattern: Optional[str]) -> str:
    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 load_json(path: Path) -> Dict[str, Any]:
    return json.loads(path.read_text(encoding="utf-8"))


def discover_ir(root: Path, key_regex: Optional[str] = None) -> Dict[str, Dict[str, Any]]:
    mapping: Dict[str, Dict[str, Any]] = {}
    if not root.exists():
        return mapping

    candidates = []
    if (root / "poster_ir.json").exists():
        candidates.append(root / "poster_ir.json")
    candidates.extend(sorted(root.glob("*/poster_ir.json"), key=lambda p: str(p)))
    candidates.extend(sorted(root.glob("*.json"), key=lambda p: str(p)))

    for ir_path in candidates:
        if ir_path.name != "poster_ir.json" and ir_path.parent != root:
            continue
        source_name = ir_path.parent.name if ir_path.name == "poster_ir.json" else ir_path.stem
        key = extract_key(source_name, key_regex)
        if key in mapping:
            continue
        try:
            ir_relpath = str(ir_path.relative_to(root))
        except ValueError:
            ir_relpath = ir_path.name
        mapping[key] = {
            "source_name": source_name,
            "ir_path": ir_path,
            "ir_relpath": ir_relpath,
        }
    return mapping


def discover_images(
    root: Optional[Path],
    key_regex: Optional[str] = None,
    image_filename: Optional[str] = None,
) -> Dict[str, Path]:
    mapping: Dict[str, Path] = {}
    if root is None or not root.exists():
        return mapping

    for child in sorted(root.iterdir(), key=lambda p: p.name):
        if child.is_dir():
            names = (image_filename,) if image_filename else DEFAULT_IMAGE_NAMES
            image_path = None
            for name in names:
                if not name:
                    continue
                candidate = child / name
                if candidate.exists():
                    image_path = candidate
                    break
            if image_path is None:
                images = []
                for pattern in ("*.png", "*.jpg", "*.jpeg"):
                    images.extend(child.glob(pattern))
                image_path = sorted(images, key=lambda p: p.name)[0] if images else None
            if image_path is not None:
                mapping[extract_key(child.name, key_regex)] = image_path
        elif child.suffix.lower() in {".png", ".jpg", ".jpeg"}:
            mapping[extract_key(child.stem, key_regex)] = child
    return mapping


def build_prefix_aliases(keys: Iterable[str], min_chars: Optional[int]) -> Dict[str, str]:
    keys = sorted(set(keys))
    if not min_chars:
        return {key: key for key in keys}

    parent = {key: key for key in keys}

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

    def union(left: str, right: str) -> None:
        root_left = find(left)
        root_right = find(right)
        if root_left != root_right:
            parent[root_right] = root_left

    for index, key_a in enumerate(keys):
        for key_b in keys[index + 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: Dict[str, List[str]] = {}
    for key in keys:
        groups.setdefault(find(key), []).append(key)

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


def apply_aliases(mapping: Dict[str, Any], aliases: Dict[str, str]) -> Dict[str, Any]:
    aliased: Dict[str, Any] = {}
    for key, value in mapping.items():
        alias = aliases.get(key, key)
        aliased.setdefault(alias, value)
    return aliased


def parse_bbox_xyxy(value: Any) -> Optional[Tuple[float, float, float, float]]:
    if isinstance(value, (list, tuple)) and len(value) >= 4:
        try:
            return float(value[0]), float(value[1]), float(value[2]), float(value[3])
        except (TypeError, ValueError):
            return None
    if isinstance(value, str):
        numbers = re.findall(r"-?\d+(?:\.\d+)?", value)
        if len(numbers) >= 4:
            try:
                return tuple(float(numbers[i]) for i in range(4))  # type: ignore[return-value]
            except ValueError:
                return None
    return None


def sort_sections_column_first(sections: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
    parsed = []
    fallback = []
    for index, section in enumerate(sections):
        bbox = parse_bbox_xyxy(section.get("bbox"))
        if bbox is None:
            fallback.append((index, section))
            continue
        x1, y1, _, _ = bbox
        parsed.append((index, x1, y1, section))

    if not parsed:
        return sections

    x_values = sorted(item[1] for item in parsed)
    column_threshold = 100.0
    if len(x_values) >= 2:
        gaps = [x_values[i + 1] - x_values[i] for i in range(len(x_values) - 1)]
        positive_gaps = [gap for gap in gaps if gap > 1e-6]
        if positive_gaps:
            median_gap = statistics.median(positive_gaps)
            column_threshold = max(40.0, min(150.0, median_gap * 0.6))

    parsed.sort(key=lambda item: item[1])
    columns: List[List[Tuple[int, float, float, Dict[str, Any]]]] = []
    current: List[Tuple[int, float, float, Dict[str, Any]]] = []
    current_x: Optional[float] = None
    for item in parsed:
        _, x1, _, _ = item
        if current_x is None or abs(x1 - current_x) <= column_threshold:
            current.append(item)
            current_x = x1 if current_x is None else statistics.fmean([e[1] for e in current])
        else:
            columns.append(current)
            current = [item]
            current_x = x1
    if current:
        columns.append(current)

    ordered: List[Dict[str, Any]] = []
    for column in columns:
        column.sort(key=lambda item: (item[2], item[1], item[0]))
        ordered.extend(item[3] for item in column)
    ordered.extend(section for _, section in sorted(fallback, key=lambda item: item[0]))
    return ordered


def compute_order_and_completeness(ir_data: Dict[str, Any]) -> Dict[str, Any]:
    sections = list(ir_data.get("sections", []))
    if not sections:
        return {
            "order": None,
            "completeness": None,
            "gnc_compat": None,
            "inversions": 0,
            "total_pairs": 0,
            "missing_roles": ["Approach", "Evidence", "Problem"],
        }

    def role(section: Dict[str, Any]) -> Optional[str]:
        return section.get("meta_role") or section.get("role")

    if all("reading_order" in section for section in sections):
        sections = sorted(sections, key=lambda item: item["reading_order"])
    else:
        sections = sort_sections_column_first(sections)

    role_order = {"Meta": 0, "Problem": 1, "Approach": 2, "Evidence": 3}
    narrative_sections = [section for section in sections if role(section) != "Meta"]

    inversions = 0
    total_pairs = 0
    for left_index, left in enumerate(narrative_sections):
        for right in narrative_sections[left_index + 1 :]:
            total_pairs += 1
            if role_order.get(role(left) or "Other", 2) > role_order.get(role(right) or "Other", 2):
                inversions += 1

    order_score = 1.0 - inversions / total_pairs if total_pairs > 0 else 1.0
    required_roles = {"Problem", "Approach", "Evidence"}
    present_roles = {role(section) for section in narrative_sections if role(section) in required_roles}
    missing_roles = sorted(required_roles - present_roles)
    completeness = 1.0 - len(missing_roles) / len(required_roles)
    return {
        "order": round(order_score, 4),
        "completeness": round(completeness, 4),
        "gnc_compat": round(0.6 * order_score + 0.4 * completeness, 4),
        "inversions": inversions,
        "total_pairs": total_pairs,
        "missing_roles": missing_roles,
    }


def extract_numeric_values(text: str) -> List[float]:
    values = []
    for raw in re.findall(r"(?<![A-Za-z0-9])\d[\d,]*(?:\.\d+)?%?(?![A-Za-z])", text or ""):
        token = raw.replace(",", "")
        if token.endswith("%"):
            token = token[:-1]
        try:
            values.append(float(token))
        except ValueError:
            continue
    return values


def numbers_match_within_tolerance_subset(
    left: str,
    right: str,
    rel_tol: float = 0.01,
) -> bool:
    left_values = extract_numeric_values(left)
    right_values = extract_numeric_values(right)

    if not left_values and not right_values:
        return True
    if not left_values or not right_values:
        return False

    smaller, larger = (
        (sorted(left_values), sorted(right_values))
        if len(left_values) <= len(right_values)
        else (sorted(right_values), sorted(left_values))
    )
    used_indices: set[int] = set()
    for target in smaller:
        best_index = None
        best_gap = None
        for index, candidate in enumerate(larger):
            if index in used_indices:
                continue
            scale = max(abs(target), abs(candidate), 1.0)
            gap = abs(target - candidate)
            if gap <= rel_tol * scale and (best_gap is None or gap < best_gap):
                best_index = index
                best_gap = gap
        if best_index is None:
            return False
        used_indices.add(best_index)
    return True


def harmonic_mean(precision: float, recall: float) -> float:
    if precision + recall == 0:
        return 0.0
    return 2.0 * precision * recall / (precision + recall)


def score_claim_pairs(
    gen_claims: Sequence[str],
    gt_claims: Sequence[str],
    model: str,
    match_mode: str,
) -> Tuple[int, List[Dict[str, Any]], str]:
    if match_mode not in {DEFAULT_CLAIM_MODE, "default"}:
        raise ValueError(
            "Only the strict_v2_t05_subset_numeric_one_side85 Claim F1 policy is included."
        )

    if not gen_claims or not gt_claims:
        return 0, [], CLAIM_VARIANT

    candidate_pairs = [
        {"gen_id": gi, "gt_id": ti, "gen_claim": gc, "gt_claim": tc}
        for gi, gc in enumerate(gen_claims)
        for ti, tc in enumerate(gt_claims)
    ]
    prompt = CLAIM_PROMPT.read_text(encoding="utf-8")
    prompt = prompt.replace(
        "{generated_claims_json}",
        json.dumps(list(gen_claims), indent=2, ensure_ascii=False),
    )
    prompt = prompt.replace(
        "{ground_truth_claims_json}",
        json.dumps(list(gt_claims), indent=2, ensure_ascii=False),
    )
    prompt = prompt.replace(
        "{candidate_pairs_json}",
        json.dumps(candidate_pairs, indent=2, ensure_ascii=False),
    )
    result = call_openrouter_json(
        prompt=prompt,
        model=model,
        image_path=None,
        max_tokens=2000,
        temperature=0.1,
        response_format_json=True,
    )
    if result.get("parse_error"):
        return 0, [], "claim_pair_scoring_parse_error"

    filtered: List[Tuple[float, int, int, str]] = []
    for proposal in result.get("pair_scores", []):
        if not isinstance(proposal, dict):
            continue
        try:
            gen_id = int(proposal["gen_id"])
            gt_id = int(proposal["gt_id"])
            score = float(proposal["score"])
        except (KeyError, TypeError, ValueError):
            continue
        if not (0 <= gen_id < len(gen_claims) and 0 <= gt_id < len(gt_claims)):
            continue
        if score < 0.5:
            continue

        gen_claim = gen_claims[gen_id]
        gt_claim = gt_claims[gt_id]
        if numbers_match_within_tolerance_subset(gen_claim, gt_claim):
            filtered.append((score, gen_id, gt_id, "subset_numeric"))
            continue
        gen_has_numbers = bool(extract_numeric_values(gen_claim))
        gt_has_numbers = bool(extract_numeric_values(gt_claim))
        if gen_has_numbers != gt_has_numbers and score >= 0.85:
            filtered.append((score, gen_id, gt_id, "one_side_high_score_waiver"))

    filtered.sort(key=lambda item: (-item[0], item[1], item[2]))
    matched_gen: set[int] = set()
    matched_gt: set[int] = set()
    selected: Dict[int, Tuple[int, float, str]] = {}
    for score, gen_id, gt_id, numeric_rule in filtered:
        if gen_id in matched_gen or gt_id in matched_gt:
            continue
        matched_gen.add(gen_id)
        matched_gt.add(gt_id)
        selected[gen_id] = (gt_id, score, numeric_rule)

    matches = []
    for gen_id, gen_claim in enumerate(gen_claims):
        if gen_id in selected:
            gt_id, score, numeric_rule = selected[gen_id]
            matches.append(
                {
                    "gen_claim": gen_claim,
                    "gt_claim": gt_claims[gt_id],
                    "matched": True,
                    "score": round(score, 4),
                    "numeric_rule": numeric_rule,
                }
            )
        else:
            matches.append(
                {
                    "gen_claim": gen_claim,
                    "gt_claim": None,
                    "matched": False,
                    "score": 0.0,
                    "numeric_rule": None,
                }
            )
    return len(selected), matches, CLAIM_VARIANT


def compute_claim_f1(
    gen_ir: Dict[str, Any],
    gt_ir: Dict[str, Any],
    model: str,
    match_mode: str,
) -> Dict[str, Any]:
    gen_claims = list(gen_ir.get("atomic_claims", []))
    gt_claims = list(gt_ir.get("atomic_claims", []))

    if not gen_claims and not gt_claims:
        precision = recall = 1.0
        matched = 0
        matches: List[Dict[str, Any]] = []
        variant = CLAIM_VARIANT
        empty_case = "empty_claim_lists"
    elif not gen_claims:
        precision = 1.0
        recall = 0.0
        matched = 0
        matches = []
        variant = CLAIM_VARIANT
        empty_case = "empty_generated_claims"
    elif not gt_claims:
        precision = recall = 1.0
        matched = 0
        matches = []
        variant = CLAIM_VARIANT
        empty_case = "empty_ground_truth_claims"
    else:
        matched, matches, variant = score_claim_pairs(gen_claims, gt_claims, model, match_mode)
        precision = matched / len(gen_claims)
        recall = matched / len(gt_claims)
        empty_case = ""

    return {
        "claim_precision": round(precision, 4),
        "claim_recall": round(recall, 4),
        "claim_f1": round(harmonic_mean(precision, recall), 4),
        "matched_count": matched,
        "gen_claims_count": len(gen_claims),
        "gt_claims_count": len(gt_claims),
        "matching_variant": variant,
        "claim_empty_case": empty_case,
        "claim_matches": matches,
    }


def crop_figure_from_poster(poster_img: Image.Image, bbox: Any) -> Optional[Image.Image]:
    coords = parse_bbox_xyxy(bbox)
    if coords is None:
        return None
    x1, y1, x2, y2 = coords
    width, height = poster_img.size
    max_coord = max(abs(x1), abs(y1), abs(x2), abs(y2))
    if 0 < max_coord <= 1.0:
        x1, y1, x2, y2 = x1 * width, y1 * height, x2 * width, y2 * height
    elif max_coord <= 1000.0:
        x1, y1, x2, y2 = x1 * width / 1000.0, y1 * height / 1000.0, x2 * width / 1000.0, y2 * height / 1000.0
    if x2 <= x1 or y2 <= y1:
        return None
    x1 = max(0, min(int(round(x1)), width - 1))
    y1 = max(0, min(int(round(y1)), height - 1))
    x2 = max(0, min(int(round(x2)), width))
    y2 = max(0, min(int(round(y2)), height))
    if x2 <= x1 or y2 <= y1:
        return None
    return poster_img.crop((x1, y1, x2, y2))


class LTAEvaluator:
    def __init__(self, model_path: str, module_dir: Optional[str] = None):
        search_dir = Path(module_dir).expanduser() if module_dir else Path(__file__).resolve().parent
        sys.path.insert(0, str(search_dir))
        module = importlib.import_module("qwen3_vl_embedding")
        self.embedder = module.Qwen3VLEmbedder(model_name_or_path=model_path)

    def compute_batch_similarity(self, texts: List[str], images: List[Image.Image]) -> List[float]:
        rgb_images = [image.convert("RGB") if image.mode != "RGB" else image for image in images]
        text_embeddings = self.embedder.process([{"text": text} for text in texts])
        image_embeddings = self.embedder.process([{"image": image} for image in rgb_images])
        return [float(text_embeddings[i] @ image_embeddings[i]) for i in range(len(texts))]


def compute_lta(
    ir_data: Dict[str, Any],
    poster_image_path: Path,
    evaluator: LTAEvaluator,
) -> Dict[str, Any]:
    poster_img = Image.open(poster_image_path)
    if poster_img.mode != "RGB":
        poster_img = poster_img.convert("RGB")

    tasks = []
    details = {
        "total_figures": 0,
        "high_similarity": 0,
        "medium_similarity": 0,
        "low_similarity": 0,
        "skipped": 0,
        "figure_scores": [],
    }
    for section in ir_data.get("sections", []):
        section_text = section.get("text_content", "") or ""
        if not section_text:
            continue
        for figure in section.get("contains_figures", []) or section.get("figures", []):
            cropped = crop_figure_from_poster(poster_img, figure.get("bbox"))
            if cropped is None:
                details["skipped"] += 1
                continue
            tasks.append(
                {
                    "figure_id": figure.get("id", "Figure"),
                    "section_title": section.get("title", "Untitled Section"),
                    "section_text": section_text,
                    "image": cropped,
                }
            )

    if not tasks:
        return {"lta": 1.0, "lta_details": details}

    similarities = evaluator.compute_batch_similarity(
        [task["section_text"][:800] for task in tasks],
        [task["image"] for task in tasks],
    )
    for task, similarity in zip(tasks, similarities):
        details["total_figures"] += 1
        if similarity >= 0.5:
            details["high_similarity"] += 1
        elif similarity >= 0.3:
            details["medium_similarity"] += 1
        else:
            details["low_similarity"] += 1
        details["figure_scores"].append(
            {
                "figure_id": task["figure_id"],
                "section_title": task["section_title"],
                "similarity": round(float(similarity), 4),
            }
        )
    return {"lta": round(float(mean(similarities)), 4), "lta_details": details}


def mean_or_none(values: List[Optional[float]]) -> Optional[float]:
    valid = [value for value in values if value is not None and not math.isnan(value)]
    return mean(valid) if valid else None


def fmt(value: Optional[float]) -> str:
    return "NA" if value is None else f"{value:.4f}"


def evaluate_method(
    method_name: str,
    method_spec: Dict[str, Any],
    gt_content: Dict[str, Dict[str, Any]],
    keys: List[str],
    metrics: set[str],
    claim_model: str,
    claim_mode: str,
    lta_evaluator: Optional[LTAEvaluator],
    include_paths: bool,
    aliases: Dict[str, str],
) -> List[Dict[str, Any]]:
    content_root = Path(method_spec["content_ir_root"]).expanduser()
    figure_root = Path(method_spec.get("figure_ir_root", "")).expanduser() if method_spec.get("figure_ir_root") else None
    image_root = Path(method_spec.get("poster_image_root", "")).expanduser() if method_spec.get("poster_image_root") else None

    gen_content = apply_aliases(discover_ir(content_root, method_spec.get("key_regex")), aliases)
    gen_figure = apply_aliases(discover_ir(figure_root, method_spec.get("key_regex")), aliases) if figure_root else {}
    images = apply_aliases(
        discover_images(image_root, method_spec.get("key_regex"), method_spec.get("image_filename")),
        aliases,
    )

    rows = []
    for key in keys:
        row: Dict[str, Any] = {"method": method_name, "key": key, "error": ""}
        try:
            content_item = gen_content.get(key)
            gt_item = gt_content.get(key)
            gen_ir = load_json(content_item["ir_path"]) if content_item else None
            gt_ir = load_json(gt_item["ir_path"]) if gt_item else None

            if {"order", "completeness"} & metrics:
                if gen_ir is None:
                    row["order"] = None
                    row["completeness"] = None
                    row["order_error"] = "missing content IR"
                else:
                    order_payload = compute_order_and_completeness(gen_ir)
                    row.update(order_payload)

            if "claim_f1" in metrics:
                if gen_ir is None or gt_ir is None:
                    row["claim_f1"] = None
                    row["claim_error"] = "missing generated or ground-truth content IR"
                else:
                    row.update(compute_claim_f1(gen_ir, gt_ir, claim_model, claim_mode))

            if "lta" in metrics:
                figure_item = gen_figure.get(key)
                image_path = images.get(key)
                if lta_evaluator is None:
                    row["lta"] = None
                    row["lta_error"] = "LTA evaluator was not initialized"
                elif figure_item is None or image_path is None:
                    row["lta"] = None
                    row["lta_error"] = "missing figure IR or poster image"
                else:
                    row.update(compute_lta(load_json(figure_item["ir_path"]), image_path, lta_evaluator))

            if include_paths:
                if content_item:
                    row["content_ir_path"] = str(content_item["ir_path"])
                if gt_item:
                    row["gt_content_ir_path"] = str(gt_item["ir_path"])
                if gen_figure.get(key):
                    row["figure_ir_path"] = str(gen_figure[key]["ir_path"])
                if images.get(key):
                    row["poster_image_path"] = str(images[key])
        except Exception as exc:
            row["error"] = repr(exc)
        rows.append(row)
    return rows


def summarize(rows: List[Dict[str, Any]], metrics: set[str]) -> Dict[str, Any]:
    summary: Dict[str, Any] = {
        "n_rows": len(rows),
        "errors": [row for row in rows if row.get("error")],
    }
    for metric in ("order", "completeness", "lta", "claim_f1"):
        if metric not in metrics:
            continue
        values = [row.get(metric) for row in rows]
        valid = [value for value in values if isinstance(value, (int, float)) and not math.isnan(float(value))]
        summary[metric] = round(float(mean(valid)), 4) if valid else None
        summary[metric + "_n"] = len(valid)
    return summary


def write_markdown(summary: Dict[str, Any], path: Path) -> None:
    metrics = summary["metrics"]
    lines = ["# PosterEval Semantic IR Results", ""]
    lines.append("IR policy: content IR for Order/Completeness/Claim F1; figure IR for LTA.")
    lines.append("")
    lines.append("| Method | " + " | ".join(metric for metric in metrics) + " |")
    lines.append("|---|" + "|".join("---:" for _ in metrics) + "|")
    for method in summary["method_order"]:
        stats = summary["methods"].get(method)
        if not stats:
            continue
        lines.append(
            "| "
            + method
            + " | "
            + " | ".join(fmt(stats.get(metric)) for metric in metrics)
            + " |"
        )
    lines.append("")
    lines.append("Valid sample counts:")
    for method in summary["method_order"]:
        stats = summary["methods"].get(method)
        if not stats:
            continue
        count_text = ", ".join(f"{metric}={stats.get(metric + '_n', 0)}" for metric in metrics)
        lines.append(f"- `{method}`: {count_text}")
    path.write_text("\n".join(lines).rstrip() + "\n", encoding="utf-8")


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


def run(config: Dict[str, Any], output_dir: Path, include_paths: bool) -> None:
    metrics = set(config.get("metrics", ["order", "completeness", "lta", "claim_f1"]))
    if "all" in metrics:
        metrics = {"order", "completeness", "lta", "claim_f1"}
    method_order = config.get("method_order") or list(config["methods"].keys())

    gt_spec = config["gt"]
    gt_content_raw = discover_ir(Path(gt_spec["content_ir_root"]).expanduser(), gt_spec.get("key_regex"))
    all_keys = set(gt_content_raw.keys())
    per_method_content = {}
    for method in method_order:
        method_spec = config["methods"][method]
        mapping = discover_ir(Path(method_spec["content_ir_root"]).expanduser(), method_spec.get("key_regex"))
        per_method_content[method] = mapping
        all_keys.update(mapping.keys())
    aliases = build_prefix_aliases(all_keys, config.get("prefix_alias_min_chars"))

    if config.get("common_only", True):
        key_sets = [{aliases.get(key, key) for key in gt_content_raw.keys()}]
        for method in method_order:
            key_sets.append({aliases.get(key, key) for key in per_method_content[method].keys()})
        keys = sorted(set.intersection(*key_sets)) if key_sets else []
    else:
        keys = sorted({aliases.get(key, key) for key in all_keys})

    gt_content = apply_aliases(gt_content_raw, aliases)

    lta_evaluator = None
    if "lta" in metrics:
        lta_cfg = config.get("lta", {})
        lta_evaluator = LTAEvaluator(
            model_path=lta_cfg.get("model_path", DEFAULT_LTA_MODEL_PATH),
            module_dir=lta_cfg.get("module_dir"),
        )

    all_rows = []
    method_summaries = {}
    for method in method_order:
        rows = evaluate_method(
            method_name=method,
            method_spec=config["methods"][method],
            gt_content=gt_content,
            keys=keys,
            metrics=metrics,
            claim_model=config.get("claim_model", "qwen3-vl-235b"),
            claim_mode=config.get("claim_match_mode", DEFAULT_CLAIM_MODE),
            lta_evaluator=lta_evaluator,
            include_paths=include_paths,
            aliases=aliases,
        )
        all_rows.extend(rows)
        method_summaries[method] = summarize(rows, metrics)

    output_dir.mkdir(parents=True, exist_ok=True)
    summary = {
        "run_name": config.get("run_name", "postereval_semantic_ir"),
        "metrics": [metric for metric in ("order", "completeness", "lta", "claim_f1") if metric in metrics],
        "ir_policy": {
            "order": "content_ir",
            "completeness": "content_ir",
            "claim_f1": "content_ir",
            "lta": "figure_ir + poster image",
        },
        "claim_match_mode": config.get("claim_match_mode", DEFAULT_CLAIM_MODE),
        "method_order": method_order,
        "n_keys": len(keys),
        "methods": method_summaries,
    }
    (output_dir / "summary.json").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 item: (item["method"], item["key"])):
            writer.writerow(clean_json(row))
    (output_dir / "per_paper.json").write_text(
        json.dumps(clean_json(all_rows), ensure_ascii=False, indent=2) + "\n",
        encoding="utf-8",
    )


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Evaluate semantic/content metrics from PosterEval IR.")
    parser.add_argument("--config", required=True, help="JSON config file.")
    parser.add_argument("--output-dir", required=True, help="Directory for result files.")
    parser.add_argument(
        "--include-paths",
        action="store_true",
        help="Include absolute local paths in outputs. Keep off for anonymous artifacts.",
    )
    return parser.parse_args()


def main() -> None:
    args = parse_args()
    run(json.loads(Path(args.config).read_text(encoding="utf-8")), Path(args.output_dir), args.include_paths)


if __name__ == "__main__":
    main()