File size: 42,752 Bytes
b31c80e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
#!/usr/bin/env python3
"""Shot Reader v2: read one video shot and write its fact sheet (camera, lens zoom, handheld, style, caption, tags,
subjects, paths, events, set) as JSON, with calibrated camera confidence.

    python shot_reader.py clip.mp4 --subject "P01: person (woman in a black polo)" --subject "O01: dog"
    python shot_reader.py clip.mp4 --backend vllm                      # fastest (needs vllm)
    python shot_reader.py clip.mp4 --load-in-4bit                      # small GPUs (needs bitsandbytes)
    python shot_reader.py clip.mp4 --camera-only                       # camera, style, tags and caption only, ~5x faster
    python shot_reader.py long.mp4 --start 12.0 --end 16.5             # one shot inside a longer video

One shot = one continuous take. The model sees 16 frames sampled evenly across the shot at 448x256, a one-line
frame-geometry measurement of those frames (point tracks + a pure-zoom fit, CPU), and the ids and classes of the
subjects you name; it keeps your ids. This file reproduces the hosted Shot Reader's prompt exactly: the geometry code
and the confidence calibrator below are verbatim copies of the serving code.
Needs: torch, transformers>=5.2, pillow, numpy, opencv-python-headless, huggingface_hub, ffmpeg + ffprobe on PATH
(+ vllm or bitsandbytes for those options).
"""
import argparse
import bisect
import collections
import json
import math
import os
import re
import subprocess
import sys
import tempfile
import time

import numpy as np

REPO = "voyager-so/shot-reader-v2"
N_FRAMES = 16
TOP_LOGPROBS = 5

# ================================================================ prompt (serving: vendor/shot_reader.PROMPT + V3R_NOTE)

PROMPT = """You are a previz shot reader. You see {nf} frames sampled evenly from one shot of {dur:.2f} s
(frame i is at t = {times}).

Write the shot's fact sheet: one JSON object exactly in the schema below. Measure positions in metres
in the ground frame defined below (origin under the camera in the FIRST frame, +x right, +y forward).
Use object sizes (people are about 1.7 m tall, doors 2 m, chairs 0.9 m, etc.) and perspective to
estimate distances. Give every listed subject a path with at least a key at t=0 and t={dur:.2f}
(add intermediate keys when it moves). Keep the given ids.

Subjects in the brief (id: class): {subjects}

{schema}

Reply with only the JSON object, no prose, no code fences."""

V3R_NOTE = """Fact sheet schema v3. Top-level keys in this order: schema_version (3), shot, camera, style, tags, caption, n_subjects, subjects, n_events, events, environment, n_set, set.
camera keys in this order: height_m, angle, pitch_deg, fov_deg, move, zoom, handheld, framing, subject, ambiguous.
camera.angle: low | eye | high | overhead
camera.move (the camera body only, never the lens): static | pan | tilt | push_in | pull_out | truck | crane | orbit | follow
camera.framing: wide | full | medium | close
camera.zoom.dir: in | out | none
style: live_action | cg_3d | anim_2d
events (typed only): jump | crouch | stand_up | sit | lie | fall | turn"""

CAMERA_ONLY_STOP = ',"n_subjects"'
CAMERA_ONLY_KEYS = ("schema_version", "output", "shot", "camera", "style", "tags", "caption")

# constrained retry for the rare sheet that does not parse (vLLM backend only)
_ARR = lambda n, items=None: {"type": "array", "maxItems": n, **({"items": items} if items else {})}  # noqa: E731
V5_SCHEMA = {
    "type": "object",
    "properties": {
        "schema_version": {"type": "integer"}, "shot": {"type": "object"}, "camera": {"type": "object"},
        "style": {"type": "string", "enum": ["live_action", "cg_3d", "anim_2d"]},
        "tags": _ARR(12, {"type": "string", "maxLength": 48}), "caption": {"type": "string", "maxLength": 240},
        "n_subjects": {"type": "integer"},
        "subjects": _ARR(24, {"type": "object"}),
        "n_events": {"type": "integer"}, "events": _ARR(12, {"type": "object"}),
        "environment": {"type": "object"}, "n_set": {"type": "integer"}, "set": _ARR(8, {"type": "object"}),
    },
    "required": ["schema_version", "shot", "camera", "n_subjects", "subjects"],
}


def build_prompt(dur, times, subjects, geo_line):
    subs = ", ".join(subjects) if subjects else "none given (name people P01, P02, ... and objects by class)"
    return PROMPT.format(nf=N_FRAMES, dur=dur, times=", ".join(f"{t:.2f}" for t in times), subjects=subs,
                         schema=V3R_NOTE + "\n\n" + geo_line)


# ================================================================ frames (serving: fast_sampling.sample_frames)

def duration(path):
    out = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", path],
                         capture_output=True, text=True, check=True).stdout
    return float(out.strip())


def sample_frames(path, dur, start=0.0):
    """16 frames at t = start + i * dur / 16, each one ffmpeg seek -> JPEG q2 -> RGB -> 448x256 bicubic."""
    from PIL import Image
    times = [i * dur / N_FRAMES for i in range(N_FRAMES)]
    imgs = []
    with tempfile.TemporaryDirectory() as d:
        for i, t in enumerate(times):
            f = os.path.join(d, f"{i}.jpg")
            subprocess.run(["ffmpeg", "-v", "error", "-y", "-ss", f"{start + t:.3f}", "-i", path, "-frames:v", "1",
                            "-q:v", "2", f], check=True)
            with Image.open(f) as im:
                imgs.append(im.convert("RGB").resize(SIZE, Image.BICUBIC))
    return times, imgs


# ================================================================ frame geometry (verbatim: eval/v2/geo_baseline.py)

SIZE = (448, 256)                        # reader input (qwen3vl in train/common.py)

