Spaces:
Sleeping
Sleeping
| import streamlit as st | |
| import pandas as pd | |
| import duckdb | |
| import requests | |
| import re | |
| import io | |
| import os | |
| # === π Safe API key input (streamlit secrets optional) === | |
| TOGETHER_API_KEY = os.environ.get("TOGETHER_API_KEY", "") # Preferred for Hugging Face or env deployment | |
| if not TOGETHER_API_KEY: | |
| TOGETHER_API_KEY = st.text_input("π Enter Together API Key", type="password") | |
| # === SQL Generator Function === | |
| def generate_sql_from_prompt(prompt, df): | |
| schema = ", ".join([f"{col} ({str(dtype)})" for col, dtype in df.dtypes.items()]) | |
| full_prompt = f""" | |
| You are a SQL expert. Here is a table called 'df' with the following schema: | |
| {schema} | |
| User question: "{prompt}" | |
| Write a valid SQL query using the 'df' table. Return only the SQL code. | |
| """ | |
| url = "https://api.together.xyz/v1/chat/completions" | |
| headers = { | |
| "Authorization": f"Bearer {TOGETHER_API_KEY}", | |
| "Content-Type": "application/json" | |
| } | |
| payload = { | |
| "model": "mistralai/Mixtral-8x7B-Instruct-v0.1", | |
| "messages": [{"role": "user", "content": full_prompt}], | |
| "temperature": 0.2, | |
| "max_tokens": 200 | |
| } | |
| response = requests.post(url, headers=headers, json=payload) | |
| response.raise_for_status() | |
| result = response.json() | |
| return result['choices'][0]['message']['content'].strip("```sql").strip("```").strip() | |
| # === SQL Cleaner === | |
| def clean_sql_for_duckdb(sql, df_columns): | |
| sql = sql.replace("`", '"') | |
| for col in df_columns: | |
| if " " in col and f'"{col}"' not in sql: | |
| pattern = r'\b' + re.escape(col) + r'\b' | |
| sql = re.sub(pattern, f'"{col}"', sql) | |
| return sql | |
| # === UI === | |
| st.set_page_config(page_title="π§ Excel SQL Chatbot", layout="centered") | |
| st.title("π Excel SQL Chatbot with LLM") | |
| st.markdown("Upload your **Excel file**, ask a question in natural language, and get results via generated SQL.") | |
| uploaded_file = st.file_uploader("π Upload Excel file", type=["xlsx"]) | |
| if TOGETHER_API_KEY and uploaded_file: | |
| df = pd.read_excel(uploaded_file) | |
| st.success(f"β Loaded: {uploaded_file.name} with shape {df.shape}") | |
| st.dataframe(df.head(), use_container_width=True) | |
| user_prompt = st.text_input("π¬ Ask a question about your data") | |
| if st.button("π Generate SQL & Run") and user_prompt: | |
| try: | |
| sql_query = generate_sql_from_prompt(user_prompt, df) | |
| cleaned_sql = clean_sql_for_duckdb(sql_query, df.columns) | |
| st.code(sql_query, language="sql") | |
| con = duckdb.connect() | |
| con.register("df", df) | |
| result_df = con.execute(cleaned_sql).fetchdf() | |
| st.success("β Query executed successfully") | |
| st.dataframe(result_df, use_container_width=True) | |
| except Exception as e: | |
| st.error(f"β Error: {e}") | |
| elif not TOGETHER_API_KEY: | |
| st.warning("π Please enter your Together API key to continue.") | |