Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +46 -56
src/streamlit_app.py
CHANGED
|
@@ -1,76 +1,66 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
import pandas as pd
|
| 3 |
-
import duckdb
|
| 4 |
-
import requests
|
| 5 |
-
import re
|
| 6 |
import os
|
|
|
|
| 7 |
|
| 8 |
-
|
|
|
|
|
|
|
| 9 |
|
| 10 |
-
#
|
| 11 |
-
GROQ_API_KEY =
|
| 12 |
|
|
|
|
| 13 |
if not GROQ_API_KEY:
|
| 14 |
-
st.error("β
|
| 15 |
st.stop()
|
| 16 |
|
| 17 |
-
#
|
| 18 |
-
|
| 19 |
-
schema = ", ".join([f"{col} ({dtype})" for col, dtype in df.dtypes.items()])
|
| 20 |
-
full_prompt = f"""
|
| 21 |
-
You are a SQL expert. The table 'df' has the following columns and types:
|
| 22 |
-
{schema}
|
| 23 |
|
| 24 |
-
|
|
|
|
|
|
|
| 25 |
|
| 26 |
-
|
| 27 |
-
""
|
| 28 |
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
"messages": [{"role": "user", "content": full_prompt}],
|
| 36 |
-
"temperature": 0.2,
|
| 37 |
-
"max_tokens": 300
|
| 38 |
-
}
|
| 39 |
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
result = response.json()
|
| 44 |
-
return result["choices"][0]["message"]["content"].strip()
|
| 45 |
|
| 46 |
-
#
|
| 47 |
-
|
| 48 |
-
sql = sql.replace("`", '"')
|
| 49 |
-
for col in df_columns:
|
| 50 |
-
if " " in col and f'"{col}"' not in sql:
|
| 51 |
-
pattern = r'\b' + re.escape(col) + r'\b'
|
| 52 |
-
sql = re.sub(pattern, f'"{col}"', sql)
|
| 53 |
-
return sql
|
| 54 |
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
try:
|
| 63 |
-
df = pd.read_excel(uploaded_file)
|
| 64 |
-
sql = generate_sql(user_prompt, df)
|
| 65 |
-
cleaned_sql = clean_sql(sql, df.columns)
|
| 66 |
-
result = duckdb.query(cleaned_sql).to_df()
|
| 67 |
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
except Exception as e:
|
| 74 |
-
st.error(f"β Error: {
|
| 75 |
else:
|
| 76 |
-
st.warning("β οΈ Please upload a file and enter a question.")
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
| 3 |
import os
|
| 4 |
+
from groq import Groq
|
| 5 |
|
| 6 |
+
# Set page configuration
|
| 7 |
+
st.set_page_config(page_title="π Excel SQL Assistant", layout="centered")
|
| 8 |
+
st.title("π§ Excel to SQL with GROQ + Streamlit")
|
| 9 |
|
| 10 |
+
# Load Groq API key from Streamlit secrets
|
| 11 |
+
GROQ_API_KEY = st.secrets.get("GROQ_API_KEY", None)
|
| 12 |
|
| 13 |
+
# Fallback warning if API key not found
|
| 14 |
if not GROQ_API_KEY:
|
| 15 |
+
st.error("β GROQ API key not found. Please set it in your Hugging Face `secrets` tab.")
|
| 16 |
st.stop()
|
| 17 |
|
| 18 |
+
# Initialize Groq client
|
| 19 |
+
client = Groq(api_key=GROQ_API_KEY)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
+
# Upload Excel file
|
| 22 |
+
uploaded_file = st.file_uploader("π Upload your Excel file", type=["xlsx"])
|
| 23 |
+
st.write("π Uploaded file object:", uploaded_file) # Debugging aid
|
| 24 |
|
| 25 |
+
# Text input for user query
|
| 26 |
+
user_query = st.text_input("π¬ Ask a question about your data")
|
| 27 |
|
| 28 |
+
# Generate button
|
| 29 |
+
if st.button("π Generate & Run SQL"):
|
| 30 |
+
if uploaded_file is not None and user_query.strip() != "":
|
| 31 |
+
try:
|
| 32 |
+
df = pd.read_excel(uploaded_file)
|
| 33 |
+
st.success("β
File successfully loaded!")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
+
# Create schema-like string from the DataFrame
|
| 36 |
+
preview = df.head(5).to_string(index=False)
|
| 37 |
+
schema = f"Here are the first few rows of the dataset:\n\n{preview}"
|
|
|
|
|
|
|
| 38 |
|
| 39 |
+
# Prompt to Groq
|
| 40 |
+
full_prompt = f"""You are a data expert. Write a Pandas code snippet to answer the following question based on the data:\n\n{schema}\n\nQuestion: {user_query}"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
+
with st.spinner("β³ Generating SQL-like response using Groq..."):
|
| 43 |
+
response = client.chat.completions.create(
|
| 44 |
+
model="mixtral-8x7b-32768",
|
| 45 |
+
messages=[
|
| 46 |
+
{"role": "system", "content": "You are an expert data assistant that writes pandas code based on user questions."},
|
| 47 |
+
{"role": "user", "content": full_prompt}
|
| 48 |
+
]
|
| 49 |
+
)
|
| 50 |
|
| 51 |
+
answer = response.choices[0].message.content
|
| 52 |
+
st.code(answer, language="python")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
+
# Optionally: try to run it
|
| 55 |
+
try:
|
| 56 |
+
local_vars = {"df": df.copy()}
|
| 57 |
+
exec(answer, {}, local_vars)
|
| 58 |
+
if 'df' in local_vars:
|
| 59 |
+
st.dataframe(local_vars['df'])
|
| 60 |
+
except Exception as e:
|
| 61 |
+
st.warning(f"β οΈ Could not execute the code:\n\n{e}")
|
| 62 |
|
| 63 |
except Exception as e:
|
| 64 |
+
st.error(f"β Error processing file: {e}")
|
| 65 |
else:
|
| 66 |
+
st.warning("β οΈ Please upload a file and enter a question.")
|