CEN = np.array([(SIZE[0] - 1) / 2.0, (SIZE[1] - 1) / 2.0])

FB_MAX = 0.5                             # px, forward-backward error allowed per frame step

CENTRE_BOX = (0.25, 0.35)                # half-width, half-height of the central box as a fraction of W, H

FAIL = "direct refinement failed"


def _cv2():
    import cv2
    cv2.setNumThreads(1)
    return cv2


def detect(img):
    cv2 = _cv2()
    p = cv2.goodFeaturesToTrack(img, maxCorners=2000, qualityLevel=0.003, minDistance=5, blockSize=7)
    return np.zeros((0, 2), np.float32) if p is None else p.reshape(-1, 2).astype(np.float32)


def track(frames, p0):
    """chain LK through frames; returns (start points, end points) of the tracks that survive every step"""
    cv2 = _cv2()
    lk = dict(winSize=(21, 21), maxLevel=3, criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 30, 0.01))
    h, w = frames[0].shape
    idx = np.arange(len(p0))
    p = p0.reshape(-1, 1, 2).copy()
    for i in range(len(frames) - 1):
        if not len(idx):
            break
        q, st, _ = cv2.calcOpticalFlowPyrLK(frames[i], frames[i + 1], p, None, **lk)
        r, st2, _ = cv2.calcOpticalFlowPyrLK(frames[i + 1], frames[i], q, None, **lk)
        fb = np.linalg.norm((r - p).reshape(-1, 2), axis=1)
        qq = q.reshape(-1, 2)
        ok = ((st.ravel() == 1) & (st2.ravel() == 1) & (fb < FB_MAX) & (qq[:, 0] >= 1) & (qq[:, 0] <= w - 2)
              & (qq[:, 1] >= 1) & (qq[:, 1] <= h - 2))
        idx, p = idx[ok], q[ok]
    return p0.reshape(-1, 2)[idx].astype(np.float64), p.reshape(-1, 2).astype(np.float64)


def correspondences(frames):
    a0, b0 = track(frames, detect(frames[0]))
    b1, a1 = track(frames[::-1], detect(frames[-1]))
    return np.concatenate([a0, a1]), np.concatenate([b0, b1]), len(a0), len(a1)


def _rsig(res):
    return max(1.4826 * float(np.median(res)), 0.25)


def fit_scale(A, B):
    """model A: B = s A (A, B centred). LMedS over per-point radial scales, then IRLS on inliers."""
    rad2 = (A * A).sum(1)
    m = rad2 > 15.0 ** 2
    if m.sum() < 5:
        m = rad2 > 0
    cand = (A[m] * B[m]).sum(1) / rad2[m]
    cand = np.unique(np.quantile(cand, np.linspace(0.01, 0.99, 99)))
    med = [np.median(np.linalg.norm(B - s * A, axis=1)) for s in cand]
    s = float(cand[int(np.argmin(med))])
    for _ in range(10):
        res = np.linalg.norm(B - s * A, axis=1)
        inl = res < 2.5 * _rsig(res)
        if inl.sum() < 3:
            break
        s_new = float((A[inl] * B[inl]).sum() / max((A[inl] * A[inl]).sum(), 1e-9))
        if abs(s_new - s) < 1e-7:
            s = s_new
            break
        s = s_new
    return s, np.zeros(2)


def fit_scale_t(A, B, s0=None):
    """model B (or a local fit): B = s A + t, IRLS from s0 (default: LMedS-free LS start)"""
    s = s0 if s0 is not None else float(((A - A.mean(0)) * (B - B.mean(0))).sum() / max(((A - A.mean(0)) ** 2).sum(), 1e-9))
    t = np.median(B - s * A, axis=0)
    for _ in range(12):
        res = np.linalg.norm(B - s * A - t, axis=1)
        inl = res < 2.5 * _rsig(res)
        if inl.sum() < 3:
            break
        a, b = A[inl], B[inl]
        am, bm = a.mean(0), b.mean(0)
        s_new = float(((a - am) * (b - bm)).sum() / max(((a - am) ** 2).sum(), 1e-9))
        t_new = bm - s_new * am
        done = abs(s_new - s) < 1e-7 and np.abs(t_new - t).max() < 1e-5
        s, t = s_new, t_new
        if done:
            break
    return s, t


def res_stats(A, B, s, t, div=None):
    res = np.linalg.norm(B - s * A - t, axis=1) / (max(s, 1.0) if div is None else div)   # wide-end pixels
    inl = res < 2.5 * _rsig(res)
    q = lambda x, p: round(float(np.percentile(x, p)), 4) if len(x) else None  # noqa: E731
    return {"s": round(s, 5), "t": [round(float(v), 3) for v in t],
            "p50": q(res, 50), "p75": q(res, 75), "p90": q(res, 90), "p95": q(res, 95), "max": q(res, 100),
            "out05": round(float((res > 0.5).mean()), 4), "out1": round(float((res > 1.0).mean()), 4),
            "out2": round(float((res > 2.0).mean()), 4), "n_inl": int(inl.sum()),
            "inl_p50": q(res[inl], 50), "inl_p90": q(res[inl], 90)}


def local_scale(A, B, mask, n_pairs=4000, seed=0):
    """size change of a point set, translation-free and robust: median ratio of pairwise distances (last / first) over
    random pairs at least 10 px apart"""
    if mask.sum() < 8:
        return None
    a, b = A[mask], B[mask]
    rng = np.random.default_rng(seed)
    i, j = rng.integers(0, len(a), n_pairs), rng.integers(0, len(a), n_pairs)
    da, db = np.linalg.norm(a[i] - a[j], axis=1), np.linalg.norm(b[i] - b[j], axis=1)
    ok = da > 10
    if ok.sum() < 20:
        return None
    return round(float(np.exp(np.median(np.log(np.maximum(db[ok], 1e-6) / da[ok])))), 5)


