File size: 32,165 Bytes
e39a6b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f02d8a
 
 
 
 
 
 
 
 
 
e39a6b5
 
7f02d8a
 
e39a6b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f02d8a
 
 
 
e39a6b5
 
 
 
7f02d8a
 
 
 
 
 
 
 
 
 
 
 
e39a6b5
 
 
 
7f02d8a
 
 
 
e39a6b5
 
 
 
 
 
 
 
 
 
 
 
 
 
7f02d8a
 
e39a6b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Builds the public part of the vision benchmark (photo / ocr / video) from the published datasets, reproducibly.

Most people never run this: they fetch the finished images and clips with get_data.py. This is how the question sets
in photo/sets, ocr/sets, video/sets and the files in the release were made, so anyone can check or redo it.

    python3 -I vision/fetch.py download --raw <folder>            # the source files, at pinned revisions (~2.5 GB)
    python3 -I vision/fetch.py build --raw <that folder>          # picks the questions, writes sets/ and <cache>/vision/
    python3 -I vision/get_data.py vision --pack <folder>          # then the tar for the release vision-data-v1

Needs (not the standard library; a virtual environment of your own): huggingface_hub, pyarrow. And ffmpeg for video.
Videos are read member by member out of the published zips with HTTP range requests (rzip.py), so the 100 GB of
Video-MME and the 17 GB of MVBench are never downloaded whole.

