File size: 45,864 Bytes
ced6859
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
#!/usr/bin/env python3
"""
Public RealVideo-Bench evaluation script.

This file merges the dataset/meta preparation flow from process.py with the
response parsing and accuracy flow from result/parse_res.py. It intentionally
contains no private paths, private imports, API keys, or vendor-specific secrets.

Typical usage:

1. Build task jsonl files from the released dataset layout:
   python public_eval.py build-meta --dataset-root /path/to/RealVideo-Bench/data --output-dir task

2. Run model inference with an OpenAI-compatible vision API:
   export REALVIDEO_API_KEY="YOUR_API_KEY"
   export REALVIDEO_BASE_URL="https://your.openai-compatible.endpoint/v1"
   python public_eval.py infer --task-file task/task1_meta.jsonl --task-type 1 \
       --video-root /path/to/RealVideo-Bench/data --model YOUR_MODEL \
       --output result/task_1/your_model_fps5.jsonl

3. Parse model responses:
   python public_eval.py parse --input result/task_1/your_model_fps5.jsonl \
       --task-type 1 --output result/parse_res/task_1/your_model_fps5.jsonl \
       --parser api --model YOUR_TEXT_MODEL

4. Calculate accuracy:
   python public_eval.py accuracy --input result/parse_res/task_1/your_model_fps5.jsonl \
       --task-type 1 --meta-file task/task1_meta.jsonl
"""

from __future__ import annotations

import argparse
import base64
import copy
import json
import os
import random
import re
import threading
import time
import traceback
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple

try:
    from tqdm import tqdm
except ImportError:  # pragma: no cover
    def tqdm(iterable: Iterable[Any], **_: Any) -> Iterable[Any]:
        return iterable


VIDEO_SUFFIXES = (".mp4", ".avi", ".mkv", ".mov", ".webm")
DEFAULT_API_KEY_ENVS = ("REALVIDEO_API_KEY", "OPENAI_API_KEY")
DEFAULT_BASE_URL_ENVS = ("REALVIDEO_BASE_URL", "OPENAI_BASE_URL")


PROMPT_TASK_1 = """Determine whether the given video is generated by modern AI-based generative models (AIGC).

Videos created using traditional computer graphics (CG), animation pipelines, game engines, or professional rendering tools should NOT be classified as AIGC, even though they are not captured from the real world. This includes stylized or animated content, as well as game footage.

Such videos may exhibit visual artifacts due to artistic design, rendering limitations, compression, or real-time graphics constraints. However, these artifacts are fundamentally different from those introduced by AI generative models and should NOT be used as evidence for AIGC classification.

Your judgment should be based on the presence of artifacts that are characteristic of AIGC methods, arising from the limitations of generative models.

Typical AIGC artifacts include, but are not limited to:
- temporal inconsistency (e.g., flickering, unstable details across frames),
- structural distortions (e.g., warped objects, inconsistent geometry),
- unnatural motion or dynamics,
- semantic incoherence (e.g., objects appearing/disappearing or morphing inconsistently),
- abnormal visual appearance or texture anomalies (e.g., overly smooth, painterly, or "oily" rendering).

Do NOT rely solely on visual style (e.g., animation, rendering style, or game graphics) when making your judgment. Instead, focus on identifying artifact patterns that are indicative of AI-based generation.

If such AIGC-specific artifacts are clearly present, classify the video as "yes". Otherwise, classify it as "no".

Respond with "yes" if the video is AIGC, and "no" otherwise."""


PROMPT_TASK_2 = """You are given two videos, <Video A> and <Video B>. Both videos are generated by modern AI-based generative models (AIGC).

Your task is to determine which video exhibits higher perceptual realism, i.e., which video contains fewer, less noticeable, or less severe artifacts introduced by generative models.

The comparison should be based on the presence and severity of AIGC-specific artifacts, rather than overall visual style or aesthetic preference.

Typical AIGC artifacts include, but are not limited to:
- temporal inconsistency (e.g., flickering, unstable details across frames),
- structural distortions (e.g., warped objects, inconsistent geometry),
- unnatural motion or dynamics,
- semantic incoherence (e.g., objects appearing/disappearing or morphing inconsistently),
- abnormal visual appearance or texture anomalies (e.g., overly smooth, painterly, or "oily" rendering).

When making your decision:
- Focus on the **severity, frequency, and perceptibility** of such artifacts.
- A video with fewer and less perceptible artifacts should be considered more realistic.
- Minor or barely noticeable artifacts are less important than severe or obvious ones.

Do NOT base your decision on:
- stylistic differences,
- resolution or sharpness alone,
- color grading or lighting preferences,
- high-level semantics or scene plausibility.

Do not be biased by video length, scene complexity, or content diversity.

Even if both videos contain artifacts, you must choose the one that is relatively more realistic.

Respond with:
- "<Video A>" if <Video A> is more realistic,
- "<Video B>" if <Video B> is more realistic."""


PROMPT_TASK_3 = """You are given a video that is generated by a modern AI-based generative model (AIGC).

For the following options, select all AIGC-specific artifacts that are clearly observable in the video.

Option:
{OPTION}

Respond using the corresponding letter(s), separated by commas if multiple are selected (e.g., "A", "B,D", "A,C,E")."""


