Spaces:
Running
Running
Download app.py from Jpreval/GlobalGems: direct link, hf CLI and curl.
- Browser
- Download file 16.1 kB
-
https://huggingface.co/spaces/Jpreval/GlobalGems/resolve/main/app.py
- Command line
-
hf download hf://spaces/Jpreval/GlobalGems/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Jpreval/GlobalGems/resolve/main/app.py
16.1 kB
| import pandas as pd | |
| import numpy as np | |
| import plotly.express as px | |
| import plotly.graph_objects as go | |
| from sklearn.ensemble import GradientBoostingRegressor | |
| from sklearn.pipeline import Pipeline | |
| from sklearn.preprocessing import StandardScaler, OneHotEncoder | |
| from sklearn.compose import ColumnTransformer | |
| from sklearn.model_selection import train_test_split | |
| from sklearn.metrics import mean_absolute_error, r2_score | |
| import joblib | |
| from datetime import datetime | |
| import io | |
| # Page config | |
| st.set_page_config( | |
| page_title="Global Gems Dynamic Pricing", | |
| page_icon="๐", | |
| layout="wide", | |
| initial_sidebar_state="expanded" | |
| ) | |
| # Custom CSS | |
| st.markdown(""" | |
| <style> | |
| .main-header { | |
| font-size: 3rem; | |
| font-weight: bold; | |
| background: linear-gradient(90deg, #667eea 0%, #764ba2 100%); | |
| -webkit-background-clip: text; | |
| -webkit-text-fill-color: transparent; | |
| margin-bottom: 0.5rem; | |
| } | |
| .metric-card { | |
| background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); | |
| padding: 1.5rem; | |
| border-radius: 10px; | |
| color: white; | |
| box-shadow: 0 4px 6px rgba(0,0,0,0.1); | |
| } | |
| .stButton>button { | |
| background: linear-gradient(90deg, #667eea 0%, #764ba2 100%); | |
| color: white; | |
| border: none; | |
| padding: 0.5rem 2rem; | |
| border-radius: 5px; | |
| font-weight: bold; | |
| } | |
| </style> | |
| """, unsafe_allow_html=True) | |
| # Helper Functions | |
| def baseline_price_from_rule(comp_avg, margin_pct=0.30, weight_comp=0.70, weight_margin=0.30): | |
| return weight_comp * comp_avg + weight_margin * (comp_avg * (1 + margin_pct)) | |
| def extract_unit_num(u): | |
| try: | |
| s = str(u) | |
| digits = "" | |
| for ch in s: | |
| if ch.isdigit(): | |
| digits += ch | |
| elif digits: | |
| break | |
| return float(digits) if digits else np.nan | |
| except: | |
| return np.nan | |
| def generate_synthetic_labels(df): | |
| rng = np.random.default_rng(42) | |
| df = df.copy() | |
| elasticity = { | |
| "Paper": 0.05, "Sanitizer": 0.03, "Wipes": 0.02, | |
| "Spray": 0.08, "Cleaner": 0.10, "Gloves": 0.04, "Trash": 0.06 | |
| } | |
| noise = rng.normal(0, 0.02, size=len(df)) | |
| optimal_prices, quantities = [], [] | |
| for idx, r in df.iterrows(): | |
| base = r["baseline_price"] | |
| e = elasticity.get(r["category"], 0.05) | |
| demand = r["category_demand_prior"] | |
| pos_shift = -0.03 if r["pct_vs_market"] > 0.05 else (0.02 if r["pct_vs_market"] < -0.05 else 0.0) | |
| adj_pct = -e * demand + pos_shift + noise[idx] | |
| opt_price = base * (1 + adj_pct) | |
| optimal_prices.append(opt_price) | |
| qty = (demand * (1 / (1 + (opt_price / max(r["competitor_avg"], 1e-6)))) * 100).clip(0, 1000) | |
| quantities.append(qty) | |
| df["synthetic_optimal_price"] = np.array(optimal_prices) | |
| df["synthetic_qty"] = np.array(quantities) | |
| return df | |
| def process_data(df): | |
| demand_prior = { | |
| "Paper": 1.0, "Sanitizer": 0.9, "Wipes": 0.8, | |
| "Spray": 0.6, "Cleaner": 0.5, "Gloves": 0.6, "Trash": 0.4 | |
| } | |
| df["competitor_avg"] = df[["competitor1Price", "competitor2Price", "competitor3Price"]].mean(axis=1) | |
| df["pct_vs_market"] = (df["continentalPrice"] - df["marketAvg"]) / df["marketAvg"] | |
| df["baseline_price"] = df["competitor_avg"].apply(lambda x: baseline_price_from_rule(x, margin_pct=0.30)) | |
| df["category_demand_prior"] = df["category"].map(demand_prior).fillna(0.5) | |
| df["unit_number"] = df["unit"].apply(extract_unit_num).fillna(1.0) | |
| df["rel_continental_vs_comp"] = df["continentalPrice"] / df["competitor_avg"] | |
| df["staples_vs_comp"] = df["staplesPrice"] / df["competitor_avg"] | |
| df = df.fillna(0) | |
| df = generate_synthetic_labels(df) | |
| return df | |
| def train_model(df): | |
| features = ["competitor_avg", "marketAvg", "staplesPrice", "category", "unit_number", | |
| "category_demand_prior", "pct_vs_market", "rel_continental_vs_comp", "baseline_price"] | |
| target = "synthetic_optimal_price" | |
| X = df[features] | |
| y = df[target] | |
| numeric_features = ["competitor_avg", "marketAvg", "staplesPrice", "unit_number", | |
| "category_demand_prior", "pct_vs_market", "rel_continental_vs_comp", "baseline_price"] | |
| categorical_features = ["category"] | |
| numeric_transformer = Pipeline([("scaler", StandardScaler())]) | |
| categorical_transformer = Pipeline([("ohe", OneHotEncoder(handle_unknown="ignore"))]) | |
| preprocessor = ColumnTransformer([ | |
| ("num", numeric_transformer, numeric_features), | |
| ("cat", categorical_transformer, categorical_features) | |
| ]) | |
| model_pipeline = Pipeline([ | |
| ("preproc", preprocessor), | |
| ("reg", GradientBoostingRegressor(n_estimators=300, learning_rate=0.05, max_depth=4, random_state=42)) | |
| ]) | |
| X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) | |
| model_pipeline.fit(X_train, y_train) | |
| y_pred = model_pipeline.predict(X_test) | |
| mae = mean_absolute_error(y_test, y_pred) | |
| r2 = r2_score(y_test, y_pred) | |
| return model_pipeline, mae, r2 | |
| def add_governance_features(df): | |
| df['pricing_action'] = df['delta_pct_vs_baseline'].apply( | |
| lambda x: 'Raise Price' if x > 5 else ('Discount' if x < -5 else 'Stable') | |
| ) | |
| df['approval_status'] = df['pricing_action'].apply( | |
| lambda x: 'Pending Review' if x in ['Raise Price', 'Discount'] else 'Auto-Approved' | |
| ) | |
| df['reviewer_role'] = df['pricing_action'].apply( | |
| lambda x: 'Pricing Manager' if x == 'Raise Price' else ('Inventory Analyst' if x == 'Discount' else 'System') | |
| ) | |
| df['approval_timestamp'] = df['approval_status'].apply( | |
| lambda x: datetime.now().strftime('%Y-%m-%d %H:%M:%S') if x == 'Auto-Approved' else '' | |
| ) | |
| def urgency_tag(row): | |
| if row['pricing_action'] == 'Raise Price' and row['synthetic_qty'] > 80: | |
| return '๐ฅ Fast-Moving' | |
| elif row['pricing_action'] == 'Discount' and row['synthetic_qty'] < 10: | |
| return '๐ฆ Overstocked' | |
| else: | |
| return 'โ Normal' | |
| df['urgency_tag'] = df.apply(urgency_tag, axis=1) | |
| return df | |
| # Initialize session state | |
| if 'df_processed' not in st.session_state: | |
| st.session_state.df_processed = None | |
| if 'model' not in st.session_state: | |
| st.session_state.model = None | |
| if 'metrics' not in st.session_state: | |
| st.session_state.metrics = None | |
| # Sidebar | |
| with st.sidebar: | |
| st.markdown("### ๐ Global Gems") | |
| st.markdown("**AI-Powered Dynamic Pricing**") | |
| st.markdown("---") | |
| uploaded_file = st.file_uploader("๐ Upload Competitor Data", type=['csv', 'xlsx']) | |
| if uploaded_file: | |
| if st.button("๐ Process & Train Model"): | |
| with st.spinner("Processing data and training model..."): | |
| try: | |
| if uploaded_file.name.endswith('.csv'): | |
| df = pd.read_csv(uploaded_file) | |
| else: | |
| df = pd.read_excel(uploaded_file) | |
| df_processed = process_data(df) | |
| model, mae, r2 = train_model(df_processed) | |
| # Generate predictions | |
| features = ["competitor_avg", "marketAvg", "staplesPrice", "category", "unit_number", | |
| "category_demand_prior", "pct_vs_market", "rel_continental_vs_comp", "baseline_price"] | |
| df_processed["predicted_price"] = model.predict(df_processed[features]) | |
| df_processed["delta_pct_vs_baseline"] = ((df_processed["predicted_price"] - df_processed["baseline_price"]) / df_processed["baseline_price"]) * 100 | |
| df_processed = add_governance_features(df_processed) | |
| st.session_state.df_processed = df_processed | |
| st.session_state.model = model | |
| st.session_state.metrics = {'mae': mae, 'r2': r2} | |
| st.success("โ Model trained successfully!") | |
| except Exception as e: | |
| st.error(f"Error: {str(e)}") | |
| st.markdown("---") | |
| st.markdown("### ๐ Features") | |
| st.markdown(""" | |
| - AI Price Optimization | |
| - Governance Workflow | |
| - Real-time Analytics | |
| - Smart Urgency Tags | |
| """) | |
| # Main Content | |
| st.markdown('<p class="main-header">๐ Global Gems Dynamic Pricing System</p>', unsafe_allow_html=True) | |
| st.markdown("**AI-Powered Pricing Intelligence for Janitorial Supply**") | |
| if st.session_state.df_processed is None: | |
| st.info("๐ Upload your competitor pricing data to get started!") | |
| col1, col2, col3 = st.columns(3) | |
| with col1: | |
| st.markdown("### ๐ค AI Engine") | |
| st.write("Gradient Boosting ML model analyzes competitor pricing, demand signals, and market dynamics") | |
| with col2: | |
| st.markdown("### ๐ก๏ธ Governance") | |
| st.write("Automated approval workflows with role-based review for pricing changes") | |
| with col3: | |
| st.markdown("### ๐ Analytics") | |
| st.write("Interactive dashboards visualize pricing performance and opportunities") | |
| else: | |
| df = st.session_state.df_processed | |
| metrics = st.session_state.metrics | |
| # Metrics Row | |
| col1, col2, col3, col4 = st.columns(4) | |
| with col1: | |
| st.metric("๐ฆ Total Products", len(df)) | |
| with col2: | |
| st.metric("๐ฏ Model MAE", f"${metrics['mae']:.2f}") | |
| with col3: | |
| st.metric("๐ Model Rยฒ", f"{metrics['r2']:.3f}") | |
| with col4: | |
| pending = len(df[df['approval_status'] == 'Pending Review']) | |
| st.metric("โณ Pending Review", pending) | |
| st.markdown("---") | |
| # Tabs | |
| tab1, tab2, tab3, tab4 = st.tabs(["๐ Dashboard", "๐ก๏ธ Governance", "๐ Product Explorer", "๐ Analytics"]) | |
| with tab1: | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| # Pricing Action Distribution | |
| fig = px.pie(df, names='pricing_action', title='๐งฎ Pricing Action Distribution', | |
| color_discrete_sequence=px.colors.sequential.Purples_r) | |
| st.plotly_chart(fig, use_container_width=True) | |
| # Baseline vs Predicted | |
| fig = px.scatter(df, x='baseline_price', y='predicted_price', | |
| color='urgency_tag', hover_data=['product', 'category'], | |
| title='๐ Baseline vs Predicted Pricing') | |
| fig.add_shape(type='line', x0=0, y0=0, x1=df['baseline_price'].max(), | |
| y1=df['baseline_price'].max(), line=dict(dash='dash', color='gray')) | |
| st.plotly_chart(fig, use_container_width=True) | |
| with col2: | |
| # Urgency Distribution | |
| fig = px.histogram(df, x='urgency_tag', color='pricing_action', | |
| title='๐จ Urgency Tags by Action') | |
| st.plotly_chart(fig, use_container_width=True) | |
| # Price Delta by Category | |
| fig = px.box(df, x='category', y='delta_pct_vs_baseline', | |
| color='pricing_action', title='๐ฐ Price Delta by Category') | |
| st.plotly_chart(fig, use_container_width=True) | |
| with tab2: | |
| st.markdown("### ๐ก๏ธ Pricing Governance & Approval Workflow") | |
| # Reviewer workload | |
| role_counts = df['reviewer_role'].value_counts().reset_index() | |
| role_counts.columns = ['Reviewer Role', 'Count'] | |
| fig = px.bar(role_counts, x='Reviewer Role', y='Count', | |
| title='๐ฅ Reviewer Role Distribution', | |
| color='Count', color_continuous_scale='Purples') | |
| st.plotly_chart(fig, use_container_width=True) | |
| # Pending approvals | |
| st.markdown("### โณ Items Pending Review") | |
| pending_df = df[df['approval_status'] == 'Pending Review'][ | |
| ['product', 'category', 'baseline_price', 'predicted_price', | |
| 'delta_pct_vs_baseline', 'pricing_action', 'reviewer_role', 'urgency_tag'] | |
| ].sort_values('delta_pct_vs_baseline', ascending=False) | |
| st.dataframe(pending_df, use_container_width=True, height=400) | |
| # Export pending items | |
| csv = pending_df.to_csv(index=False) | |
| st.download_button( | |
| label="๐ฅ Download Pending Reviews", | |
| data=csv, | |
| file_name=f"pending_reviews_{datetime.now().strftime('%Y%m%d')}.csv", | |
| mime="text/csv" | |
| ) | |
| with tab3: | |
| st.markdown("### ๐ Product-Level Price Explorer") | |
| # Filters | |
| col1, col2, col3 = st.columns(3) | |
| with col1: | |
| selected_category = st.multiselect("Category", options=df['category'].unique(), default=df['category'].unique()) | |
| with col2: | |
| selected_action = st.multiselect("Pricing Action", options=df['pricing_action'].unique(), default=df['pricing_action'].unique()) | |
| with col3: | |
| selected_urgency = st.multiselect("Urgency", options=df['urgency_tag'].unique(), default=df['urgency_tag'].unique()) | |
| filtered_df = df[ | |
| (df['category'].isin(selected_category)) & | |
| (df['pricing_action'].isin(selected_action)) & | |
| (df['urgency_tag'].isin(selected_urgency)) | |
| ] | |
| st.dataframe( | |
| filtered_df[['product', 'category', 'competitor_avg', 'baseline_price', | |
| 'predicted_price', 'delta_pct_vs_baseline', 'pricing_action', | |
| 'urgency_tag', 'approval_status']], | |
| use_container_width=True, | |
| height=500 | |
| ) | |
| # Export filtered data | |
| csv = filtered_df.to_csv(index=False) | |
| st.download_button( | |
| label="๐ฅ Export Filtered Data", | |
| data=csv, | |
| file_name=f"pricing_data_{datetime.now().strftime('%Y%m%d')}.csv", | |
| mime="text/csv" | |
| ) | |
| with tab4: | |
| st.markdown("### ๐ Advanced Analytics") | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| # Elasticity chart | |
| if 'synthetic_qty' in df.columns: | |
| fig = px.scatter(df, x='predicted_price', y='synthetic_qty', | |
| color='category', title='๐ Price Elasticity Analysis', | |
| trendline="lowess") | |
| st.plotly_chart(fig, use_container_width=True) | |
| with col2: | |
| # Category performance | |
| category_stats = df.groupby('category').agg({ | |
| 'predicted_price': 'mean', | |
| 'delta_pct_vs_baseline': 'mean', | |
| 'synthetic_qty': 'sum' | |
| }).reset_index() | |
| fig = px.bar(category_stats, x='category', y='delta_pct_vs_baseline', | |
| title='๐ Average Price Delta by Category', | |
| color='delta_pct_vs_baseline', | |
| color_continuous_scale='RdYlGn_r') | |
| st.plotly_chart(fig, use_container_width=True) | |
| # Summary statistics | |
| st.markdown("### ๐ Summary Statistics") | |
| col1, col2, col3 = st.columns(3) | |
| with col1: | |
| st.metric("Average Baseline Price", f"${df['baseline_price'].mean():.2f}") | |
| st.metric("Average Predicted Price", f"${df['predicted_price'].mean():.2f}") | |
| with col2: | |
| st.metric("Avg Price Increase %", f"{df[df['pricing_action']=='Raise Price']['delta_pct_vs_baseline'].mean():.2f}%") | |
| st.metric("Avg Discount %", f"{df[df['pricing_action']=='Discount']['delta_pct_vs_baseline'].mean():.2f}%") | |
| with col3: | |
| st.metric("Fast-Moving Items", len(df[df['urgency_tag']=='๐ฅ Fast-Moving'])) | |
| st.metric("Overstocked Items", len(df[df['urgency_tag']=='๐ฆ Overstocked'])) | |
| # Footer | |
| st.markdown("---") | |
| st.markdown("**๐ Global Gems Dynamic Pricing System** | Powered by AI & Machine Learning") |