The downloaded files are data, never run. Every random choice comes from SEED, so the same sources give the same
picks. Images keep their published bytes (no re-encoding: OCR needs every pixel); videos are re-encoded to at most
480 px high, H.264, without sound, to keep the release small; so only Video-MME's perception questions are kept
(what is seen, counted, read), not the reasoning and synopsis ones that often hang on the narration.
"""
from __future__ import annotations

import argparse
import base64
import collections
import csv
import hashlib
import json
import os
import random
import re
import subprocess
import sys
import tempfile

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import rzip  # noqa: E402

SEED = 20261124
CACHE = os.path.abspath(os.path.expanduser(os.environ.get("LUOKE_BENCH_CACHE") or "~/.cache/luoke-bench"))
OUT = os.path.join(CACHE, "vision")

HF = {
    "lmms-lab/MMBench_CN": ("78601bcca41a57248c05f130d9902db624aa6f4d", [
        "data/dev-00000-of-00001-d459e48a71003d0c.parquet",
        "chinese_culture/test-00000-of-00001-74dfcafe06897a0b.parquet"]),
    "lmms-lab/HallusionBench": ("cd417161857aefb23d878d42cf1bb53aa9dd646f", ["data/image-00000-of-00001.parquet"]),
    "lmms-lab/POPE": ("4db1276663dfa5eb8ad16a52d24c31a09e470896", [
        "Full/adversarial-00000-of-00001.parquet", "Full/popular-00000-of-00001.parquet",
        "Full/random-00000-of-00001.parquet"]),
    "wulipc/CC-OCR": ("c64517e92179991d509776064174776700cdd5a2", [
        "LICENSE", "multi_scene_ocr/document_text/zh_doc_100.tsv",
        "multi_scene_ocr/document_text/zh_handwriting_50.tsv", "multi_scene_ocr/scene_text/zh_scene_450.tsv",
        "multi_scene_ocr/ugc_text/zh_dense_50.tsv", "multi_scene_ocr/ugc_text/zh_vertical_100.tsv",
        "kie/constrained_category/EPHOIE_SCUT_311.tsv", "kie/open_category/COLD_CELL_600.tsv",
        "doc_parsing/doc/doc_photo_chn_75.tsv", "doc_parsing/doc/doc_scan_chn_75.tsv"]),
    "ling99/OCRBench_v2": ("c7e7cdf23bdb6774661e9b0caf0d9935a42feb8b", [
        "data/test-00000-of-00003.parquet", "data/test-00001-of-00003.parquet", "data/test-00002-of-00003.parquet"]),
    "mteb/XM3600T2IRetrieval": ("963e5fcdc6b2f222360cec3df3869cc9b8343cb0", ["zh-corpus/test-00000-of-00001.parquet"]),
    "OpenGVLab/MVBench": ("230a2d4fac8900333c61754641c7a13e069ac9c6", []),   # json/<task>.json, filled below
    "lmms-lab/Video-MME": ("ead1408f75b618502df9a1d8e0950166bf0a2a0b", ["videomme/test-00000-of-00001.parquet"]),
    "Uni-MoE/VideoVista-CulturalLingo": ("7f4632a7b0d5aacd4a8af3982cc5fd4ad4b5cc15", ["VideoVista-CulturalLingo.json", "README.md"]),
}
MVB_TASKS = {   # MVBench task -> (zip under video/, folder prefix inside the zip, how many we take); 2 each, 20
    "action_sequence": ("star.zip", "star/Charades_v1_480/", 2),
    "action_prediction": ("star.zip", "star/Charades_v1_480/", 2),
    "object_interaction": ("star.zip", "star/Charades_v1_480/", 2),
    "action_antonym": ("ssv2_video.zip", "ssv2_video/", 2),
    "fine_grained_action": ("Moments_in_Time_Raw.zip", "Moments_in_Time_Raw/videos/", 2),
    "scene_transition": ("scene_qa.zip", "scene_qa/video/", 2),
    "action_count": ("perception.zip", "perception/videos/", 2),
    "object_shuffle": ("perception.zip", "perception/videos/", 2),
    "state_change": ("perception.zip", "perception/videos/", 2),
    "unexpected_action": ("FunQA_test.zip", "FunQA_test/test/", 2),
}
HF["OpenGVLab/MVBench"][1].extend(f"json/{t}.json" for t in MVB_TASKS)


def hf_url(repo, path):
    return f"https://huggingface.co/datasets/{repo}/resolve/{HF[repo][0]}/{path}"


def raw_path(raw, repo, path):
    return os.path.join(raw, repo.replace("/", "__"), path)


def download(raw):
    from huggingface_hub import hf_hub_download
    for repo, (rev, files) in HF.items():
        for f in files:
            if not os.path.exists(raw_path(raw, repo, f)):
                hf_hub_download(repo, f, repo_type="dataset", revision=rev, local_dir=os.path.join(raw, repo.replace("/", "__")))
            print(repo, f, flush=True)


# ------------------------------------------------------------------------------------------------ helpers

def parquet_rows(path, columns=None):
    import pyarrow.parquet as pq
    return pq.read_table(path, columns=columns).to_pylist()


def tsv_rows(path):
    csv.field_size_limit(10 ** 9)
    with open(path, encoding="utf-8", newline="") as fh:
        reader = csv.reader(fh, delimiter="\t")
        head = next(reader)
        for row in reader:
            yield dict(zip(head, row))


def ext_of(data):
    if data[:8] == b"\x89PNG\r\n\x1a\n":
        return ".png"
    if data[:3] == b"\xff\xd8\xff":
        return ".jpg"
    if data[:4] == b"RIFF" and data[8:12] == b"WEBP":
        return ".webp"
    if data[:3] == b"GIF":
        return ".gif"
    raise ValueError("unknown image type")


def save_image(data, name):
    os.makedirs(os.path.join(OUT, "img"), exist_ok=True)
    fname = name + ext_of(data)
    with open(os.path.join(OUT, "img", fname), "wb") as fh:
        fh.write(data)
    return fname


def img_bytes(v):
    return v["bytes"] if isinstance(v, dict) else v


def sha(data):
    return hashlib.sha256(data).hexdigest()


# Questions drawn as before but not written: the key can't be told from what the model is shown. Their ids stay taken,
# so the other questions keep theirs.
RETIRED = {
    "mvbench.jsonl": {"mvb009": "口红那段,「putting」和答案「placing」一样说得通(答案只是 Moments in Time 的类名)",
                      "mvb017": "壶往茶包上倒水,画面看不出水是凉的(Perception Test 的答案是 cold)"},
    "videovista_zh.jsonl": {"vvc007": "麻将馆的介绍,答案「看到摆宝特饮的牌子并讨论」从视频里推不出来",
                            "vvc016": "4 分钟的口播,牌子只在说话和一闪而过的字幕里,16 帧里看不出先后"},
}


def write_set(path, rows):
    os.makedirs(os.path.dirname(path), exist_ok=True)
    gone = RETIRED.get(os.path.basename(path), {})
    rows = [r for r in rows if r["id"] not in gone]
    with open(path, "w", encoding="utf-8") as fh:
        for r in rows:
            fh.write(json.dumps(r, ensure_ascii=False) + "\n")
    print(f"{len(rows):4d}  {os.path.relpath(path, HERE)}")


def stratified(rng, groups, per, total=None):
    """groups: key -> list. `per`: dict key -> count or an int for every key. Order of keys sorted, items shuffled."""
    out = []
    for k in sorted(groups):
        items = list(groups[k])
        rng.shuffle(items)
        n = per[k] if isinstance(per, dict) else per
        out += items[:n]
    return out[:total] if total else out


def opts(r):
    return [r[k] for k in "ABCD" if r.get(k) not in (None, "", "nan")]


# ------------------------------------------------------------------------------------------------ photo

MMB_CATS = ["image_scene", "object_localization", "attribute_recognition", "action_recognition", "image_emotion",
            "spatial_relationship", "attribute_comparison", "image_topic", "future_prediction", "physical_relation",
            "social_relation", "function_reasoning", "image_quality", "image_style"]
MMB_SKIP_SOURCES = {"scienceqa"}
CCB_CATS = ["food_clothes", "scenery_building", "cultural_relic", "traditional_show", "calligraphy_painting"]


def unique_mc(rows):
    """MMBench's published rows repeat each question with its options rotated (CircularEval). One copy per question:
    the one whose answer is the earliest letter; the runner does the rotating itself."""
    by = {}
    for r in rows:
        o = opts(r)
        key = (r["question"], r.get("hint") or "", tuple(sorted(o)), sha(img_bytes(r["image"])))
        ans = o["ABCD".index(r["answer"])] if r["answer"] in "ABCD" else None
        if ans is None:
            continue
        cand = dict(r, _options=o, _answer=ans)
        if key not in by or r["answer"] < by[key]["answer"]:
            by[key] = cand
    return list(by.values())


WEB_PHOTO = ("mmbench_cn", "ccbench", "hallusion")   # pictures from the web: still drawn (so the others' picks stay the same) but
                                                     # not written unless asked; they are never published


COCO_ANN = "http://images.cocodataset.org/annotations/annotations_trainval2014.zip"   # instances_val2014.json in it
COCO_FREE = {4: "CC BY 2.0", 5: "CC BY-SA 2.0", 7: "No known copyright restrictions (Flickr Commons)"}


def coco_index(raw):
    """From the official COCO val2014 annotations (COCO_ANN, unzipped under <raw>/coco/annotations/): image ->
    (license id, Flickr url), and image -> the object classes annotated in it. COCO does not own the pictures: each
    keeps its Flickr license."""
    path = os.path.join(raw, "coco", "annotations", "instances_val2014.json")
    if not os.path.exists(path):
        sys.exit(f"need {path}: download {COCO_ANN} and unzip annotations/instances_val2014.json there")
    d = json.load(open(path, encoding="utf-8"))
    stem = {i["id"]: i["file_name"].rsplit(".", 1)[0] for i in d["images"]}
    cat = {c["id"]: c["name"] for c in d["categories"]}
    objects = {}
    for a in d["annotations"]:
        objects.setdefault(stem[a["image_id"]], set()).add(cat[a["category_id"]])
    lic = {i["file_name"].rsplit(".", 1)[0]: (i["license"], i.get("flickr_url") or "") for i in d["images"]}
    return lic, objects


# POPE "yes" questions whose object is in COCO's boxes but not what a person would call it: the "tv" is a computer
# monitor; the "dining table" box is the whole frame, a plate on cloth with no table to see
POPE_UNCLEAR = {"COCO_val2014_000000141278", "COCO_val2014_000000379404"}


def build_pope(raw, rng):
    """POPE asked in Chinese: 5 yes and 5 no from each of random / popular / adversarial, only on pictures whose
    Flickr license lets them be passed on (COCO_FREE); each picture's license and source go to pope_attribution.json.
    A "yes" is kept only when COCO annotates that object in the picture (some POPE keys name an object COCO has no box
    for), and not on the pictures in POPE_UNCLEAR."""
    lic, objects = coco_index(raw)
    sets, used, credits = [], set(), []
    for split in ("random", "popular", "adversarial"):
        rows = parquet_rows(raw_path(raw, "lmms-lab/POPE", f"Full/{split}-00000-of-00001.parquet"))
        rng.shuffle(rows)
        for want in ("yes", "no"):
            k = 0
            for r in rows:
                m = re.match(r"Is there an? (.+) in the image\?", r["question"])
                if not m:
                    continue
                obj = m.group(1)
                l_id, url = lic.get(r["image_source"], (None, ""))
                if r["answer"] != want or r["image_source"] in used or obj not in COCO_ZH or l_id not in COCO_FREE:
                    continue
                if want == "yes" and (obj not in objects.get(r["image_source"], ()) or r["image_source"] in POPE_UNCLEAR):
                    continue
                used.add(r["image_source"])
                qid = f"pope{len(sets) + 1:03d}"
                fname = save_image(img_bytes(r["image"]), qid)
                sets.append({"id": qid, "image": fname,
                             "q": f"这张照片里有{COCO_ZH[obj]}吗?", "object": obj, "answer": want, "category": split,
                             "source": {"set": "POPE", "split": split, "question_id": r["question_id"],
                                        "image": r["image_source"]}})
                credits.append({"image": fname, "coco": r["image_source"], "license": COCO_FREE[l_id], "flickr": url})
                k += 1
                if k == 5:
                    break
    with open(os.path.join(HERE, "photo", "pope_attribution.json"), "w", encoding="utf-8") as fh:
        json.dump(credits, fh, ensure_ascii=False, indent=1)
    return sets


def build_photo(raw, rng, keep=("pope",)):
    out = {}
    # MMBench-CN dev
    rows = parquet_rows(raw_path(raw, "lmms-lab/MMBench_CN", HF["lmms-lab/MMBench_CN"][1][0]))
    rows = [r for r in rows if r["category"] in MMB_CATS and r["source"] not in MMB_SKIP_SOURCES]
    groups = collections.defaultdict(list)
    for r in unique_mc(rows):
        groups[r["category"]].append(r)
    per = {c: (5 if i < 4 else 4) for i, c in enumerate(sorted(MMB_CATS))}   # 4*5 + 10*4 = 60
    per["future_prediction"] = 5   # the reasoning group (function_reasoning + future_prediction) reaches 10
    picks = stratified(rng, groups, per)
    sets = []
    for n, r in enumerate(sorted(picks, key=lambda r: (r["category"], int(r["index"]))), 1):
        qid = f"mmb{n:03d}"
        hint = r.get("hint") if r.get("hint") not in (None, "nan") else ""
        sets.append({"id": qid, "image": save_image(img_bytes(r["image"]), qid), "q": r["question"], "hint": hint,
                     "options": r["_options"], "answer": r["_answer"], "category": r["category"],
                     "source": {"set": "MMBench-CN dev", "index": int(r["index"])}})
    out["mmbench_cn"] = sets
    # CCBench (MMBench-CN chinese_culture)
    rows = parquet_rows(raw_path(raw, "lmms-lab/MMBench_CN", HF["lmms-lab/MMBench_CN"][1][1]))
    groups = collections.defaultdict(list)
    for r in unique_mc([r for r in rows if r["category"] in CCB_CATS and r["answer"] in "ABCD"]):
        groups[r["category"]].append(r)
    sets = []
    for n, r in enumerate(sorted(stratified(rng, groups, 10), key=lambda r: (r["category"], int(r["index"]))), 1):
        qid = f"ccb{n:03d}"
        sets.append({"id": qid, "image": save_image(img_bytes(r["image"]), qid), "q": r["question"], "hint": "",
                     "options": r["_options"], "answer": r["_answer"], "category": r["category"],
                     "source": {"set": "CCBench", "index": int(r["index"])}})
    out["ccbench"] = sets
    # HallusionBench: yes / no on one figure; math is left out (not an album question)
    rows = parquet_rows(raw_path(raw, "lmms-lab/HallusionBench", HF["lmms-lab/HallusionBench"][1][0]))
    groups = collections.defaultdict(list)
    for r in rows:
        if r["subcategory"] != "math" and r["image"]:
            groups[r["subcategory"]].append(r)
    per = {k: 4 for k in groups}
    per["illusion"] = 5
    per["figure"] = 5   # illusion + figure reach 10; ocr + video too
    per["ocr"] = 5
    per["video"] = 5
    sets = []
    picks = stratified(rng, groups, per)
    for n, r in enumerate(sorted(picks, key=lambda r: (r["subcategory"], int(r["set_id"]), int(r["figure_id"]), int(r["question_id"]))), 1):
        qid = f"hal{n:03d}"
        sets.append({"id": qid, "image": save_image(img_bytes(r["image"]), qid), "q": r["question"],
                     "answer": "yes" if r["gt_answer"] == "1" else "no", "category": f"{r['category']}/{r['subcategory']}",
                     "source": {"set": "HallusionBench", "file": r["filename"], "question_id": r["question_id"]}})
    out["hallusion"] = sets
    out["pope"] = build_pope(raw, random.Random(f"{SEED}-pope"))
    for name, rows in out.items():
        if name in keep:
            write_set(os.path.join(HERE, "photo", "sets", name + ".jsonl"), rows)


COCO_ZH = {
    "person": "人", "bicycle": "自行车", "car": "汽车", "motorcycle": "摩托车", "airplane": "飞机", "bus": "公交车",
    "train": "火车", "truck": "卡车", "boat": "船", "traffic light": "红绿灯", "fire hydrant": "消防栓",
    "stop sign": "停车标志", "parking meter": "停车计时器", "bench": "长椅", "bird": "鸟", "cat": "猫", "dog": "狗",
    "horse": "马", "sheep": "羊", "cow": "牛", "elephant": "大象", "bear": "熊", "zebra": "斑马", "giraffe": "长颈鹿",
    "backpack": "双肩包", "umbrella": "伞", "handbag": "手提包", "tie": "领带", "suitcase": "行李箱", "frisbee": "飞盘",
    "skis": "滑雪板(双板)", "snowboard": "单板滑雪板", "sports ball": "球", "kite": "风筝", "baseball bat": "棒球棒",
    "baseball glove": "棒球手套", "skateboard": "滑板", "surfboard": "冲浪板", "tennis racket": "网球拍",
    "bottle": "瓶子", "wine glass": "高脚杯", "cup": "杯子", "fork": "叉子", "knife": "刀", "spoon": "勺子",
    "bowl": "碗", "banana": "香蕉", "apple": "苹果", "sandwich": "三明治", "orange": "橙子", "broccoli": "西兰花",
    "carrot": "胡萝卜", "hot dog": "热狗", "pizza": "披萨", "donut": "甜甜圈", "cake": "蛋糕", "chair": "椅子",
    "couch": "沙发", "potted plant": "盆栽", "bed": "床", "dining table": "餐桌", "toilet": "马桶", "tv": "电视",
    "laptop": "笔记本电脑", "mouse": "鼠标", "remote": "遥控器", "keyboard": "键盘", "cell phone": "手机",
    "microwave": "微波炉", "oven": "烤箱", "toaster": "烤面包机", "sink": "水槽", "refrigerator": "冰箱", "book": "书",
    "clock": "钟", "vase": "花瓶", "scissors": "剪刀", "teddy bear": "泰迪熊玩偶", "hair drier": "吹风机",
    "toothbrush": "牙刷",
}


# ------------------------------------------------------------------------------------------------ ocr

CCOCR_TEXT = {"zh_doc_100": 15, "zh_handwriting_50": 10, "zh_scene_450": 20, "zh_dense_50": 10, "zh_vertical_100": 10}
CCOCR_KIE = {"EPHOIE_SCUT_311": 12, "COLD_CELL_600": 18}
CCOCR_DOC = {"doc_photo_chn_75": 15, "doc_scan_chn_75": 15}


def ccocr_file(name):
    for f in HF["wulipc/CC-OCR"][1]:
        if os.path.basename(f) == name + ".tsv":
            return f
    raise KeyError(name)


def ccocr_pick(raw, rng, table, prefix, kind, keep=None):
    sets = []
    for name, n in table.items():
        rows = [r for r in tsv_rows(raw_path(raw, "wulipc/CC-OCR", ccocr_file(name))) if keep is None or keep(r)]
        rng.shuffle(rows)
        for r in sorted(rows[:n], key=lambda r: int(r["index"])):
            qid = f"{prefix}{len(sets) + 1:03d}"
            data = base64.b64decode(r["image"])
            row = {"id": qid, "image": save_image(data, qid), "q": r["question"], "answer": r["answer"],
                   "category": name.rsplit("_", 1)[0], "kind": kind,
                   "source": {"set": "CC-OCR", "file": ccocr_file(name), "index": int(r["index"]), "image": r["image_name"]}}
            sets.append(row)
    return sets


def kie_ok(r):
    """Keep forms whose answer is a flat-ish JSON of at most 12 leaf fields: long nested tables measure the JSON writing
    more than the reading."""
    try:
        a = json.loads(r["answer"])
    except ValueError:
        return False
    return 2 <= len(leaves(a)) <= 12


def leaves(v, path=""):
    if isinstance(v, dict):
        return [x for k, w in v.items() for x in leaves(w, f"{path}.{k}" if path else k)]
    if isinstance(v, list):
        return [x for i, w in enumerate(v) for x in leaves(w, f"{path}[{i}]")]
    return [(path, "" if v is None else str(v))]


def build_ocr(raw, rng):
    write_set(os.path.join(HERE, "ocr", "sets", "ccocr_text.jsonl"), ccocr_pick(raw, rng, CCOCR_TEXT, "oct", "text"))
    write_set(os.path.join(HERE, "ocr", "sets", "ccocr_kie.jsonl"), ccocr_pick(raw, rng, CCOCR_KIE, "ock", "kie", kie_ok))
    write_set(os.path.join(HERE, "ocr", "sets", "ccocr_doc.jsonl"), ccocr_pick(raw, rng, CCOCR_DOC, "ocd", "doc"))
    build_ocrbench(raw, rng)


def build_ocrbench(raw, rng):
    rows = []
    for f in HF["ling99/OCRBench_v2"][1]:
        rows += [r for r in parquet_rows(raw_path(raw, "ling99/OCRBench_v2", f)) if is_zh_ocrbench(r)]
    groups = collections.defaultdict(list)
    for r in rows:
        groups[r["type"]].append(r)
    picks = stratified(rng, groups, {k: OCRB_PER.get(k, 0) for k in groups})
    sets = []
    for n, r in enumerate(sorted(picks, key=lambda r: (r["type"], int(r["id"]))), 1):
        qid = f"ocb{n:03d}"
        sets.append({"id": qid, "image": save_image(img_bytes(r["image"]), qid), "q": r["question"],
                     "answers": list(r["answers"]) if isinstance(r["answers"], (list, tuple)) else [r["answers"]],
                     "category": r["type"], "eval": r.get("eval"),
                     "source": {"set": "OCRBench v2", "id": int(r["id"]), "dataset": r.get("dataset_name")}})
    write_set(os.path.join(HERE, "ocr", "sets", "ocrbench_v2_zh.jsonl"), sets)


OCRB_PER = {"cognition VQA cn": 25, "key information extraction cn": 25, "full-page OCR cn": 10,
            "handwritten answer extraction cn": 10}   # more Chinese


def is_zh_ocrbench(r):
    return (r.get("type") or "").endswith(" cn")


# ------------------------------------------------------------------------------------------------ video

def reencode(src_bytes, dst, start=None, end=None):
    os.makedirs(os.path.dirname(dst), exist_ok=True)
    with tempfile.NamedTemporaryFile(suffix=".mp4") as tmp:
        tmp.write(src_bytes)
        tmp.flush()
        cut = (["-ss", f"{start:.3f}"] if start is not None else []) + (["-to", f"{end:.3f}"] if end is not None else [])
        subprocess.run(["ffmpeg", "-v", "error", "-y", *cut, "-i", tmp.name, "-an", "-vf",
                        "scale=-2:'min(480,ih)':flags=bicubic,format=yuv420p", "-c:v", "libx264", "-crf", "26",
                        "-preset", "slow", "-map_metadata", "-1", "-fflags", "+bitexact", "-flags:v", "+bitexact",
                        "-movflags", "+faststart", dst], check=True)


def build_video(raw, rng, only=None):
    os.makedirs(os.path.join(OUT, "video"), exist_ok=True)
    if only == "videomme":
        return build_videomme(raw, rng)
    listings = {}
    sets = []
    for task, (zname, prefix, n) in MVB_TASKS.items():
        items = json.load(open(raw_path(raw, "OpenGVLab/MVBench", f"json/{task}.json"), encoding="utf-8"))
        if zname not in listings:
            listings[zname] = rzip.listing(hf_url("OpenGVLab/MVBench", f"video/{zname}"))
        url, ents = listings[zname]
        items = [it for it in items if prefix + it["video"] in ents]
        rng.shuffle(items)
        for it in items[:n]:
            qid = f"mvb{len(sets) + 1:03d}"
            data = rzip.extract(url, ents[prefix + it["video"]])
            fname = qid + ".mp4"
            if it["video"].endswith(".webm") or it["video"].endswith(".mp4") or it["video"].endswith(".avi"):
                reencode(data, os.path.join(OUT, "video", fname), it.get("start"), it.get("end"))
            sets.append({"id": qid, "video": fname, "q": it["question"], "options": it["candidates"],
                         "answer": it["answer"], "category": task,
                         "source": {"set": "MVBench", "task": task, "video": it["video"],
                                    "start": it.get("start"), "end": it.get("end")}})
    write_set(os.path.join(HERE, "video", "sets", "mvbench.jsonl"), sets)
    # Video-MME is not built by default: its terms forbid redistribution, so its questions and videos are kept out of
    # this repository and the Release (`--only videomme` still builds it locally, for one-off checks)
    build_videovista(raw, random.Random(f"{SEED}-videovista"))


VMME_DOMAINS = None
VMME_N = 20


def build_videomme(raw, rng):
    rows = parquet_rows(raw_path(raw, "lmms-lab/Video-MME", HF["lmms-lab/Video-MME"][1][0]))
    rows = [r for r in rows if r["duration"] == "short"]
    # one question per video, spread over the domains of everyday life
    byvid = collections.defaultdict(list)
    for r in rows:
        byvid[r["videoID"]].append(r)
    vids = sorted(byvid)
    rng.shuffle(vids)
    domains = collections.Counter()
    picks = []
    for v in vids:
        qs = [r for r in byvid[v] if r["task_type"] in VMME_TASKS]
        if not qs:
            continue
        r = rng.choice(qs)
        if r["domain"] not in VMME_KEEP or domains[r["domain"]] >= VMME_PER_DOMAIN:
            continue
        domains[r["domain"]] += 1
        picks.append(r)
        if len(picks) == VMME_N:
            break
    listing = {}
    for k in range(1, 21):
        url, ents = rzip.listing(hf_url_vmme(k))
        for name, e in ents.items():
            listing[os.path.splitext(os.path.basename(name))[0]] = (url, e)
    sets = []
    for n, r in enumerate(sorted(picks, key=lambda r: r["question_id"]), 1):
        qid = f"vmm{n:03d}"
        url, e = listing[r["videoID"]]
        reencode(rzip.extract(url, e), os.path.join(OUT, "video", qid + ".mp4"))
        options = [re.sub(r"^[A-D]\.\s*", "", o) for o in r["options"]]
        sets.append({"id": qid, "video": qid + ".mp4", "q": r["question"], "options": options,
                     "answer": options["ABCD".index(r["answer"])], "category": f"{r['domain']}/{r['task_type']}",
                     "source": {"set": "Video-MME", "question_id": r["question_id"], "video_id": r["videoID"],
                                "url": r["url"]}})
    write_set(os.path.join(HERE, "video", "sets", "videomme.jsonl"), sets)


VMME_KEEP = {"Life Record", "Knowledge", "Film & Television", "Sports Competition", "Artistic Performance"}
VMME_PER_DOMAIN = 5
# Only the perception kinds: the clips go without sound, and reasoning / synopsis questions often hang on what is said.
VMME_TASKS = {"Attribute Perception", "Action Recognition", "Object Recognition", "OCR Problems", "Counting Problem",
              "Spatial Perception", "Temporal Perception"}


def hf_url_vmme(k):
    return hf_url("lmms-lab/Video-MME", f"videos_chunked_{k:02d}.zip")


# VideoVista-CulturalLingo: Chinese short videos (most from a Chinese lifestyle-sharing app), questions in Chinese. Only
# part of the answers are published (the rest read "[MASK]"); we take Chinese questions with an answer, one per video,
# from the kinds that can be answered from the picture (no "Event Description" / science talks / "Chinese Culture",
# which hang on speech or outside knowledge).
VV_KINDS = {"Object Temporal Localization": 5, "Event Localization": 5,      # 什么时候出现(物体 5、事件 5)
            "Object Spatial Localization": 10,                                     # 在画面哪里
            "Object Temporal Sequence": 5, "Event Sequence": 5,                    # 先后顺序(物体 5、事件 5)
            "Event Prediction": 10}                                                # 接下来会发生什么
# About 40 Chinese video questions, in four groups of 10 (run_vision.py GROUPS).
# "Chinese Culture" is left out: its questions hang on the narration and on outside knowledge
# ("in which dynasty did the food mentioned first spread"), not on what the frames show.
VV_MAX_BYTES = 60_000_000


def build_videovista(raw, rng):
    repo = "Uni-MoE/VideoVista-CulturalLingo"
    rows = json.load(open(raw_path(raw, repo, "VideoVista-CulturalLingo.json"), encoding="utf-8"))
    rows = [r for r in rows if r["answer"] in ("A", "B", "C", "D") and re.search(r"[\u4e00-\u9fff]", r["question"])
            and r["subcategory"] in VV_KINDS]
    url, ents = rzip.listing(rzip.Parts([hf_url(repo, f"videos.zip.{i:03d}") for i in range(1, 8)]))
    rows = [r for r in rows if "videos/" + r["video_path"] in ents and ents["videos/" + r["video_path"]][1] <= VV_MAX_BYTES]
    rows.sort(key=lambda r: r["question_id"])
    rng.shuffle(rows)
    used, picks, n = set(), [], collections.Counter()
    for r in rows:
        base = r["video_path"].split(".")[0].split("_")[0]
        if base in used or n[r["subcategory"]] >= VV_KINDS[r["subcategory"]]:
            continue
        used.add(base)
        n[r["subcategory"]] += 1
        picks.append(r)
    sets = []
    for k, r in enumerate(sorted(picks, key=lambda r: (r["subcategory"], r["question_id"])), 1):
        qid = f"vvc{k:03d}"
        reencode(rzip.extract(url, ents["videos/" + r["video_path"]]), os.path.join(OUT, "video", qid + ".mp4"))
        sets.append({"id": qid, "video": qid + ".mp4", "q": r["question"], "options": r["options"],
                     "answer": r["options"]["ABCD".index(r["answer"])], "category": r["subcategory"], "lang": "zh",
                     "source": {"set": "VideoVista-CulturalLingo", "question_id": r["question_id"], "video": r["video_path"]}})
    write_set(os.path.join(HERE, "video", "sets", "videovista_zh.jsonl"), sets)


# ------------------------------------------------------------------------------------------------ own photos

def build_own(raw, rng=None):
    """Our own photo questions (photo/sets/own.jsonl, written by hand) use Crossmodal-3600 pictures: copy each named
    one out of the dataset as xm_<id>.jpg (published bytes), and record its author and license next to the set."""
    import pyarrow.parquet as pq
    rows = [json.loads(l) for l in open(os.path.join(HERE, "photo", "sets", "own.jsonl"), encoding="utf-8") if l.strip()]
    want = {r["src"].split(":", 1)[1] for r in rows if r["src"].startswith("xm3600:")}
    attr = json.load(open(os.path.join(os.path.dirname(HERE), "search", "ids", "xm3600-zh.json"), encoding="utf-8"))["attribution"]
    pf = pq.ParquetFile(raw_path(raw, "mteb/XM3600T2IRetrieval", HF["mteb/XM3600T2IRetrieval"][1][0]))
    got = {}
    for g in range(pf.num_row_groups):
        for row in pf.read_row_group(g, columns=["id", "image"]).to_pylist():
            k = row["id"].removeprefix("corpus-")
            if k in want:
                got[k] = save_image(img_bytes(row["image"]), f"xm_{k}")
    missing = want - set(got)
    if missing or any(k not in attr for k in want):
        sys.exit(f"own photos: missing {sorted(missing)[:5]}, or without a recorded license")
    with open(os.path.join(HERE, "photo", "own_attribution.json"), "w", encoding="utf-8") as fh:
        json.dump({k: attr[k] for k in sorted(want)}, fh, ensure_ascii=False, indent=1)
    print(f"{len(want):4d}  own photos from Crossmodal-3600 (CC BY 2.0) -> {OUT}/img")


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    sub = ap.add_subparsers(dest="cmd", required=True)
    sub.add_parser("download").add_argument("--raw", required=True)
    b = sub.add_parser("build")
    b.add_argument("--raw", required=True)
    b.add_argument("--only", help="photo,ocr,video,own (own: the pictures our own photo questions use); videomme or videovista "
                                  "alone; webphoto: with photo, also write MMBench-CN, CCBench and HallusionBench (web pictures, "
                                  "for local one-off checks only)")
    a = ap.parse_args()
    if a.cmd == "download":
        download(a.raw)
    elif a.cmd == "build":
        only = set((a.only or "photo,ocr,video,own").split(","))
        if "photo" in only:
            build_photo(a.raw, random.Random(f"{SEED}-photo"), ("pope",) + (WEB_PHOTO if "webphoto" in only else ()))
        for part, fn in (("ocr", build_ocr), ("video", build_video)):
            if part in only:
                fn(a.raw, random.Random(f"{SEED}-{part}"))
        if "own" in only:
            build_own(a.raw)
        if "videovista" in only:
            os.makedirs(os.path.join(OUT, "video"), exist_ok=True)
            build_videovista(a.raw, random.Random(f"{SEED}-videovista"))
        if "videomme" in only:
            build_video(a.raw, random.Random(f"{SEED}-videomme"), "videomme")


if __name__ == "__main__":
    main()