| |
| |
| """ |
| 将基于 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_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: |
| |
| 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 |
|
|
| 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。""" |
| |
| 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() |
|
|
|
|
|
|