Download data_pack.py from wj-inf/MagicData340k: direct link, hf CLI and curl.
- Browser
- Download file 2.7 kB
-
https://huggingface.co/datasets/wj-inf/MagicData340k/resolve/refs%2Fpr%2F1/data_pack.py
- Command line
-
hf download hf://datasets/wj-inf/MagicData340k@refs/pr/1/data_pack.py
-
curl -L -o data_pack.py https://huggingface.co/datasets/wj-inf/MagicData340k/resolve/refs%2Fpr%2F1/data_pack.py
2.7 kB
| import os | |
| import json | |
| from PIL import Image | |
| from datasets import Dataset, DatasetDict, Features, Sequence, Value | |
| from datasets import Image as ImageData | |
| from io import BytesIO # 新增导入 | |
| from datasets import disable_caching | |
| disable_caching() # 完全禁用缓存 | |
| def generate_examples(json_path): | |
| with open(json_path, 'r', encoding='utf-8') as f: | |
| # i = 0 | |
| for line in f: | |
| # i += 2 # renew cache | |
| # print(i) # verify cache renewed | |
| try: | |
| data = json.loads(line) | |
| # 转换图片路径并加载图像 | |
| raw_path = data['images'][0] | |
| # ========== 新增图像处理部分开始 ========== | |
| with Image.open(raw_path, "r") as img: | |
| # 统一转换为RGB模式 | |
| if img.mode != 'RGB': | |
| img = img.convert('RGB') | |
| resized_img = img | |
| # ========== 新增图像处理部分结束 ========== | |
| # 提取图片ID(文件名数字部分) | |
| filename = os.path.basename(raw_path) # 141126815887.jpg | |
| img_id = os.path.splitext(filename)[0] # 141126815887 | |
| yield { | |
| "images": [resized_img], | |
| "problem": data["query"], | |
| "answer": data["response"], | |
| "id": img_id | |
| } | |
| # print(data["query"]) | |
| # print(data["response"]) | |
| # exit() | |
| except Exception as e: | |
| data = json.loads(line) | |
| print(data) | |
| print(f"Error processing {raw_path}: {str(e)}") | |
| continue | |
| def main(): | |
| train_json_path="./magic_mirror_data_train_r1.jsonl" | |
| test_json_path="./magic_mirror_data_test_r1.jsonl" | |
| base_dir = "./" | |
| train_parquet_path =base_dir + "magic_mirror_data_train_r1.parquet" | |
| test_parquet_path =base_dir + "magic_mirror_data_test_r1.parquet" | |
| train_json_path = "./magic_mirror_data_train_resample_r1.jsonl" | |
| train_parquet_path = "./magic_mirror_data_train_resample_r1.parquet" | |
| # 创建训练集和测试集 | |
| test_ds = Dataset.from_generator(generate_examples, gen_kwargs={"json_path": test_json_path}) | |
| test_ds.cast_column("images", Sequence(ImageData())).to_parquet(test_parquet_path) | |
| train_ds = Dataset.from_generator(generate_examples, gen_kwargs={"json_path": train_json_path}) | |
| train_ds.cast_column("images", Sequence(ImageData())).to_parquet(train_parquet_path) | |
| if __name__ == "__main__": | |
| main() | |