Validjson / app.py
Oranblock's picture
Update app.py
212ac8d verified
raw
history blame
2.03 kB
import gradio as gr
import json
from transformers import pipeline
# Load a text generation model from Hugging Face without an API key
# You can use a smaller model if gpt-3.5-turbo isn't available
generator = pipeline("text-generation", model="gpt-3.5-turbo")
# Function to attempt to fix JSON using a Hugging Face model
def ai_fix_json(json_data):
# Prepare a prompt for the AI model to fix the JSON
prompt = f"Fix the following JSON data and make it valid:\n\n{json_data}\n\nFixed JSON:"
# Generate a response from the model
response = generator(prompt, max_length=1024, num_return_sequences=1)[0]['generated_text']
# Extract the fixed JSON from the response (you may need to fine-tune this depending on the model's output format)
fixed_json = response.split("Fixed JSON:")[-1].strip()
# Try to load the fixed JSON to ensure it's valid
try:
parsed_data = json.loads(fixed_json)
pretty_json = json.dumps(parsed_data, indent=4)
return pretty_json, "JSON fixed using AI."
except json.JSONDecodeError as e:
return None, f"Failed to fix JSON: {str(e)}"
# Function to handle file uploads and processing
def process_file(uploaded_file):
# Read the content of the uploaded file directly
json_data = uploaded_file # This is already the content of the file as a string
# Attempt to fix the JSON using AI
cleaned_json, message = ai_fix_json(json_data)
if cleaned_json:
# Return the fixed JSON for display and as a downloadable file
return cleaned_json, message, cleaned_json
else:
return None, message, None
# Gradio interface
iface = gr.Interface(
fn=process_file,
inputs=gr.File(label="Upload your JSON file"),
outputs=[gr.JSON(label="Fixed JSON"), "text", gr.File(label="Download cleaned JSON file")],
title="AI-Powered JSON Cleaner",
description="Upload a JSON file to automatically fix, remove duplicates, and download the cleaned version using AI."
)
iface.launch()