PARSE_PROMPT_TASK_1 = """You are an answer extraction system.

The original task is to determine whether a video is generated by an AI-based generative model (AIGC):
- "yes" means the video is AI-generated.
- "no" means the video is not AI-generated.

You are given a model response that may contain lengthy reasoning, analysis, self-corrections, or <think>...</think> blocks.

Your task is to extract only the model's final intended answer.

Model Response:
{Response}

Rules:
1. Ignore all reasoning, explanations, and intermediate analysis.
2. Focus only on the final conclusion.
3. The only valid outputs are:
   - "yes"
   - "no"
4. Output exactly one valid answer without any additional text or explanation.
5. If the response does not contain a clear final answer indicating whether the video is AI-generated, output:
   "Invalid"
"""


PARSE_PROMPT_TASK_2 = """You are an answer extraction system.

The original task is to compare two AI-generated videos, <Video A> and <Video B>, and determine which video has higher perceptual realism, i.e., which video contains fewer or less severe AIGC-specific artifacts.

The only valid answers are:
- "<Video A>"
- "<Video B>"

You are given a model response that may contain lengthy reasoning, analysis, self-corrections, or <think>...</think> blocks.

Your task is to extract only the model's final intended answer.

Model Response:
{Response}

Rules:
1. Ignore all reasoning, explanations, and intermediate analysis.
2. Focus only on the final conclusion.
3. Output exactly one of the following:
   - "<Video A>"
   - "<Video B>"
4. Do not output any additional text or explanation.
5. If the response does not contain a clear final answer indicating which video is more realistic, output:
   "Invalid"
"""


PARSE_PROMPT_TASK_3 = """You are an answer extraction system.

The original task is to identify all AIGC-specific artifacts that are clearly observable in a given AI-generated video.

The candidate options are multiple-choice options labeled with letters (e.g., A-F). Multiple options may be correct.

You are given a model response that may contain lengthy reasoning, analysis, self-corrections, or <think>...</think> blocks.

Your task is to extract only the model's final intended answer.

Model Response:
{Response}

Rules:
1. Ignore all reasoning, explanations, and intermediate analysis.
2. Focus only on the final conclusion.
3. Extract only the selected option letters.
4. If multiple options are selected, output them separated by commas (e.g., "A,C,E").
5. Do not output any additional text or explanation.
6. Only output valid option letters that appear in the final answer.
7. If the response does not contain a clear final answer, output:
   "Invalid"
"""


PARSE_PROMPTS = {
    1: PARSE_PROMPT_TASK_1,
    2: PARSE_PROMPT_TASK_2,
    3: PARSE_PROMPT_TASK_3,
}


def ensure_parent(file_path: str | Path) -> None:
    parent = Path(file_path).expanduser().parent
    if str(parent) and str(parent) != ".":
        parent.mkdir(parents=True, exist_ok=True)


def load_json(file_path: str | Path) -> Any:
    with open(file_path, "r", encoding="utf-8") as file:
        return json.load(file)


def save_json(data: Any, file_path: str | Path) -> None:
    ensure_parent(file_path)
    with open(file_path, "w", encoding="utf-8") as file:
        json.dump(data, file, ensure_ascii=False, indent=4)


def load_jsonl(file_path: str | Path) -> List[Dict[str, Any]]:
    data = []
    with open(file_path, "r", encoding="utf-8") as file:
        for line_no, line in enumerate(file, start=1):
            line = line.strip()
            if not line:
                continue
            try:
                data.append(json.loads(line))
            except json.JSONDecodeError as exc:
                raise ValueError(f"Invalid JSONL at {file_path}:{line_no}") from exc
    return data


def save_jsonl(data: Sequence[Dict[str, Any]], file_path: str | Path) -> None:
    ensure_parent(file_path)
    with open(file_path, "w", encoding="utf-8") as file:
        for item in data:
            file.write(json.dumps(item, ensure_ascii=False) + "\n")


def append_jsonl(item: Dict[str, Any], file_path: str | Path) -> None:
    ensure_parent(file_path)
    with open(file_path, "a", encoding="utf-8") as file:
        file.write(json.dumps(item, ensure_ascii=False) + "\n")
        file.flush()


def list_video_files(video_dir: str | Path) -> List[Path]:
    video_dir = Path(video_dir)
    return sorted(
        path
        for path in video_dir.iterdir()
        if path.is_file() and path.suffix.lower() in VIDEO_SUFFIXES
    )


def public_path(path: str | Path, root: str | Path, use_absolute_paths: bool) -> str:
    path = Path(path)
    root = Path(root)
    if use_absolute_paths:
        return str(path.resolve())
    return path.relative_to(root).as_posix()


def build_task3_prompt(option: Optional[Sequence[str]] = None) -> str:
    if option is None:
        raise ValueError("Task 3 requires an 'option' list in each item.")
    option_str = "\n".join(f"{chr(65 + idx)}. {opt}" for idx, opt in enumerate(option))
    return PROMPT_TASK_3.format(OPTION=option_str)


def get_item_question(item: Dict[str, Any], default_task_type: Optional[int] = None) -> str:
    task_type = int(item.get("task_type", default_task_type))
    if task_type == 1:
        return PROMPT_TASK_1
    if task_type == 2:
        return PROMPT_TASK_2
    if task_type == 3:
        return build_task3_prompt(item.get("option"))
    raise ValueError(f"Unsupported task_type: {task_type}")


