File size: 2,549 Bytes
e6cd1d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import pandas as pd
import os
from groq import Groq

# Set page configuration
st.set_page_config(page_title="πŸ“Š Excel SQL Assistant", layout="centered")
st.title("🧠 Excel to SQL with GROQ + Streamlit")

# Load Groq API key from Streamlit secrets
GROQ_API_KEY = st.secrets.get("GROQ_API_KEY", None)

# Fallback warning if API key not found
if not GROQ_API_KEY:
    st.error("❌ GROQ API key not found. Please set it in your Hugging Face `secrets` tab.")
    st.stop()

# Initialize Groq client
client = Groq(api_key=GROQ_API_KEY)

# Upload Excel file
uploaded_file = st.file_uploader("πŸ“‚ Upload your Excel file", type=["xlsx"])
st.write("πŸ“ Uploaded file object:", uploaded_file)  # Debugging aid

# Text input for user query
user_query = st.text_input("πŸ’¬ Ask a question about your data")

# Generate button
if st.button("πŸš€ Generate & Run SQL"):
    if uploaded_file is not None and user_query.strip() != "":
        try:
            df = pd.read_excel(uploaded_file)
            st.success("βœ… File successfully loaded!")

            # Create schema-like string from the DataFrame
            preview = df.head(5).to_string(index=False)
            schema = f"Here are the first few rows of the dataset:\n\n{preview}"

            # Prompt to Groq
            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}"""

            with st.spinner("⏳ Generating SQL-like response using Groq..."):
                response = client.chat.completions.create(
                    model="mixtral-8x7b-32768",
                    messages=[
                        {"role": "system", "content": "You are an expert data assistant that writes pandas code based on user questions."},
                        {"role": "user", "content": full_prompt}
                    ]
                )

            answer = response.choices[0].message.content
            st.code(answer, language="python")

            # Optionally: try to run it
            try:
                local_vars = {"df": df.copy()}
                exec(answer, {}, local_vars)
                if 'df' in local_vars:
                    st.dataframe(local_vars['df'])
            except Exception as e:
                st.warning(f"⚠️ Could not execute the code:\n\n{e}")

        except Exception as e:
            st.error(f"❌ Error processing file: {e}")
    else:
        st.warning("⚠️ Please upload a file and enter a question.")