def sift_matches(f0, f1):
    """first<->last SIFT matches (ratio 0.8, mutual best): immune to occlusions in the middle of the shot"""
    cv2 = _cv2()
    sift = cv2.SIFT_create(nfeatures=3000, contrastThreshold=0.01)
    k0, d0 = sift.detectAndCompute(f0, None)
    k1, d1 = sift.detectAndCompute(f1, None)
    e = np.zeros((0, 2))
    if d0 is None or d1 is None or len(k0) < 3 or len(k1) < 3:
        return e, e
    bf = cv2.BFMatcher(cv2.NORM_L2)
    m01 = bf.knnMatch(d0, d1, k=2)
    m10 = {m[0].queryIdx: m[0].trainIdx for m in bf.knnMatch(d1, d0, k=1) if m}
    good = [m[0] for m in m01 if len(m) == 2 and m[0].distance < 0.8 * m[1].distance
            and m10.get(m[0].trainIdx) == m[0].queryIdx]
    if not good:
        return e, e
    a = np.array([k0[g.queryIdx].pt for g in good], float)
    b = np.array([k1[g.trainIdx].pt for g in good], float)
    return a, b


def warp_wide(frames, s):
    """(narrow frame blurred to the warped frame's bandwidth, wide end frame warped into the narrow frame's geometry,
    magnification m >= 1, narrow end index)"""
    cv2 = _cv2()
    narrow_is_last = s >= 1.0
    m = s if narrow_is_last else 1.0 / s
    N, Wf = (frames[-1], frames[0]) if narrow_is_last else (frames[0], frames[-1])
    M = np.array([[1 / m, 0, CEN[0] * (1 - 1 / m)], [0, 1 / m, CEN[1] * (1 - 1 / m)]])
    Wd = cv2.warpAffine(Wf, M, (SIZE[0], SIZE[1]), flags=cv2.INTER_CUBIC | cv2.WARP_INVERSE_MAP,
                        borderMode=cv2.BORDER_REPLICATE)
    sig = 0.6 * math.sqrt(max(m * m - 1, 0.0))
    Nb = cv2.GaussianBlur(N, (0, 0), sig) if sig > 0.15 else N
    return Nb, Wd, m, (15 if narrow_is_last else 0)


def search_scale(frames):
    """image-based estimate of the first->last scale about the centre: maximise the normalised cross-correlation of
    the gradient images of the narrow frame and the warped wide frame over a log grid (no features needed)"""
    cv2 = _cv2()

    def score(s):
        Nb, Wd, _, _ = warp_wide(frames, s)
        g = [cv2.magnitude(cv2.Sobel(x, cv2.CV_32F, 1, 0), cv2.Sobel(x, cv2.CV_32F, 0, 1)) for x in (Nb, Wd)]
        g = [(x - x.mean()) / (x.std() + 1e-6) for x in g]
        return float((g[0] * g[1]).mean())
    grid = np.exp(np.linspace(math.log(0.33), math.log(3.0), 89))
    best = max(grid, key=score)
    fine = best * np.exp(np.linspace(-0.03, 0.03, 25))
    return float(max(fine, key=score))


def refine_direct(frames, s):
    """residual flow after the zoom: warp the wide end frame into the narrow end frame's geometry by magnification m
    (cubic), blur the narrow frame to match, detect corners in the narrow frame and LK them (zero initial flow) into the
    warped frame with a forward-backward check; returns (narrow points q, displacement d in narrow px, m, narrow end)"""
    cv2 = _cv2()
    Nb, Wd, m, ne = warp_wide(frames, s)
    q = cv2.goodFeaturesToTrack(Nb, maxCorners=3000, qualityLevel=0.001, minDistance=4, blockSize=7)
    if q is None or len(q) < 10:
        return np.zeros((0, 2)), np.zeros((0, 2)), m, ne, 0 if q is None else len(q)
    q32 = q.reshape(-1, 1, 2).astype(np.float32)
    lk = dict(winSize=(21, 21), maxLevel=3, criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 40, 0.003))
    f, st, _ = cv2.calcOpticalFlowPyrLK(Nb, Wd, q32, None, **lk)
    r, st2, _ = cv2.calcOpticalFlowPyrLK(Wd, Nb, f, None, **lk)
    fb = np.linalg.norm((r - q32).reshape(-1, 2), axis=1)
    ff = f.reshape(-1, 2).astype(np.float64)
    qq = q32.reshape(-1, 2).astype(np.float64)
    ok = ((st.ravel() == 1) & (st2.ravel() == 1) & (fb < 0.3) & (ff[:, 0] >= 0) & (ff[:, 0] <= SIZE[0] - 1)
          & (ff[:, 1] >= 0) & (ff[:, 1] <= SIZE[1] - 1))
    return qq[ok], ff[ok] - qq[ok], m, ne, len(qq)


def direct_pass(frames, s):
    """two passes of refine_direct (the second with the scale corrected by the first's model-A fit)"""
    q, d, m, ne, nd = refine_direct(frames, s)
    if len(q) >= 10:
        Q = q - CEN
        e, _ = fit_scale(Q, Q + d)                       # matched = e * q about the centre -> true magnification m / e
        s2 = (m / e) if ne == 15 else e / m
        q, d, m, ne, nd = refine_direct(frames, s2)
    return q, d, m, ne, nd


