""" Transport Cost Predictor — Hugging Face Spaces app (Gradio) This is a self-contained Gradio app that loads the trained LightGBM model and serves predictions through a web UI. Designed for HF Spaces free CPU tier. Usage on HF Spaces: 1. Create a new Space at https://huggingface.co/new-space (SDK = Gradio, CPU, free) 2. Upload this file as app.py, plus best_model.joblib, requirements.txt, README.md 3. The Space builds and serves automatically at https://huggingface.co/spaces// Usage locally: python app.py # then open http://127.0.0.1:7860 """ import os import sys import json import warnings import unicodedata from datetime import datetime from pathlib import Path warnings.filterwarnings("ignore") import numpy as np import pandas as pd import joblib import gradio as gr # ============================================================ # Configuration # ============================================================ MODEL_PATH = "best_model.joblib" MONTH_MAP = { "janvier": 1, "jan": 1, "january": 1, "fevrier": 2, "février": 2, "feb": 2, "february": 2, "mars": 3, "mar": 3, "march": 3, "avril": 4, "avrl": 4, "apr": 4, "april": 4, "mai": 5, "may": 5, "juin": 6, "jun": 6, "june": 6, "juillet": 7, "jul": 7, "july": 7, "aout": 8, "août": 8, "aug": 8, "august": 8, "septembre": 9, "sep": 9, "september": 9, "octobre": 10, "october": 10, "oct": 10, "novembre": 11, "nov": 11, "november": 11, "decembre": 12, "décembre": 12, "dec": 12, "december": 12, } def normalize_text(t): t = str(t).strip().lower() t = unicodedata.normalize("NFKD", t) t = "".join(c for c in t if not unicodedata.combining(c)) return t # ============================================================ # Load model artifact (cached at module level) # ============================================================ print(f"[app] Loading model from {MODEL_PATH} ...") artifact = joblib.load(MODEL_PATH) print(f"[app] Loaded: {artifact['best_model_name']}, " f"test_R²={artifact['training_metrics']['test_R2']:.4f}") CLIENTS = sorted([c for c in artifact.get("rare_client_set", []) if c != "OTHER"]) print(f"[app] Known clients: {len(CLIENTS)}") # ============================================================ # Feature engineering (mirrors training pipeline) # ============================================================ def add_intrinsic_features(df): df = df.copy() df["Date"] = pd.to_datetime(df["Date"], errors="coerce") df["DayOfYear"] = df["Date"].dt.dayofyear.astype(float) df["Quarter"] = df["Date"].dt.quarter.astype(float) df["Month_sin"] = np.sin(2 * np.pi * df["MonthNum"] / 12) df["Month_cos"] = np.cos(2 * np.pi * df["MonthNum"] / 12) df["Day_sin"] = np.sin(2 * np.pi * df["DayOfYear"] / 365) df["Day_cos"] = np.cos(2 * np.pi * df["DayOfYear"] / 365) df["log_Weight"] = np.log1p(df["Weight"].clip(lower=0)) df["log_Volume"] = np.log1p(df["Volume"].clip(lower=0)) df["Weight_x_Volume"] = df["Weight"] * df["Volume"] df["Density"] = df["Weight"] / df["Volume"].replace(0, np.nan) df["Density"] = df["Density"].fillna(7.0) df["Is_heavy"] = (df["Weight"] > 100).astype(int) df["Is_light"] = (df["Weight"] < 30).astype(int) ref = pd.Timestamp("2025-01-01") df["DaysSince2025"] = (df["Date"] - ref).dt.days.astype(float) return df def apply_target_encoding(df, te_encodings, global_mean): df = df.copy() df["_CT"] = df["Client_Grouped"] + "|" + df["Type"] df["_CI"] = df["Client_Grouped"] + "|" + df["Incoterm"] for col, (mapping, key) in te_encodings.items(): df[col] = df[key].map(mapping).fillna(global_mean) df = df.drop(columns=["_CT", "_CI"]) return df # ============================================================ # Prediction function # ============================================================ def predict_cost(date_str, type_str, client, incoterm, weight, volume, packages): """Predict transport cost in TND for a single shipment.""" # Parse date try: date = pd.to_datetime(date_str, errors="coerce") if pd.isna(date): return "❌ Invalid date format. Use YYYY-MM-DD." except Exception as e: return f"❌ Invalid date: {e}" # Normalize inputs type_clean = str(type_str).strip().upper() if "IMPORT" in type_clean: type_clean = "IMPORT" elif "EXPORT" in type_clean: type_clean = "EXPORT" else: return "❌ Type must be Import or Export." client_clean = str(client).strip().upper() incoterm_clean = str(incoterm).strip().upper() try: weight = float(weight) volume = float(volume) packages = int(packages) except Exception as e: return f"❌ Invalid numeric value: {e}" if weight <= 0 or volume <= 0: return "❌ Weight and volume must be positive." if packages < 1: return "❌ Packages must be at least 1." # Build dataframe row row = pd.DataFrame([{ "Date": date, "Type": type_clean, "Client": client_clean, "Incoterm": incoterm_clean, "Packages": packages, "Weight": weight, "Volume": volume, "Year": int(date.year), "MonthNum": int(date.month), }]) # Group rare clients rare_set = set(artifact.get("rare_client_set", [])) row["Client_Grouped"] = client_clean if client_clean in rare_set else "OTHER" # Feature engineering row = add_intrinsic_features(row) row = apply_target_encoding(row, artifact["te_encodings"], artifact["global_mean"]) features = artifact["features"] for f in features: if f not in row.columns: row[f] = 0.0 X_input = row[features] # Predict preprocessor = artifact["preprocessor"] X_proc = preprocessor.transform(X_input).astype(float) model = artifact["best_model"] pred_log = float(np.clip(model.predict(X_proc)[0], -1.0, 20.0)) pred_tnd = float(np.clip(np.expm1(pred_log), 0.0, None)) pred_eur = pred_tnd / 3.4 low = pred_tnd * 0.85 high = pred_tnd * 1.15 # Format output client_display = row["Client_Grouped"].iloc[0] output = f""" ## 💰 Predicted Cost: **{pred_tnd:,.2f} TND** | Field | Value | |---|---| | Estimated EUR | €{pred_eur:,.2f} | | Confidence band (±15%) | {low:,.2f} – {high:,.2f} TND | | Model used | {artifact['best_model_name']} | ### 📋 Input Summary - **Date**: {date.date()} - **Type**: {type_clean} - **Client**: {client_clean} → grouped as `{client_display}` - **Incoterm**: {incoterm_clean} - **Weight**: {weight} kg - **Volume**: {volume} m³ - **Packages**: {packages} ### 📊 Model Performance - Test R²: {artifact['training_metrics']['test_R2']:.4f} - Test RMSE: {artifact['training_metrics']['test_RMSE']:.2f} TND - Test MAE: {artifact['training_metrics']['test_MAE']:.2f} TND - Test MAPE: {artifact['training_metrics']['test_MAPE']:.2f}% - Cross-validated R²: {artifact['cv_metrics']['mean_R2']:.4f} ± {artifact['cv_metrics']['std_R2']:.4f} """ return output def predict_batch(file_obj): """Predict for a CSV file. Returns a CSV file with predictions.""" if file_obj is None: return None, "❌ Please upload a CSV file." try: df = pd.read_csv(file_obj.name) except Exception as e: return None, f"❌ Could not read CSV: {e}" required_cols = ["date", "type", "client", "incoterm", "weight", "volume"] missing = [c for c in required_cols if c not in df.columns] if missing: return None, f"❌ CSV missing required columns: {missing}. Required: {required_cols + ['packages']}" if "packages" not in df.columns: df["packages"] = 1 results = [] for idx, r in df.iterrows(): try: date = pd.to_datetime(r["date"], errors="coerce") if pd.isna(date): results.append({**r.to_dict(), "predicted_tnd": None, "error": "invalid date"}) continue type_clean = str(r["type"]).strip().upper() if "IMPORT" in type_clean: type_clean = "IMPORT" elif "EXPORT" in type_clean: type_clean = "EXPORT" client_clean = str(r["client"]).strip().upper() incoterm_clean = str(r["incoterm"]).strip().upper() row = pd.DataFrame([{ "Date": date, "Type": type_clean, "Client": client_clean, "Incoterm": incoterm_clean, "Packages": int(r["packages"]), "Weight": float(r["weight"]), "Volume": float(r["volume"]), "Year": int(date.year), "MonthNum": int(date.month), }]) rare_set = set(artifact.get("rare_client_set", [])) row["Client_Grouped"] = client_clean if client_clean in rare_set else "OTHER" row = add_intrinsic_features(row) row = apply_target_encoding(row, artifact["te_encodings"], artifact["global_mean"]) features = artifact["features"] for f in features: if f not in row.columns: row[f] = 0.0 X_proc = artifact["preprocessor"].transform(row[features]).astype(float) pred_log = float(np.clip(artifact["best_model"].predict(X_proc)[0], -1.0, 20.0)) pred_tnd = float(np.clip(np.expm1(pred_log), 0.0, None)) results.append({**r.to_dict(), "predicted_tnd": round(pred_tnd, 2), "error": ""}) except Exception as e: results.append({**r.to_dict(), "predicted_tnd": None, "error": str(e)}) out_df = pd.DataFrame(results) out_path = "/tmp/predictions.csv" out_df.to_csv(out_path, index=False) return out_path, f"✅ Predicted {len(out_df)} rows. Download the CSV below." # ============================================================ # Build Gradio UI # ============================================================ CUSTOM_CSS = """ .gradio-container { max-width: 1100px !important; } .title-bar { background: linear-gradient(135deg, #059669 0%, #10b981 100%); color: white; padding: 1.5rem; border-radius: 0.5rem; margin-bottom: 1rem; } .title-bar h1 { color: white; margin: 0; font-size: 1.75rem; } .title-bar p { color: rgba(255,255,255,0.9); margin: 0.25rem 0 0 0; } """ with gr.Blocks(css=CUSTOM_CSS, title="Transport Cost Predictor") as demo: gr.HTML("""

