将大模型指令微调数据从parquet转为json格式

将大模型指令微调数据从parquet转为json格式

python 复制代码
import os
import json
import random
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq

def read_json_file(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            data = json.load(file)
            return data
    except FileNotFoundError:
        print(f"File {file_path} not found.")
    except json.JSONDecodeError:
        print(f"File {file_path} is not a valid JSON file.")
    except Exception as e:
        print(f"An error occurred: {e}")

def read_jsonl_file(file_path):
    data = []
    with open(file_path, 'r', encoding='utf-8') as file:
        for line in file:
            try:
                data.append(json.loads(line))
            except:
                print(line)
                1/0
    return data

def read_praquet_file(file_path):
    table = pq.read_table(file_path)
    df = table.to_pandas()
    result=[row.tolist() for _, row in df.iterrows()]
    return result

def save_json(file_path,data):
    with open(file_path, 'w', encoding='utf-8') as file:
        json.dump(data, file, indent=4, ensure_ascii=False)
    print(f'Save {file_path} is ok!')

def save_jsonl(file_path,data):
    try:
        with open(file_path, 'w', encoding='utf-8') as file:
            for item in data:
                file.write(json.dumps(item, ensure_ascii=False) + '\n')
        print(f"Data saved to {file_path}")
    except Exception as e:
        print(f"An error occurred while saving the data: {e}")

def save_parquet(file_path, data):

    if isinstance(data, list):
        data = pd.DataFrame(data)
    if not isinstance(data, pd.DataFrame):
        raise ValueError("data must be a pandas DataFrame or a list of lists")
    pq.write_table(pa.Table.from_pandas(data), file_path)
    print(f'Save {file_path} is ok!')

def convert_lists_to_json(df):
    """Convert lists in DataFrame to JSON strings."""
    for column in df.columns:
        if df[column].apply(lambda x: isinstance(x, list)).any():
            df[column] = df[column].apply(lambda x: json.dumps(x) if isinstance(x, list) else x)
    return df

root='/path/to/parquet/dir'
save_path='/path/to/savedir/save_name.json'
new_data=[]
dirs=os.listdir(root)
for one in dirs:
    if one.endswith('.parquet'):
        print(one)
        file_path=root+'/'+one
        data=read_praquet_file(file_path)
        for x in data:
            inp=x[3]
            res=x[4]
            new_entry={
                "conversations": [
                    {
                        "role": "user",
                        "content": inp
                    },
                    {
                        "role": "assistant",
                        "content": res
                    }
                ]
            }
            if len(inp)>0 and len(res)>0:
                new_data+=[new_entry]
                
save_json(save_path,new_data)
相关推荐
电商API&Tina7 小时前
【京东item_getAPI 】高稳定:API 、非爬虫、不封号、不掉线、大促稳跑
大数据·网络·人工智能·爬虫·python·sql·json
LittroInno7 小时前
T-JSON跨平台网络通信协议——边缘认知设备的二次开发实战指南
人工智能·计算机视觉·目标跟踪·json
椰汁菠萝1 天前
Mybatis-plus + PostgreSQL json格式类型转换异常
postgresql·json·mybatis
江西省遂川县常驻深圳大使1 天前
openclaw.json配置示例
服务器·json·openclaw
先做个垃圾出来………1 天前
JSON序列化问题
数据库·json
亚历克斯神1 天前
Flutter 三方库 jwt_io 的鸿蒙化适配指南 - 在鸿蒙系统上构建极致、严谨、全能的 JSON Web Token (JWT) 加解密与身份安全验证引擎
flutter·json·harmonyos
冉佳驹1 天前
Linux ——— 网络开发核心知识与协议实现详解
linux·http·https·udp·json·tcp·端口号
尘中客1 天前
Postman进阶实战:优雅调试带 GZIP 压缩与百KB级复杂嵌套 JSON 的 RESTful API
json·postman·restful·php开发·gzip解压
wefly20172 天前
纯前端架构深度解析:jsontop.cn,JSON 格式化与全栈开发效率平台
java·前端·python·架构·正则表达式·json·php
MegaDataFlowers2 天前
什么是JSON
json