def direct_stats(q, d, m, n_det):
    """residual flow d (narrow px) after the zoom warp: model DA = scale correction about the centre, DB = DA plus a
    translation; residuals in wide-end px (/ m)"""
    Q = q - CEN
    e, _ = fit_scale(Q, Q + d)                                  # (Q + d) = e' Q
    eb, tb = fit_scale_t(Q, Q + d, e)
    out = {}
    for name, (sc, t) in (("DA", (e, np.zeros(2))), ("DB", (eb, tb))):
        st = res_stats(Q, Q + d, sc, t, div=m)
        res = np.linalg.norm(Q + d - sc * Q - t, axis=1) / m
        st.update({"out025": round(float((res > 0.25).mean()), 4), "m": round(m / sc, 5), "n": int(len(res)),
                   "n_det": int(n_det), "fail": round(1 - len(res) / max(n_det, 1), 4)})
        allr = np.concatenate([res, np.full(max(n_det - len(res), 0), np.inf)])   # unmatched corners = unexplained
        st.update({"f75": float(np.percentile(allr, 75, method="higher")),
                   "f90": float(np.percentile(allr, 90, method="higher"))})
        out[name] = st
    return out


def measure_frames(frames):
    """the label-free measurement of 16 greyscale SIZE frames (load_frames): every field measure_clip records except
    the label copies and "sec". eval/v2/geo_hint.py calls this on the reader's own frames (prompt v3rg)."""
    row = {}
    a, b, nf, nb = correspondences(frames)
    sa, sb = sift_matches(frames[0], frames[-1])
    a, b = np.concatenate([a, sa]), np.concatenate([b, sb])
    row.update({"n_corr": int(len(a)), "n_fwd": nf, "n_bwd": nb, "n_sift": int(len(sa))})
    cands = {}
    if len(a) >= 10:
        A, B = a - CEN, b - CEN
        sA, tA = fit_scale(A, B)
        sB, tB = fit_scale_t(A, B, sA)
        row["A"], row["B"] = res_stats(A, B, sA, tA), res_stats(A, B, sB, tB)
        cands["tracks"] = sA
    cands["search"] = search_scale(frames)
    best = None
    for src, s0 in cands.items():                      # keep the start whose refined fit explains the most points
        q, d, m, ne, nd = direct_pass(frames, s0)
        if len(q) < 10:
            continue
        st = direct_stats(q, d, m, nd)
        key = (st["DA"]["p50"], -len(q))
        if best is None or key < best[0]:
            best = (key, src, q, d, m, ne, st)
    row["scale_init"] = {k: round(v, 5) for k, v in cands.items()}
    if best is None:
        row["error"] = FAIL
        row["s_global"] = round(cands["search"], 5)
        return row
    _, src, q, d, m, ne, st = best
    row.update(st)
    row["init_from"], row["narrow_end"] = src, ne
    # local (centre box vs periphery) size changes from the initial correspondences (not biased toward the zoom warp)
    A0, B0 = a - CEN, b - CEN
    cbox = (np.abs(A0[:, 0]) < CENTRE_BOX[0] * SIZE[0]) & (np.abs(A0[:, 1]) < CENTRE_BOX[1] * SIZE[1])
    row["s_centre"], row["s_periph"] = local_scale(A0, B0, cbox), local_scale(A0, B0, ~cbox)
    e = st["DA"]["s"]
    row["s_global"] = round(float(m / e if ne == 15 else e / m), 5)      # first -> last scale about the centre
    row["n_centre"], row["n_periph"] = int(cbox.sum()), int((~cbox).sum())
    return row


def score_of(row, name):
    """a clip's score; a clip the zoom model cannot be aligned on at all (direct refinement failed: no point matches
    after the zoom warp) gets +inf for the direct scores (a pure zoom always aligns)"""
    m, stat = name.split("_")
    if row.get("error") == FAIL and m.startswith("D"):
        return float("inf")
    v = (row.get(m) or {}).get(stat)
    return float("inf") if isinstance(v, float) and math.isnan(v) else v

# ================================================================ geometry hint line (verbatim: eval/v2/geo_hint.py)

HINT_VERSION = 1

PARAMS = {"T": 0.6564, "none_cut": 1.10, "score": "DA_p90",
          "fitted_on": "300 calibration triples (cal_triples.txt), results/v2_step5/geo/fuse_gate.json params.T / none_cut"}


def measure_images(imgs):
    """16 PIL frames (any mode; resized to 448x256 BICUBIC unless already that size) -> compact measurement dict."""
    import numpy as np
    from PIL import Image
    cv2 = _cv2()
    frames = []
    for im in imgs:
        im = im.convert("RGB")
        if im.size != SIZE:
            im = im.resize(SIZE, Image.BICUBIC)
        frames.append(cv2.cvtColor(np.asarray(im), cv2.COLOR_RGB2GRAY))
    if len(frames) != 16:
        return {"v": HINT_VERSION, "error": f"{len(frames)} frames"}
    try:
        row = measure_frames(frames)
    except Exception as e:  # noqa: BLE001  (a degenerate clip must never break a prompt)
        return {"v": HINT_VERSION, "error": f"{type(e).__name__}: {e}"[:200]}
    return compact(row)


def compact(row):
    """the fields the hint uses, from a geo_baseline row (measure_frames / measure_clip)"""
    failed = row.get("error") == FAIL
    if row.get("error") not in (None, FAIL):
        return {"v": HINT_VERSION, "error": str(row.get("error"))[:200]}
    sc = score_of(row, PARAMS["score"])
    r = lambda x: None if x is None else round(float(x), 4)  # noqa: E731
    return {"v": HINT_VERSION, "score": None if sc is None else (float("inf") if math.isinf(sc) else r(sc)),
            "align_failed": failed, "s_global": r(row.get("s_global")), "s_centre": r(row.get("s_centre")),
            "s_periph": r(row.get("s_periph")), "n_corr": row.get("n_corr")}


def _x(s):
    return f"x{s:.2f}"


