Update app.py
Browse files
app.py
CHANGED
@@ -3,19 +3,20 @@ import pandas as pd
|
|
3 |
import matplotlib.pyplot as plt
|
4 |
import io
|
5 |
import google.generativeai as genai
|
|
|
6 |
|
7 |
def process_file(api_key, file, instructions):
|
8 |
-
#
|
9 |
genai.configure(api_key=api_key)
|
10 |
model = genai.GenerativeModel('gemini-2.5-pro-preview-03-25')
|
11 |
|
12 |
-
# Read
|
13 |
if file.name.endswith('.csv'):
|
14 |
df = pd.read_csv(file.name)
|
15 |
else:
|
16 |
df = pd.read_excel(file.name)
|
17 |
|
18 |
-
#
|
19 |
data_description = df.describe().to_string()
|
20 |
columns_info = "\n".join([f"{col}: {df[col].dtype}" for col in df.columns])
|
21 |
prompt = f"""
|
@@ -28,72 +29,62 @@ def process_file(api_key, file, instructions):
|
|
28 |
|
29 |
User instructions: {instructions if instructions else 'No specific instructions provided.'}
|
30 |
|
31 |
-
Generate Python code for 3 different visualizations
|
32 |
-
|
33 |
-
Format your response as:
|
34 |
# Visualization 1
|
35 |
-
|
36 |
-
|
37 |
# Visualization 2
|
38 |
-
|
39 |
-
|
40 |
# Visualization 3
|
41 |
-
|
42 |
"""
|
43 |
|
|
|
44 |
response = model.generate_content(prompt)
|
45 |
code = response.text.strip()
|
46 |
|
47 |
-
|
48 |
-
print(code)
|
49 |
-
|
50 |
visualizations = []
|
51 |
for i, viz_code in enumerate(code.split("# Visualization")[1:4], 1):
|
52 |
plt.figure(figsize=(10, 6))
|
53 |
try:
|
54 |
-
#
|
55 |
cleaned_code = '\n'.join(line.strip() for line in viz_code.split('\n') if line.strip())
|
56 |
-
print(f"\nVisualization {i} code:")
|
57 |
-
print(cleaned_code)
|
58 |
-
|
59 |
exec(cleaned_code, {'df': df, 'plt': plt})
|
60 |
plt.title(f"Visualization {i}")
|
61 |
|
62 |
-
#
|
63 |
buf = io.BytesIO()
|
64 |
-
plt.savefig(buf, format='png')
|
65 |
-
buf.seek(0)
|
66 |
plt.close()
|
67 |
-
|
68 |
-
visualizations.append(buf)
|
69 |
except Exception as e:
|
70 |
-
print(f"
|
71 |
visualizations.append(None)
|
72 |
|
73 |
-
# Ensure
|
74 |
-
|
75 |
-
visualizations.append(None)
|
76 |
-
|
77 |
-
return visualizations
|
78 |
|
79 |
# Gradio interface
|
80 |
with gr.Blocks() as demo:
|
81 |
-
gr.Markdown("# Data
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
|
|
|
|
|
|
|
|
86 |
|
87 |
with gr.Row():
|
88 |
-
|
89 |
-
output2 = gr.Image(label="Visualization 2")
|
90 |
-
output3 = gr.Image(label="Visualization 3")
|
91 |
|
92 |
submit.click(
|
93 |
-
|
94 |
inputs=[api_key, file, instructions],
|
95 |
-
outputs=
|
96 |
-
show_progress=True,
|
97 |
)
|
98 |
|
99 |
demo.launch()
|
|
|
3 |
import matplotlib.pyplot as plt
|
4 |
import io
|
5 |
import google.generativeai as genai
|
6 |
+
from PIL import Image
|
7 |
|
8 |
def process_file(api_key, file, instructions):
|
9 |
+
# Configure Gemini API
|
10 |
genai.configure(api_key=api_key)
|
11 |
model = genai.GenerativeModel('gemini-2.5-pro-preview-03-25')
|
12 |
|
13 |
+
# Read uploaded file
|
14 |
if file.name.endswith('.csv'):
|
15 |
df = pd.read_csv(file.name)
|
16 |
else:
|
17 |
df = pd.read_excel(file.name)
|
18 |
|
19 |
+
# Generate analysis prompt
|
20 |
data_description = df.describe().to_string()
|
21 |
columns_info = "\n".join([f"{col}: {df[col].dtype}" for col in df.columns])
|
22 |
prompt = f"""
|
|
|
29 |
|
30 |
User instructions: {instructions if instructions else 'No specific instructions provided.'}
|
31 |
|
32 |
+
Generate Python code for 3 different matplotlib visualizations. Only provide executable code without explanations.
|
33 |
+
Format as:
|
|
|
34 |
# Visualization 1
|
35 |
+
[code]
|
|
|
36 |
# Visualization 2
|
37 |
+
[code]
|
|
|
38 |
# Visualization 3
|
39 |
+
[code]
|
40 |
"""
|
41 |
|
42 |
+
# Get Gemini response
|
43 |
response = model.generate_content(prompt)
|
44 |
code = response.text.strip()
|
45 |
|
46 |
+
# Process visualizations
|
|
|
|
|
47 |
visualizations = []
|
48 |
for i, viz_code in enumerate(code.split("# Visualization")[1:4], 1):
|
49 |
plt.figure(figsize=(10, 6))
|
50 |
try:
|
51 |
+
# Clean and execute generated code
|
52 |
cleaned_code = '\n'.join(line.strip() for line in viz_code.split('\n') if line.strip())
|
|
|
|
|
|
|
53 |
exec(cleaned_code, {'df': df, 'plt': plt})
|
54 |
plt.title(f"Visualization {i}")
|
55 |
|
56 |
+
# Convert plot to Gradio-compatible format
|
57 |
buf = io.BytesIO()
|
58 |
+
plt.savefig(buf, format='png', bbox_inches='tight')
|
|
|
59 |
plt.close()
|
60 |
+
buf.seek(0)
|
61 |
+
visualizations.append(Image.open(buf))
|
62 |
except Exception as e:
|
63 |
+
print(f"Visualization {i} error: {str(e)}")
|
64 |
visualizations.append(None)
|
65 |
|
66 |
+
# Ensure 3 outputs for Gradio
|
67 |
+
return visualizations + [None]*(3-len(visualizations))
|
|
|
|
|
|
|
68 |
|
69 |
# Gradio interface
|
70 |
with gr.Blocks() as demo:
|
71 |
+
gr.Markdown("""# AI-Powered Data Visualizer
|
72 |
+
Upload your data file and get automatic visualizations powered by Gemini""")
|
73 |
+
|
74 |
+
with gr.Row():
|
75 |
+
api_key = gr.Textbox(label="Gemini API Key", type="password")
|
76 |
+
instructions = gr.Textbox(label="Custom Instructions (optional)")
|
77 |
+
|
78 |
+
file = gr.File(label="Dataset (CSV/Excel)", file_types=[".csv", ".xlsx"])
|
79 |
+
submit = gr.Button("Generate Insights", variant="primary")
|
80 |
|
81 |
with gr.Row():
|
82 |
+
outputs = [gr.Image(label=f"Visualization {i+1}") for i in range(3)]
|
|
|
|
|
83 |
|
84 |
submit.click(
|
85 |
+
process_file,
|
86 |
inputs=[api_key, file, instructions],
|
87 |
+
outputs=outputs
|
|
|
88 |
)
|
89 |
|
90 |
demo.launch()
|