Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +73 -34
src/streamlit_app.py
CHANGED
|
@@ -1,40 +1,79 @@
|
|
| 1 |
-
import altair as alt
|
| 2 |
-
import numpy as np
|
| 3 |
-
import pandas as pd
|
| 4 |
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
|
| 10 |
-
If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
|
| 11 |
-
forums](https://discuss.streamlit.io).
|
| 12 |
|
| 13 |
-
|
| 14 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
theta = 2 * np.pi * num_turns * indices
|
| 21 |
-
radius = indices
|
| 22 |
-
|
| 23 |
-
x = radius * np.cos(theta)
|
| 24 |
-
y = radius * np.sin(theta)
|
| 25 |
-
|
| 26 |
-
df = pd.DataFrame({
|
| 27 |
-
"x": x,
|
| 28 |
-
"y": y,
|
| 29 |
-
"idx": indices,
|
| 30 |
-
"rand": np.random.randn(num_points),
|
| 31 |
-
})
|
| 32 |
-
|
| 33 |
-
st.altair_chart(alt.Chart(df, height=700, width=700)
|
| 34 |
-
.mark_point(filled=True)
|
| 35 |
-
.encode(
|
| 36 |
-
x=alt.X("x", axis=None),
|
| 37 |
-
y=alt.Y("y", axis=None),
|
| 38 |
-
color=alt.Color("idx", legend=None, scale=alt.Scale()),
|
| 39 |
-
size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
|
| 40 |
-
))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import duckdb
|
| 4 |
+
import requests
|
| 5 |
+
import re
|
| 6 |
+
import io
|
| 7 |
|
| 8 |
+
# π Set your Together API key securely
|
| 9 |
+
TOGETHER_API_KEY = st.secrets["TOGETHER_API_KEY"] if "TOGETHER_API_KEY" in st.secrets else st.text_input("Enter Together API Key", type="password")
|
| 10 |
+
|
| 11 |
+
# π§ Generate SQL using Together API
|
| 12 |
+
def generate_sql_from_prompt(prompt, df):
|
| 13 |
+
schema = ", ".join([f"{col} ({str(dtype)})" for col, dtype in df.dtypes.items()])
|
| 14 |
+
full_prompt = f"""
|
| 15 |
+
You are a SQL expert. Here is a table called 'df' with the following schema:
|
| 16 |
+
{schema}
|
| 17 |
|
| 18 |
+
User question: "{prompt}"
|
|
|
|
|
|
|
| 19 |
|
| 20 |
+
Write a valid SQL query using the 'df' table. Return only the SQL code.
|
| 21 |
"""
|
| 22 |
+
url = "https://api.together.xyz/v1/chat/completions"
|
| 23 |
+
headers = {
|
| 24 |
+
"Authorization": f"Bearer {TOGETHER_API_KEY}",
|
| 25 |
+
"Content-Type": "application/json"
|
| 26 |
+
}
|
| 27 |
+
payload = {
|
| 28 |
+
"model": "mistralai/Mixtral-8x7B-Instruct-v0.1",
|
| 29 |
+
"messages": [{"role": "user", "content": full_prompt}],
|
| 30 |
+
"temperature": 0.2,
|
| 31 |
+
"max_tokens": 200
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
response = requests.post(url, headers=headers, json=payload)
|
| 35 |
+
response.raise_for_status()
|
| 36 |
+
result = response.json()
|
| 37 |
+
return result['choices'][0]['message']['content'].strip("```sql").strip("```").strip()
|
| 38 |
+
|
| 39 |
+
# π§½ Clean SQL for DuckDB
|
| 40 |
+
def clean_sql_for_duckdb(sql, df_columns):
|
| 41 |
+
sql = sql.replace("`", '"')
|
| 42 |
+
for col in df_columns:
|
| 43 |
+
if " " in col and f'"{col}"' not in sql:
|
| 44 |
+
pattern = r'\b' + re.escape(col) + r'\b'
|
| 45 |
+
sql = re.sub(pattern, f'"{col}"', sql)
|
| 46 |
+
return sql
|
| 47 |
+
|
| 48 |
+
# === Streamlit UI ===
|
| 49 |
+
st.set_page_config(page_title="π§ Excel SQL Chatbot", layout="centered")
|
| 50 |
+
st.title("π Excel SQL Chatbot with LLM")
|
| 51 |
+
st.markdown("Upload your **Excel file**, ask a question in natural language, and get results from SQL queries generated by an LLM.")
|
| 52 |
+
|
| 53 |
+
uploaded_file = st.file_uploader("π Upload Excel file", type=["xlsx"])
|
| 54 |
+
|
| 55 |
+
if uploaded_file and TOGETHER_API_KEY:
|
| 56 |
+
df = pd.read_excel(uploaded_file)
|
| 57 |
+
st.success(f"β
Loaded: {uploaded_file.name} with shape {df.shape}")
|
| 58 |
+
st.dataframe(df.head(), use_container_width=True)
|
| 59 |
+
|
| 60 |
+
user_prompt = st.text_input("π¬ Ask a question about your data")
|
| 61 |
+
|
| 62 |
+
if st.button("π Generate SQL & Run") and user_prompt:
|
| 63 |
+
try:
|
| 64 |
+
sql_query = generate_sql_from_prompt(user_prompt, df)
|
| 65 |
+
cleaned_sql = clean_sql_for_duckdb(sql_query, df.columns)
|
| 66 |
+
|
| 67 |
+
st.code(sql_query, language="sql")
|
| 68 |
+
|
| 69 |
+
con = duckdb.connect()
|
| 70 |
+
con.register("df", df)
|
| 71 |
+
result_df = con.execute(cleaned_sql).fetchdf()
|
| 72 |
+
|
| 73 |
+
st.success("β
Query executed successfully")
|
| 74 |
+
st.dataframe(result_df, use_container_width=True)
|
| 75 |
|
| 76 |
+
except Exception as e:
|
| 77 |
+
st.error(f"β Error: {e}")
|
| 78 |
+
else:
|
| 79 |
+
st.info("π Please upload a file and provide the API key to continue.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|