def hint_line(g, P=PARAMS):
    """compact measurement -> the one prompt line"""
    head = "Frame geometry (point tracks, frame 0 to 15): "
    if not g or g.get("error") or not g.get("s_global"):
        return head + "not measurable on these frames."
    sc, T = g.get("score"), P["T"]
    if sc is None or g.get("align_failed") or math.isinf(sc):   # the scale is then only an image-search guess
        return head + "no pure zoom aligns the first and last frames (the camera body or the scene moves)."
    sg = g["s_global"]
    parts = [f"scale {_x(sg)}"]
    if g.get("s_centre"):
        parts.append(f"centre {_x(g['s_centre'])}")
    if g.get("s_periph"):
        parts.append(f"edges {_x(g['s_periph'])}")
    if sc <= T:
        ls = math.log(sg)
        z = "no zoom" if abs(ls) < math.log(P["none_cut"]) else ("zoom in" if ls > 0 else "zoom out")
        tail = f"residual after the best pure zoom {sc:.2f} px, within the {T:.2f} px a lens-only zoom leaves (lens-only: {z})."
    else:
        shown = f"{sc:.2f}" if sc < 100 else ">100"
        tail = (f"residual after the best pure zoom {shown} px, above the {T:.2f} px a lens-only zoom leaves "
                f"(the camera body or the scene moves).")
    return head + ", ".join(parts) + "; " + tail


def geo_hint_line(imgs):
    """the prompt's frame-geometry line for the 16 448x256 frames (serving: geo_hint.hint_for(None, imgs=frames))"""
    return hint_line(measure_images(imgs))


# ================================================================ calibrated confidence (verbatim: eval/v2/calibrate.py)

MOVES = ["static", "pan", "tilt", "push_in", "pull_out", "truck", "crane", "orbit", "follow"]

ZOOM_DIRS = ["in", "out", "none"]

PAIR_CODES = {frozenset(("pan", "truck")): "pan_vs_truck", frozenset(("tilt", "crane")): "tilt_vs_crane",
              frozenset(("follow", "orbit")): "follow_vs_orbit", frozenset(("static", "push_in")): "zoom_vs_dolly",
              frozenset(("static", "pull_out")): "zoom_vs_dolly", frozenset(("static", "follow")): "static_vs_moving"}

FIELDS = {"move": (("camera", "move"), MOVES), "zoom": (("camera", "zoom", "dir"), ZOOM_DIRS),
          "height": (("camera", "height_m"), None)}

ALT_MIN = 0.15

AMBIGUOUS_BELOW = {"move": 0.6, "zoom": 0.6, "height": 0.4}

CLIP = (0.02, 0.98)


def normalize_tokens(obj):
    """-> [(text, logprob, [(alt_text, alt_logprob), ...])] or None."""
    if isinstance(obj, dict):
        if "tokens" in obj:
            obj = obj["tokens"]
        elif isinstance(obj.get("logprobs"), dict):
            obj = obj["logprobs"].get("content")
        elif isinstance(obj.get("logprobs"), list):
            obj = obj["logprobs"]
        else:
            return None
    if not isinstance(obj, list) or not obj:
        return None
    out = []
    for t in obj:
        if isinstance(t, dict):
            text = t.get("text", t.get("token"))
            lp = t.get("logprob", t.get("lp"))
            top = t.get("top", t.get("top_logprobs")) or []
        elif isinstance(t, (list, tuple)) and len(t) >= 2:
            text, lp = t[0], t[1]
            top = t[2] if len(t) > 2 else []
        else:
            return None
        alts = []
        for a in top:
            if isinstance(a, dict):
                alts.append((a.get("text", a.get("token")), float(a.get("logprob", a.get("lp")))))
            elif isinstance(a, (list, tuple)) and len(a) >= 2:
                alts.append((a[0], float(a[1])))
        if not isinstance(text, str) or lp is None:
            return None
        out.append((text, float(lp), [(x, y) for x, y in alts if isinstance(x, str)]))
    return out

_NUM = re.compile(r"-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?")


class _Spans:
    """Recursive-descent JSON scan that records the character span of every value by key path.
    Strings: span of the content inside the quotes. Truncated or broken JSON: keeps what it saw."""

    def __init__(self, text):
        self.t, self.i, self.spans = text, 0, {}

    def ws(self):
        while self.i < len(self.t) and self.t[self.i] in " \t\r\n":
            self.i += 1

    def string(self):
        s0 = self.i
        self.i += 1
        while self.t[self.i] != '"':
            self.i += 2 if self.t[self.i] == "\\" else 1
        self.i += 1
        return s0, json.loads(self.t[s0:self.i])

    def value(self, path):
        self.ws()
        c = self.t[self.i]
        if c == "{":
            s0 = self.i
            self.i += 1
            self.ws()
            if self.t[self.i] == "}":
                self.i += 1
            else:
                while True:
                    self.ws()
                    _, key = self.string()
                    self.ws()
                    if self.t[self.i] != ":":
                        raise ValueError("expected :")
                    self.i += 1
                    self.value(path + (key,))
                    self.ws()
                    if self.t[self.i] == ",":
                        self.i += 1
                        continue
                    if self.t[self.i] == "}":
                        self.i += 1
                        break
                    raise ValueError("expected , or }")
            self.spans[path] = (s0, self.i, "obj", None)
        elif c == "[":
            s0, k = self.i, 0
            self.i += 1
            self.ws()
            if self.t[self.i] == "]":
                self.i += 1
            else:
                while True:
                    self.value(path + (k,))
                    k += 1
                    self.ws()
                    if self.t[self.i] == ",":
                        self.i += 1
                        continue
                    if self.t[self.i] == "]":
                        self.i += 1
                        break
                    raise ValueError("expected , or ]")
            self.spans[path] = (s0, self.i, "arr", None)
        elif c == '"':
            s0, v = self.string()
            self.spans[path] = (s0 + 1, self.i - 1, "str", v)
        else:
            m = _NUM.match(self.t, self.i)
            if m:
                self.i = m.end()
                self.spans[path] = (m.start(), m.end(), "num", m.group(0))
                return
            for lit in ("true", "false", "null"):
                if self.t.startswith(lit, self.i):
                    self.spans[path] = (self.i, self.i + len(lit), "lit", lit)
                    self.i += len(lit)
                    return
            raise ValueError(f"bad value at {self.i}")


