File size: 2,522 Bytes
1f77085 4ece57f 1f77085 4ece57f 1f77085 4ece57f 1f77085 b465b1c 1f77085 b465b1c 1f77085 b465b1c 1f77085 b465b1c 1f77085 4ece57f 1f77085 4ece57f 1f77085 | 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 68 69 70 71 72 73 74 75 76 77 78 79 | import os
import gradio as gr
import pandas as pd
import matplotlib.pyplot as plt
from groq import Groq
import io
# Load Groq API key from Hugging Face secrets
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
if not GROQ_API_KEY:
raise ValueError("❌ GROQ_API_KEY not found. Please add it in Hugging Face Secrets.")
client = Groq(api_key=GROQ_API_KEY)
# Function to query Groq LLM
def ask_groq(prompt):
response = client.chat.completions.create(
model="mixtral-8x7b-32768", # good for structured reasoning
messages=[
{"role": "system", "content": "You are a data visualization assistant. Convert user requests into Python Pandas + Matplotlib code."},
{"role": "user", "content": prompt}
],
temperature=0.3,
max_tokens=500
)
return response.choices[0].message["content"]
# Function to generate chart
def generate_dashboard(file, query):
try:
df = pd.read_csv(file.name)
# Build prompt for Groq
prompt = f"""
I have the following dataset columns: {', '.join(df.columns)}.
User wants: {query}.
Write Python code using Pandas + Matplotlib to create the chart.
The dataframe variable is `df`. Do not load the CSV again.
Only return the code inside ```python ... ``` fences.
"""
code_response = ask_groq(prompt)
# Extract python code block
if "```python" in code_response:
code = code_response.split("```python")[1].split("```")[0].strip()
else:
code = code_response.strip()
# Run the code safely
local_vars = {"df": df, "plt": plt}
exec(code, {}, local_vars)
# Save plot to buffer
buf = io.BytesIO()
plt.savefig(buf, format="png")
buf.seek(0)
plt.close()
return buf, code
except Exception as e:
return None, f"❌ Error: {str(e)}"
# Gradio UI
with gr.Blocks() as demo:
gr.Markdown("## 📊 AI-Powered Dashboard Generator (Groq + Matplotlib)")
file_input = gr.File(label="Upload CSV", file_types=[".csv"])
query_input = gr.Textbox(label="What do you want to see?", placeholder="e.g. Show a bar chart of subscribers per subject")
output_plot = gr.Image(label="Generated Chart")
output_code = gr.Code(label="Generated Python Code")
run_btn = gr.Button("Generate Chart")
run_btn.click(fn=generate_dashboard, inputs=[file_input, query_input], outputs=[output_plot, output_code])
demo.launch()
|