Frappe / app.py
HusnaManakkot's picture
Update app.py
0f2dfa7 verified
raw
history blame
2.26 kB
import gradio as gr
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
from datasets import load_dataset
# Load the Spider dataset
spider_dataset = load_dataset("spider", split='train') # Load a subset of the dataset
# Load tokenizer and model
tokenizer = AutoTokenizer.from_pretrained("mrm8488/t5-base-finetuned-wikiSQL")
model = AutoModelForSeq2SeqLM.from_pretrained("mrm8488/t5-base-finetuned-wikiSQL")
def post_process_sql_query(sql_query, db_schema):
# Modify the SQL query to match the dataset's schema
# This is just an example and might need to be adapted based on the dataset and model output
for table_name in db_schema['table_names']:
if "TABLE" in sql_query:
sql_query = sql_query.replace("TABLE", table_name)
break # Assuming only one table is referenced in the query
for column_name in db_schema['column_names']:
if "COLUMN" in sql_query:
sql_query = sql_query.replace("COLUMN", column_name[1], 1)
return sql_query
def generate_sql_from_user_input(query, db_id):
# Find the corresponding database schema
db_schema = None
for item in spider_dataset:
if item['db_id'] == db_id:
db_schema = item
break
if db_schema is None:
return "Database schema not found for the given DB ID."
# Generate SQL for the user's query
input_text = "translate English to SQL: " + query
inputs = tokenizer(input_text, return_tensors="pt", padding=True)
outputs = model.generate(**inputs, max_length=512)
sql_query = tokenizer.decode(outputs[0], skip_special_tokens=True)
# Post-process the SQL query to match the dataset's schema
sql_query = post_process_sql_query(sql_query, db_schema)
return sql_query
# Create a Gradio interface
interface = gr.Interface(
fn=generate_sql_from_user_input,
inputs=[gr.Textbox(label="Enter your natural language query"), gr.Textbox(label="Enter DB ID")],
outputs=gr.Textbox(label="Generated SQL Query"),
title="NL to SQL with T5 using Spider Dataset",
description="This model generates an SQL query for your natural language input based on the Spider dataset."
)
# Launch the app
if __name__ == "__main__":
interface.launch()