def json_spans(text):
    """{key path tuple: (start, end, kind, value)} for the first JSON object in text."""
    p = _Spans(text)
    p.i = text.find("{")
    if p.i < 0:
        return {}
    try:
        p.value(())
    except (IndexError, ValueError, json.JSONDecodeError):
        pass
    return p.spans


def _overlapping(offs, toks, s, e):
    return [k for k in range(len(toks)) if offs[k] < e and offs[k] + len(toks[k][0]) > s]


def as_tokens(x):
    """already-normalized token list -> itself; anything normalize_tokens accepts -> normalized; else None."""
    if isinstance(x, list) and x and isinstance(x[0], tuple):
        return x
    return normalize_tokens(x)


def raw_features(tokens):
    """{field: {"raw": p | None, "value": str | None, "dist": {word: p}}} from tokens (any accepted format)."""
    tokens = as_tokens(tokens)
    out = {f: {"raw": None, "value": None, "dist": {}} for f in FIELDS}
    if not tokens:
        return out
    text = "".join(t[0] for t in tokens)
    offs, o = [], 0
    for t in tokens:
        offs.append(o)
        o += len(t[0])
    spans = json_spans(text)
    for f, (path, vocab) in FIELDS.items():
        sp = spans.get(path)
        if not sp or sp[2] not in ("str", "num"):
            continue
        s, e, kind, val = sp
        if kind == "num":
            dot = text.find(".", s, e)
            if dot >= 0:
                e = min(e, dot + 2)
        ks = _overlapping(offs, tokens, s, e)
        if not ks:
            continue
        joint = math.exp(sum(tokens[k][1] for k in ks))
        out[f]["raw"], out[f]["value"] = joint, str(val)
        if vocab and kind == "str":
            out[f]["dist"] = word_dist(text, tokens, offs, ks, s, str(val), vocab, joint)
    return out


def word_dist(text, tokens, offs, ks, s, chosen, vocab, joint):
    """Approximate P(word) over vocab from the top-k alternatives at each token of the value: an alternative token
    that leads to exactly one other word adds P(prefix so far) * P(alt) to that word."""
    dist = collections.defaultdict(float)
    prefix_p = 1.0
    for k in ks:
        tok, lp, top = tokens[k]
        t0 = offs[k]
        lead = text[t0:s] if t0 < s else ""  # chars of this token before the value starts (an opening quote)
        so_far = text[s:t0] if t0 > s else ""  # value chars already emitted by earlier tokens
        for alt, alp in top:
            if alt == tok or not alt.startswith(lead):
                continue
            hyp = so_far + alt[len(lead):]
            closed = '"' in hyp
            word = hyp.split('"')[0]
            if not word:
                continue
            cands = [w for w in vocab if (w == word if closed else w.startswith(word))]
            if len(cands) == 1 and cands[0] != chosen:
                dist[cands[0]] += prefix_p * math.exp(alp)
        prefix_p *= math.exp(lp)
    dist[chosen] = joint
    return dict(dist)


def _logit(p):
    p = min(1 - 1e-6, max(1e-6, p))
    return math.log(p / (1 - p))


def _sigmoid(x):
    """overflow-free logistic (Newton steps can overshoot to |x| > 700 on separable data)."""
    if x >= 0:
        return 1 / (1 + math.exp(-x))
    e = math.exp(x)
    return e / (1 + e)


def apply_map(m, x):
    if m["method"] == "platt":
        y = _sigmoid(m["a"] * _logit(x) + m["b"])
    else:
        kx, ky = m["x"], m["y"]
        if not kx:
            return None
        if x <= kx[0]:
            y = ky[0]
        elif x >= kx[-1]:
            y = ky[-1]
        else:
            j = bisect.bisect_right(kx, x)
            x0, x1, y0, y1 = kx[j - 1], kx[j], ky[j - 1], ky[j]
            y = y0 if x1 == x0 else y0 + (y1 - y0) * (x - x0) / (x1 - x0)
    return min(CLIP[1], max(CLIP[0], y))


class Calibrator:
    def __init__(self, spec):
        self.spec = spec
        self.maps = spec.get("fields", {})
        self.alt_min = spec.get("alt_min", ALT_MIN)
        self.ambiguous_below = spec.get("ambiguous_below", AMBIGUOUS_BELOW)

    @classmethod
    def load(cls, path):
        with open(path) as f:
            return cls(json.load(f))

    def calibrate(self, field, raw):
        m = self.maps.get(field)
        if not m:
            return None
        if raw is None:
            return m.get("absent_rate")
        return apply_map(m, raw)

    def field_confidences(self, tokens):
        feats = raw_features(tokens)
        out = {f: self.calibrate(f, feats[f]["raw"]) for f in FIELDS}
        out["move_alt"] = None
        d = feats["move"]["dist"]
        chosen = feats["move"]["value"]
        others = sorted(((p, w) for w, p in d.items() if w != chosen), reverse=True)
        if others and others[0][0] >= self.alt_min:
            out["move_alt"] = others[0][1]
        out["_raw"] = {f: feats[f]["raw"] for f in FIELDS}
        return out

    def annotate(self, sheet, tokens):
        """Set camera.confidence / move_alt / ambiguous on sheet (in place) from the generation tokens."""
        if not isinstance(sheet, dict) or not isinstance(sheet.get("camera"), dict):
            return sheet
        cam = sheet["camera"]
        fc = self.field_confidences(tokens)
        conf = {f: round(fc[f], 3) for f in FIELDS if fc[f] is not None}
        if conf:
            cam["confidence"] = conf
        mv = cam.get("move")
        if fc["move_alt"] and fc["move_alt"] != mv:
            cam["move_alt"] = fc["move_alt"]
        codes = [c for c in (cam.get("ambiguous") or []) if isinstance(c, str)]
        lo = self.ambiguous_below
        if fc["move_alt"] and conf.get("move", 1) < lo.get("move", 0.6):
            code = PAIR_CODES.get(frozenset((mv, fc["move_alt"])))
            if code and code not in codes:
                codes.append(code)
        if mv in ("static", "push_in", "pull_out") and conf.get("zoom", 1) < lo.get("zoom", 0.6) \
                and "zoom_vs_dolly" not in codes:
            codes.append("zoom_vs_dolly")
        if conf.get("height", 1) < lo.get("height", 0.4) and "height" not in codes:
            codes.append("height")
        if codes:
            cam["ambiguous"] = codes
        return sheet


