Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,67 +5,76 @@ import requests
|
|
| 5 |
import re
|
| 6 |
import os
|
| 7 |
|
| 8 |
-
#
|
| 9 |
-
def
|
| 10 |
-
key = os.
|
| 11 |
if not key:
|
| 12 |
-
raise RuntimeError("
|
| 13 |
return key
|
| 14 |
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
-
# Generate SQL from prompt
|
| 18 |
-
def generate_sql(prompt, df):
|
| 19 |
-
schema = ", ".join([f"{col} ({dtype})" for col, dtype in df.dtypes.items()])
|
| 20 |
-
full_prompt = f"""You are a SQL expert. Table 'df' schema: {schema}
|
| 21 |
User question: "{prompt}"
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
|
|
|
|
|
|
| 25 |
headers = {
|
| 26 |
-
"Authorization": f"Bearer {
|
| 27 |
"Content-Type": "application/json"
|
| 28 |
}
|
| 29 |
payload = {
|
| 30 |
-
"model": "
|
| 31 |
-
"
|
| 32 |
-
"
|
| 33 |
-
"
|
| 34 |
}
|
| 35 |
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
|
|
|
| 39 |
|
| 40 |
-
# Clean SQL for DuckDB
|
| 41 |
-
def
|
| 42 |
sql = sql.replace("`", '"')
|
| 43 |
-
for
|
| 44 |
-
if " " in
|
| 45 |
-
|
|
|
|
| 46 |
return sql
|
| 47 |
|
| 48 |
-
# Main
|
| 49 |
-
def
|
| 50 |
try:
|
| 51 |
df = pd.read_excel(file)
|
| 52 |
-
sql =
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
return f"π SQL:\n```sql\n{sql}\n```",
|
| 56 |
except Exception as e:
|
| 57 |
-
return f"β Error: {e}", pd.DataFrame()
|
| 58 |
|
| 59 |
-
# Gradio UI
|
| 60 |
with gr.Blocks() as demo:
|
| 61 |
-
gr.Markdown("##
|
| 62 |
-
|
| 63 |
-
|
|
|
|
| 64 |
submit = gr.Button("π Generate & Run")
|
| 65 |
sql_output = gr.Markdown()
|
| 66 |
result_table = gr.Dataframe()
|
| 67 |
|
| 68 |
-
submit.click(fn=
|
| 69 |
|
|
|
|
| 70 |
if __name__ == "__main__":
|
| 71 |
-
demo.launch()
|
|
|
|
| 5 |
import re
|
| 6 |
import os
|
| 7 |
|
| 8 |
+
# π Load Groq API Key securely
|
| 9 |
+
def get_groq_api_key():
|
| 10 |
+
key = os.environ.get("GROQ_API_KEY")
|
| 11 |
if not key:
|
| 12 |
+
raise RuntimeError("β GROQ_API_KEY not found in environment. Add it in Hugging Face Secrets.")
|
| 13 |
return key
|
| 14 |
|
| 15 |
+
GROQ_API_KEY = get_groq_api_key()
|
| 16 |
+
|
| 17 |
+
# π§ Generate SQL using Groq LLaMA3 model
|
| 18 |
+
def generate_sql_from_prompt(prompt, df):
|
| 19 |
+
schema = ", ".join([f"{col} ({str(dtype)})" for col, dtype in df.dtypes.items()])
|
| 20 |
+
full_prompt = f"""
|
| 21 |
+
You are a SQL expert. The table is called 'df' and has the following columns:
|
| 22 |
+
{schema}
|
| 23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
User question: "{prompt}"
|
| 25 |
+
|
| 26 |
+
Write a valid SQL query using the 'df' table. Return only the SQL code.
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
url = "https://api.groq.com/openai/v1/chat/completions"
|
| 30 |
headers = {
|
| 31 |
+
"Authorization": f"Bearer {GROQ_API_KEY}",
|
| 32 |
"Content-Type": "application/json"
|
| 33 |
}
|
| 34 |
payload = {
|
| 35 |
+
"model": "llama3-70b-8192",
|
| 36 |
+
"messages": [{"role": "user", "content": full_prompt}],
|
| 37 |
+
"temperature": 0.3,
|
| 38 |
+
"max_tokens": 300
|
| 39 |
}
|
| 40 |
|
| 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("```sql").strip("```").strip()
|
| 45 |
|
| 46 |
+
# π§½ Clean SQL for DuckDB
|
| 47 |
+
def clean_sql_for_duckdb(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 |
+
# π¬ Main chatbot logic
|
| 56 |
+
def chatbot_interface(file, question):
|
| 57 |
try:
|
| 58 |
df = pd.read_excel(file)
|
| 59 |
+
sql = generate_sql_from_prompt(question, df)
|
| 60 |
+
cleaned_sql = clean_sql_for_duckdb(sql, df.columns)
|
| 61 |
+
result = duckdb.query(cleaned_sql).to_df()
|
| 62 |
+
return f"π SQL Query:\n```sql\n{sql}\n```", result
|
| 63 |
except Exception as e:
|
| 64 |
+
return f"β Error: {str(e)}", pd.DataFrame()
|
| 65 |
|
| 66 |
+
# ποΈ Gradio UI
|
| 67 |
with gr.Blocks() as demo:
|
| 68 |
+
gr.Markdown("## π§ Excel SQL Chatbot powered by Groq + LLaMA3")
|
| 69 |
+
with gr.Row():
|
| 70 |
+
file_input = gr.File(label="π Upload Excel File (.xlsx)")
|
| 71 |
+
question = gr.Textbox(label="π§ Ask your SQL question")
|
| 72 |
submit = gr.Button("π Generate & Run")
|
| 73 |
sql_output = gr.Markdown()
|
| 74 |
result_table = gr.Dataframe()
|
| 75 |
|
| 76 |
+
submit.click(fn=chatbot_interface, inputs=[file_input, question], outputs=[sql_output, result_table])
|
| 77 |
|
| 78 |
+
# π Run the app
|
| 79 |
if __name__ == "__main__":
|
| 80 |
+
demo.launch()
|