File size: 33,965 Bytes
b03bcfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a75268
fd837e4
 
2a75268
 
 
 
b03bcfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a75268
 
 
 
 
b03bcfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e4c4080
 
b03bcfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a75268
b03bcfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f53389c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b03bcfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f52926f
b03bcfe
 
f53389c
b03bcfe
 
 
 
 
 
 
e4c4080
b03bcfe
 
 
 
 
 
f53389c
b03bcfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f53389c
b03bcfe
f52926f
b03bcfe
 
 
 
 
 
 
 
 
 
f53389c
b03bcfe
 
 
 
 
f53389c
b03bcfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Prepare the timestamped SpaVoBench image-and-caption release.

The source export is kept unchanged.  This script writes a publication-ready
release with one annotation per numbered caption item, exact timestamp parsing,
English captions, frame extraction, and source-video provenance.
"""

from __future__ import annotations

import argparse
import collections
import concurrent.futures
import io
import json
import re
import shutil
import subprocess
import unicodedata
from datetime import UTC, datetime
from pathlib import Path
from typing import Any

import imageio_ffmpeg
from huggingface_hub import HfApi, hf_hub_download
from PIL import Image


SOURCE_REPOSITORY = "Xinyun-Liu/WorldModelBench"
TARGET_REPOSITORY = "Xinyun-Liu/SpaVoBench"
SCHEMA_VERSION = "spavobench-v1"
FRAME_TIME_OVERRIDES = {
    # The source stream ends just before the requested 8-second timestamp.
    "spavobench-0248-01": (7.9, "Requested timestamp 8.0 s is beyond the source stream; extracted the last decodable frame at 7.9 s."),
}
SCENE_NORMALIZATION = {
    "": "interaction",
    "animal": "interaction",
    "object physics": "object",
    "living space": "indoor space",
    "human interaction": "interaction",
}
NUMBERED_ITEM = re.compile(r"(?m)^\s*(\d+)\s*[.)]\s*")
TIMESTAMP_AT_END = re.compile(r"\s*[\uFF08(]\s*(\d{1,4}(?:\.\d+)?)\s*[\uFF09)]\s*$")
HAN = re.compile(r"[\u4e00-\u9fff]")


# Faithful, instruction-ready translations for every source caption containing
# Chinese.  Values are ordered by the original numeric item labels when present.
CAPTION_OVERRIDES: dict[int, list[str]] = {
    0: [
        "Use a shovel to scoop cement from the box and throw it into the bucket.",
        "Put the tool into the sink on the right and wash hands using the faucet in the middle.",
    ],
    3: ["Take the item out of the refrigerator and close the refrigerator door."],
    4: ["Keep the camera stationary while the person climbs upward."],
    5: ["Swim forward underwater."],
    6: ["Ride forward, turn right at the end of the road, then turn left."],
    7: ["Turn left, then continue forward after completing the turn."],
    8: ["Drive forward; a vehicle merging from the right forces the vehicle ahead to brake."],
    12: ["Drive into the garage ahead on the right."],
    13: ["Go around the flower bed."],
    14: ["People cross the road from opposite directions."],
    15: ["Drive counterclockwise 270 degrees around the flower bed, then continue forward."],
    20: ["Open the topmost drawer with the right hand."],
    21: ["Fold the clothes."],
    23: ["Pick up the transparent inflatable object and place it in the box."],
    24: ["Pick up the cup with the left hand."],
    25: ["Pick up the top item from the box with the right hand and hang it on the shelf."],
    26: ["Drive forward while the left lane is congested."],
    27: ["From the vehicle's perspective, the camera moves forward."],
    29: ["Drive along the road."],
    30: ["Drive along the road."],
    31: ["Drive along a coastal road with continuous traffic and pedestrians walking along the roadside."],
    36: ["Reach for the climbing hold in the front left with the left hand."],
    37: ["Reach up with the left hand to grasp a higher climbing hold."],
    38: ["Move the camera upward."],
    39: ["Move the camera around the group of dancers."],
    42: ["Move the camera slowly to the left without rotating it."],
    45: ["The woman gently pokes the baby's right cheek with the fingers of her right hand."],
    46: ["Film cyclists riding on the road from a train."],
    48: ["Move the camera to the left without rotating it."],
    49: ["The host enters the room and hands the microphone to the interviewee on the left from the camera's perspective."],
    50: ["Move the camera to the left without rotating it."],
    51: ["The camera follows the man to the middle window, revealing the view outside."],
    53: ["The basketball player receives a pass from the right and takes a shot."],
    56: ["A CNC milling machine carves wood away from the glass."],
    61: ["Zoom the map toward the yellow-circled location."],
    62: ["The man skateboard-jumps over a handrail."],
    63: ["The player on the right passes to a teammate in the middle, who scores with a shot."],
    64: ["A person walks into a shipping container."],
    65: ["A person introduces craft materials from left to right from their own perspective."],
    66: ["Turn the camera to the right to show the view outside the window."],
    67: [
        "Keep the camera stationary while the sports car drifts in a complete circle.",
        "Rotate the camera to follow the sports car as it drifts in a complete circle, maintaining a constant relative position to it.",
    ],
    68: ["The camera follows a man riding a skateboard on a city sidewalk."],
    73: ["Insert the wire into the lower port."],
    74: ["Drive on the road while filming the rear-view mirror."],
    75: ["Begin drifting to the right in a complete circle, then return to the initial direction."],
    76: ["A person places a plate in the oven and closes the door."],
    83: ["A man rides a skateboard through a rail; he jumps over the rail while the skateboard passes beneath it."],
    87: ["The camera follows a young man as he skateboards onto a wooden box."],
    90: ["A skydiver jumps from an airplane with a parachute; the camera faces the airplane during the final seconds before landing."],
    93: ["Tilt the camera upward."],
    95: ["A person rides a skateboard in a U-shaped pool."],
    96: ["Pipe alternating red and white cream.", "Cut off one corner of the cake with a fork."],
    97: ["Ride a bicycle up the slope and perform a 360-degree spin in the air."],
    99: ["The curtain rises, revealing the full car."],
    105: ["A man strikes the ball with a club, and the golf ball rolls along the grass into the hole."],
    109: ["Pan the camera from left to right.", "The man climbs up from the bottom of the U-shaped pool."],
    110: [
        "Invert the cake onto the table and remove the gray mold.",
        "Pipe a ring of cream onto the bundt pan.",
        "Place the sliced cake on a white plate.",
    ],
    111: ["The number 1 player on the dark blue team receives a teammate's pass and runs toward the sideline; the white-uniformed player cannot catch up."],
    113: ["Cut the potato in half.", "The person stands opposite the camera and cuts the dough into small pieces starting from her left."],
    114: [
        "Keep the camera at a constant relative position to the person. A person wearing roller skates rolls down the street while cars parked along the road remain stationary.",
        "Keep the camera directly in front of the person at a constant height. A person wearing roller skates rolls and prepares to skate onto the road to their left.",
        "Keep the camera at a constant relative position to the person. A person wearing roller skates rolls down the street as a taxi passes on their left.",
    ],
    116: ["Use a handheld camera."],
    124: ["The camera follows a player riding a horse in a virtual world."],
    125: ["A baseball player throws the ball forward, and another player hits it with a bat."],
    127: ["The camera follows the drop-tower ride as it rises.", "The drop-tower ride descends."],
    128: ["Move the clip holding the ball vertically downward while the paper board rotates."],
    129: ["Align the launcher and the duck, then launch a ball from the launcher."],
    130: ["Drop the basketball vertically."],
    131: ["Release the clip to let the ball fall vertically."],
    132: ["Position the two launchers in the same direction and launch the balls simultaneously."],
    133: ["Rotate the turntable clockwise."],
    134: ["Rotate the turntable clockwise."],
    135: ["Pour the liquid from the bucket into the glass."],
    136: ["Pour the liquid from the bucket into the glass."],
    137: ["Turn on the switch to let the liquid flow out of the container."],
    141: ["A ball rolls out of the launcher on the left."],
    142: ["A ball rolls out of the launcher on the left."],
    143: ["A ball rolls out of the launcher on the left."],
    144: ["A yellow tennis ball rolls away from the camera."],
    145: ["Lower the container vertically onto the table.", "Lower the container vertically onto the table, then pick it up."],
    146: ["The two launchers face different directions and launch balls simultaneously."],
    147: ["Place the blue wooden block down vertically and release it."],
    148: ["Pour the liquid from the bucket into the glass."],
    149: ["The object's initial position is directly above the pillow. Lower the weight.", ""],
    150: ["Rotate the camera 360 degrees starting from the left to reveal the surrounding geometry."],
    151: ["Walk forward and turn right at the end."],
    152: ["Walk across the road while pedestrians approach from the opposite direction."],
    153: ["Walk forward and enter the door."],
    154: ["Tilt the camera slowly upward until it is parallel to the ceiling.", "Keep the camera parallel to the ceiling and rotate once."],
    155: ["Descend in the elevator while keeping the camera stationary."],
    156: ["Walk forward while pedestrians approach from the opposite direction."],
    157: ["Move the camera forward."],
    158: ["Raise the camera upward."],
    159: ["Enter the building through the revolving door on the right."],
    161: ["Rotate the camera to the right."],
    162: ["Rotate the camera to the left to reveal the surrounding view."],
    163: ["Walk forward while turning the camera to the left."],
    164: ["Walk forward as a bus approaches from ahead."],
    165: ["Move forward through the scene and turn left at the intersection, finishing fully facing left."],
    166: ["Tilt the camera upward until it is parallel with the ceiling."],
    167: ["Rotate the camera right to show the other side of the room."],
    168: ["Raise and rotate the camera upward."],
    169: ["Rotate the camera 90 degrees to the left."],
    170: ["Capture a diving view down along the mountainside."],
    171: ["Move the camera forward to the right side of the distant rock wall."],
    172: ["Rotate and move the camera behind the reef to capture a view from the ocean toward the land."],
    173: ["Move the camera to the right of the bed from the camera's perspective and capture the room from that position."],
    205: ["Travel along the track."],
    206: ["Ride along the road while cyclists travel in the opposite direction in the left lane."],
    207: ["Travel along the road."],
    208: ["Pull the camera backward to widen the view."],
    212: ["Drive out of the tunnel."],
    213: ["Move the camera right without rotating it."],
    214: ["Walk along a path through the woods."],
    215: ["As the car drives, a boy runs from the left side of the road and crosses in front of it."],
    216: ["The camera follows the station wagon. A rabbit runs out from the platform and crosses in front of the car."],
    217: ["The camera follows the bicycle. A soccer ball rolls in from the right and stops in front of it."],
    219: ["The camera follows the Black hockey player as he advances the puck with his stick."],
    220: ["An athlete swims in the ocean as a dolphin leaps from the water on the right and dives into the water on the left."],
    221: ["Move the camera from a side view to a top-down view above the rectangular container, then translate it horizontally to a top-down view above the round container."],
    222: ["Move the camera from a side view to a top-down view above the rectangular container, then translate it horizontally to a top-down view above the round container."],
    223: ["Move the camera from a side view to a top-down view above the white container, then translate it horizontally to a top-down view above the blue container."],
    224: ["Move the camera from a side view to a top-down view of the left container, then rotate it to a top-down view of the right container."],
    225: ["Move the camera from a side view to a top-down view of the bamboo basket on the left, then translate it horizontally to a top-down view of the ceramic container."],
    226: ["A man presses the button on the right with his right hand, and the light on the same side turns on."],
    227: ["A person presses the button on the right with their left hand, and the light on the same side turns on from the person's perspective."],
    228: ["A person presses a button with their left hand, and the cabinet on the left opens from the person's perspective."],
    229: ["A naval officer pushes the switch on his right forward, then pushes the switch on his left forward."],
    230: ["Walk forward, pass the wall, and turn right.", "Rotate the camera to the right."],
    231: ["Translate the camera to the left side of the floating wall light, then translate it back to the initial position."],
    232: ["Walk forward, then turn left."],
    234: ["Walk forward, turn left, then turn right and continue forward."],
    235: ["Walk straight forward and stop in front of the sign."],
    236: ["Walk forward and turn right at the first intersection."],
    237: ["Walk forward to the sign and turn left."],
    238: ["Move the camera to show a top-down view of the object and an opposite side view."],
    239: ["The person places a water cup on the TV cabinet opposite."],
    240: ["The person places a passport on the table to their left."],
    241: ["The chef brings the ketchup closer and places it directly in front of the lemon from the chef's perspective."],
    243: ["The person places the Red Resistance Band Coil and Blue Foam Roller Block on the black table, to the left of the blue rectangular prism from the camera's perspective."],
    244: ["Rotate around the central wall of the room once, showing the room.", "Place the comb on the middle shelf of the cabinet at the back."],
    245: ["The person places the trophy on the lower shelf of the table opposite."],
    246: ["Move the camera to a top-down view directly above the brown building.", "Move the camera around the tallest building once."],
    247: ["Move the camera to show a vertical top-down view of the brown building."],
    248: ["Move the camera to the center of the castle and look around it once."],
    249: ["Move the camera until the view is parallel to the tabletop."],
    251: ["Keep the camera stationary. Place the red object on the table into the black container.", "Keep the camera stationary after placing the red object from the table into the black container."],
    254: ["Drive on the road slower than the black car in the left lane but faster than the train in the right lane."],
    255: ["Drive on the road faster than the train in the left lane but slower than the motorcycle in the right lane."],
    256: ["Paddle forward on a paddleboard as a yacht passes on the right."],
    257: ["The thief walks to the side where the police cannot see them."],
    258: ["The child moves through the ball pit to the other side."],
    259: [
        "The camera remains stationary. Within the 5-second clip, the cat moves around the side of the table to the opposite side of the billiard table.",
        "The camera remains stationary. Within the 5-second clip, the cat moves underneath the table to the opposite side of the billiard table.",
    ],
    260: ["The person on the right from the camera's perspective rises from the chair and walks to her left."],
    261: ["The dog walks toward the person."],
    262: ["An elephant's foot stomps downward on a television."],
    263: ["The water surface rotates clockwise."],
    264: ["Rotate the camera counterclockwise while keeping it pointed at the cup."],
    266: ["A yellow peach is thrown rightward into milk."],
    267: ["Pour chocolate over the dessert."],
    268: ["The camera gradually transitions from an overhead view to a view parallel to the tabletop."],
    270: ["The transparent ball continues to rotate."],
    271: ["The charcoal continues to burn."],
    272: ["Keep the camera stationary as the sky lantern flies into the sky."],
    274: ["Pour water from far to near relative to the camera."],
    275: ["Rotate the camera 180 degrees counterclockwise while keeping it pointed at the cup.", "Rotate the camera 180 degrees clockwise while keeping it pointed at the cup."],
    276: ["Pour tea clockwise from the camera's perspective."],
    277: ["A strawberry falls into water."],
    278: ["Seawater continually crashes against the rocks."],
    279: ["Pour honey onto the spoon."],
    280: ["Slowly pull the camera upward and away.", "Push the camera forward to move in."],
    281: ["Float in a kayak as visitors drift downstream from upstream."],
    283: ["The sea of clouds moves left while the camera pans slowly right."],
    287: ["An orange slice falls into orange juice."],
    288: ["Pour white sauce over the salmon."],
    290: ["The camera gradually moves closer."],
    291: ["A small ball rolls toward the camera from a distance."],
}


def utc_now() -> str:
    return datetime.now(UTC).replace(microsecond=0).isoformat().replace("+00:00", "Z")


def normalize_scene(scene: Any) -> str:
    value = str(scene or "").strip()
    return SCENE_NORMALIZATION.get(value, value)


def parse_timestamp(raw: Any) -> float | None:
    """Decode the project's timestamp convention into seconds.

    One- and two-digit values are seconds.  Three- and four-digit whole values
    use the final two digits as seconds and the leading digits as minutes.
    Decimal values are already seconds.
    """
    value = str(raw if raw is not None else "").strip()
    if not value:
        return None
    if "." in value:
        try:
            return float(value)
        except ValueError:
            return None
    if not value.isdigit():
        return None
    if len(value) <= 2:
        return float(int(value))
    minutes, seconds = int(value[:-2]), int(value[-2:])
    if seconds >= 60:
        return None
    return float(minutes * 60 + seconds)


def split_caption(caption: str) -> list[dict[str, Any]]:
    matches = list(NUMBERED_ITEM.finditer(caption))
    if not matches:
        chunks = [(None, caption)]
    else:
        chunks = []
        for position, match in enumerate(matches):
            end = matches[position + 1].start() if position + 1 < len(matches) else len(caption)
            chunks.append((int(match.group(1)), caption[match.end() : end]))

    result: list[dict[str, Any]] = []
    for number, text in chunks:
        text = text.strip()
        timestamp = None
        found = TIMESTAMP_AT_END.search(text)
        if found:
            timestamp = found.group(1)
            text = text[: found.start()].strip()
        result.append({"source_item_number": number, "raw_caption": text, "timestamp_raw": timestamp})
    return result


def normalize_english(text: str) -> str:
    text = unicodedata.normalize("NFKC", text)
    replacements = {
        "figerater": "refrigerator",
        "th e": "the",
        "A  ": "A ",
        "a  ": "a ",
        "The camera follow ": "The camera follows ",
        "The camera zoom out": "The camera zooms out",
        "the video also": "The video also",
        "It is night time": "It is nighttime",
    }
    for source, target in replacements.items():
        text = text.replace(source, target)
    text = re.sub(r"\s+", " ", text).strip()
    if text and text[-1] not in ".?!":
        text += "."
    return text


def caption_for_segment(source_index: int, segment_index: int, raw_caption: str) -> str:
    if source_index in CAPTION_OVERRIDES:
        overrides = CAPTION_OVERRIDES[source_index]
        if segment_index > len(overrides):
            raise ValueError(f"missing translation for source row {source_index}, segment {segment_index}")
        caption = overrides[segment_index - 1]
    else:
        caption = raw_caption
    if HAN.search(caption):
        raise ValueError(f"untranslated Chinese remains in source row {source_index}, segment {segment_index}: {caption}")
    return normalize_english(caption)


def build_records(source: dict[str, Any]) -> list[dict[str, Any]]:
    records: list[dict[str, Any]] = []
    for source_index, row in enumerate(source["annotations"]):
        parts = split_caption(str(row.get("text_caption") or ""))
        for segment_index, part in enumerate(parts, start=1):
            if not part["raw_caption"] and len(parts) > 1:
                continue
            timestamp_raw = part["timestamp_raw"] or str(row.get("timestamp_seconds") or "").strip()
            caption = caption_for_segment(source_index, segment_index, part["raw_caption"])
            annotation_id = f"spavobench-{source_index:04d}-{segment_index:02d}"
            record = {
                "annotation_id": annotation_id,
                "sample_id": row["sample_id"],
                "source_annotation_index": source_index,
                "source_caption_segment_index": segment_index,
                "source_caption_item_number": part["source_item_number"],
                "text_caption": caption,
                "caption_status": "complete" if caption else "incomplete_source_caption",
                "timestamp_raw": timestamp_raw,
                "timestamp_seconds": parse_timestamp(timestamp_raw),
                "timestamp_provenance": "caption" if part["timestamp_raw"] else "record",
                "data_source": row.get("data_source", ""),
                "annotator": row.get("annotator", ""),
                "decision": row.get("decision", ""),
                "track": row.get("track", ""),
                "scene": normalize_scene(row.get("scene", "")),
                "spatial_ability": row.get("spatial_ability", ""),
                "perspective": row.get("perspective", ""),
                "video_path": row.get("video_path", ""),
                "source_video_url": row.get("video_url", ""),
                "source_video_repository": SOURCE_REPOSITORY,
                "source_video_included": False,
                "submitted_at": row.get("submitted_at"),
                "local_saved_at": row.get("local_saved_at"),
                "updated_at": row.get("updated_at"),
            }
            frame_override = FRAME_TIME_OVERRIDES.get(annotation_id)
            record["frame_timestamp_seconds"] = frame_override[0] if frame_override else record["timestamp_seconds"]
            if frame_override:
                record["frame_timestamp_note"] = frame_override[1]
            records.append(record)
    return records


def write_json(path: Path, value: Any) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")


def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("w", encoding="utf-8") as handle:
        for row in rows:
            handle.write(json.dumps(row, ensure_ascii=False) + "\n")


def build_source_manifest(records: list[dict[str, Any]]) -> list[dict[str, Any]]:
    grouped: dict[str, list[dict[str, Any]]] = collections.defaultdict(list)
    for row in records:
        grouped[row["video_path"]].append(row)
    result: list[dict[str, Any]] = []
    for video_path, rows in sorted(grouped.items()):
        first = rows[0]
        result.append(
            {
                "source_video_repository": SOURCE_REPOSITORY,
                "video_path": video_path,
                "source_video_url": first["source_video_url"],
                "data_source": first["data_source"],
                "annotation_ids": [row["annotation_id"] for row in rows],
                "timestamp_seconds": [row["timestamp_seconds"] for row in rows],
            }
        )
    return result


def dataset_card() -> str:
    return """---