def get_item_video_paths(item: Dict[str, Any]) -> List[str]:
    if "video_path" in item:
        video_path = item["video_path"]
        if isinstance(video_path, (list, tuple)):
            return [str(path) for path in video_path]
        return [str(video_path)]

    candidate_key_pairs = [
        ("video_path_a", "video_path_b"),
        ("video_path_A", "video_path_B"),
        ("video_a_path", "video_b_path"),
        ("video_A_path", "video_B_path"),
        ("video_a", "video_b"),
        ("video_A", "video_B"),
        ("Video A", "Video B"),
    ]
    for key_a, key_b in candidate_key_pairs:
        if key_a in item and key_b in item:
            return [str(item[key_a]), str(item[key_b])]

    raise KeyError("Cannot find video path field(s) in item.")


def build_item_key(item: Dict[str, Any]) -> str:
    if "sample_id" in item:
        task_type = item.get("task_type")
        if task_type is not None:
            return f"task_{task_type}:sample_{item['sample_id']}"
        return f"sample_{item['sample_id']}"

    video_paths = get_item_video_paths(item)
    if len(video_paths) == 1:
        return video_paths[0]
    return json.dumps(video_paths, ensure_ascii=False)


def resolve_video_path(video_path: str, video_root: Optional[str | Path]) -> Path:
    path = Path(video_path).expanduser()
    if path.is_absolute():
        if not path.exists():
            raise FileNotFoundError(f"Video not found: {path}")
        return path

    candidates = []
    if video_root:
        candidates.append(Path(video_root).expanduser() / path)
    candidates.append(Path.cwd() / path)

    for candidate in candidates:
        if candidate.exists():
            return candidate
    raise FileNotFoundError(
        f"Video not found: {video_path}. Pass --video-root if paths are relative."
    )


def resolve_item_video_paths(
    item: Dict[str, Any],
    video_root: Optional[str | Path],
) -> List[Path]:
    return [resolve_video_path(path, video_root) for path in get_item_video_paths(item)]


def infer_answer_from_task1_filename(video_name: str) -> str:
    lower_name = video_name.lower()
    if "fake" in lower_name:
        return "yes"
    if "real" in lower_name:
        return "no"
    raise ValueError(
        f"Cannot infer Task 1 answer from filename '{video_name}'. "
        "Expected filename to contain 'fake' or 'real'."
    )


def replace_real_with_fake(video_name: str) -> str:
    if "real" in video_name:
        return video_name.replace("real", "fake", 1)
    if "Real" in video_name:
        return video_name.replace("Real", "Fake", 1)
    if "REAL" in video_name:
        return video_name.replace("REAL", "FAKE", 1)
    raise ValueError(f"Cannot derive fake filename from real filename: {video_name}")


def build_meta_for_task1(
    dataset_root: str | Path,
    output_dir: str | Path,
    use_absolute_paths: bool = False,
) -> List[Dict[str, Any]]:
    dataset_root = Path(dataset_root)
    video_dir = dataset_root / "Task_1" / "videos"
    data = []
    for sample_id, video_path in enumerate(list_video_files(video_dir), start=1):
        data.append(
            {
                "task_type": 1,
                "sample_id": sample_id,
                "video_path": [public_path(video_path, dataset_root, use_absolute_paths)],
                "answer": infer_answer_from_task1_filename(video_path.name),
                "level": None,
            }
        )
    save_jsonl(data, Path(output_dir) / "task1_meta.jsonl")
    return data


def build_meta_for_task2(
    dataset_root: str | Path,
    output_dir: str | Path,
    use_absolute_paths: bool = False,
) -> List[Dict[str, Any]]:
    dataset_root = Path(dataset_root)
    video_dir = dataset_root / "Task_2" / "videos"
    real_videos = [
        path for path in list_video_files(video_dir) if "real" in path.name.lower()
    ]

    data = []
    for sample_id, real_video_path in enumerate(real_videos, start=1):
        fake_video_path = video_dir / replace_real_with_fake(real_video_path.name)
        if not fake_video_path.exists():
            raise FileNotFoundError(f"Expected fake video not found: {fake_video_path}")

        real_path = public_path(real_video_path, dataset_root, use_absolute_paths)
        fake_path = public_path(fake_video_path, dataset_root, use_absolute_paths)
        if sample_id % 2 == 1:
            video_paths = [fake_path, real_path]
            answer = "<Video B>"
        else:
            video_paths = [real_path, fake_path]
            answer = "<Video A>"

        data.append(
            {
                "task_type": 2,
                "sample_id": sample_id,
                "video_path": video_paths,
                "answer": answer,
                "level": None,
            }
        )

    save_jsonl(data, Path(output_dir) / "task2_meta.jsonl")
    return data


def build_meta_for_task3(
    dataset_root: str | Path,
    output_dir: str | Path,
    use_absolute_paths: bool = False,
    seed: int = 42,
) -> List[Dict[str, Any]]:
    dataset_root = Path(dataset_root)
    video_dir = dataset_root / "Task_3" / "videos"
    question_json = dataset_root / "Task_3" / "task3_questions.json"
    question_data = load_json(question_json)
    rng = random.Random(seed)

    data = []
    for sample_id, qa_item in enumerate(question_data, start=1):
        video_name = Path(qa_item["video"][0]).name
        video_path = video_dir / video_name
        if not video_path.exists():
            raise FileNotFoundError(f"Expected video not found: {video_path}")

        shuffled_options = copy.deepcopy(qa_item["options"])
        rng.shuffle(shuffled_options)

        option_labels = []
        answer_idx = []
        answer_letter = []
        correct_labels = []
        for option_idx, option in enumerate(shuffled_options):
            option_labels.append(option["label"])
            if option["is_correct"] is True:
                answer_idx.append(option_idx)
                answer_letter.append(chr(65 + option_idx))
                correct_labels.append(option["label"])

        matched_answer_num = 0
        for expected_answer in qa_item["answer"]:
            if any(expected_answer in correct_label for correct_label in correct_labels):
                matched_answer_num += 1
            else:
                raise ValueError(
                    f"Answer '{expected_answer}' not found in options for sample_id {sample_id}"
                )
        if matched_answer_num != len(qa_item["answer"]):
            raise ValueError(
                f"Matched answer count ({matched_answer_num}) does not equal "
                f"expected ({len(qa_item['answer'])}) for sample_id {sample_id}"
            )

        data.append(
            {
                "task_type": 3,
                "sample_id": sample_id,
                "video_path": [public_path(video_path, dataset_root, use_absolute_paths)],
                "option": option_labels,
                "answer_idx": answer_idx,
                "answer_letter": answer_letter,
                "option_dic": copy.deepcopy(qa_item["options"]),
                "answer": ",".join(answer_letter),
                "level": None,
            }
        )

    save_jsonl(data, Path(output_dir) / "task3_meta.jsonl")
    return data


