File size: 7,859 Bytes
203a7fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Print sync accuracy split into:
  - original (gt_synced=True)        : did the model correctly say 'synced'?
  - shifted  (gt_direction=delay/early): did the model correctly call it desync?
                                         (and, separately, get the direction right?)

Usage:
  python3 /home/ubuntu/sync_split_acc.py <eval_results.jsonl OR its parent dir> [more...]

Examples:
  python3 /home/ubuntu/sync_split_acc.py ~/eval_results/sync/sync_qwen3omni_vanilla
  python3 /home/ubuntu/sync_split_acc.py ~/eval_results/sync/sync_qwen3omni_vanilla/eval_results.jsonl
  python3 /home/ubuntu/sync_split_acc.py ~/eval_results/sync/sync_*    # multiple at once
"""
import json
import sys
from pathlib import Path


def resolve(arg: str) -> Path:
    """Return either an eval_results.jsonl (preferred) or a metrics.json
    (fallback when per-sample data isn't available)."""
    p = Path(arg).expanduser()
    if p.is_dir():
        jsonl = p / "eval_results.jsonl"
        metrics = p / "metrics.json"
        return jsonl if jsonl.exists() else metrics
    return p


def report_from_metrics(metrics_path: Path) -> None:
    """Fallback: derive original-vs-shifted breakdown from a pre-computed
    metrics.json that has total_samples, sync_desync_accuracy,
    three_class_accuracy, per_category{synced/delay/early _accuracy/_count}."""
    m = json.load(open(metrics_path))
    total = m.get("total_samples")
    pc = m.get("per_category", {})
    if not total or not pc:
        print(f"[skip] {metrics_path} missing fields needed for split")
        return

    n_orig  = pc.get("synced_count", 0)
    n_delay = pc.get("delay_count", 0)
    n_early = pc.get("early_count", 0)
    n_shift = n_delay + n_early

    syn_acc   = pc.get("synced_accuracy") or 0
    delay_acc = pc.get("delay_accuracy") or 0    # strict: detected AND direction right
    early_acc = pc.get("early_accuracy") or 0    # strict: detected AND direction right

    sync_desync_acc  = m.get("sync_desync_accuracy") or 0
    three_class_acc  = m.get("three_class_accuracy") or 0

    orig_correct = n_orig * syn_acc                 # said 'synced' on originals
    delay_dir_correct = n_delay * delay_acc         # detected + dir right
    early_dir_correct = n_early * early_acc
    shifted_dir_correct = delay_dir_correct + early_dir_correct

    # detected desync (looser, ignores direction): from sync_desync_accuracy.
    # sync_desync_acc = (orig_correct + shifted_detected) / total
    shifted_detected = sync_desync_acc * total - orig_correct

    print("=" * 64)
    print(f"  {metrics_path.parent.name}   [from metrics.json — no per-sample jsonl]")
    print("=" * 64)
    print(f"  total samples                 : {int(total)}")
    print(f"  --- original (gt = synced) ---")
    if n_orig:
        print(f"    n                           : {n_orig}")
        print(f"    correctly said 'synced'     : {int(round(orig_correct))} / {n_orig} = {syn_acc:.4%}")
    print(f"  --- shifted  (gt = delay/early) ---")
    print(f"    n                           : {n_shift}  (delay={n_delay}, early={n_early})")
    if n_shift:
        print(f"    detected desync             : {int(round(shifted_detected))} / {n_shift} = "
              f"{shifted_detected / n_shift:.4%}")
        print(f"    + got direction right       : {int(round(shifted_dir_correct))} / {n_shift} = "
              f"{shifted_dir_correct / n_shift:.4%}")
        if n_delay:
            print(f"      delay direction right     : {int(round(delay_dir_correct))} / {n_delay} = "
                  f"{delay_acc:.4%}")
        if n_early:
            print(f"      early direction right     : {int(round(early_dir_correct))} / {n_early} = "
                  f"{early_acc:.4%}")
    if m.get("offset_mae_sec") is not None:
        print(f"  --- offset estimate ---")
        print(f"    MAE                         : {m['offset_mae_sec']:.4f}s "
              f"(n={m.get('offset_evaluated_count', '?')})")
        if m.get("offset_median_sec") is not None:
            print(f"    median                      : {m['offset_median_sec']:.4f}s")
    print("=" * 64)
    print()


def report(jsonl: Path) -> None:
    if not jsonl.exists():
        print(f"[skip] {jsonl} does not exist")
        return
    if jsonl.name == "metrics.json":
        report_from_metrics(jsonl)
        return
    rows = [json.loads(l) for l in open(jsonl) if l.strip()]
    n = len(rows)
    if n == 0:
        print(f"[skip] {jsonl} is empty")
        return

    orig    = [r for r in rows if r["gt_synced"]]
    delay   = [r for r in rows if r.get("gt_direction") == "delay"]
    early   = [r for r in rows if r.get("gt_direction") == "early"]
    shifted = delay + early

    # On originals: correct iff pred_synced is True.
    orig_correct = sum(1 for r in orig if r["pred_synced"])
    # On shifted: correct iff pred_synced is False (i.e. detected desync).
    shifted_detected = sum(1 for r in shifted if not r["pred_synced"])
    # Stricter: also got the direction right.
    shifted_dir_correct = sum(
        1 for r in shifted
        if not r["pred_synced"] and r.get("pred_direction") == r["gt_direction"]
    )

    print("=" * 64)
    print(f"  {jsonl.parent.name}")
    print("=" * 64)
    print(f"  total samples                 : {n}")
    print(f"  --- original (gt = synced) ---")
    print(f"    n                           : {len(orig)}")
    if orig:
        print(f"    correctly said 'synced'     : {orig_correct} / {len(orig)} = "
              f"{(orig_correct / len(orig)):.4%}")
    print(f"  --- shifted  (gt = delay/early) ---")
    print(f"    n                           : {len(shifted)}  (delay={len(delay)}, early={len(early)})")
    if shifted:
        print(f"    detected desync             : {shifted_detected} / {len(shifted)} = "
              f"{(shifted_detected / len(shifted)):.4%}")
        print(f"    + got direction right       : {shifted_dir_correct} / {len(shifted)} = "
              f"{(shifted_dir_correct / len(shifted)):.4%}")
        if delay:
            d_det = sum(1 for r in delay if not r["pred_synced"])
            d_dir = sum(1 for r in delay if not r["pred_synced"] and r["pred_direction"] == "delay")
            print(f"      delay only detected       : {d_det} / {len(delay)} = {d_det / len(delay):.4%}"
                  f"   (direction right: {d_dir} = {d_dir / len(delay):.4%})")
        if early:
            e_det = sum(1 for r in early if not r["pred_synced"])
            e_dir = sum(1 for r in early if not r["pred_synced"] and r["pred_direction"] == "early")
            print(f"      early only detected       : {e_det} / {len(early)} = {e_det / len(early):.4%}"
                  f"   (direction right: {e_dir} = {e_dir / len(early):.4%})")

    # offset MAE on shifted videos that were predicted as desync with a non-zero offset
    errs = [abs(r["pred_offset_sec"] - r["gt_offset_sec"])
            for r in shifted
            if not r["pred_synced"] and r.get("pred_offset_sec", 0) > 0]
    if errs:
        errs.sort()
        med = errs[len(errs) // 2]
        print(f"  --- offset estimate on detected shifted ---")
        print(f"    MAE                         : {sum(errs) / len(errs):.4f}s  (n={len(errs)})")
        print(f"    median                      : {med:.4f}s")
        print(f"    within 0.5s                 : {sum(1 for e in errs if e <= 0.5)} / {len(errs)} = "
              f"{sum(1 for e in errs if e <= 0.5) / len(errs):.4%}")
        print(f"    within 1.0s                 : {sum(1 for e in errs if e <= 1.0)} / {len(errs)} = "
              f"{sum(1 for e in errs if e <= 1.0) / len(errs):.4%}")
    print("=" * 64)
    print()


def main():
    args = sys.argv[1:]
    if not args:
        print(__doc__)
        sys.exit(1)
    for a in args:
        report(resolve(a))


if __name__ == "__main__":
    main()