Update app.py
Browse files
app.py
CHANGED
|
@@ -1,146 +1,69 @@
|
|
| 1 |
-
|
| 2 |
-
import matplotlib.pyplot as plt
|
| 3 |
-
import tempfile
|
| 4 |
-
import gradio as gr
|
| 5 |
-
from transformers import pipeline
|
| 6 |
-
from sklearn.cluster import KMeans
|
| 7 |
-
import numpy as np
|
| 8 |
-
|
| 9 |
-
class TaskAgent:
|
| 10 |
-
def parse_query(self, query):
|
| 11 |
-
if "trend" in query.lower():
|
| 12 |
-
return {"task": "trend_analysis"}
|
| 13 |
-
elif "cluster" in query.lower():
|
| 14 |
-
return {"task": "clustering"}
|
| 15 |
-
else:
|
| 16 |
-
return {"task": "distribution"}
|
| 17 |
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
f"Columns: {len(data.columns)}",
|
| 24 |
-
"Means: " + ", ".join([f"{col}: {val:.2f}"
|
| 25 |
-
for col, val in numeric_data.mean().items()])
|
| 26 |
-
]
|
| 27 |
-
return "\n".join(insights)
|
| 28 |
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
self.nlp_pipeline = pipeline("text-classification",
|
| 32 |
-
model="distilbert-base-uncased")
|
| 33 |
-
self.task_agent = TaskAgent()
|
| 34 |
-
self.analysis_agent = AnalysisAgent()
|
| 35 |
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
try:
|
| 42 |
-
data[col] = pd.to_datetime(data[col])
|
| 43 |
-
except:
|
| 44 |
-
pass
|
| 45 |
-
return data
|
| 46 |
|
| 47 |
-
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
if task['task'] == 'trend_analysis':
|
| 67 |
-
data.plot(kind='line', ax=ax, title='Trend Analysis')
|
| 68 |
-
elif task['task'] == 'clustering':
|
| 69 |
-
ax.scatter(data.iloc[:, 0], data.iloc[:, 1], c=data['cluster'])
|
| 70 |
-
ax.set_title('Cluster Analysis')
|
| 71 |
-
else:
|
| 72 |
-
data.plot(kind='bar', ax=ax, title='Distribution Analysis')
|
| 73 |
-
|
| 74 |
-
plt.tight_layout()
|
| 75 |
-
temp_file = tempfile.NamedTemporaryFile(suffix=".png", delete=False)
|
| 76 |
-
plt.savefig(temp_file.name)
|
| 77 |
-
plt.close()
|
| 78 |
-
return temp_file.name
|
| 79 |
-
except Exception as e:
|
| 80 |
-
print(f"Visualization error: {e}")
|
| 81 |
-
return None
|
| 82 |
|
| 83 |
-
|
| 84 |
-
agent = DataAnalysisAgent()
|
| 85 |
-
|
| 86 |
-
try:
|
| 87 |
-
# Validate CSV file
|
| 88 |
-
if not file.name.endswith('.csv'):
|
| 89 |
-
raise ValueError("Please upload a CSV file")
|
| 90 |
-
|
| 91 |
-
df = pd.read_csv(file.name)
|
| 92 |
-
df = agent.preprocess_data(df)
|
| 93 |
-
|
| 94 |
-
task = agent.parse_query(query)
|
| 95 |
-
analyzed_data = agent.analyze(df, task)
|
| 96 |
-
|
| 97 |
-
insights = agent.analysis_agent.generate_insights(analyzed_data)
|
| 98 |
-
chart_path = agent.visualize(analyzed_data, task)
|
| 99 |
-
|
| 100 |
-
return insights, chart_path if chart_path else None
|
| 101 |
-
|
| 102 |
-
except Exception as e:
|
| 103 |
-
return f"Error: {str(e)}", None
|
| 104 |
|
| 105 |
-
# Gradio
|
| 106 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 107 |
-
gr.Markdown(""
|
| 108 |
-
# Intelligent Data Analysis Agent
|
| 109 |
-
**Upload your CSV file and ask questions about your data**
|
| 110 |
-
""")
|
| 111 |
|
| 112 |
with gr.Row():
|
| 113 |
with gr.Column():
|
| 114 |
-
gr.
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
type="filepath"
|
| 119 |
-
)
|
| 120 |
-
gr.Markdown("## Step 2: Ask your question")
|
| 121 |
-
query_input = gr.Textbox(
|
| 122 |
-
label="Data Question",
|
| 123 |
-
placeholder="e.g., 'Show sales trends by region'"
|
| 124 |
-
)
|
| 125 |
-
submit_btn = gr.Button("Analyze", variant="primary")
|
| 126 |
-
|
| 127 |
with gr.Column():
|
| 128 |
-
gr.
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
label="Visualization",
|
| 136 |
-
show_label=True
|
| 137 |
-
)
|
| 138 |
-
|
| 139 |
-
submit_btn.click(
|
| 140 |
-
fn=process_data,
|
| 141 |
-
inputs=[file_input, query_input],
|
| 142 |
-
outputs=[insights_output, chart_output]
|
| 143 |
)
|
| 144 |
|
| 145 |
-
|
| 146 |
-
demo.queue().launch(debug=True)
|
|
|
|
| 1 |
+
!pip install gradio seaborn smolagents transformers -q -U
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
+
import gradio as gr
|
| 4 |
+
from smolagents import HfApiModel, CodeAgent
|
| 5 |
+
from huggingface_hub import login
|
| 6 |
+
import os
|
| 7 |
+
import shutil
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
+
# Authenticate with Hugging Face
|
| 10 |
+
login(os.getenv("HF_TOKEN"))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
+
def analyze_data(csv_file, additional_notes=""):
|
| 13 |
+
# Clear previous figures
|
| 14 |
+
if os.path.exists('./figures'):
|
| 15 |
+
shutil.rmtree('./figures')
|
| 16 |
+
os.makedirs('./figures', exist_ok=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
+
# Initialize model and agent
|
| 19 |
+
model = HfApiModel("meta-llama/Llama-3.1-70B-Instruct")
|
| 20 |
+
agent = CodeAgent(
|
| 21 |
+
tools=[],
|
| 22 |
+
model=model,
|
| 23 |
+
additional_authorized_imports=["numpy", "pandas", "matplotlib.pyplot", "seaborn"],
|
| 24 |
+
max_iterations=10,
|
| 25 |
+
)
|
| 26 |
|
| 27 |
+
# Run analysis
|
| 28 |
+
analysis_result = agent.run(
|
| 29 |
+
"""You are an expert data analyst. Perform comprehensive analysis including:
|
| 30 |
+
1. Basic statistics and data quality checks
|
| 31 |
+
2. 3 insightful analytical questions about relationships in the data
|
| 32 |
+
3. Visualization of key patterns and correlations
|
| 33 |
+
4. Actionable real-world insights derived from findings
|
| 34 |
+
|
| 35 |
+
Generate publication-quality visualizations and save to './figures/'
|
| 36 |
+
""",
|
| 37 |
+
additional_args={
|
| 38 |
+
"additional_notes": additional_notes,
|
| 39 |
+
"source_file": csv_file
|
| 40 |
+
}
|
| 41 |
+
)
|
| 42 |
|
| 43 |
+
# Collect generated visuals
|
| 44 |
+
visuals = [os.path.join('./figures', f) for f in os.listdir('./figures')
|
| 45 |
+
if f.endswith(('.png', '.jpg', '.jpeg'))]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
+
return analysis_result, visuals
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
+
# Create Gradio interface
|
| 50 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 51 |
+
gr.Markdown("## 📊 AI Data Analysis Agent")
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
with gr.Row():
|
| 54 |
with gr.Column():
|
| 55 |
+
file_input = gr.File(label="Upload CSV Dataset", type="filepath")
|
| 56 |
+
notes_input = gr.Textbox(label="Dataset Notes (Optional)", lines=3)
|
| 57 |
+
analyze_btn = gr.Button("Analyze", variant="primary")
|
| 58 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
with gr.Column():
|
| 60 |
+
analysis_output = gr.Textbox(label="Analysis Report", interactive=False)
|
| 61 |
+
gallery = gr.Gallery(label="Data Visualizations", columns=2)
|
| 62 |
+
|
| 63 |
+
analyze_btn.click(
|
| 64 |
+
fn=analyze_data,
|
| 65 |
+
inputs=[file_input, notes_input],
|
| 66 |
+
outputs=[analysis_output, gallery]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
)
|
| 68 |
|
| 69 |
+
demo.launch(debug=True)
|
|
|