AliInamdar commited on
Commit
25d1164
Β·
verified Β·
1 Parent(s): 7124725

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +70 -34
src/streamlit_app.py CHANGED
@@ -1,40 +1,76 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
 
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
  """
15
 
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
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 os
7
 
8
+ st.set_page_config(page_title="🧠 SQL Chatbot with Groq", layout="centered")
9
+
10
+ # πŸ” Load Groq API Key from Hugging Face secret or env var
11
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY")
12
+
13
+ if not GROQ_API_KEY:
14
+ st.error("❌ GROQ_API_KEY not found. Please set it in Streamlit Secrets or environment.")
15
+ st.stop()
16
+
17
+ # 🧠 Generate SQL using Groq API
18
+ def generate_sql(prompt, df):
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
+ User question: "{prompt}"
 
 
25
 
26
+ Write a valid SQL query using the 'df' table. Return only the SQL.
27
  """
28
 
29
+ headers = {
30
+ "Authorization": f"Bearer {GROQ_API_KEY}",
31
+ "Content-Type": "application/json"
32
+ }
33
+ payload = {
34
+ "model": "llama3-70b-8192",
35
+ "messages": [{"role": "user", "content": full_prompt}],
36
+ "temperature": 0.2,
37
+ "max_tokens": 300
38
+ }
39
+
40
+ url = "https://api.groq.com/openai/v1/chat/completions"
41
+ response = requests.post(url, headers=headers, json=payload)
42
+ response.raise_for_status()
43
+ result = response.json()
44
+ return result["choices"][0]["message"]["content"].strip()
45
+
46
+ # 🧽 Clean SQL
47
+ def clean_sql(sql, df_columns):
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
+ # πŸ–₯️ UI
56
+ st.title("πŸ“Š Excel SQL Chatbot (Groq + Streamlit)")
57
+ uploaded_file = st.file_uploader("πŸ“‚ Upload your Excel file", type=["xlsx"])
58
+ user_prompt = st.text_input("🧠 Ask a question about your data")
59
+
60
+ if st.button("πŸš€ Generate & Run SQL"):
61
+ if uploaded_file and user_prompt:
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
+ st.markdown(f"### 🧾 Generated SQL")
69
+ st.code(sql, language="sql")
70
+ st.markdown("### πŸ“ˆ Query Results")
71
+ st.dataframe(result)
72
+
73
+ except Exception as e:
74
+ st.error(f"❌ Error: {str(e)}")
75
+ else:
76
+ st.warning("⚠️ Please upload a file and enter a question.")