Update app.py
Browse files
app.py
CHANGED
@@ -1,216 +1,141 @@
|
|
1 |
-
from transformers import Tool
|
2 |
-
import gradio as gr
|
3 |
import pandas as pd
|
4 |
import numpy as np
|
5 |
import plotly.express as px
|
6 |
-
import plotly.graph_objects as go
|
7 |
-
from typing import Dict, List, Optional
|
8 |
-
import openai
|
9 |
import seaborn as sns
|
10 |
-
import
|
11 |
-
import io
|
12 |
-
import base64
|
13 |
|
14 |
-
#
|
15 |
-
class
|
16 |
-
name = "
|
17 |
-
description = "
|
18 |
-
- Correlation heatmaps
|
19 |
-
- Distribution plots
|
20 |
-
- Scatter plots
|
21 |
-
- Time series plots
|
22 |
-
Returns the plots as base64 encoded images."""
|
23 |
|
24 |
inputs = {
|
25 |
-
"data": {
|
26 |
-
|
27 |
-
"description": "DataFrame as dictionary"
|
28 |
-
},
|
29 |
-
"plot_type": {
|
30 |
-
"type": "string",
|
31 |
-
"description": "Type of plot to create: 'heatmap', 'distribution', 'scatter'"
|
32 |
-
},
|
33 |
-
"columns": {
|
34 |
-
"type": "list",
|
35 |
-
"description": "List of columns to plot"
|
36 |
-
}
|
37 |
}
|
38 |
-
output_type = "
|
39 |
|
40 |
-
def forward(self, data:
|
41 |
df = pd.DataFrame(data)
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
|
|
56 |
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
buf.seek(0)
|
62 |
-
return base64.b64encode(buf.read()).decode('utf-8')
|
63 |
-
|
64 |
-
class DataAnalysisTool(Tool):
|
65 |
-
name = "data_analyzer"
|
66 |
-
description = """Performs statistical analysis on data:
|
67 |
-
- Basic statistics (mean, median, std)
|
68 |
-
- Correlation analysis
|
69 |
-
- Missing value analysis
|
70 |
-
- Outlier detection"""
|
71 |
|
72 |
inputs = {
|
73 |
-
"data": {
|
74 |
-
|
75 |
-
"description": "DataFrame as dictionary"
|
76 |
-
},
|
77 |
-
"analysis_type": {
|
78 |
-
"type": "string",
|
79 |
-
"description": "Type of analysis: 'basic', 'correlation', 'missing', 'outliers'"
|
80 |
-
},
|
81 |
-
"columns": {
|
82 |
-
"type": "list",
|
83 |
-
"description": "List of columns to analyze"
|
84 |
-
}
|
85 |
}
|
86 |
output_type = "dict"
|
87 |
|
88 |
-
def forward(self, data:
|
89 |
df = pd.DataFrame(data)
|
90 |
-
|
91 |
-
|
92 |
-
if analysis_type == "basic":
|
93 |
-
return {
|
94 |
-
"statistics": df[selected_cols].describe().to_dict(),
|
95 |
-
"skew": df[selected_cols].skew().to_dict(),
|
96 |
-
"kurtosis": df[selected_cols].kurtosis().to_dict()
|
97 |
-
}
|
98 |
-
elif analysis_type == "correlation":
|
99 |
-
numeric_cols = df[selected_cols].select_dtypes(include=[np.number])
|
100 |
-
return {
|
101 |
-
"correlation": numeric_cols.corr().to_dict(),
|
102 |
-
"covariance": numeric_cols.cov().to_dict()
|
103 |
-
}
|
104 |
-
elif analysis_type == "missing":
|
105 |
return {
|
106 |
-
"
|
107 |
-
"
|
|
|
108 |
}
|
109 |
-
elif analysis_type == "
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
"upper_bound": Q3 + 1.5 * IQR
|
120 |
-
}
|
121 |
-
return {"outliers": outliers}
|
122 |
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
# Create agent with tools
|
129 |
-
llm_engine = HfApiEngine() # Uses default model
|
130 |
-
agent = ReactCodeAgent(
|
131 |
-
tools=[viz_tool, analysis_tool],
|
132 |
-
llm_engine=llm_engine
|
133 |
-
)
|
134 |
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
# Convert DataFrame to dict for tools
|
179 |
-
data_dict = df.to_dict()
|
180 |
-
|
181 |
-
# Get all columns for potential analysis
|
182 |
-
columns = list(df.columns)
|
183 |
-
|
184 |
-
# Use agent to analyze and create visualizations
|
185 |
-
response = agent.run(
|
186 |
-
f"""Analyze this data: {message}
|
187 |
-
Available columns: {columns}
|
188 |
-
Use the data_analyzer and data_visualizer tools to create insights."""
|
189 |
-
)
|
190 |
-
|
191 |
-
return chat_history + [(message, response)]
|
192 |
-
|
193 |
-
except Exception as e:
|
194 |
-
return chat_history + [(message, f"Error: {str(e)}")]
|
195 |
-
|
196 |
-
file_input.change(
|
197 |
-
process_file,
|
198 |
-
inputs=[file_input],
|
199 |
-
outputs=[df_state]
|
200 |
-
)
|
201 |
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
outputs=[chat]
|
206 |
-
)
|
207 |
|
208 |
-
|
209 |
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import Tool
|
|
|
2 |
import pandas as pd
|
3 |
import numpy as np
|
4 |
import plotly.express as px
|
|
|
|
|
|
|
5 |
import seaborn as sns
|
6 |
+
from sklearn import preprocessing, decomposition, metrics
|
|
|
|
|
7 |
|
8 |
+
# 1. Data Loading and Preprocessing Tool
|
9 |
+
class DataPreprocessingTool(Tool):
|
10 |
+
name = "data_preprocessor"
|
11 |
+
description = "Handles data loading, cleaning, and preprocessing tasks"
|
|
|
|
|
|
|
|
|
|
|
12 |
|
13 |
inputs = {
|
14 |
+
"data": {"type": "dict", "description": "Input data dictionary"},
|
15 |
+
"operation": {"type": "string", "description": "Operation to perform: clean/encode/normalize/impute"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
}
|
17 |
+
output_type = "dict"
|
18 |
|
19 |
+
def forward(self, data: dict, operation: str) -> dict:
|
20 |
df = pd.DataFrame(data)
|
21 |
+
if operation == "clean":
|
22 |
+
# Handle duplicates, missing values
|
23 |
+
df = df.drop_duplicates()
|
24 |
+
df = df.fillna(df.mean(numeric_only=True))
|
25 |
+
elif operation == "encode":
|
26 |
+
# Encode categorical variables
|
27 |
+
le = preprocessing.LabelEncoder()
|
28 |
+
for col in df.select_dtypes(include=['object']):
|
29 |
+
df[col] = le.fit_transform(df[col].astype(str))
|
30 |
+
elif operation == "normalize":
|
31 |
+
# Normalize numeric columns
|
32 |
+
scaler = preprocessing.StandardScaler()
|
33 |
+
numeric_cols = df.select_dtypes(include=[np.number]).columns
|
34 |
+
df[numeric_cols] = scaler.fit_transform(df[numeric_cols])
|
35 |
+
return df.to_dict()
|
36 |
|
37 |
+
# 2. Statistical Analysis Tool
|
38 |
+
class StatisticalAnalysisTool(Tool):
|
39 |
+
name = "statistical_analyzer"
|
40 |
+
description = "Performs statistical analysis on data"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
41 |
|
42 |
inputs = {
|
43 |
+
"data": {"type": "dict", "description": "Input data dictionary"},
|
44 |
+
"analysis_type": {"type": "string", "description": "Type of analysis: descriptive/inferential/correlation"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
}
|
46 |
output_type = "dict"
|
47 |
|
48 |
+
def forward(self, data: dict, analysis_type: str) -> dict:
|
49 |
df = pd.DataFrame(data)
|
50 |
+
if analysis_type == "descriptive":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
51 |
return {
|
52 |
+
"summary": df.describe().to_dict(),
|
53 |
+
"skewness": df.skew().to_dict(),
|
54 |
+
"kurtosis": df.kurtosis().to_dict()
|
55 |
}
|
56 |
+
elif analysis_type == "inferential":
|
57 |
+
# Perform statistical tests
|
58 |
+
results = {}
|
59 |
+
numeric_cols = df.select_dtypes(include=[np.number]).columns
|
60 |
+
for col in numeric_cols:
|
61 |
+
from scipy import stats
|
62 |
+
stat, p_value = stats.normaltest(df[col].dropna())
|
63 |
+
results[col] = {"statistic": stat, "p_value": p_value}
|
64 |
+
return results
|
65 |
+
return df.corr().to_dict()
|
|
|
|
|
|
|
66 |
|
67 |
+
# 3. Advanced Visualization Tool
|
68 |
+
class AdvancedVisualizationTool(Tool):
|
69 |
+
name = "advanced_visualizer"
|
70 |
+
description = "Creates advanced statistical and ML visualizations"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
71 |
|
72 |
+
inputs = {
|
73 |
+
"data": {"type": "dict", "description": "Input data dictionary"},
|
74 |
+
"viz_type": {"type": "string", "description": "Type of visualization"},
|
75 |
+
"params": {"type": "dict", "description": "Additional parameters"}
|
76 |
+
}
|
77 |
+
output_type = "dict"
|
78 |
+
|
79 |
+
def forward(self, data: dict, viz_type: str, params: dict) -> dict:
|
80 |
+
df = pd.DataFrame(data)
|
81 |
+
if viz_type == "pca":
|
82 |
+
# PCA visualization
|
83 |
+
pca = decomposition.PCA(n_components=2)
|
84 |
+
numeric_cols = df.select_dtypes(include=[np.number]).columns
|
85 |
+
pca_result = pca.fit_transform(df[numeric_cols])
|
86 |
+
fig = px.scatter(x=pca_result[:, 0], y=pca_result[:, 1],
|
87 |
+
title='PCA Visualization')
|
88 |
+
return {"plot": fig.to_dict()}
|
89 |
+
elif viz_type == "cluster":
|
90 |
+
# Clustering visualization
|
91 |
+
from sklearn.cluster import KMeans
|
92 |
+
kmeans = KMeans(n_clusters=params.get("n_clusters", 3))
|
93 |
+
numeric_cols = df.select_dtypes(include=[np.number]).columns
|
94 |
+
clusters = kmeans.fit_predict(df[numeric_cols])
|
95 |
+
fig = px.scatter(df, x=params.get("x"), y=params.get("y"),
|
96 |
+
color=clusters, title='Cluster Visualization')
|
97 |
+
return {"plot": fig.to_dict()}
|
98 |
+
return {}
|
99 |
+
|
100 |
+
# 4. Machine Learning Tool
|
101 |
+
class MLModelTool(Tool):
|
102 |
+
name = "ml_modeler"
|
103 |
+
description = "Trains and evaluates machine learning models"
|
104 |
+
|
105 |
+
inputs = {
|
106 |
+
"data": {"type": "dict", "description": "Input data dictionary"},
|
107 |
+
"target": {"type": "string", "description": "Target column name"},
|
108 |
+
"model_type": {"type": "string", "description": "Type of model to train"}
|
109 |
+
}
|
110 |
+
output_type = "dict"
|
111 |
+
|
112 |
+
def forward(self, data: dict, target: str, model_type: str) -> dict:
|
113 |
+
from sklearn.model_selection import train_test_split
|
114 |
+
from sklearn.metrics import mean_squared_error, accuracy_score
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
115 |
|
116 |
+
df = pd.DataFrame(data)
|
117 |
+
X = df.drop(columns=[target])
|
118 |
+
y = df[target]
|
|
|
|
|
119 |
|
120 |
+
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
|
121 |
|
122 |
+
if model_type == "regression":
|
123 |
+
from sklearn.linear_model import LinearRegression
|
124 |
+
model = LinearRegression()
|
125 |
+
model.fit(X_train, y_train)
|
126 |
+
y_pred = model.predict(X_test)
|
127 |
+
return {
|
128 |
+
"mse": mean_squared_error(y_test, y_pred),
|
129 |
+
"r2": model.score(X_test, y_test),
|
130 |
+
"coefficients": dict(zip(X.columns, model.coef_))
|
131 |
+
}
|
132 |
+
elif model_type == "classification":
|
133 |
+
from sklearn.ensemble import RandomForestClassifier
|
134 |
+
model = RandomForestClassifier()
|
135 |
+
model.fit(X_train, y_train)
|
136 |
+
y_pred = model.predict(X_test)
|
137 |
+
return {
|
138 |
+
"accuracy": accuracy_score(y_test, y_pred),
|
139 |
+
"feature_importance": dict(zip(X.columns, model.feature_importances_))
|
140 |
+
}
|
141 |
+
return {}
|