File size: 4,644 Bytes
0160d0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
将基于 gen_sft_and_val_data.py 生成的 val JSONL 还原为与原始 OCR-VQA Arrow 相同的列类型与 schema metadata。

输入 JSONL 的 images 字段元素形如:
  {"base64": "...", "metadata": {...}} 或 {"error": "..."}
本脚本恢复为原始的 list<struct<bytes: binary, path: string>>,其中 path 无法从 JSONL 恢复,统一置为 None。
"""
import os
import json
import base64
from typing import Any, Dict, List

import pyarrow as pa
import pyarrow.ipc as ipc
from tqdm import tqdm


# 与现有脚本保持一致的默认目录
DATASET_DIR = "/mnt/moonfs/kimiv-ksyun/xulin/datasets/OCR-VQA/ocr_vqa_clean_dataset/validation"
INPUT_JSONL = "/mnt/moonfs/kimiv-ksyun/xulin/abs/data/ocr_vqa_val_512.jsonl"
OUTPUT_ARROW = "/mnt/moonfs/kimiv-ksyun/xulin/abs/data/ocr_vqa_val_512_restored.arrow"


def load_reference_schema(dataset_dir: str) -> pa.Schema:
    """从原始验证集的任意一个 Arrow 分片加载 schema(含 metadata)。"""
    arrow_files = sorted(
        [f for f in os.listdir(dataset_dir) if f.startswith("data-") and f.endswith(".arrow")]
    )
    if not arrow_files:
        raise RuntimeError("未找到任何 data-*.arrow 文件用于参考 schema")

    fpath = os.path.join(dataset_dir, arrow_files[0])
    with open(fpath, "rb") as f:
        reader = ipc.RecordBatchStreamReader(f)
        table = reader.read_all()
    return table.schema


def record_from_json(rec: Dict[str, Any]) -> Dict[str, Any]:
    """将 JSONL 的一条记录转为 Python 原生对象,列名与原始 Arrow 对齐。

    - images: list[ {"bytes": bytes, "path": Optional[str]} ]
    - problem: Optional[str]
    - answer: Optional[str]
    """
    # 恢复 images
    images_py: List[Dict[str, Any]] = []
    raw_images = rec.get("images")
    if isinstance(raw_images, list):
        for it in raw_images:
            if isinstance(it, dict) and "base64" in it:
                try:
                    img_bytes = base64.b64decode(it["base64"]) if it["base64"] else b""
                except Exception:
                    img_bytes = b""
                images_py.append({"bytes": img_bytes, "path": None})
            elif isinstance(it, dict) and "bytes" in it:
                # 罕见:如果 JSONL 中直接保留了 bytes(不太可能)
                images_py.append({"bytes": it.get("bytes") or b"", "path": it.get("path")})
            else:
                # 出错或不支持格式,跳过或置空
                images_py.append({"bytes": b"", "path": None})
    else:
        images_py = None  # 与 Arrow 的可空语义对齐

    return {
        "images": images_py,
        "problem": rec.get("problem"),
        "answer": rec.get("answer"),
    }


def build_table_from_records(records: List[Dict[str, Any]], ref_schema: pa.Schema) -> pa.Table:
    """根据参考 schema 构建表,并复制 schema metadata。"""
    # 直接使用参考 schema 的各列类型,确保完全一致
    images_type = ref_schema.field("images").type
    problem_type = ref_schema.field("problem").type
    answer_type = ref_schema.field("answer").type

    images_col = pa.array([r.get("images") for r in records], type=images_type)
    problem_col = pa.array([r.get("problem") for r in records], type=problem_type)
    answer_col = pa.array([r.get("answer") for r in records], type=answer_type)

    table = pa.Table.from_arrays([images_col, problem_col, answer_col], names=["images", "problem", "answer"])
    table = table.replace_schema_metadata(ref_schema.metadata)
    return table


def write_arrow_stream(table: pa.Table, out_path: str) -> None:
    os.makedirs(os.path.dirname(out_path), exist_ok=True)
    with open(out_path, "wb") as f:
        with ipc.RecordBatchStreamWriter(f, table.schema) as writer:
            writer.write_table(table)


def main():
    ref_schema = load_reference_schema(DATASET_DIR)

    records: List[Dict[str, Any]] = []
    with open(INPUT_JSONL, "r", encoding="utf-8") as f:
        for line in tqdm(f, desc="读取 JSONL"):
            if not line.strip():
                continue
            rec_json = json.loads(line)
            records.append(record_from_json(rec_json))

    table = build_table_from_records(records, ref_schema)
    write_arrow_stream(table, OUTPUT_ARROW)

    # 读回校验
    with open(OUTPUT_ARROW, "rb") as f:
        back = ipc.RecordBatchStreamReader(f).read_all()
    print("写出条数:", back.num_rows)
    print("schema 一致:", back.schema == ref_schema)
    print(back.schema)
    print("输出:", OUTPUT_ARROW)


if __name__ == "__main__":
    main()