Datasets:

Modalities:
Image
ArXiv:
File size: 2,923 Bytes
1f085d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import pandas as pd
import json
import os
import io
import numpy as np  # 新增:导入 numpy
from PIL import Image

# 新增:自定义的 JSON 编码器
class NumpyEncoder(json.JSONEncoder):
    def default(self, obj):
        # 如果是 numpy 数组,转为 python 列表
        if isinstance(obj, np.ndarray):
            return obj.tolist()
        # 如果是 numpy 的整数,转为 python 原生 int
        if isinstance(obj, (np.integer, np.int64, np.int32, np.int16, np.int8)):
            return int(obj)
        # 如果是 numpy 的浮点数,转为 python 原生 float
        if isinstance(obj, (np.floating, np.float64, np.float32, np.float16)):
            return float(obj)
        # 其他类型交由默认处理
        return super(NumpyEncoder, self).default(obj)


def process_parquet(file_path, output_dir, jsonl_name):
    # 1. 创建保存图片的文件夹
    img_save_dir = os.path.join(output_dir, "images")
    if not os.path.exists(img_save_dir):
        os.makedirs(img_save_dir)

    # 2. 读取 Parquet 文件
    print(f"正在读取文件: {file_path}")
    df = pd.read_parquet(file_path)

    # 3. 准备写入 JSONL 文件
    jsonl_path = os.path.join(output_dir, jsonl_name)
    
    print(f"开始处理数据,图片将保存至: {img_save_dir}")
    
    with open(jsonl_path, 'w', encoding='utf-8') as f_jsonl:
        for index, row in df.iterrows():
            # --- 处理图片列 ---
            img_data = row['image']
            image_filename = f"image_{index:05d}.png" # 编号命名
            image_path = os.path.join(img_save_dir, image_filename)

            try:
                # 判断图片数据格式并转换
                if isinstance(img_data, dict) and 'bytes' in img_data:
                    image = Image.open(io.BytesIO(img_data['bytes']))
                elif isinstance(img_data, bytes):
                    image = Image.open(io.BytesIO(img_data))
                else:
                    image = img_data
                
                # 保存为图片文件
                image.save(image_path)
            except Exception as e:
                print(f"第 {index} 行图片处理失败: {e}")
                continue

            # --- 处理元数据列 ---
            meta_data = row.to_dict()
            
            # 将图片原始字节数据替换为本地文件路径
            meta_data['image'] = os.path.join("images", image_filename)
            
            # 关键修改:在 dumps 中加入 cls=NumpyEncoder 参数
            f_jsonl.write(json.dumps(meta_data, ensure_ascii=False, cls=NumpyEncoder) + '\n')

    print(f"处理完成!JSONL 文件已生成: {jsonl_path}")

# 使用示例
if __name__ == "__main__":
    process_parquet(
        file_path='./data/train-00000-of-00001.parquet', # 根据你的路径做了调整
        output_dir='./', 
        jsonl_name='metadata.jsonl'
    )