|
import gradio as gr |
|
import pandas as pd |
|
import matplotlib.pyplot as plt |
|
import io |
|
import google.generativeai as genai |
|
from PIL import Image |
|
|
|
def process_file(api_key, file, instructions): |
|
|
|
genai.configure(api_key=api_key) |
|
model = genai.GenerativeModel('gemini-2.5-pro-preview-03-25') |
|
|
|
|
|
if file.name.endswith('.csv'): |
|
df = pd.read_csv(file.name) |
|
else: |
|
df = pd.read_excel(file.name) |
|
|
|
|
|
data_description = df.describe().to_string() |
|
columns_info = "\n".join([f"{col}: {df[col].dtype}" for col in df.columns]) |
|
prompt = f""" |
|
Given this dataset: |
|
Columns and types: |
|
{columns_info} |
|
|
|
Data summary: |
|
{data_description} |
|
|
|
User instructions: {instructions if instructions else 'No specific instructions provided.'} |
|
|
|
Generate Python code for 3 different matplotlib visualizations. Only provide executable code without explanations. |
|
Format as: |
|
# Visualization 1 |
|
[code] |
|
# Visualization 2 |
|
[code] |
|
# Visualization 3 |
|
[code] |
|
""" |
|
|
|
|
|
response = model.generate_content(prompt) |
|
code = response.text.strip() |
|
|
|
|
|
visualizations = [] |
|
for i, viz_code in enumerate(code.split("# Visualization")[1:4], 1): |
|
plt.figure(figsize=(10, 6)) |
|
try: |
|
|
|
cleaned_code = '\n'.join(line.strip() for line in viz_code.split('\n') if line.strip()) |
|
exec(cleaned_code, {'df': df, 'plt': plt}) |
|
plt.title(f"Visualization {i}") |
|
|
|
|
|
buf = io.BytesIO() |
|
plt.savefig(buf, format='png', bbox_inches='tight') |
|
plt.close() |
|
buf.seek(0) |
|
visualizations.append(Image.open(buf)) |
|
except Exception as e: |
|
print(f"Visualization {i} error: {str(e)}") |
|
visualizations.append(None) |
|
|
|
|
|
return visualizations + [None]*(3-len(visualizations)) |
|
|
|
|
|
with gr.Blocks() as demo: |
|
gr.Markdown("""# AI-Powered Data Visualizer |
|
Upload your data file and get automatic visualizations powered by Gemini""") |
|
|
|
with gr.Row(): |
|
api_key = gr.Textbox(label="Gemini API Key", type="password") |
|
instructions = gr.Textbox(label="Custom Instructions (optional)") |
|
|
|
file = gr.File(label="Dataset (CSV/Excel)", file_types=[".csv", ".xlsx"]) |
|
submit = gr.Button("Generate Insights", variant="primary") |
|
|
|
with gr.Row(): |
|
outputs = [gr.Image(label=f"Visualization {i+1}") for i in range(3)] |
|
|
|
submit.click( |
|
process_file, |
|
inputs=[api_key, file, instructions], |
|
outputs=outputs |
|
) |
|
|
|
demo.launch() |