-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapp.py
More file actions
363 lines (318 loc) · 13.5 KB
/
Copy pathapp.py
File metadata and controls
363 lines (318 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
from dash import html, dcc, Input, Output, State, callback, Dash, no_update
import dash_ag_grid as dag
import pandas as pd
import google.generativeai as genai
from datetime import datetime
import json
app=Dash(__name__)
app.title="AI Dash-ag-grid"
def create_enhanced_sample_data():
"""Create an enhanced sample dataset with more features"""
import numpy as np
np.random.seed(42)
dates = pd.date_range(start='2024-01-01', periods=200, freq='D')
data = {
'Date': dates,
'Region': np.random.choice(['North', 'South', 'East', 'West'], 200),
'Product': np.random.choice(['Electronics', 'Clothing', 'Home & Garden', 'Sports', 'Books'], 200),
'Sales': np.random.normal(5_000, 1_500, 200).clip(min=100),
'Units': np.random.randint(5, 50, 200),
'Customer_Type': np.random.choice(['B2B', 'B2C'], 200, p=[0.6, 0.4]),
'Satisfaction_Score': np.random.uniform(3.0, 5.0, 200),
'Marketing_Spend': np.random.uniform(100, 1000, 200)
}
df = pd.DataFrame(data)
# Add seasonal variation
df['Sales'] = df['Sales'] * (1 + 0.3 * np.sin(2 * np.pi * df.index / 365))
# Calculate derived metrics
df['Revenue'] = df['Sales'] * df['Units']
df['Profit_Margin'] = 0.15 + np.random.uniform(-0.05, 0.10, 200)
df['Profit'] = df['Revenue'] * df['Profit_Margin']
df['ROI'] = (df['Profit'] / df['Marketing_Spend']) * 100
return df
# Load data
df = create_enhanced_sample_data()
# Convert dates to string format for JSON serialization
df['Date_str'] = df['Date'].dt.strftime('%Y-%m-%d')
# Enhanced AG-Grid column definitions
columnDefs = [
{"field": "Date_str", "headerName": "Date", "filter": "agDateColumnFilter"},
{"field": "Region", "filter": True},
{"field": "Product", "filter": True},
{"field": "Sales", "filter": "agNumberColumnFilter",
"valueFormatter": {"function": "d3.format('$,.0f')(params.value)"}},
{"field": "Units", "filter": "agNumberColumnFilter"},
{"field": "Customer_Type", "headerName": "Customer Type", "filter": True},
{"field": "Revenue", "filter": "agNumberColumnFilter",
"valueFormatter": {"function": "d3.format('$,.0f')(params.value)"}},
{"field": "Profit", "filter": "agNumberColumnFilter",
"valueFormatter": {"function": "d3.format('$,.0f')(params.value)"}},
{"field": "Profit_Margin", "headerName": "Profit Margin", "filter": "agNumberColumnFilter",
"valueFormatter": {"function": "d3.format('.1%')(params.value)"}},
{"field": "Satisfaction_Score", "headerName": "Satisfaction", "filter": "agNumberColumnFilter",
"valueFormatter": {"function": "d3.format('.2f')(params.value)"}},
{"field": "Marketing_Spend", "headerName": "Marketing Spend", "filter": "agNumberColumnFilter",
"valueFormatter": {"function": "d3.format('$,.0f')(params.value)"}},
{"field": "ROI", "filter": "agNumberColumnFilter",
"valueFormatter": {"function": "d3.format('.1f')(params.value) + '%'"}}
]
# App layout
app.layout = html.Div([
# Header
html.Div([
html.H1("📊 Advanced Data Analysis Dashboard",
style={'margin': '0 0 10px 0', 'color': 'white'}),
html.P("Interactive data grid with AI-powered insights",
style={'margin': '0', 'opacity': '0.9', 'color': 'white'})
], style={
'background': 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
'padding': '30px',
'borderRadius': '15px',
'marginBottom': '30px',
'boxShadow': '0 10px 30px rgba(0,0,0,0.1)'
}),
# API Key and Controls
html.Div([
html.H3("Configuration & Actions"),
html.Div([
html.Div([
dcc.Input(
id='api-key-input',
type='password',
placeholder='Enter Gemini API Key',
style={
'width': '300px',
'padding': '8px 12px',
'border': '1px solid #ddd',
'borderRadius': '6px',
'marginRight': '10px'
}
),
html.Button(
'🤖 Generate AI Summary',
id='generate-summary-btn',
style={
'background': 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
'color': 'white',
'border': 'none',
'padding': '12px 24px',
'borderRadius': '6px',
'fontSize': '16px',
'cursor': 'pointer',
'marginRight': '10px'
}
),
html.Button(
'📥 Export to CSV',
id='export-btn',
style={
'background': '#48bb78',
'color': 'white',
'border': 'none',
'padding': '12px 24px',
'borderRadius': '6px',
'fontSize': '16px',
'cursor': 'pointer'
}
),
dcc.Download(id="download-dataframe-csv"),
dcc.Loading(
id="loading-summary",
type="circle",
children=[html.Div(id="loading-output")]
)
], style={'display': 'flex', 'alignItems': 'center'}),
html.Div(id='api-key-status', style={'marginTop': '10px'})
])
], style={
'background': 'white',
'padding': '20px',
'borderRadius': '10px',
'marginBottom': '20px',
'boxShadow': '0 2px 10px rgba(0,0,0,0.05)'
}),
# Data Grid
html.Div([
html.H3("Sales Data Table"),
dag.AgGrid(
id="data-grid",
rowData=df.to_dict("records"),
columnDefs=columnDefs,
defaultColDef={
"sortable": True,
"filter": True,
"resizable": True,
"floatingFilter": True
},
dashGridOptions={
"pagination": True,
"paginationPageSize": 20,
"domLayout": "normal",
"rowSelection": "multiple"
},
style={"height": "600px"}
)
], style={
'background': 'white',
'padding': '20px',
'borderRadius': '10px',
'marginBottom': '20px',
'boxShadow': '0 2px 10px rgba(0,0,0,0.05)'
}),
# Summary Display
html.Div([
html.Div([
html.H3("🤖 AI-Generated Summary",
style={'margin': '0', 'color': '#333', 'flexGrow': '1'})
], style={'display': 'flex', 'alignItems': 'center', 'marginBottom': '15px'}),
html.Div(
id='summary-content',
children=dcc.Markdown("Click 'Generate AI Summary' to analyze the dataset using Google Gemini..."),
style={
'color': '#555',
'lineHeight': '1.8',
'fontSize': '16px'
}
)
], style={
'background': 'white',
'padding': '25px',
'borderRadius': '10px',
'boxShadow': '0 2px 10px rgba(0,0,0,0.05)',
'marginBottom': '20px'
}),
# Hidden div to store the filtered data
html.Div(id='filtered-data', style={'display': 'none'})
], style={
'maxWidth': '1600px',
'margin': '0 auto',
'padding': '20px',
'backgroundColor': '#f5f7fa',
'minHeight': '100vh'
})
# Callback to get filtered data from AG-Grid
@app.callback(
Output('filtered-data', 'children'),
Input('data-grid', 'virtualRowData')
)
def store_filtered_data(virtual_row_data):
if virtual_row_data:
return json.dumps(virtual_row_data)
# Convert DataFrame to dict and handle datetime serialization
df_dict = df.to_dict('records')
for record in df_dict:
# Convert any datetime objects to strings
for key, value in record.items():
if hasattr(value, 'isoformat'):
record[key] = value.isoformat()
elif pd.isna(value):
record[key] = None
return json.dumps(df_dict)
# Callback for CSV export
@app.callback(
Output("download-dataframe-csv", "data"),
Input("export-btn", "n_clicks"),
State('filtered-data', 'children'),
prevent_initial_call=True,
)
def export_csv(n_clicks, filtered_data_json):
filtered_data = json.loads(filtered_data_json)
filtered_df = pd.DataFrame(filtered_data)
# Rename Date_str back to Date for export if it exists
if 'Date_str' in filtered_df.columns:
filtered_df = filtered_df.rename(columns={'Date_str': 'Date'})
return dcc.send_data_frame(filtered_df.to_csv, f"data_export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv")
# Enhanced callback to generate summary with more analysis
@app.callback(
Output('summary-content', 'children'),
Output('api-key-status', 'children'),
Input('generate-summary-btn', 'n_clicks'),
State('api-key-input', 'value'),
State('filtered-data', 'children')
)
def generate_enhanced_summary(n_clicks, api_key, filtered_data_json):
if not n_clicks:
return no_update, ""
if not api_key:
return no_update, html.Div("⚠️ Please enter your Gemini API key!",
style={'color': '#e53e3e'})
try:
# Configure Gemini
genai.configure(api_key=api_key)
model = genai.GenerativeModel('gemini-2.5-flash-preview-05-20')
# Parse filtered data
filtered_data = json.loads(filtered_data_json)
filtered_df = pd.DataFrame(filtered_data)
# Handle date conversion
if 'Date_str' in filtered_df.columns:
filtered_df['Date'] = pd.to_datetime(filtered_df['Date_str'])
elif 'Date' in filtered_df.columns and filtered_df['Date'].dtype == 'object':
filtered_df['Date'] = pd.to_datetime(filtered_df['Date'])
# Calculate additional metrics
revenue_growth = filtered_df.groupby('Date')['Revenue'].sum().pct_change().mean() * 100
best_product = filtered_df.groupby('Product')['Revenue'].sum().idxmax()
best_region = filtered_df.groupby('Region')['Revenue'].sum().idxmax()
avg_satisfaction = filtered_df['Satisfaction_Score'].mean()
# Prepare enhanced data summary for Gemini
data_summary = f"""
Analyze this comprehensive sales dataset and provide strategic insights:
DATASET OVERVIEW:
- Total Records: {len(filtered_df)}
- Date Range: {filtered_df['Date'].min()} to {filtered_df['Date'].max()}
- Unique Regions: {filtered_df['Region'].unique().tolist()}
- Product Categories: {filtered_df['Product'].unique().tolist()}
KEY PERFORMANCE METRICS:
- Total Revenue: ${filtered_df['Revenue'].sum():,.2f}
- Total Profit: ${filtered_df['Profit'].sum():,.2f}
- Average Profit Margin: {filtered_df['Profit_Margin'].mean():.1%}
- Total Units Sold: {filtered_df['Units'].sum():,}
- Average Sale Value: ${filtered_df['Sales'].mean():,.2f}
- Daily Revenue Growth Rate: {revenue_growth:.2f}%
CUSTOMER INSIGHTS:
- Average Satisfaction Score: {avg_satisfaction:.2f}/5.0
- Customer Type Revenue Split:
{filtered_df.groupby('Customer_Type')['Revenue'].sum().to_dict()}
REGIONAL PERFORMANCE:
{filtered_df.groupby('Region').agg({'Revenue': 'sum', 'Profit': 'sum', 'Units': 'sum'}).to_dict()}
PRODUCT PERFORMANCE:
{filtered_df.groupby('Product').agg({'Revenue': 'sum', 'Profit': 'sum', 'Units': 'sum', 'Satisfaction_Score': 'mean'}).to_dict()}
MARKETING EFFECTIVENESS:
- Total Marketing Spend: ${filtered_df['Marketing_Spend'].sum():,.2f}
- Average ROI: {filtered_df['ROI'].mean():.1f}%
- Best ROI Product: {filtered_df.groupby('Product')['ROI'].mean().idxmax()}
Please provide:
1. Executive Summary (3-4 key takeaways)
2. Performance Analysis with specific numbers and percentages
3. Customer Satisfaction Insights
4. Regional Strategy Recommendations
5. Product Portfolio Optimization suggestions
6. Marketing Investment Recommendations based on ROI
7. Risk factors and areas of concern
8. 3-5 specific, actionable next steps with expected impact
Format the response using proper Markdown syntax with:
- Headers using ## for main sections and ### for subsections
- Bullet points using * or - for lists
- **Bold** text for emphasis on key metrics
- Clear section breaks between topics
"""
# Generate summary
response = model.generate_content(data_summary)
# Create a formatted markdown component
summary_markdown = dcc.Markdown(
response.text,
style={
'backgroundColor': '#f8f9fa',
'padding': '20px',
'borderRadius': '8px',
'border': '1px solid #e9ecef'
}
)
return summary_markdown, html.Div("✅ API key validated - Summary generated successfully!",
style={'color': '#52c41a'})
except Exception as e:
error_msg = f"❌ **Error generating summary:** {str(e)}"
return dcc.Markdown(error_msg), html.Div("❌ API key error - Please check your key",
style={'color': '#e53e3e'})
# Run the app
if __name__ == '__main__':
app.run(debug=True, port=1260)