license: other
task_categories:
- image-to-text
language:
- en
tags:
- spatial-reasoning
- video-understanding
- world-model
---

# SpaVoBench

SpaVoBench is a timestamped image-and-instruction release derived from the human-reviewed `keep` records in WorldModelBench. Each JSONL row corresponds to exactly one image and one English caption.

## Layout

- `data/annotations.jsonl`: release records, one per extracted frame.
- `data/annotations.json`: the same keep-only records as a standard JSON array.
- `data/manifest.json`: release counts, source policy, and timestamp convention.
- `images/`: JPEG frames named by `annotation_id`.
- `source-videos/README.md` and `source-videos/manifest.jsonl`: canonical source-video policy and grouped source links. Complete MP4s remain in `Xinyun-Liu/WorldModelBench` and are not duplicated here.

## Timestamp Convention

One- and two-digit timestamps are seconds. Three- and four-digit timestamps use the final two digits as seconds and the leading digits as minutes. For example, `515` is 5:15 (315 seconds), and `0158` is 1:58 (118 seconds). `timestamp_raw` preserves the submitted value and `timestamp_seconds` contains the decoded extraction time.

## Provenance

Every record contains the original WorldModelBench file path and public URL. Use `text_caption` as the English instruction. The release does not duplicate source MP4 files, so the source dataset's terms and provenance remain attached to the original video assets.
"""


def source_video_readme() -> str:
    return """# Source videos

