-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
159 lines (134 loc) · 5.2 KB
/
app.py
File metadata and controls
159 lines (134 loc) · 5.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
import streamlit as st
import sqlite3
import pandas as pd
import sqlparse
import google.generativeai as genai
st.set_page_config(page_title="NL2SQL", layout="wide")
api_key = st.secrets.get("GEMINI_API_KEY", "")
if not api_key:
st.error("Please set GEMINI_API_KEY in .streamlit/secrets.toml")
st.stop()
genai.configure(api_key=api_key)
def get_model():
"""Return the best available Gemini model with fallback."""
preferred_models = [
"models/gemini-2.5-flash",
"models/gemini-flash-latest",
"models/gemini-2.0-flash",
"models/gemini-pro-latest",
]
for name in preferred_models:
try:
model = genai.GenerativeModel(name)
#st.caption(f"Using model: **{name}**")
return model
except Exception:
continue
st.error("⚠️ No suitable Gemini model found. Please check your API quota.")
st.stop()
# Initialize model
model = get_model()
def get_schema(conn):
"""Return schema as dict: {table: [columns]}"""
schema = {}
cursor = conn.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = [row[0] for row in cursor.fetchall()]
for table in tables:
cursor.execute(f"PRAGMA table_info({table});")
columns = [row[1] for row in cursor.fetchall()]
schema[table] = columns
return schema
def format_schema(schema):
"""Nicely format schema for display & prompt"""
return "\n".join([f"{table}: {', '.join(cols)}" for table, cols in schema.items()])
def get_raw_schema(conn):
"""Return raw CREATE TABLE DDLs"""
cursor = conn.cursor()
cursor.execute("SELECT name, sql FROM sqlite_master WHERE type='table';")
return cursor.fetchall()
def format_raw_schema(raw_schema):
"""Format DDLs into text block"""
return "\n".join([f"{tbl}: {ddl}" for tbl, ddl in raw_schema if ddl])
def clean_sql(sql_text: str) -> str:
"""Clean LLM output to get valid SQL for SQLite execution."""
sql_text = sql_text.strip()
if sql_text.startswith("```"):
parts = sql_text.split("```")
if len(parts) >= 2:
sql_text = parts[1]
sql_text = sql_text.replace("sql\n", "").replace("sqlite", "").replace("ite", "")
sql_text = sql_text.replace("sql", "")
sql_text = sql_text.strip()
if sql_text.endswith(";"):
sql_text = sql_text[:-1]
return sql_text
def execute_sql(conn, query):
"""Run SQL query (SELECT or non-SELECT) and return results or status"""
cursor = conn.cursor()
try:
cursor.execute(query)
if query.strip().lower().startswith("select"):
rows = cursor.fetchall()
cols = [desc[0] for desc in cursor.description]
return pd.DataFrame(rows, columns=cols), None
else:
conn.commit()
return None, f"Query executed successfully: {query}"
except Exception as e:
return None, f"⚠️ Error executing SQL: {e}"
st.title("💬 Natural Language → SQL Query Generator")
uploaded_file = st.file_uploader("Upload your SQLite database (.db)", type=["db"])
if uploaded_file:
db_path = "uploaded.db"
with open(db_path, "wb") as f:
f.write(uploaded_file.read())
st.success("Database uploaded successfully!")
conn = sqlite3.connect(db_path)
schema = get_schema(conn)
st.subheader("Database Schema")
for table, cols in schema.items():
st.markdown(f"**{table}**: {', '.join(cols)}")
show_ddl = st.checkbox("Show raw schema (DDL statements)")
raw_schema = None
if show_ddl:
raw_schema = get_raw_schema(conn)
st.subheader("Raw Schema DDL")
for table, ddl in raw_schema:
if ddl:
st.code(ddl, language="sql")
nl_query = st.text_area(
"Write your query in English",
placeholder="e.g. Show me top 5 students by GPA in 2023",
)
if st.button("Generate SQL"):
if nl_query.strip() == "":
st.warning("Please enter a query.")
else:
ddl_context = format_raw_schema(raw_schema) if raw_schema else ""
prompt = f"""
You are a SQL assistant. Convert the following natural language query
into a valid SQLite SQL query. Only use the provided tables and columns.
Database schema:
{format_schema(schema)}
DDL:
{ddl_context}
Query: {nl_query}
"""
try:
response = model.generate_content(prompt)
raw_sql = response.text.strip()
sql_query = clean_sql(raw_sql)
sql_query = sqlparse.format(sql_query, reindent=True)
st.subheader("🧠 Generated SQL")
st.code(sql_query, language="sql")
df, msg = execute_sql(conn, sql_query)
if df is not None:
st.dataframe(df, use_container_width=True)
csv = df.to_csv(index=False).encode("utf-8")
st.download_button("Download Results", csv, "results.csv", "text/csv")
elif msg:
st.success(msg)
except Exception as e:
st.error(f"⚠️ Error generating SQL: {e}")
conn.close()