def add_level_info(dataset_root: str | Path, output_dir: str | Path) -> None:
    dataset_root = Path(dataset_root)
    output_dir = Path(output_dir)

    task1_meta = output_dir / "task1_meta.jsonl"
    task1_level_json = dataset_root / "Task_1" / "metadata.json"
    if task1_meta.exists() and task1_level_json.exists():
        task1_level_info = {}
        for item in load_json(task1_level_json):
            task1_level_info[item["real_filename"]] = item["real_rating"]
            task1_level_info[item["fake_filename"]] = item["fake_rating"]
        data = load_jsonl(task1_meta)
        for item in data:
            item["level"] = task1_level_info.get(Path(item["video_path"][0]).name)
        save_jsonl(data, task1_meta)

    task2_meta = output_dir / "task2_meta.jsonl"
    task2_level_json = dataset_root / "Task_2" / "metadata.json"
    if task2_meta.exists() and task2_level_json.exists():
        task2_level_info = {}
        for item in load_json(task2_level_json):
            task2_level_info[item["real_filename"]] = item["pair_rating"]
        data = load_jsonl(task2_meta)
        for item in data:
            real_video = next(
                path for path in item["video_path"] if "real" in Path(path).name.lower()
            )
            item["level"] = task2_level_info.get(Path(real_video).name)
        save_jsonl(data, task2_meta)

    task3_meta = output_dir / "task3_meta.jsonl"
    task3_level_json = dataset_root / "Task_3" / "metadata.json"
    if task3_meta.exists() and task3_level_json.exists():
        task3_level_info = {}
        for item in load_json(task3_level_json):
            task3_level_info[item["stable_identity"]["filename"]] = item["rating"]
        data = load_jsonl(task3_meta)
        for item in data:
            item["level"] = task3_level_info.get(Path(item["video_path"][0]).name)
        save_jsonl(data, task3_meta)


def build_meta_files(args: argparse.Namespace) -> None:
    if 1 in args.tasks:
        task1 = build_meta_for_task1(
            dataset_root=args.dataset_root,
            output_dir=args.output_dir,
            use_absolute_paths=args.absolute_video_paths,
        )
        print(f"Task 1 meta samples: {len(task1)}")
    if 2 in args.tasks:
        task2 = build_meta_for_task2(
            dataset_root=args.dataset_root,
            output_dir=args.output_dir,
            use_absolute_paths=args.absolute_video_paths,
        )
        print(f"Task 2 meta samples: {len(task2)}")
    if 3 in args.tasks:
        task3 = build_meta_for_task3(
            dataset_root=args.dataset_root,
            output_dir=args.output_dir,
            use_absolute_paths=args.absolute_video_paths,
            seed=args.seed,
        )
        print(f"Task 3 meta samples: {len(task3)}")
    if args.add_level:
        add_level_info(args.dataset_root, args.output_dir)
        print("Level info added when metadata.json files were available.")


def get_env_value(names: Sequence[str]) -> Optional[str]:
    for name in names:
        value = os.environ.get(name)
        if value:
            return value
    return None


class OpenAICompatibleClient:
    """Small wrapper around an OpenAI-compatible chat-completions endpoint."""

    def __init__(
        self,
        model: str,
        api_key: Optional[str] = None,
        base_url: Optional[str] = None,
        timeout: float = 300.0,
    ) -> None:
        self.model = model
        self.api_key = api_key or get_env_value(DEFAULT_API_KEY_ENVS)
        self.base_url = base_url or get_env_value(DEFAULT_BASE_URL_ENVS)
        self.timeout = timeout
        if not self.api_key:
            envs = " or ".join(DEFAULT_API_KEY_ENVS)
            raise ValueError(f"Missing API key. Set {envs}, or pass --api-key.")

        try:
            from openai import OpenAI
        except ImportError as exc:
            raise ImportError("Please install the OpenAI Python package: pip install openai") from exc

        kwargs = {"api_key": self.api_key, "timeout": self.timeout}
        if self.base_url:
            kwargs["base_url"] = self.base_url
        self.client = OpenAI(**kwargs)

    def generate(
        self,
        content: str | List[Dict[str, Any]],
        max_tokens: int,
        temperature: float,
        max_retries: int,
        retry_interval: float,
    ) -> str:
        messages = [{"role": "user", "content": content}]
        last_error = None
        for attempt in range(1, max_retries + 1):
            try:
                response = self.client.chat.completions.create(
                    model=self.model,
                    messages=messages,
                    temperature=temperature,
                    max_tokens=max_tokens,
                )
                return response.choices[0].message.content or ""
            except Exception as exc:  # noqa: BLE001
                last_error = exc
                if attempt == max_retries:
                    raise
                time.sleep(retry_interval * attempt)
        raise RuntimeError("API request failed") from last_error