The complete, unmodified source MP4 for every SpaVoBench record is available from `Xinyun-Liu/WorldModelBench` at the `video_path` and `source_video_url` stored in its matching annotation record. `manifest.jsonl` groups those links by source video.

Videos are deliberately not duplicated in this repository. This keeps each source file under its original provenance and distribution terms while allowing any released frame to be reproduced exactly from its decoded timestamp.
"""


def download_video(video_path: str) -> tuple[str, str | None, str | None]:
    try:
        local_path = hf_hub_download(
            repo_id=SOURCE_REPOSITORY,
            repo_type="dataset",
            filename=video_path,
        )
        return video_path, local_path, None
    except Exception as error:  # Captured in the release manifest for retry.
        return video_path, None, f"{type(error).__name__}: {error}"


def extract_frame(video: Path, timestamp_seconds: float, destination: Path, ffmpeg: str) -> str | None:
    if destination.exists():
        return None
    destination.parent.mkdir(parents=True, exist_ok=True)
    command = [
        ffmpeg,
        "-hide_banner",
        "-loglevel",
        "error",
        "-i",
        str(video),
        "-ss",
        f"{timestamp_seconds:.3f}",
        "-frames:v",
        "1",
        "-vf",
        "format=yuv420p",
        "-q:v",
        "2",
        str(destination),
    ]
    try:
        subprocess.run(command, check=True, timeout=600)
        if not destination.exists() or destination.stat().st_size == 0:
            return "ffmpeg completed without an image"
        return None
    except subprocess.TimeoutExpired:
        return "ffmpeg extraction timed out after 600 seconds"
    except subprocess.CalledProcessError as error:
        # A few source files use a pixel format that the JPEG encoder rejects.
        # Decode one PNG frame through stdout, then normalize it with Pillow.
        fallback = [
            ffmpeg,
            "-hide_banner",
            "-loglevel",
            "error",
            "-i",
            str(video),
            "-ss",
            f"{timestamp_seconds:.3f}",
            "-frames:v",
            "1",
            "-f",
            "image2pipe",
            "-vcodec",
            "png",
            "-",
        ]
        try:
            decoded = subprocess.run(fallback, check=True, timeout=600, capture_output=True).stdout
            with Image.open(io.BytesIO(decoded)) as image:
                image.convert("RGB").save(destination, format="JPEG", quality=95)
            return None if destination.exists() and destination.stat().st_size else "PNG fallback produced no image"
        except Exception as fallback_error:
            return f"ffmpeg failed with exit status {error.returncode}; PNG fallback: {fallback_error}"


def extract_release_frames(records: list[dict[str, Any]], output: Path, workers: int) -> list[dict[str, str]]:
    release_records = [row for row in records if row["decision"] == "keep"]
    video_paths = sorted({row["video_path"] for row in release_records})
    downloads: dict[str, Path] = {}
    failures: list[dict[str, str]] = []
    with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:
        for video_path, local_path, error in pool.map(download_video, video_paths):
            if error:
                failures.append({"kind": "download", "video_path": video_path, "error": error})
            elif local_path:
                downloads[video_path] = Path(local_path)

    ffmpeg = imageio_ffmpeg.get_ffmpeg_exe()
    image_root = output / "images"
    jobs: list[dict[str, Any]] = []
    for row in release_records:
        row["image_path"] = f"images/{row['annotation_id']}.jpg"
        timestamp = row["frame_timestamp_seconds"]
        if timestamp is None:
            failures.append({"kind": "timestamp", "annotation_id": row["annotation_id"], "error": "missing or invalid timestamp"})
            continue
        video = downloads.get(row["video_path"])
        if not video:
            continue

        jobs.append(row)

    def run_frame_job(row: dict[str, Any]) -> tuple[str, str | None]:
        video = downloads[row["video_path"]]
        error = extract_frame(video, row["timestamp_seconds"], image_root / f"{row['annotation_id']}.jpg", ffmpeg)
        return row["annotation_id"], error

    with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:
        for annotation_id, error in pool.map(run_frame_job, jobs):
            if error:
                failures.append({"kind": "frame", "annotation_id": annotation_id, "error": error})
    return failures


def build_manifest(records: list[dict[str, Any]], failures: list[dict[str, str]]) -> dict[str, Any]:
    keep = [row for row in records if row["decision"] == "keep"]
    return {
        "schema_version": SCHEMA_VERSION,
        "generated_at": utc_now(),
        "source_repository": SOURCE_REPOSITORY,
        "source_video_policy": "Complete source MP4s remain in WorldModelBench. This release stores stable paths and URLs without duplicating video files.",
        "timestamp_convention": "One or two digits: seconds. Three or four digits: leading digits are minutes and final two digits are seconds. Decimal timestamps are seconds.",
        "record_counts": {
            "all_reviewed": len(records),
            "release_keep": len(keep),
            "source_videos": len({row['video_path'] for row in keep}),
            "numbered_source_rows_split": len({row['source_annotation_index'] for row in records if row['source_caption_segment_index'] > 1}),
            "frame_failures": len(failures),
        },
        "by_decision": dict(sorted(collections.Counter(row["decision"] for row in records).items())),
        "by_data_source": dict(sorted(collections.Counter(row["data_source"] for row in keep).items())),
    }


def write_release(source_path: Path, output: Path, extract_frames: bool, workers: int) -> dict[str, Any]:
    source = json.loads(source_path.read_text(encoding="utf-8"))
    records = build_records(source)
    kept = [row.copy() for row in records if row["decision"] == "keep"]
    failures: list[dict[str, str]] = []

    if extract_frames:
        failures = extract_release_frames(kept, output, workers)
    else:
        for row in kept:
            row["image_path"] = f"images/{row['annotation_id']}.jpg"

    manifest = build_manifest(kept, failures)
    output.mkdir(parents=True, exist_ok=True)
    (output / "README.md").write_text(dataset_card(), encoding="utf-8")
    (output / "source-videos").mkdir(exist_ok=True)
    (output / "source-videos" / "README.md").write_text(source_video_readme(), encoding="utf-8")
    write_jsonl(output / "source-videos" / "manifest.jsonl", build_source_manifest(kept))
    write_jsonl(output / "data" / "annotations.jsonl", kept)
    write_json(output / "data" / "annotations.json", {"schema_version": SCHEMA_VERSION, "annotations": kept})
    write_json(output / "data" / "manifest.json", manifest)
    write_jsonl(output / "data" / "frame_failures.jsonl", failures)
    (output / "scripts").mkdir(exist_ok=True)
    shutil.copy2(Path(__file__), output / "scripts" / Path(__file__).name)
    return manifest


def upload_release(output: Path, message: str) -> str:
    api = HfApi()
    api.create_repo(TARGET_REPOSITORY, repo_type="dataset", exist_ok=True, private=False)
    api.upload_folder(
        repo_id=TARGET_REPOSITORY,
        repo_type="dataset",
        folder_path=str(output),
        commit_message=message,
    )
    return f"https://huggingface.co/datasets/{TARGET_REPOSITORY}"


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--source",
        type=Path,
        default=Path("/Users/liusmac/Downloads/worldmodelbench-review-2026-08-08 (6).json"),
    )
    parser.add_argument("--output", type=Path, default=Path("artifacts/spavobench/v1/release"))
    parser.add_argument("--extract-frames", action="store_true")
    parser.add_argument("--download-workers", type=int, default=4)
    parser.add_argument("--upload", action="store_true")
    args = parser.parse_args()

    manifest = write_release(args.source, args.output, args.extract_frames, args.download_workers)
    print(json.dumps(manifest, indent=2))
    if args.upload:
        print(upload_release(args.output, "Publish SpaVoBench v1 timestamped image release"))


if __name__ == "__main__":
    main()