Jpreval commited on
Commit
8b99285
ยท
verified ยท
1 Parent(s): c4f0c58

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +400 -0
app.py ADDED
@@ -0,0 +1,400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+ import plotly.express as px
4
+ import plotly.graph_objects as go
5
+ from sklearn.ensemble import GradientBoostingRegressor
6
+ from sklearn.pipeline import Pipeline
7
+ from sklearn.preprocessing import StandardScaler, OneHotEncoder
8
+ from sklearn.compose import ColumnTransformer
9
+ from sklearn.model_selection import train_test_split
10
+ from sklearn.metrics import mean_absolute_error, r2_score
11
+ import joblib
12
+ from datetime import datetime
13
+ import io
14
+
15
+ # Page config
16
+ st.set_page_config(
17
+ page_title="Global Gems Dynamic Pricing",
18
+ page_icon="๐Ÿ’Ž",
19
+ layout="wide",
20
+ initial_sidebar_state="expanded"
21
+ )
22
+
23
+ # Custom CSS
24
+ st.markdown("""
25
+ <style>
26
+ .main-header {
27
+ font-size: 3rem;
28
+ font-weight: bold;
29
+ background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
30
+ -webkit-background-clip: text;
31
+ -webkit-text-fill-color: transparent;
32
+ margin-bottom: 0.5rem;
33
+ }
34
+ .metric-card {
35
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
36
+ padding: 1.5rem;
37
+ border-radius: 10px;
38
+ color: white;
39
+ box-shadow: 0 4px 6px rgba(0,0,0,0.1);
40
+ }
41
+ .stButton>button {
42
+ background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
43
+ color: white;
44
+ border: none;
45
+ padding: 0.5rem 2rem;
46
+ border-radius: 5px;
47
+ font-weight: bold;
48
+ }
49
+ </style>
50
+ """, unsafe_allow_html=True)
51
+
52
+ # Helper Functions
53
+ def baseline_price_from_rule(comp_avg, margin_pct=0.30, weight_comp=0.70, weight_margin=0.30):
54
+ return weight_comp * comp_avg + weight_margin * (comp_avg * (1 + margin_pct))
55
+
56
+ def extract_unit_num(u):
57
+ try:
58
+ s = str(u)
59
+ digits = ""
60
+ for ch in s:
61
+ if ch.isdigit():
62
+ digits += ch
63
+ elif digits:
64
+ break
65
+ return float(digits) if digits else np.nan
66
+ except:
67
+ return np.nan
68
+
69
+ def generate_synthetic_labels(df):
70
+ rng = np.random.default_rng(42)
71
+ df = df.copy()
72
+ elasticity = {
73
+ "Paper": 0.05, "Sanitizer": 0.03, "Wipes": 0.02,
74
+ "Spray": 0.08, "Cleaner": 0.10, "Gloves": 0.04, "Trash": 0.06
75
+ }
76
+ noise = rng.normal(0, 0.02, size=len(df))
77
+ optimal_prices, quantities = [], []
78
+
79
+ for idx, r in df.iterrows():
80
+ base = r["baseline_price"]
81
+ e = elasticity.get(r["category"], 0.05)
82
+ demand = r["category_demand_prior"]
83
+ pos_shift = -0.03 if r["pct_vs_market"] > 0.05 else (0.02 if r["pct_vs_market"] < -0.05 else 0.0)
84
+ adj_pct = -e * demand + pos_shift + noise[idx]
85
+ opt_price = base * (1 + adj_pct)
86
+ optimal_prices.append(opt_price)
87
+ qty = (demand * (1 / (1 + (opt_price / max(r["competitor_avg"], 1e-6)))) * 100).clip(0, 1000)
88
+ quantities.append(qty)
89
+
90
+ df["synthetic_optimal_price"] = np.array(optimal_prices)
91
+ df["synthetic_qty"] = np.array(quantities)
92
+ return df
93
+
94
+ def process_data(df):
95
+ demand_prior = {
96
+ "Paper": 1.0, "Sanitizer": 0.9, "Wipes": 0.8,
97
+ "Spray": 0.6, "Cleaner": 0.5, "Gloves": 0.6, "Trash": 0.4
98
+ }
99
+
100
+ df["competitor_avg"] = df[["competitor1Price", "competitor2Price", "competitor3Price"]].mean(axis=1)
101
+ df["pct_vs_market"] = (df["continentalPrice"] - df["marketAvg"]) / df["marketAvg"]
102
+ df["baseline_price"] = df["competitor_avg"].apply(lambda x: baseline_price_from_rule(x, margin_pct=0.30))
103
+ df["category_demand_prior"] = df["category"].map(demand_prior).fillna(0.5)
104
+ df["unit_number"] = df["unit"].apply(extract_unit_num).fillna(1.0)
105
+ df["rel_continental_vs_comp"] = df["continentalPrice"] / df["competitor_avg"]
106
+ df["staples_vs_comp"] = df["staplesPrice"] / df["competitor_avg"]
107
+ df = df.fillna(0)
108
+ df = generate_synthetic_labels(df)
109
+
110
+ return df
111
+
112
+ def train_model(df):
113
+ features = ["competitor_avg", "marketAvg", "staplesPrice", "category", "unit_number",
114
+ "category_demand_prior", "pct_vs_market", "rel_continental_vs_comp", "baseline_price"]
115
+ target = "synthetic_optimal_price"
116
+
117
+ X = df[features]
118
+ y = df[target]
119
+
120
+ numeric_features = ["competitor_avg", "marketAvg", "staplesPrice", "unit_number",
121
+ "category_demand_prior", "pct_vs_market", "rel_continental_vs_comp", "baseline_price"]
122
+ categorical_features = ["category"]
123
+
124
+ numeric_transformer = Pipeline([("scaler", StandardScaler())])
125
+ categorical_transformer = Pipeline([("ohe", OneHotEncoder(handle_unknown="ignore"))])
126
+
127
+ preprocessor = ColumnTransformer([
128
+ ("num", numeric_transformer, numeric_features),
129
+ ("cat", categorical_transformer, categorical_features)
130
+ ])
131
+
132
+ model_pipeline = Pipeline([
133
+ ("preproc", preprocessor),
134
+ ("reg", GradientBoostingRegressor(n_estimators=300, learning_rate=0.05, max_depth=4, random_state=42))
135
+ ])
136
+
137
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
138
+ model_pipeline.fit(X_train, y_train)
139
+ y_pred = model_pipeline.predict(X_test)
140
+
141
+ mae = mean_absolute_error(y_test, y_pred)
142
+ r2 = r2_score(y_test, y_pred)
143
+
144
+ return model_pipeline, mae, r2
145
+
146
+ def add_governance_features(df):
147
+ df['pricing_action'] = df['delta_pct_vs_baseline'].apply(
148
+ lambda x: 'Raise Price' if x > 5 else ('Discount' if x < -5 else 'Stable')
149
+ )
150
+ df['approval_status'] = df['pricing_action'].apply(
151
+ lambda x: 'Pending Review' if x in ['Raise Price', 'Discount'] else 'Auto-Approved'
152
+ )
153
+ df['reviewer_role'] = df['pricing_action'].apply(
154
+ lambda x: 'Pricing Manager' if x == 'Raise Price' else ('Inventory Analyst' if x == 'Discount' else 'System')
155
+ )
156
+ df['approval_timestamp'] = df['approval_status'].apply(
157
+ lambda x: datetime.now().strftime('%Y-%m-%d %H:%M:%S') if x == 'Auto-Approved' else ''
158
+ )
159
+
160
+ def urgency_tag(row):
161
+ if row['pricing_action'] == 'Raise Price' and row['synthetic_qty'] > 80:
162
+ return '๐Ÿ”ฅ Fast-Moving'
163
+ elif row['pricing_action'] == 'Discount' and row['synthetic_qty'] < 10:
164
+ return '๐Ÿ“ฆ Overstocked'
165
+ else:
166
+ return 'โœ… Normal'
167
+
168
+ df['urgency_tag'] = df.apply(urgency_tag, axis=1)
169
+ return df
170
+
171
+ # Initialize session state
172
+ if 'df_processed' not in st.session_state:
173
+ st.session_state.df_processed = None
174
+ if 'model' not in st.session_state:
175
+ st.session_state.model = None
176
+ if 'metrics' not in st.session_state:
177
+ st.session_state.metrics = None
178
+
179
+ # Sidebar
180
+ with st.sidebar:
181
+ st.markdown("### ๐Ÿ’Ž Global Gems")
182
+ st.markdown("**AI-Powered Dynamic Pricing**")
183
+ st.markdown("---")
184
+
185
+ uploaded_file = st.file_uploader("๐Ÿ“ Upload Competitor Data", type=['csv', 'xlsx'])
186
+
187
+ if uploaded_file:
188
+ if st.button("๐Ÿš€ Process & Train Model"):
189
+ with st.spinner("Processing data and training model..."):
190
+ try:
191
+ if uploaded_file.name.endswith('.csv'):
192
+ df = pd.read_csv(uploaded_file)
193
+ else:
194
+ df = pd.read_excel(uploaded_file)
195
+
196
+ df_processed = process_data(df)
197
+ model, mae, r2 = train_model(df_processed)
198
+
199
+ # Generate predictions
200
+ features = ["competitor_avg", "marketAvg", "staplesPrice", "category", "unit_number",
201
+ "category_demand_prior", "pct_vs_market", "rel_continental_vs_comp", "baseline_price"]
202
+ df_processed["predicted_price"] = model.predict(df_processed[features])
203
+ df_processed["delta_pct_vs_baseline"] = ((df_processed["predicted_price"] - df_processed["baseline_price"]) / df_processed["baseline_price"]) * 100
204
+ df_processed = add_governance_features(df_processed)
205
+
206
+ st.session_state.df_processed = df_processed
207
+ st.session_state.model = model
208
+ st.session_state.metrics = {'mae': mae, 'r2': r2}
209
+
210
+ st.success("โœ… Model trained successfully!")
211
+ except Exception as e:
212
+ st.error(f"Error: {str(e)}")
213
+
214
+ st.markdown("---")
215
+ st.markdown("### ๐Ÿ“Š Features")
216
+ st.markdown("""
217
+ - AI Price Optimization
218
+ - Governance Workflow
219
+ - Real-time Analytics
220
+ - Smart Urgency Tags
221
+ """)
222
+
223
+ # Main Content
224
+ st.markdown('<p class="main-header">๐Ÿ’Ž Global Gems Dynamic Pricing System</p>', unsafe_allow_html=True)
225
+ st.markdown("**AI-Powered Pricing Intelligence for Janitorial Supply**")
226
+
227
+ if st.session_state.df_processed is None:
228
+ st.info("๐Ÿ‘ˆ Upload your competitor pricing data to get started!")
229
+
230
+ col1, col2, col3 = st.columns(3)
231
+ with col1:
232
+ st.markdown("### ๐Ÿค– AI Engine")
233
+ st.write("Gradient Boosting ML model analyzes competitor pricing, demand signals, and market dynamics")
234
+ with col2:
235
+ st.markdown("### ๐Ÿ›ก๏ธ Governance")
236
+ st.write("Automated approval workflows with role-based review for pricing changes")
237
+ with col3:
238
+ st.markdown("### ๐Ÿ“ˆ Analytics")
239
+ st.write("Interactive dashboards visualize pricing performance and opportunities")
240
+
241
+ else:
242
+ df = st.session_state.df_processed
243
+ metrics = st.session_state.metrics
244
+
245
+ # Metrics Row
246
+ col1, col2, col3, col4 = st.columns(4)
247
+
248
+ with col1:
249
+ st.metric("๐Ÿ“ฆ Total Products", len(df))
250
+ with col2:
251
+ st.metric("๐ŸŽฏ Model MAE", f"${metrics['mae']:.2f}")
252
+ with col3:
253
+ st.metric("๐Ÿ“Š Model Rยฒ", f"{metrics['r2']:.3f}")
254
+ with col4:
255
+ pending = len(df[df['approval_status'] == 'Pending Review'])
256
+ st.metric("โณ Pending Review", pending)
257
+
258
+ st.markdown("---")
259
+
260
+ # Tabs
261
+ tab1, tab2, tab3, tab4 = st.tabs(["๐Ÿ“Š Dashboard", "๐Ÿ›ก๏ธ Governance", "๐Ÿ” Product Explorer", "๐Ÿ“ˆ Analytics"])
262
+
263
+ with tab1:
264
+ col1, col2 = st.columns(2)
265
+
266
+ with col1:
267
+ # Pricing Action Distribution
268
+ fig = px.pie(df, names='pricing_action', title='๐Ÿงฎ Pricing Action Distribution',
269
+ color_discrete_sequence=px.colors.sequential.Purples_r)
270
+ st.plotly_chart(fig, use_container_width=True)
271
+
272
+ # Baseline vs Predicted
273
+ fig = px.scatter(df, x='baseline_price', y='predicted_price',
274
+ color='urgency_tag', hover_data=['product', 'category'],
275
+ title='๐Ÿ“ˆ Baseline vs Predicted Pricing')
276
+ fig.add_shape(type='line', x0=0, y0=0, x1=df['baseline_price'].max(),
277
+ y1=df['baseline_price'].max(), line=dict(dash='dash', color='gray'))
278
+ st.plotly_chart(fig, use_container_width=True)
279
+
280
+ with col2:
281
+ # Urgency Distribution
282
+ fig = px.histogram(df, x='urgency_tag', color='pricing_action',
283
+ title='๐Ÿšจ Urgency Tags by Action')
284
+ st.plotly_chart(fig, use_container_width=True)
285
+
286
+ # Price Delta by Category
287
+ fig = px.box(df, x='category', y='delta_pct_vs_baseline',
288
+ color='pricing_action', title='๐Ÿ’ฐ Price Delta by Category')
289
+ st.plotly_chart(fig, use_container_width=True)
290
+
291
+ with tab2:
292
+ st.markdown("### ๐Ÿ›ก๏ธ Pricing Governance & Approval Workflow")
293
+
294
+ # Reviewer workload
295
+ role_counts = df['reviewer_role'].value_counts().reset_index()
296
+ role_counts.columns = ['Reviewer Role', 'Count']
297
+ fig = px.bar(role_counts, x='Reviewer Role', y='Count',
298
+ title='๐Ÿ‘ฅ Reviewer Role Distribution',
299
+ color='Count', color_continuous_scale='Purples')
300
+ st.plotly_chart(fig, use_container_width=True)
301
+
302
+ # Pending approvals
303
+ st.markdown("### โณ Items Pending Review")
304
+ pending_df = df[df['approval_status'] == 'Pending Review'][
305
+ ['product', 'category', 'baseline_price', 'predicted_price',
306
+ 'delta_pct_vs_baseline', 'pricing_action', 'reviewer_role', 'urgency_tag']
307
+ ].sort_values('delta_pct_vs_baseline', ascending=False)
308
+
309
+ st.dataframe(pending_df, use_container_width=True, height=400)
310
+
311
+ # Export pending items
312
+ csv = pending_df.to_csv(index=False)
313
+ st.download_button(
314
+ label="๐Ÿ“ฅ Download Pending Reviews",
315
+ data=csv,
316
+ file_name=f"pending_reviews_{datetime.now().strftime('%Y%m%d')}.csv",
317
+ mime="text/csv"
318
+ )
319
+
320
+ with tab3:
321
+ st.markdown("### ๐Ÿ” Product-Level Price Explorer")
322
+
323
+ # Filters
324
+ col1, col2, col3 = st.columns(3)
325
+ with col1:
326
+ selected_category = st.multiselect("Category", options=df['category'].unique(), default=df['category'].unique())
327
+ with col2:
328
+ selected_action = st.multiselect("Pricing Action", options=df['pricing_action'].unique(), default=df['pricing_action'].unique())
329
+ with col3:
330
+ selected_urgency = st.multiselect("Urgency", options=df['urgency_tag'].unique(), default=df['urgency_tag'].unique())
331
+
332
+ filtered_df = df[
333
+ (df['category'].isin(selected_category)) &
334
+ (df['pricing_action'].isin(selected_action)) &
335
+ (df['urgency_tag'].isin(selected_urgency))
336
+ ]
337
+
338
+ st.dataframe(
339
+ filtered_df[['product', 'category', 'competitor_avg', 'baseline_price',
340
+ 'predicted_price', 'delta_pct_vs_baseline', 'pricing_action',
341
+ 'urgency_tag', 'approval_status']],
342
+ use_container_width=True,
343
+ height=500
344
+ )
345
+
346
+ # Export filtered data
347
+ csv = filtered_df.to_csv(index=False)
348
+ st.download_button(
349
+ label="๐Ÿ“ฅ Export Filtered Data",
350
+ data=csv,
351
+ file_name=f"pricing_data_{datetime.now().strftime('%Y%m%d')}.csv",
352
+ mime="text/csv"
353
+ )
354
+
355
+ with tab4:
356
+ st.markdown("### ๐Ÿ“ˆ Advanced Analytics")
357
+
358
+ col1, col2 = st.columns(2)
359
+
360
+ with col1:
361
+ # Elasticity chart
362
+ if 'synthetic_qty' in df.columns:
363
+ fig = px.scatter(df, x='predicted_price', y='synthetic_qty',
364
+ color='category', title='๐Ÿ“Š Price Elasticity Analysis',
365
+ trendline="lowess")
366
+ st.plotly_chart(fig, use_container_width=True)
367
+
368
+ with col2:
369
+ # Category performance
370
+ category_stats = df.groupby('category').agg({
371
+ 'predicted_price': 'mean',
372
+ 'delta_pct_vs_baseline': 'mean',
373
+ 'synthetic_qty': 'sum'
374
+ }).reset_index()
375
+
376
+ fig = px.bar(category_stats, x='category', y='delta_pct_vs_baseline',
377
+ title='๐Ÿ“Š Average Price Delta by Category',
378
+ color='delta_pct_vs_baseline',
379
+ color_continuous_scale='RdYlGn_r')
380
+ st.plotly_chart(fig, use_container_width=True)
381
+
382
+ # Summary statistics
383
+ st.markdown("### ๐Ÿ“‹ Summary Statistics")
384
+ col1, col2, col3 = st.columns(3)
385
+
386
+ with col1:
387
+ st.metric("Average Baseline Price", f"${df['baseline_price'].mean():.2f}")
388
+ st.metric("Average Predicted Price", f"${df['predicted_price'].mean():.2f}")
389
+
390
+ with col2:
391
+ st.metric("Avg Price Increase %", f"{df[df['pricing_action']=='Raise Price']['delta_pct_vs_baseline'].mean():.2f}%")
392
+ st.metric("Avg Discount %", f"{df[df['pricing_action']=='Discount']['delta_pct_vs_baseline'].mean():.2f}%")
393
+
394
+ with col3:
395
+ st.metric("Fast-Moving Items", len(df[df['urgency_tag']=='๐Ÿ”ฅ Fast-Moving']))
396
+ st.metric("Overstocked Items", len(df[df['urgency_tag']=='๐Ÿ“ฆ Overstocked']))
397
+
398
+ # Footer
399
+ st.markdown("---")
400
+ st.markdown("**๐Ÿ’Ž Global Gems Dynamic Pricing System** | Powered by AI & Machine Learning")