Update app.py
Browse files
app.py
CHANGED
|
@@ -1,28 +1,81 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
from openai import OpenAI
|
| 3 |
import sqlite3
|
| 4 |
-
from init_db import initialize_database
|
| 5 |
|
| 6 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
initialize_database()
|
| 8 |
|
| 9 |
-
# App
|
| 10 |
st.set_page_config(page_title="Zero SQL", layout="wide")
|
| 11 |
st.title("Zero SQL - Natural Language to SQL Query")
|
| 12 |
|
| 13 |
-
# Sidebar for API key
|
| 14 |
with st.sidebar:
|
| 15 |
-
st.header("
|
| 16 |
api_key = st.text_input("OpenAI API Key", type="password")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
# Main form
|
| 19 |
with st.form("query_form"):
|
| 20 |
user_input = st.text_area(
|
| 21 |
"Enter your data request in natural language:",
|
| 22 |
-
placeholder="e.g. Show all orders
|
| 23 |
-
height=
|
| 24 |
)
|
| 25 |
-
submitted = st.form_submit_button("Generate Query")
|
| 26 |
|
| 27 |
if submitted:
|
| 28 |
if not api_key:
|
|
@@ -31,63 +84,59 @@ if submitted:
|
|
| 31 |
st.error("📝 Please enter your data request!")
|
| 32 |
else:
|
| 33 |
try:
|
| 34 |
-
# Initialize OpenAI client
|
| 35 |
client = OpenAI(api_key=api_key)
|
| 36 |
|
| 37 |
-
# System
|
| 38 |
-
system_context = """
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
|
| 54 |
-
# Generate SQL query
|
| 55 |
response = client.chat.completions.create(
|
| 56 |
model="gpt-4o",
|
| 57 |
messages=[
|
| 58 |
{"role": "system", "content": system_context},
|
| 59 |
-
{"role": "user", "content":
|
| 60 |
],
|
| 61 |
-
|
| 62 |
)
|
| 63 |
|
| 64 |
sql_query = response.choices[0].message.content.strip()
|
| 65 |
|
| 66 |
-
# Execute
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
column_names = [description[0] for description in cursor.description]
|
| 73 |
-
conn.close()
|
| 74 |
|
| 75 |
-
|
| 76 |
-
st.subheader("Generated SQL Query")
|
| 77 |
st.code(sql_query, language="sql")
|
| 78 |
|
| 79 |
-
st.subheader("
|
| 80 |
if results:
|
| 81 |
st.dataframe(
|
| 82 |
data=results,
|
| 83 |
-
columns=
|
| 84 |
use_container_width=True,
|
| 85 |
hide_index=True
|
| 86 |
)
|
| 87 |
else:
|
| 88 |
st.info("No results found", icon="ℹ️")
|
| 89 |
-
|
| 90 |
except sqlite3.Error as e:
|
| 91 |
-
st.error(f"SQL Error: {str(e)}")
|
| 92 |
except Exception as e:
|
| 93 |
-
st.error(f"
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
from openai import OpenAI
|
| 3 |
import sqlite3
|
|
|
|
| 4 |
|
| 5 |
+
# Database initialization with caching
|
| 6 |
+
@st.cache_resource
|
| 7 |
+
def initialize_database():
|
| 8 |
+
conn = sqlite3.connect('database.db')
|
| 9 |
+
cursor = conn.cursor()
|
| 10 |
+
|
| 11 |
+
# Create tables
|
| 12 |
+
cursor.execute('''
|
| 13 |
+
CREATE TABLE IF NOT EXISTS Produkte (
|
| 14 |
+
ProduktID INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 15 |
+
Produktname TEXT NOT NULL,
|
| 16 |
+
Preis REAL NOT NULL
|
| 17 |
+
)
|
| 18 |
+
''')
|
| 19 |
+
|
| 20 |
+
cursor.execute('''
|
| 21 |
+
CREATE TABLE IF NOT EXISTS Bestellungen (
|
| 22 |
+
BestellungID INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 23 |
+
ProduktID INTEGER NOT NULL,
|
| 24 |
+
Menge INTEGER NOT NULL,
|
| 25 |
+
Bestelldatum TEXT NOT NULL,
|
| 26 |
+
Person TEXT NOT NULL,
|
| 27 |
+
FOREIGN KEY (ProduktID) REFERENCES Produkte(ProduktID)
|
| 28 |
+
)
|
| 29 |
+
''')
|
| 30 |
+
|
| 31 |
+
# Insert sample products
|
| 32 |
+
cursor.execute("SELECT COUNT(*) FROM Produkte")
|
| 33 |
+
if cursor.fetchone()[0] == 0:
|
| 34 |
+
products = [
|
| 35 |
+
('Laptop', 999.99),
|
| 36 |
+
('Smartphone', 699.99),
|
| 37 |
+
('Tablet', 399.99)
|
| 38 |
+
]
|
| 39 |
+
cursor.executemany("INSERT INTO Produkte (Produktname, Preis) VALUES (?, ?)", products)
|
| 40 |
+
|
| 41 |
+
# Insert sample orders
|
| 42 |
+
cursor.execute("SELECT COUNT(*) FROM Bestellungen")
|
| 43 |
+
if cursor.fetchone()[0] == 0:
|
| 44 |
+
orders = [
|
| 45 |
+
(1, 2, '2024-10-20', 'Max Mustermann'),
|
| 46 |
+
(2, 1, '2024-10-21', 'Erika Musterfrau'),
|
| 47 |
+
(3, 3, '2024-10-22', 'Hans Meier')
|
| 48 |
+
]
|
| 49 |
+
cursor.executemany("INSERT INTO Bestellungen (ProduktID, Menge, Bestelldatum, Person) VALUES (?, ?, ?, ?)", orders)
|
| 50 |
+
|
| 51 |
+
conn.commit()
|
| 52 |
+
conn.close()
|
| 53 |
+
|
| 54 |
+
# Initialize the database
|
| 55 |
initialize_database()
|
| 56 |
|
| 57 |
+
# App UI
|
| 58 |
st.set_page_config(page_title="Zero SQL", layout="wide")
|
| 59 |
st.title("Zero SQL - Natural Language to SQL Query")
|
| 60 |
|
| 61 |
+
# Sidebar for API key
|
| 62 |
with st.sidebar:
|
| 63 |
+
st.header("Configuration")
|
| 64 |
api_key = st.text_input("OpenAI API Key", type="password")
|
| 65 |
+
st.markdown("---")
|
| 66 |
+
st.markdown("**Sample Questions:**")
|
| 67 |
+
st.markdown("- Show total sales per product")
|
| 68 |
+
st.markdown("- List orders from Max Mustermann")
|
| 69 |
+
st.markdown("- Find most popular product by quantity")
|
| 70 |
|
| 71 |
# Main form
|
| 72 |
with st.form("query_form"):
|
| 73 |
user_input = st.text_area(
|
| 74 |
"Enter your data request in natural language:",
|
| 75 |
+
placeholder="e.g. Show all orders over €500",
|
| 76 |
+
height=100
|
| 77 |
)
|
| 78 |
+
submitted = st.form_submit_button("🚀 Generate Query")
|
| 79 |
|
| 80 |
if submitted:
|
| 81 |
if not api_key:
|
|
|
|
| 84 |
st.error("📝 Please enter your data request!")
|
| 85 |
else:
|
| 86 |
try:
|
|
|
|
| 87 |
client = OpenAI(api_key=api_key)
|
| 88 |
|
| 89 |
+
# System prompt with schema
|
| 90 |
+
system_context = """You are a SQL expert. Given these SQL tables:
|
| 91 |
+
CREATE TABLE Produkte (
|
| 92 |
+
ProduktID INTEGER PRIMARY KEY,
|
| 93 |
+
Produktname TEXT NOT NULL,
|
| 94 |
+
Preis REAL NOT NULL
|
| 95 |
+
);
|
| 96 |
+
CREATE TABLE Bestellungen (
|
| 97 |
+
BestellungID INTEGER PRIMARY KEY,
|
| 98 |
+
ProduktID INTEGER,
|
| 99 |
+
Menge INTEGER,
|
| 100 |
+
Bestelldatum TEXT,
|
| 101 |
+
Person TEXT,
|
| 102 |
+
FOREIGN KEY (ProduktID) REFERENCES Produkte(ProduktID)
|
| 103 |
+
);
|
| 104 |
+
Generate ONLY the SQL query for the user's request. Output raw SQL without any formatting or explanations."""
|
| 105 |
|
| 106 |
+
# Generate SQL query
|
| 107 |
response = client.chat.completions.create(
|
| 108 |
model="gpt-4o",
|
| 109 |
messages=[
|
| 110 |
{"role": "system", "content": system_context},
|
| 111 |
+
{"role": "user", "content": user_input}
|
| 112 |
],
|
| 113 |
+
temperature=0.3
|
| 114 |
)
|
| 115 |
|
| 116 |
sql_query = response.choices[0].message.content.strip()
|
| 117 |
|
| 118 |
+
# Execute and display results
|
| 119 |
+
with sqlite3.connect('database.db') as conn:
|
| 120 |
+
cursor = conn.cursor()
|
| 121 |
+
cursor.execute(sql_query)
|
| 122 |
+
results = cursor.fetchall()
|
| 123 |
+
columns = [desc[0] for desc in cursor.description]
|
|
|
|
|
|
|
| 124 |
|
| 125 |
+
st.subheader("Generated SQL")
|
|
|
|
| 126 |
st.code(sql_query, language="sql")
|
| 127 |
|
| 128 |
+
st.subheader("Results")
|
| 129 |
if results:
|
| 130 |
st.dataframe(
|
| 131 |
data=results,
|
| 132 |
+
columns=columns,
|
| 133 |
use_container_width=True,
|
| 134 |
hide_index=True
|
| 135 |
)
|
| 136 |
else:
|
| 137 |
st.info("No results found", icon="ℹ️")
|
| 138 |
+
|
| 139 |
except sqlite3.Error as e:
|
| 140 |
+
st.error(f"🚨 SQL Error: {str(e)}")
|
| 141 |
except Exception as e:
|
| 142 |
+
st.error(f"💥 Unexpected Error: {str(e)}")
|