def encode_jpeg_frame(frame: Any, max_image_side: int, jpeg_quality: int) -> str:
    try:
        import cv2
    except ImportError as exc:
        raise ImportError("Please install OpenCV for frame sampling: pip install opencv-python") from exc

    height, width = frame.shape[:2]
    if max_image_side > 0 and max(height, width) > max_image_side:
        scale = max_image_side / max(height, width)
        new_size = (max(1, int(width * scale)), max(1, int(height * scale)))
        frame = cv2.resize(frame, new_size, interpolation=cv2.INTER_AREA)

    ok, buffer = cv2.imencode(
        ".jpg",
        frame,
        [int(cv2.IMWRITE_JPEG_QUALITY), int(jpeg_quality)],
    )
    if not ok:
        raise RuntimeError("Failed to encode sampled video frame as JPEG.")
    encoded = base64.b64encode(buffer.tobytes()).decode("utf-8")
    return f"data:image/jpeg;base64,{encoded}"


def sample_video_frames_as_data_urls(
    video_path: str | Path,
    fps: float,
    max_frames: int,
    max_image_side: int,
    jpeg_quality: int,
) -> List[str]:
    try:
        import cv2
    except ImportError as exc:
        raise ImportError("Please install OpenCV for frame sampling: pip install opencv-python") from exc

    video_path = Path(video_path)
    cap = cv2.VideoCapture(str(video_path))
    if not cap.isOpened():
        raise RuntimeError(f"Failed to open video: {video_path}")

    native_fps = cap.get(cv2.CAP_PROP_FPS) or fps or 1.0
    frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0)

    frame_indices = []
    if frame_count > 0:
        duration = frame_count / max(native_fps, 1e-6)
        target_count = max(1, int(round(duration * fps))) if fps > 0 else frame_count
        if max_frames > 0:
            target_count = min(target_count, max_frames)
        if target_count == 1:
            frame_indices = [0]
        else:
            step = max(frame_count - 1, 1) / float(target_count - 1)
            frame_indices = [min(frame_count - 1, int(round(idx * step))) for idx in range(target_count)]
    else:
        step = max(1, int(round(native_fps / fps))) if fps > 0 else 1
        idx = 0
        while True:
            ok, _ = cap.read()
            if not ok:
                break
            if idx % step == 0:
                frame_indices.append(idx)
                if max_frames > 0 and len(frame_indices) >= max_frames:
                    break
            idx += 1

    data_urls = []
    for frame_idx in frame_indices:
        cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx)
        ok, frame = cap.read()
        if not ok:
            continue
        data_urls.append(encode_jpeg_frame(frame, max_image_side, jpeg_quality))
    cap.release()

    if not data_urls:
        raise RuntimeError(f"No frames sampled from video: {video_path}")
    return data_urls


def image_part(data_url: str, image_detail: str) -> Dict[str, Any]:
    part = {"type": "image_url", "image_url": {"url": data_url}}
    if image_detail:
        part["image_url"]["detail"] = image_detail
    return part


def build_vision_content(
    item: Dict[str, Any],
    video_paths: Sequence[Path],
    task_type: int,
    fps: float,
    max_frames: int,
    max_image_side: int,
    jpeg_quality: int,
    image_detail: str,
) -> List[Dict[str, Any]]:
    question = get_item_question(item, default_task_type=task_type)
    frame_groups = [
        sample_video_frames_as_data_urls(
            video_path=video_path,
            fps=fps,
            max_frames=max_frames,
            max_image_side=max_image_side,
            jpeg_quality=jpeg_quality,
        )
        for video_path in video_paths
    ]

    parts: List[Dict[str, Any]] = []
    if task_type == 1:
        for data_url in frame_groups[0]:
            parts.append(image_part(data_url, image_detail))
        parts.append({"type": "text", "text": question})
        return parts

    if task_type == 2:
        if len(frame_groups) != 2:
            raise ValueError(f"Task 2 expects exactly two videos, got {len(frame_groups)}.")
        parts.append({"type": "text", "text": "Video A:\n"})
        for data_url in frame_groups[0]:
            parts.append(image_part(data_url, image_detail))
        parts.append({"type": "text", "text": "\nVideo B:\n"})
        for data_url in frame_groups[1]:
            parts.append(image_part(data_url, image_detail))
        parts.append({"type": "text", "text": f"\n{question}"})
        return parts

    if task_type == 3:
        for data_url in frame_groups[0]:
            parts.append(image_part(data_url, image_detail))
        parts.append({"type": "text", "text": question})
        return parts

    raise ValueError(f"Unsupported task_type: {task_type}")


def load_completed_results(output_file: str | Path) -> Dict[str, Dict[str, Any]]:
    if not Path(output_file).exists():
        return {}
    completed = {}
    for item in load_jsonl(output_file):
        completed[build_item_key(item)] = item
    return completed


