Omkar1872 commited on
Commit
ac1d120
·
verified ·
1 Parent(s): dbf6b52

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +57 -0
  2. requirements.txt +5 -0
app.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ import sqlite3
4
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
5
+
6
+ # Load NL2SQL model
7
+ MODEL_NAME = "mrm8488/t5-base-finetuned-wikiSQL"
8
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
9
+ model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_NAME)
10
+
11
+ def nl_to_sql(nl_query, uploaded_file):
12
+ try:
13
+ # Load CSV
14
+ df = pd.read_csv(uploaded_file.name)
15
+ table_name = "user_table"
16
+
17
+ # Save DataFrame to SQLite
18
+ conn = sqlite3.connect(":memory:")
19
+ df.to_sql(table_name, conn, index=False, if_exists='replace')
20
+
21
+ # Generate SQL
22
+ input_ids = tokenizer(nl_query, return_tensors="pt").input_ids
23
+ outputs = model.generate(input_ids)
24
+ sql_query = tokenizer.decode(outputs[0], skip_special_tokens=True)
25
+
26
+ # Adjust SQL to use uploaded table name if needed
27
+ sql_query = sql_query.replace("table", table_name)
28
+
29
+ # Execute SQL safely
30
+ try:
31
+ result_df = pd.read_sql_query(sql_query, conn)
32
+ result = result_df.to_string(index=False)
33
+ except Exception as e:
34
+ result = f"SQL execution failed:\n{e}\n\nGenerated SQL:\n{sql_query}"
35
+
36
+ return sql_query, result
37
+
38
+ except Exception as e:
39
+ return "", f"Error processing file: {e}"
40
+
41
+ # Gradio UI
42
+ iface = gr.Interface(
43
+ fn=nl_to_sql,
44
+ inputs=[
45
+ gr.Textbox(label="Enter your question in natural language"),
46
+ gr.File(label="Upload CSV", type="file")
47
+ ],
48
+ outputs=[
49
+ gr.Textbox(label="Generated SQL Query"),
50
+ gr.Textbox(label="Query Result")
51
+ ],
52
+ title="Natural Language to SQL",
53
+ description="Upload a CSV dataset and ask questions in English. SQL queries and results will be generated automatically."
54
+ )
55
+
56
+ if __name__ == "__main__":
57
+ iface.launch()
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ transformers==4.34.0
2
+ torch
3
+ pandas
4
+ gradio
5
+ sqlalchemy