|
|
import os |
|
|
import gradio as gr |
|
|
import pandas as pd |
|
|
import matplotlib.pyplot as plt |
|
|
from groq import Groq |
|
|
import io |
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
def ask_groq(prompt): |
|
|
response = client.chat.completions.create( |
|
|
model="mixtral-8x7b-32768", |
|
|
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"] |
|
|
|
|
|
|
|
|
def generate_dashboard(file, query): |
|
|
try: |
|
|
df = pd.read_csv(file.name) |
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
if "```python" in code_response: |
|
|
code = code_response.split("```python")[1].split("```")[0].strip() |
|
|
else: |
|
|
code = code_response.strip() |
|
|
|
|
|
|
|
|
local_vars = {"df": df, "plt": plt} |
|
|
exec(code, {}, local_vars) |
|
|
|
|
|
|
|
|
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)}" |
|
|
|
|
|
|
|
|
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() |
|
|
|