# ================================================================ model

def chat(processor, text):
    msgs = [{"role": "user", "content": [{"type": "image"}] * N_FRAMES + [{"type": "text", "text": text}]}]
    return processor.apply_chat_template(msgs, add_generation_prompt=True, tokenize=False, enable_thinking=False)


def eos_ids(model_dir, tok):
    gen = {}
    p = os.path.join(model_dir, "generation_config.json")
    if os.path.exists(p):
        gen = json.load(open(p))
    e = gen.get("eos_token_id")
    eos = set(e if isinstance(e, list) else [e]) | {tok.convert_tokens_to_ids("<|im_end|>")}
    eos.discard(None)
    return sorted(eos)


def token_texts(tok, ids):
    """per-token texts that concatenate to decode(ids) (serving: runtime_v2.token_texts)"""
    out, start = [], 0
    for k in range(len(ids)):
        s = tok.decode(ids[start:k + 1], skip_special_tokens=True, clean_up_tokenization_spaces=False)
        if s.endswith("�") and k - start < 8:
            out.append("")
            continue
        out.append(s)
        start = k + 1
    return out


def _lp(x):
    x = float(x)
    return round(x, 5) if x > -1e4 else -1e4


def calib_tokens(tok, ids, tops, special):
    """[{text, logprob, top}] for the calibrator; tops[k] = [(token id, raw logprob), ...] best first, or None"""
    texts = token_texts(tok, ids)
    out = []
    for k, i in enumerate(ids):
        if i in special:
            continue
        d = dict(tops[k]) if tops and k < len(tops) and tops[k] else {}
        ranked = tops[k][:TOP_LOGPROBS] if tops and k < len(tops) and tops[k] else []
        out.append({"text": texts[k], "logprob": _lp(d[i]) if i in d else -1e4,
                    "top": [{"text": tok.decode([a], skip_special_tokens=False), "logprob": _lp(b)} for a, b in ranked]})
    return out


def run_transformers(model_dir, prompt_text, imgs, a):
    import torch
    from transformers import AutoModelForImageTextToText, AutoProcessor
    proc = AutoProcessor.from_pretrained(model_dir)
    tok = proc.tokenizer
    kw = {"dtype": torch.bfloat16, "device_map": "auto"}
    if a.load_in_4bit:
        from transformers import BitsAndBytesConfig
        kw["quantization_config"] = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",
                                                       bnb_4bit_compute_dtype=torch.bfloat16)
    model = AutoModelForImageTextToText.from_pretrained(model_dir, **kw).eval()
    enc = proc(text=[chat(proc, prompt_text)], images=imgs, return_tensors="pt").to(model.device)
    gk = dict(max_new_tokens=a.max_new_tokens, do_sample=False, eos_token_id=eos_ids(model_dir, tok),
              return_dict_in_generate=True, output_logits=True)
    if a.camera_only:
        gk.update(stop_strings=[CAMERA_ONLY_STOP], tokenizer=tok)
    with torch.no_grad():
        out = model.generate(**enc, **gk)
    ids = out.sequences[0, enc["input_ids"].shape[1]:].tolist()
    tops = []
    for k, lg in enumerate(out.logits[:len(ids)]):   # raw logits -> raw logprobs (= vLLM logprobs_mode="raw_logprobs")
        lp = torch.log_softmax(lg[0].float(), -1)
        v, ix = lp.topk(TOP_LOGPROBS)
        tops.append([(ids[k], float(lp[ids[k]]))] + [(int(i), float(x)) for i, x in zip(ix, v) if int(i) != ids[k]])
    finished = not ids or ids[-1] in eos_ids(model_dir, tok) or a.camera_only
    # the chosen token first, then the ranked top-5 (calib_tokens uses the dict for the chosen logprob)
    tops = [sorted(t, key=lambda x: -x[1]) for t in tops]
    return ids, tops, tok, set(tok.all_special_ids), finished


