regulatories / dataconversion.py
sangramdh's picture
firstcommit
94ac42b verified
Raw History Blame Contribute Delete
10.4 kB
import json
import pandas as pd
class DataConversion:
def __init__(self, columns=None):
# Define the default columns
self.columns = columns if columns else ['instruction', 'context', 'response']
def json_to_excel(self, json_file, excel_file):
"""
Converts a JSON file to an Excel sheet.
:param json_file: Path to the input JSON file.
:param excel_file: Path to the output Excel file.
"""
# Load JSON data
with open(json_file, 'r') as f:
data = json.load(f)
# Create a DataFrame and write it to an Excel file
df = pd.DataFrame(data, columns=self.columns)
df.to_excel(excel_file, index=False, engine='openpyxl')
print(f"Data successfully converted from JSON to Excel: {excel_file}")
def excel_to_jsonl(self, excel_file, jsonl_file):
"""
Converts an Excel file to a JSONL file.
:param excel_file: Path to the input Excel file.
:param jsonl_file: Path to the output JSONL file.
"""
# Load the Excel data into a DataFrame
df = pd.read_excel(excel_file, engine='openpyxl')
# Write each row as a JSON object to the JSONL file
with open(jsonl_file, 'w') as f:
for _, row in df.iterrows():
json_line = row.to_json(orient='records')
f.write(json_line + '\n')
print(f"Data successfully converted from Excel to JSONL: {jsonl_file}")
def jsonl_to_text(self, jsonl_file, text_file):
"""
Converts a JSONL file to a text file.
:param jsonl_file: Path to the input JSONL file.
:param text_file: Path to the output text file.
"""
# Read the JSONL file and convert each line into a formatted text
with open(jsonl_file, 'r') as f:
lines = f.readlines()
with open(text_file, 'w') as f:
for line in lines:
json_obj = json.loads(line.strip())
f.write(f"Instruction: {json_obj['instruction']}\n")
f.write(f"Context: {json_obj['context']}\n")
f.write(f"Response: {json_obj['response']}\n\n")
print(f"Data successfully converted from JSONL to Text: {text_file}")
def text_to_jsonl(self, text_file, jsonl_file):
"""
Converts a text file to a JSONL file.
:param text_file: Path to the input text file.
:param jsonl_file: Path to the output JSONL file.
"""
# Read the text file
with open(text_file, 'r') as f:
lines = f.readlines()
data = []
current_entry = {}
for line in lines:
line = line.strip()
if line.startswith('Instruction:'):
if current_entry:
data.append(current_entry)
current_entry = {'instruction': line.replace('Instruction: ', '').strip()}
elif line.startswith('Context:'):
current_entry['context'] = line.replace('Context: ', '').strip()
elif line.startswith('Response:'):
current_entry['response'] = line.replace('Response: ', '').strip()
# Append the last entry
if current_entry:
data.append(current_entry)
# Write to the JSONL file
with open(jsonl_file, 'w') as f:
for entry in data:
f.write(json.dumps(entry, ensure_ascii=False) + '\n')
print(f"Data successfully converted from Text to JSONL: {jsonl_file}")
def jsonl_to_excel(self, jsonl_file, excel_file):
"""
Converts a JSONL file to an Excel sheet.
:param jsonl_file: Path to the input JSONL file.
:param excel_file: Path to the output Excel file.
"""
# Read the JSONL file and convert each line into a Python dictionary
data = []
with open(jsonl_file, 'r') as f:
for line in f.readlines():
data.append(json.loads(line.strip()))
# Create a DataFrame from the list of dictionaries and write it to an Excel file
df = pd.DataFrame(data, columns=self.columns)
df.to_excel(excel_file, index=False, engine='openpyxl')
print(f"Data successfully converted from JSONL to Excel: {excel_file}")
# Merge functionality
def merge_jsonl_files(self, jsonl_file1, jsonl_file2, output_jsonl_file):
"""Merge two JSONL files into a single JSONL file."""
data = []
# Read first JSONL file
with open(jsonl_file1, 'r') as f:
for line in f.readlines():
data.append(json.loads(line.strip()))
# Read second JSONL file
with open(jsonl_file2, 'r') as f:
for line in f.readlines():
data.append(json.loads(line.strip()))
# Write merged data to output JSONL file
with open(output_jsonl_file, 'w') as f:
for entry in data:
f.write(json.dumps(entry, ensure_ascii=False) + '\n')
print(f"Data successfully merged from {jsonl_file1} and {jsonl_file2} into {output_jsonl_file}")
def merge_excel_files(self, excel_file1, excel_file2, output_excel_file):
"""Merge two Excel files into a single Excel sheet."""
# Read the first Excel file
df1 = pd.read_excel(excel_file1, engine='openpyxl')
# Read the second Excel file
df2 = pd.read_excel(excel_file2, engine='openpyxl')
# Concatenate the DataFrames
merged_df = pd.concat([df1, df2], ignore_index=True)
# Write the merged DataFrame to the output Excel file
merged_df.to_excel(self, output_excel_file, index=False, engine='openpyxl')
print(f"Data successfully merged from {excel_file1} and {excel_file2} into {output_excel_file}")
def jsonl_to_csv(jsonl_file, csv_file):
"""
Converts a JSONL file to a CSV file.
Parameters:
jsonl_file (str): The path to the input JSONL file.
csv_file (str): The path to the output CSV file.
"""
data = []
# Read the JSONL file line by line
with open(jsonl_file, 'r') as f:
for line in f.readlines():
data.append(json.loads(line.strip())) # Convert each line to a dictionary
# Create a DataFrame from the data and save it to CSV
df = pd.DataFrame(data)
df.to_csv(csv_file, index=False)
print(f"Data successfully converted from JSONL to CSV: {csv_file}")
def csv_to_jsonl(self, csv_file, jsonl_file):
"""
Converts a CSV file to a JSONL file with structured JSON objects.
Parameters:
csv_file (str): The path to the input CSV file.
jsonl_file (str): The path to the output JSONL file.
"""
try:
# Read the CSV file into a DataFrame
df = pd.read_csv(csv_file, encoding='latin1', on_bad_lines='skip', dtype=str)
# Write each row of the DataFrame as a JSON object to the JSONL file
with open(jsonl_file, 'w', encoding='utf-8') as f:
for _, row in df.iterrows():
json_object = {
"instruction": row["instruction"],
"context": row["context"],
"response": row["response"]
} # Create a structured dictionary
f.write(json.dumps(json_object, ensure_ascii=False) + '\n') # Write as JSON line
print(f"Data successfully converted from CSV to JSONL: {jsonl_file}")
except UnicodeDecodeError as e:
print(f"Error decoding file: {e}")
print("Try specifying a different encoding such as 'latin1' or 'ISO-8859-1'.")
def csv_to_excel(self, csv_file, excel_file):
"""
Converts a CSV file to an Excel file.
Parameters:
csv_file (str): The path to the input CSV file.
excel_file (str): The path to the output Excel file.
"""
df = pd.read_csv(csv_file) # Read the CSV file into a DataFrame
# Write the DataFrame to an Excel file
df.to_excel(excel_file, index=False, engine='openpyxl')
print(f"Data successfully converted from CSV to Excel: {excel_file}")
def excel_to_csv(self, excel_file, csv_file):
"""
Converts an Excel file to a CSV file.
Parameters:
excel_file (str): The path to the input Excel file.
csv_file (str): The path to the output CSV file.
"""
df = pd.read_excel(excel_file, engine='openpyxl') # Read the Excel file into a DataFrame
# Write the DataFrame to a CSV file
df.to_csv(csv_file, index=False)
print(f"Data successfully converted from Excel to CSV: {csv_file}")
# Example usage:
if __name__ == '__main__':
# Initialize DataConversion class
converter = DataConversion()
# Convert JSON to Excel
# converter.json_to_excel('input_data.json', 'output_data.xlsx')
# Convert Excel to JSONL
# converter.excel_to_jsonl('output_data.xlsx', 'output_data.jsonl')
# Convert JSONL to Text
# converter.jsonl_to_text('output_data.jsonl', 'output_data.txt')
# Convert Text to JSONL
# converter.text_to_jsonl('output_data.txt', 'final_output.jsonl')
# Convert JSONL to Excel (newly added method)
# converter.jsonl_to_excel('dataset.jsonl', 'final_output_data.xlsx')
# Merge two JSONL files
# converter.merge_jsonl_files('dataset1.jsonl', 'dataset2.jsonl', 'merged_dataset.jsonl')
# Merge two Excel files
# converter.merge_excel_files('dataset1.xlsx', 'dataset2.xlsx', 'merged_dataset.xlsx')
# Example usage:
# JSONL to CSV conversion
# converter.jsonl_to_csv('data.jsonl', 'data.csv')
# CSV to JSONL conversion
# converter.csv_to_jsonl('data.csv', 'data.jsonl')
# CSV to Excel conversion
# converter.csv_to_excel('data.csv', 'data.xlsx')
# Excel to CSV conversion
# converter.excel_to_csv('data.xlsx', 'data.csv')