import gradio as gr from transformers import AutoTokenizer, AutoModelForSeq2SeqLM from datasets import load_dataset # Load the WikiSQL dataset (only the table schemas are needed for validation) wikisql_dataset = load_dataset("wikisql", split='train') # Load tokenizer and model tokenizer = AutoTokenizer.from_pretrained("mrm8488/t5-base-finetuned-wikiSQL") model = AutoModelForSeq2SeqLM.from_pretrained("mrm8488/t5-base-finetuned-wikiSQL") def validate_sql_against_schema(sql_query, schema): # This is a placeholder function. You need to implement the logic to validate # the SQL query against the table schema. The validation can be as simple or as # complex as you need, depending on the requirements. return True # Assume the query is valid for now def generate_sql_from_user_input(query): # 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) # Validate the generated SQL query against the schemas in the dataset for item in wikisql_dataset: if validate_sql_against_schema(sql_query, item['sql']): return query, sql_query return query, "Generated SQL query is not consistent with the dataset." # Create a Gradio interface interface = gr.Interface( fn=generate_sql_from_user_input, inputs=gr.Textbox(label="Enter your natural language query"), outputs=[gr.Textbox(label="Your Query"), gr.Textbox(label="Generated SQL Query")], title="NL to SQL with T5 using WikiSQL Dataset", description="This model generates an SQL query for your natural language input and validates it against the WikiSQL dataset." ) # Launch the app if __name__ == "__main__": interface.launch()