def run_vllm(model_dir, prompt_text, imgs, a):
    from transformers import AutoProcessor
    from vllm import LLM, SamplingParams
    proc = AutoProcessor.from_pretrained(model_dir)
    tok = proc.tokenizer
    eos = eos_ids(model_dir, tok)
    llm = LLM(model=model_dir, dtype="bfloat16", max_model_len=16384, limit_mm_per_prompt={"image": N_FRAMES, "video": 0},
              gpu_memory_utilization=a.gpu_memory_utilization, seed=0, logprobs_mode="raw_logprobs", max_logprobs=20)
    req = {"prompt": chat(proc, prompt_text), "multi_modal_data": {"image": imgs}}

    def params(repair=False):
        kw = dict(temperature=0.0, max_tokens=a.max_new_tokens, seed=0, stop_token_ids=eos, logprobs=TOP_LOGPROBS,
                  stop=[CAMERA_ONLY_STOP] if a.camera_only else None)
        if repair:
            from vllm.sampling_params import StructuredOutputsParams
            kw["structured_outputs"] = StructuredOutputsParams(json=V5_SCHEMA, disable_any_whitespace=True)
        return SamplingParams(**kw)

    def one(repair=False):
        c = llm.generate([req], params(repair), use_tqdm=False)[0].outputs[0]
        ids = list(c.token_ids)
        tops = []
        for k, i in enumerate(ids):
            d = c.logprobs[k] if c.logprobs and k < len(c.logprobs) and c.logprobs[k] is not None else {}
            ranked = sorted(d.items(), key=lambda kv: (kv[1].rank or 1e9))
            t = [(x, y.logprob) for x, y in ranked if (y.rank or 1e9) <= TOP_LOGPROBS]
            if i in d and all(x != i for x, _ in t):
                t.append((i, d[i].logprob))   # chosen token outside the top 5: kept for its logprob only
            tops.append(t)
        return ids, tops, c.finish_reason == "stop"

    ids, tops, fin = one()
    if decode_sheet(tok, ids, a.camera_only) is None or not fin:
        ids, tops, fin = one(repair=True)
    return ids, tops, tok, set(tok.all_special_ids), fin


def parse_sheet(raw):
    m = re.search(r"\{.*\}", raw, re.S)
    if not m:
        return None
    try:
        sheet = json.loads(m.group(0))
    except ValueError:
        return None
    return sheet if isinstance(sheet, dict) else None


def close_camera_only(raw):
    """text cut at the stop string -> closed camera-only sheet, or None (serving: runtime_v2.close_camera_only)"""
    s = raw.strip()
    i = s.find("{")
    if i < 0:
        return None
    s = s[i:]
    j = s.find(CAMERA_ONLY_STOP)
    if j >= 0:
        s = s[:j]
    o = None
    for cand in (s + "}", s):
        try:
            o = json.loads(cand)
        except ValueError:
            continue
        if isinstance(o, dict):
            break
        o = None
    if o is None:
        return None
    out = {"schema_version": o["schema_version"]} if "schema_version" in o else {}
    out["output"] = "camera_only"
    for k in CAMERA_ONLY_KEYS[2:]:
        if k in o:
            out[k] = o[k]
    return out


def decode_sheet(tok, ids, camera_only):
    raw = tok.decode(ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)
    return close_camera_only(raw) if camera_only else parse_sheet(raw)


def cut_tokens(tokens, j):
    out, o = [], 0
    for t in tokens:
        if o >= j:
            break
        n = len(t["text"])
        out.append(t if o + n <= j else dict(t, text=t["text"][: j - o]))
        o += n
    return out


def model_path(model):
    if os.path.isdir(model):
        return model
    from huggingface_hub import snapshot_download
    return snapshot_download(model, allow_patterns=["*.json", "*.safetensors", "*.txt", "*.jinja", "*.model",
                                                     "merges.txt", "vocab*"], ignore_patterns=["adapter/*"])


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("video")
    ap.add_argument("--subject", action="append", default=[], help='"ID: class (optional description)", repeatable')
    ap.add_argument("--model", default=REPO, help="hub repo id or local folder")
    ap.add_argument("--backend", choices=["transformers", "vllm"], default="transformers")
    ap.add_argument("--load-in-4bit", action="store_true", help="transformers + bitsandbytes NF4, for small GPUs")
    ap.add_argument("--camera-only", action="store_true", help="stop after camera, style, tags and caption")
    ap.add_argument("--no-confidence", action="store_true", help="skip camera.confidence / move_alt / ambiguous")
    ap.add_argument("--start", type=float, default=0.0, help="shot start in the video, seconds")
    ap.add_argument("--end", type=float, help="shot end in the video, seconds (default: end of the video)")
    ap.add_argument("--max-new-tokens", type=int, default=8192)
    ap.add_argument("--gpu-memory-utilization", type=float, default=0.85, help="vLLM only")
    ap.add_argument("--print-prompt", action="store_true", help="also print the geometry line to stderr")
    ap.add_argument("-o", "--out", help="write the sheet here (default: stdout)")
    a = ap.parse_args()

    t0 = time.time()
    end = a.end if a.end is not None else duration(a.video)
    dur = end - a.start
    times, imgs = sample_frames(a.video, dur, a.start)
    geo = geo_hint_line(imgs)
    if a.print_prompt:
        print(geo, file=sys.stderr)
    text = build_prompt(dur, times, a.subject, geo)
    mdir = model_path(a.model)
    run = run_vllm if a.backend == "vllm" else run_transformers
    ids, tops, tok, special, finished = run(mdir, text, imgs, a)
    raw = tok.decode(ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)
    tokens = calib_tokens(tok, ids, tops, special)
    if a.camera_only:
        j = raw.find(CAMERA_ONLY_STOP)
        if j >= 0:
            raw, tokens = raw[:j], cut_tokens(tokens, j)
        sheet = close_camera_only(raw)
    else:
        sheet = parse_sheet(raw) if finished else None
    if sheet is None:
        print(raw, file=sys.stderr)
        sys.exit("could not parse a JSON sheet from the model output")
    if not a.no_confidence:
        Calibrator.load(os.path.join(mdir, "cal.json")).annotate(sheet, tokens)
    sheet.setdefault("schema_version", 3)
    if not isinstance(sheet.get("shot"), dict):
        sheet["shot"] = {}
    sheet["shot"]["start"], sheet["shot"]["end"] = a.start, end
    s = json.dumps(sheet, indent=2)
    if a.out:
        with open(a.out, "w") as f:
            f.write(s + "\n")
    else:
        print(s)
    print(f"[shot_reader] {time.time() - t0:.1f} s", file=sys.stderr)


if __name__ == "__main__":
    main()