def infer_one_item(
    item: Dict[str, Any],
    task_type: int,
    video_root: Optional[str | Path],
    client: OpenAICompatibleClient,
    args: argparse.Namespace,
) -> Dict[str, Any]:
    result_item = dict(item)
    item_task_type = int(item.get("task_type", task_type))
    try:
        video_paths = resolve_item_video_paths(item, video_root)
        content = build_vision_content(
            item=item,
            video_paths=video_paths,
            task_type=item_task_type,
            fps=args.fps,
            max_frames=args.max_frames,
            max_image_side=args.max_image_side,
            jpeg_quality=args.jpeg_quality,
            image_detail=args.image_detail,
        )
        response = client.generate(
            content=content,
            max_tokens=args.max_tokens,
            temperature=args.temperature,
            max_retries=args.max_retries,
            retry_interval=args.retry_interval,
        )
        result_item["model_response"] = response
    except Exception:  # noqa: BLE001
        result_item["model_response"] = None
        result_item["infer_error"] = traceback.format_exc()

    result_item["eval_info"] = {
        "model": args.model,
        "fps": args.fps,
        "max_frames": args.max_frames,
        "max_image_side": args.max_image_side,
        "temperature": args.temperature,
    }
    return result_item


def run_inference(args: argparse.Namespace) -> None:
    data = load_jsonl(args.task_file)
    completed = load_completed_results(args.output)
    pending = [item for item in data if build_item_key(item) not in completed]

    if not pending:
        print(f"All samples already completed in {args.output}.")
        return

    client = OpenAICompatibleClient(
        model=args.model,
        api_key=args.api_key,
        base_url=args.base_url,
        timeout=args.timeout,
    )
    write_lock = threading.Lock()

    workers = max(1, min(args.workers, len(pending)))
    with ThreadPoolExecutor(max_workers=workers) as executor:
        futures = [
            executor.submit(infer_one_item, item, args.task_type, args.video_root, client, args)
            for item in pending
        ]
        for future in tqdm(as_completed(futures), total=len(futures), desc="Calling API"):
            result_item = future.result()
            with write_lock:
                append_jsonl(result_item, args.output)

    print(
        f"Finish inference. skipped={len(completed)}, newly_processed={len(pending)}, "
        f"output={args.output}"
    )


def strip_think_blocks(text: str) -> str:
    return re.sub(r"<think>.*?</think>", "", text, flags=re.IGNORECASE | re.DOTALL)


def normalize_task1_answer(text: str) -> str:
    if not text:
        return "Invalid"
    text = strip_think_blocks(text).strip()
    if text.lower() == "invalid":
        return "Invalid"
    matches = re.findall(r"\b(yes|no)\b", text, flags=re.IGNORECASE)
    if not matches:
        return "Invalid"
    return matches[-1].lower()


def normalize_task2_answer(text: str) -> str:
    if not text:
        return "Invalid"
    text = strip_think_blocks(text).strip()
    if text.lower() == "invalid":
        return "Invalid"
    matches = list(
        re.finditer(r"<\s*Video\s*([AB])\s*>|\bVideo\s*([AB])\b", text, flags=re.IGNORECASE)
    )
    if not matches:
        return "Invalid"
    letter = (matches[-1].group(1) or matches[-1].group(2)).upper()
    return f"<Video {letter}>"


def normalize_letters(text: str) -> str:
    if not text:
        return "Invalid"
    text = strip_think_blocks(text).strip()
    if text.lower() == "invalid":
        return "Invalid"
    letters = re.findall(r"[A-Z]", text.upper())
    if not letters:
        return "Invalid"
    deduped = []
    for letter in letters:
        if letter not in deduped:
            deduped.append(letter)
    return ",".join(deduped)


def parse_task3_locally(text: str) -> str:
    if not text:
        return "Invalid"
    cleaned = strip_think_blocks(text).strip()
    if cleaned.lower() == "invalid":
        return "Invalid"

    lines = [line.strip() for line in cleaned.splitlines() if line.strip()]
    for line in reversed(lines[-8:]):
        exact = re.fullmatch(r"[A-Z](?:\s*,\s*[A-Z])*\s*\.?", line.upper())
        if exact:
            return normalize_letters(line.rstrip("."))
        keyword = re.search(
            r"(?:final answer|answer|selected options?|therefore)\s*[:\-]?\s*"
            r"([A-Z](?:\s*,\s*[A-Z])*)",
            line,
            flags=re.IGNORECASE,
        )
        if keyword:
            return normalize_letters(keyword.group(1))
    return "Invalid"


def parse_response_locally(task_type: int, response: str) -> str:
    if task_type == 1:
        return normalize_task1_answer(response)
    if task_type == 2:
        return normalize_task2_answer(response)
    if task_type == 3:
        return parse_task3_locally(response)
    raise ValueError(f"Unsupported task_type: {task_type}")


def parse_response_with_api(
    task_type: int,
    response: str,
    client: OpenAICompatibleClient,
    args: argparse.Namespace,
) -> str:
    prompt = PARSE_PROMPTS[task_type].format(Response=response or "")
    parse_response = client.generate(
        content=prompt,
        max_tokens=args.parse_max_tokens,
        temperature=args.parse_temperature,
        max_retries=args.max_retries,
        retry_interval=args.retry_interval,
    )
    if task_type == 1:
        return normalize_task1_answer(parse_response)
    if task_type == 2:
        return normalize_task2_answer(parse_response)
    if task_type == 3:
        return parse_task3_locally(parse_response)
    raise ValueError(f"Unsupported task_type: {task_type}")


def clean_inference_data(data: Sequence[Dict[str, Any]]) -> List[Dict[str, Any]]:
    cleaned = []
    seen = set()
    for item in data:
        if item.get("infer_error") or not item.get("model_response"):
            continue
        key = build_item_key(item)
        if key in seen:
            continue
        seen.add(key)
        cleaned.append(item)
    return cleaned


