pavanmutha commited on
Commit
c67bdba
·
verified ·
1 Parent(s): 5ad7d6f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -131
app.py CHANGED
@@ -1,146 +1,69 @@
1
- import pandas as pd
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
- class AnalysisAgent:
19
- def generate_insights(self, data):
20
- numeric_data = data.select_dtypes(include=np.number)
21
- insights = [
22
- f"Rows: {len(data)}",
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
- class DataAnalysisAgent:
30
- def __init__(self):
31
- self.nlp_pipeline = pipeline("text-classification",
32
- model="distilbert-base-uncased")
33
- self.task_agent = TaskAgent()
34
- self.analysis_agent = AnalysisAgent()
35
 
36
- def preprocess_data(self, data):
37
- data = data.dropna(axis=1, how='all')
38
- data = data.fillna(data.mean(numeric_only=True))
39
- for col in data.columns:
40
- if data[col].dtype == 'object':
41
- try:
42
- data[col] = pd.to_datetime(data[col])
43
- except:
44
- pass
45
- return data
46
 
47
- def parse_query(self, query):
48
- return self.task_agent.parse_query(query)
 
 
 
 
 
 
49
 
50
- def analyze(self, data, task):
51
- if task['task'] == 'trend_analysis':
52
- group_col = task['params'].get('group_by', data.columns[0])
53
- return data.groupby(group_col).mean().reset_index()
54
- elif task['task'] == 'clustering':
55
- numeric_cols = data.select_dtypes(include=np.number).columns
56
- kmeans = KMeans(n_clusters=3)
57
- data['cluster'] = kmeans.fit_predict(data[numeric_cols])
58
- return data
59
- elif task['task'] == 'distribution':
60
- return data.describe()
61
- return data
 
 
 
62
 
63
- def visualize(self, data, task):
64
- try:
65
- fig, ax = plt.subplots(figsize=(8, 4))
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
- def process_data(file, query):
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 Interface with CSV-specific upload
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.Markdown("## Step 1: Upload your CSV file")
115
- file_input = gr.File(
116
- label="Select CSV File",
117
- file_types=[".csv"],
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.Markdown("## Analysis Results")
129
- insights_output = gr.Textbox(
130
- label="Insights",
131
- interactive=False,
132
- lines=10
133
- )
134
- chart_output = gr.Image(
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
- if __name__ == "__main__":
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)