🚚 Transport Cost Predictor

Predict shipment cost in Tunisian Dinar (TND) — powered by LightGBM + Optuna

""") with gr.Tabs(): # ---------- Tab 1: Single prediction ---------- with gr.TabItem("🎯 Single Prediction"): with gr.Row(): with gr.Column(scale=1): date_in = gr.Textbox( label="Operation Date (YYYY-MM-DD)", value=datetime.now().strftime("%Y-%m-%d"), placeholder="2026-06-15", ) type_in = gr.Radio( choices=["Import", "Export"], value="Import", label="Type / Type", ) client_in = gr.Textbox( label="Client / Fournisseur", placeholder="e.g., BIKAR, METHAL, BODYCOTE", info=f"{len(CLIENTS)} known clients. Unknown clients are auto-grouped as 'OTHER'.", ) incoterm_in = gr.Dropdown( choices=["EXW", "FCA", "DDP", "DAP"], value="EXW", label="Incoterm", ) weight_in = gr.Number(label="Weight (kg) / Poids", value=100, minimum=0.1) volume_in = gr.Number(label="Volume (m³)", value=0.5, minimum=0.01) packages_in = gr.Number(label="Packages / Colis", value=1, minimum=1, precision=0) predict_btn = gr.Button("🔮 Predict Cost", variant="primary") clear_btn = gr.Button("🔄 Clear", variant="secondary") with gr.Column(scale=1): output_md = gr.Markdown( value="**Enter shipment details on the left and click Predict Cost.**\n\n" "The model was trained on 258 shipments from 2025 and tested on 248 shipments from 2026." ) predict_btn.click( fn=predict_cost, inputs=[date_in, type_in, client_in, incoterm_in, weight_in, volume_in, packages_in], outputs=output_md, ) clear_btn.click( fn=lambda: ("", "Import", "", "EXW", 100, 0.5, 1, "**Enter shipment details on the left and click Predict Cost.**"), outputs=[date_in, type_in, client_in, incoterm_in, weight_in, volume_in, packages_in, output_md], ) # ---------- Tab 2: Batch prediction ---------- with gr.TabItem("📑 Batch Prediction (CSV)"): gr.Markdown(""" Upload a CSV file with columns: `date,type,client,incoterm,weight,volume,packages` Example: ```csv date,type,client,incoterm,weight,volume,packages 2026-06-15,Import,BIKAR,FCA,500,0.8,2 2026-06-20,Export,METHAL,DDP,80,0.4,1 ``` """) file_in = gr.File(label="Upload CSV", file_types=[".csv"]) batch_btn = gr.Button("Run Batch Prediction", variant="primary") batch_status = gr.Markdown("") file_out = gr.File(label="Download Predictions") batch_btn.click( fn=predict_batch, inputs=file_in, outputs=[file_out, batch_status], ) # ---------- Tab 3: Model info ---------- with gr.TabItem("📊 Model Info"): gr.Markdown(f""" ## Model: {artifact['best_model_name']} ### Training Metrics (2025 train → 2026 test) | Metric | Value | |---|---| | Train R² | {artifact['training_metrics']['train_R2']:.4f} | | Test R² | {artifact['training_metrics']['test_R2']:.4f} | | Test RMSE | {artifact['training_metrics']['test_RMSE']:.2f} TND | | Test MAE | {artifact['training_metrics']['test_MAE']:.2f} TND | | Test MAPE | {artifact['training_metrics']['test_MAPE']:.2f}% | ### Cross-Validation (3-fold TimeSeriesSplit) | Metric | Value | |---|---| | Mean R² | {artifact['cv_metrics']['mean_R2']:.4f} ± {artifact['cv_metrics']['std_R2']:.4f} | | Mean RMSE | {artifact['cv_metrics']['mean_RMSE']:.2f} TND | ### Features ({len(artifact['features'])} total) {chr(10).join(f'- `{f}`' for f in artifact['features'])} ### Known Clients ({len(CLIENTS)}) {', '.join(CLIENTS)} """) gr.HTML("""

Transport Cost Predictor · Powered by LightGBM + Optuna · Trained on 2025 data, validated on 2026 data

Built with Gradio · Deployed on Hugging Face Spaces (free CPU tier)

""") # ============================================================ # Launch # ============================================================ if __name__ == "__main__": # HF Spaces uses port 7860 by default port = int(os.environ.get("PORT", 7860)) demo.launch(server_name="0.0.0.0", server_port=port, share=False)