def parse_results(args: argparse.Namespace) -> None:
    data = clean_inference_data(load_jsonl(args.input))
    client = None
    if args.parser == "api":
        parser_model = args.parse_model or args.model
        if not parser_model:
            raise ValueError("Pass --model or --parse-model when using --parser api.")
        client = OpenAICompatibleClient(
            model=parser_model,
            api_key=args.api_key,
            base_url=args.base_url,
            timeout=args.timeout,
        )

    parsed_data = []
    for item in tqdm(data, desc="Parsing"):
        new_item = dict(item)
        try:
            if args.parser == "api":
                assert client is not None
                new_item["parse_response"] = parse_response_with_api(
                    task_type=args.task_type,
                    response=item.get("model_response", ""),
                    client=client,
                    args=args,
                )
            else:
                new_item["parse_response"] = parse_response_locally(
                    args.task_type,
                    item.get("model_response", ""),
                )
        except Exception:  # noqa: BLE001
            new_item["parse_response"] = "Parse Error"
            new_item["parse_error"] = traceback.format_exc()
        parsed_data.append(new_item)

    save_jsonl(parsed_data, args.output)
    print(f"Finish parsing. input={args.input}, output={args.output}, samples={len(parsed_data)}")


def answer_letter_set(text: str) -> set[str]:
    if not text or text.lower().startswith("invalid"):
        return set()
    return set(re.findall(r"[A-Z]", text.upper()))


def is_correct_answer(item: Dict[str, Any], task_type: int) -> bool:
    pred = item.get("parse_response", "")
    answer = item.get("answer", "")
    if task_type == 1:
        return normalize_task1_answer(pred) == answer.lower()
    if task_type == 2:
        return normalize_task2_answer(pred).lower() == answer.lower()
    if task_type == 3:
        return answer_letter_set(pred) == answer_letter_set(answer)
    raise ValueError(f"Unsupported task_type: {task_type}")


def load_level_info(
    meta_file: Optional[str | Path],
    parsed_data: Sequence[Dict[str, Any]],
) -> Tuple[Dict[str, Any], Dict[str, int]]:
    source_data = load_jsonl(meta_file) if meta_file else list(parsed_data)
    level_by_sample_id = {}
    actual_level_total: Dict[str, int] = {}
    for item in source_data:
        level = item.get("level", "unknown") or "unknown"
        sample_id = str(item["sample_id"])
        level_by_sample_id[sample_id] = level
        actual_level_total[level] = actual_level_total.get(level, 0) + 1
    return level_by_sample_id, actual_level_total


def get_level_stats(
    data: Sequence[Dict[str, Any]],
    task_type: int,
    level_by_sample_id: Dict[str, Any],
    actual_level_total: Dict[str, int],
) -> Dict[str, Dict[str, Any]]:
    level_stats = {
        level: {"correct_num": 0, "total": 0, "actual_total": actual_total}
        for level, actual_total in actual_level_total.items()
    }

    for item in data:
        sample_id = str(item["sample_id"])
        level = item.get("level") or level_by_sample_id.get(sample_id, "unknown")
        if level not in level_stats:
            level_stats[level] = {"correct_num": 0, "total": 0, "actual_total": 0}
        level_stats[level]["total"] += 1
        if is_correct_answer(item, task_type):
            level_stats[level]["correct_num"] += 1

    for level_result in level_stats.values():
        total = level_result["total"]
        level_result["accuracy"] = level_result["correct_num"] / total if total > 0 else 0.0
    return level_stats


def print_accuracy_table(
    input_file: str | Path,
    task_type: int,
    result: Dict[str, Any],
    actual_level_total: Dict[str, int],
) -> None:
    model_name = Path(input_file).stem
    level_names = list(actual_level_total.keys()) or ["unknown"]
    model_name_width = max(len("Model"), len(model_name))
    level_width = max(len("Level"), len("all"), *(len(str(level)) for level in level_names))
    table_width = model_name_width + level_width + 61

    print(f"\n{'=' * table_width}")
    print(f"Task: task_{task_type}")
    print(f"{'-' * table_width}")
    print(
        f"{'Model':<{model_name_width}}  {'Level':<{level_width}}  "
        f"{'Accuracy':>10}  {'Correct':>10}  {'Total':>6}  {'Actual Total':>12}"
    )
    print(f"{'-' * table_width}")
    print(
        f"{model_name:<{model_name_width}}  {'all':<{level_width}}  "
        f"{result['accuracy'] * 100:>9.2f}%  {result['correct_num']:>10}  "
        f"{result['total']:>6}  {result['actual_total']:>12}"
    )
    for level, level_result in result["level_stats"].items():
        print(
            f"{'':<{model_name_width}}  {level:<{level_width}}  "
            f"{level_result['accuracy'] * 100:>9.2f}%  "
            f"{level_result['correct_num']:>10}  {level_result['total']:>6}  "
            f"{level_result['actual_total']:>12}"
        )
    print(f"{'=' * table_width}\n")


def calculate_accuracy(args: argparse.Namespace) -> Dict[str, Any]:
    data = load_jsonl(args.input)
    level_by_sample_id, actual_level_total = load_level_info(args.meta_file, data)
    total = len(data)
    correct = sum(1 for item in data if is_correct_answer(item, args.task_type))
    result = {
        "accuracy": correct / total if total > 0 else 0.0,
        "total": total,
        "correct_num": correct,
        "actual_total": len(level_by_sample_id),
        "level_stats": get_level_stats(
            data=data,
            task_type=args.task_type,
            level_by_sample_id=level_by_sample_id,
            actual_level_total=actual_level_total,
        ),
    }
    output = args.output or str(Path(args.input).with_name("accuracy.json"))
    save_json({Path(args.input).stem: result}, output)
    print_accuracy_table(args.input, args.task_type, result, actual_level_total)
    print(f"Accuracy saved to {output}")
    return result


def run_eval_task(args: argparse.Namespace) -> None:
    run_inference(args)
    parse_args = argparse.Namespace(**vars(args))
    parse_args.input = args.output
    parse_args.output = args.parsed_output
    parse_results(parse_args)
    accuracy_args = argparse.Namespace(
        input=args.parsed_output,
        task_type=args.task_type,
        meta_file=args.meta_file or args.task_file,
        output=args.accuracy_output,
    )
    calculate_accuracy(accuracy_args)


def add_api_args(parser: argparse.ArgumentParser) -> None:
    parser.add_argument("--api-key", default=None, help="API key. Defaults to REALVIDEO_API_KEY or OPENAI_API_KEY.")
    parser.add_argument("--base-url", default=None, help="OpenAI-compatible base URL. Defaults to REALVIDEO_BASE_URL or OPENAI_BASE_URL.")
    parser.add_argument("--model", default=None, help="Model name for inference or parsing.")
    parser.add_argument("--timeout", type=float, default=300.0)
    parser.add_argument("--max-retries", type=int, default=5)
    parser.add_argument("--retry-interval", type=float, default=2.0)


def add_infer_args(parser: argparse.ArgumentParser) -> None:
    add_api_args(parser)
    parser.add_argument("--task-file", required=True)
    parser.add_argument("--task-type", type=int, choices=[1, 2, 3], required=True)
    parser.add_argument("--video-root", default=None, help="Root used to resolve relative video paths.")
    parser.add_argument("--output", required=True)
    parser.add_argument("--fps", type=float, default=5.0)
    parser.add_argument("--max-frames", type=int, default=64)
    parser.add_argument("--max-image-side", type=int, default=1024)
    parser.add_argument("--jpeg-quality", type=int, default=90)
    parser.add_argument("--image-detail", default="high", choices=["low", "high", "auto", ""])
    parser.add_argument("--workers", type=int, default=4)
    parser.add_argument("--temperature", type=float, default=0.0)
    parser.add_argument("--max-tokens", type=int, default=8192)


def add_parse_args(parser: argparse.ArgumentParser) -> None:
    add_api_args(parser)
    parser.add_argument("--input", required=True)
    parser.add_argument("--task-type", type=int, choices=[1, 2, 3], required=True)
    parser.add_argument("--output", required=True)
    parser.add_argument("--parser", choices=["api", "local"], default="api")
    parser.add_argument("--parse-model", default=None, help="Optional model for API-based parsing. Defaults to --model.")
    parser.add_argument("--parse-temperature", type=float, default=0.0)
    parser.add_argument("--parse-max-tokens", type=int, default=64)


def build_arg_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="Public RealVideo-Bench eval script.")
    subparsers = parser.add_subparsers(dest="command", required=True)

    build_meta_parser = subparsers.add_parser("build-meta", help="Build task meta jsonl files.")
    build_meta_parser.add_argument("--dataset-root", required=True)
    build_meta_parser.add_argument("--output-dir", default="task")
    build_meta_parser.add_argument("--tasks", type=int, nargs="+", choices=[1, 2, 3], default=[1, 2, 3])
    build_meta_parser.add_argument("--seed", type=int, default=42)
    build_meta_parser.add_argument("--absolute-video-paths", action="store_true")
    build_meta_parser.add_argument("--no-add-level", dest="add_level", action="store_false")
    build_meta_parser.set_defaults(add_level=True, func=build_meta_files)

    infer_parser = subparsers.add_parser("infer", help="Run model inference.")
    add_infer_args(infer_parser)
    infer_parser.set_defaults(func=run_inference)

    parse_parser = subparsers.add_parser("parse", help="Parse raw model responses.")
    add_parse_args(parse_parser)
    parse_parser.set_defaults(func=parse_results)

    accuracy_parser = subparsers.add_parser("accuracy", help="Calculate accuracy.")
    accuracy_parser.add_argument("--input", required=True)
    accuracy_parser.add_argument("--task-type", type=int, choices=[1, 2, 3], required=True)
    accuracy_parser.add_argument("--meta-file", default=None)
    accuracy_parser.add_argument("--output", default=None)
    accuracy_parser.set_defaults(func=calculate_accuracy)

    eval_parser = subparsers.add_parser("eval-task", help="Run inference, parsing, and accuracy for one task.")
    add_infer_args(eval_parser)
    eval_parser.add_argument("--parser", choices=["api", "local"], default="api")
    eval_parser.add_argument("--parse-model", default=None)
    eval_parser.add_argument("--parse-temperature", type=float, default=0.0)
    eval_parser.add_argument("--parse-max-tokens", type=int, default=64)
    eval_parser.add_argument("--parsed-output", required=True)
    eval_parser.add_argument("--accuracy-output", default=None)
    eval_parser.add_argument("--meta-file", default=None)
    eval_parser.set_defaults(func=run_eval_task)

    return parser


def main() -> None:
    parser = build_arg_parser()
    args = parser.parse_args()
    if hasattr(args, "model") and not args.model and args.command in {"infer", "eval-task"}:
        parser.error("--model is required for inference.")
    args.func(args)


if __name__ == "__main__":
    main()