Skip to content

About

AI-powered logistics platform that predicts shipment delays before the truck leaves — using a 3-stage ML pipeline (Ensemble Classifier → LightGBM Regressor → Reason Classifier) with async LLM explanations via Groq Qwen 2.5.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Repository files navigation

🚢 ShipForesight — AI Supply Chain Intelligence

License: MIT Python 3.10+ FastAPI React Node.js

An enterprise-grade, AI-powered platform that predicts shipment delays, recommends optimal transport modes and carriers, and tracks real-time multi-modal routes — from Pin Code to final destination.

ShipForesight isn't just a tracking tool — it's a predictive and prescriptive supply chain intelligence system. Instead of alerting you after a truck gets stuck, it uses a 3-stage machine learning pipeline to forecast risk before dispatch, dynamically maps the best multi-modal route, and uses an LLM to explain why a delay is likely — in plain, multilingual language.


Table of Contents


Why ShipForesight

Capability Legacy Systems (SAP, Oracle, GPS Trackers) ShipForesight
Operational Mode Reactive — alerts fire after a truck is stuck Predictive — forecasts risk before dispatch
Analytics Type Descriptive — historical reports Prescriptive — recommends and applies concrete actions
AI Transparency Black-box risk score, no context Explainable (XAI) — LLM explains why in plain language
Language Support English only Multilingual — 5 Indian & international languages
Transport Modes Single-mode tracking Multi-modal — Truck, Sea, Air, Rail
Route Precision City-level Pin Code / door-address level
Form Intelligence Fully manual input Smart defaults — AI pre-fills the best mode & carrier
Recommendations Static report to review later 1-click apply — updates the form and re-runs live

Key Features

  • 🧠 AI Delay Prediction — 3-stage ensemble ML pipeline (CatBoost + LightGBM + XGBoost), 84.7% accuracy
  • 🗺️ Live Multi-Modal Route Map — satellite hybrid map with animated transport tracking
  • 🚚✈️🚢🚆 4 Transport Modes — Truck, Ocean Freight, Air Freight, Train Freight
  • 🎯 Pin Code Precision — routes to the exact pin code / door address
  • ⚡ Smart Pre-Prediction Defaults — AI suggests the best mode & carrier before you run a prediction
  • 🌍 Auto Country Detection — type any city and the country code auto-fills instantly
  • 🖱️ Interactive Prescriptive Actions — click to apply an AI recommendation; form and route update automatically
  • 🗣️ Multilingual AI Explanations — LLM explanations in English, Hindi, Marathi, Gujarati, and Tamil
  • 👥 Role-Based Dashboards — distinct Admin, Vendor, and Customer views
  • 📊 Admin Analytics — real-time delay rates, vendor performance, and cost trends
  • 🔌 REST API + Webhooks — full programmatic access for integration

Tech Stack

Layer Technologies
Frontend React (Vite), TailwindCSS, Leaflet.js
Backend Python, FastAPI
Machine Learning CatBoost, LightGBM, XGBoost, scikit-learn
Feature Store DuckDB (in-memory analytical database)
GenAI / NLP LangChain + Groq (LLaMA 3)
Geospatial APIs Nominatim (geocoding), OSRM (highway routing), searoute (ocean lanes), turf.js (great-circle arcs)

Architecture

+------------------------------------------------------------------+
|                   React Frontend (Vite)                          |
|                                                                    |
|  +-------------------+   +------------------+   +-------------+  |
|  | Smart Form        |   | Live Multi-Modal |   | Admin       |  |
|  | - Auto Country     |  | Route Map        |   | Analytics   |  |
|  | - Pin Code Input   |  | - Truck/Sea/     |   | - Delay KPI |  |
|  | - AI Pre-suggest   |  |   Air/Train      |   | - Vendor    |  |
|  | - 1-Click Apply    |  | - Animated Icon  |   |   Rankings  |  |
|  +-------------------+   | - Satellite Map  |   +-------------+  |
|                          +------------------+                    |
+------------------------------------------------------------------+
             |  REST (POST /predict, GET /fast-recommend, etc.)
             v
+------------------------------------------------------------------+
|                  FastAPI Backend (Python)                        |
|                                                                    |
|  [1] Ensemble Classifier   -> Binary Delay (Yes/No)               |
|        - CatBoost                                                 |
|        - LightGBM                                                 |
|        - XGBoost   -> Soft Voting Average                         |
|                                                                     |
|  [2] LightGBM Regressor    -> Estimated Delay Days (if delay=Yes) |
|  [3] Reason Classifier     -> WHY it delays (top-3 causes)        |
|  [4] Enrichment Layer      -> DuckDB vendor + route context       |
|  [5] LLM Explainer         -> LangChain + Groq LLaMA 3 (text)     |
|  [6] Recommendation Engine -> Best mode, vendor, cost comparison  |
|  [7] Fast-Recommend        -> Lightweight pre-prediction suggest  |
+------------------------------------------------------------------+
             |
             v
+------------------------------------------------------------------+
|                  DuckDB Feature Store                            |
|  - vendor_stats  (on-time rate, avg delay, shipment count)       |
|  - route_stats   (origin/dest pairs, avg delay, confidence)      |
|  - 106+ unique routes, 50+ vendors profiled                      |
+------------------------------------------------------------------+
             |
             v
+------------------------------------------------------------------+
|            External APIs (no API key required)                  |
|  - Nominatim (OpenStreetMap) -> city / pin code geocoding        |
|  - OSRM                       -> road routing & distance          |
|  - searoute                   -> ocean vessel routing             |
|  - turf.js (greatCircle)      -> air & train arc visualization    |
+------------------------------------------------------------------+

High-Level Flow

  1. Frontend request — the form triggers /predict or /fast-recommend on the FastAPI backend.
  2. ML pipeline — evaluates base delay risk via the CatBoost / LightGBM / XGBoost ensemble.
  3. Enrichment layer — queries DuckDB for vendor on-time rate and route reliability, adjusting the final probability.
  4. LLM explainer — Groq generates a multilingual, plain-language explanation of the prediction.
  5. Response & visualization — the frontend renders the live route, transport animation, and prescriptive recommendations.

Project Structure

ShipForesight/
├── frontend/                        # React (Vite) dashboard
│   └── src/App.jsx                  # Main UI - state, map, forms
├── src/
│   ├── api/
│   │   ├── main.py                  # FastAPI app entry point
│   │   ├── endpoints.py             # All route handlers
│   │   └── schemas.py               # Pydantic request/response models
│   ├── enrichment/
│   │   ├── inference_pipeline.py    # Two-stage ML coordinator
│   │   ├── vendor_adjustment.py     # DuckDB vendor enrichment
│   │   ├── route_validation.py      # DuckDB route context
│   │   ├── recommendation.py        # Prescriptive action engine
│   │   └── nodes.py                 # Seaport / airport finders
│   └── explainability/
│       └── llm_explainer.py         # LangChain + Groq integration
├── models/                          # Trained model artifacts (.pkl)
├── data/
│   └── feature_store/
│       └── flowsight.duckdb         # Pre-computed feature store
├── scripts/
│   └── simulate_live_traffic.py     # Live webhook simulator
├── requirements.txt
├── .env                             # API keys and config
└── docker-compose.yml               # Docker deployment

Multi-Modal Routing — How It Works

ShipForesight supports 4 transport modes, each with its own routing strategy:

Mode Route Logic Map Style Legs
Truck OSRM real highway path Green solid polyline Origin → Destination direct
Ocean Freight Nearest seaport → searoute API vessel lanes Blue ship lane Truck → Port → Ocean → Port → Truck
Air Freight Nearest airport → turf.js great-circle arc Purple dashed arc Truck → Airport → Arc → Airport → Truck
Train Freight Nearest railway station → turf.js great-circle arc Slate dashed arc Truck → Station → Arc → Station → Truck

Smart blocking: if you select Train for a route that crosses an ocean (e.g. Noida → Dubai), the system detects the water gap via OSRM, shows a red "Not viable: Ocean crossing required" error, and recommends switching to Ocean Freight.


Smart Form Intelligence

1. Auto-Country Detection Type any city name in the Origin or Destination field and click outside the box. The frontend immediately queries the Nominatim geocoding API, detects the country, and auto-fills the Country Code dropdown — even for countries not in the preset list.

2. Pre-Prediction AI Smart Default As soon as Origin and Destination countries are known, a lightweight /fast-recommend call runs silently. A blue "AI SMART DEFAULT" banner appears above the Carrier section, showing the most cost/time-friendly mode and carrier for that route type. Click Apply Smart Default to pre-fill everything before you even hit Predict.


The ML Pipeline — Deep Dive

ShipForesight uses a zero-inflated, two-stage architecture — delay days are only estimated once a delay is first confirmed, which prevents the model from randomly assigning delay days to low-risk shipments.

Stage 1 — Ensemble Binary Classifier

Will this shipment delay? (Yes / No)

Three gradient-boosting models run in parallel, each predicting the probability of delay. Their outputs are averaged via soft-voting:

  • CatBoost — handles categorical data (city names, product categories) natively
  • LightGBM — extremely fast; handles large feature spaces efficiently
  • XGBoost — stable gradient boosting; robust probability estimates

Performance: 84.7% accuracy · 0.891 AUC-ROC

Stage 2 — LightGBM Regressor

If it delays, by how many days?

Only triggered when Stage 1 confirms delay_probability >= 50%.

Performance: MAE 1.24 days · RMSE 2.15 days

Stage 3 — Reason Classifier

Why is it delaying?

A multi-class ensemble classifier that outputs the most probable cause (vendor history, weather risk, route congestion) with confidence scores for the top 3 reasons.

Performance: 78.2% accuracy

Note: traditional ensemble ML was chosen over Transformer-based models after testing — Transformers achieved only 61% accuracy on this tabular supply-chain data.


Enrichment Layer (DuckDB Feature Store)

Raw ML probability is adjusted using real-world vendor and route context.

Vendor Reliability Tiers

On-Time Rate (OTR) Tier Adjustment
≥ 65% Excellent −10% to delay probability (reward)
55–64% Good Smooth linear interpolation
45–54% Average Smooth linear interpolation
≤ 45% Poor +15% to delay probability (penalty)

Example

  • ML base probability: 40% (borderline "On Track")
  • Vendor OTR: 41.6% (Poor tier) → +15% penalty applied
  • Final probability: 55% → At Risk

Quick Start — Run Locally

Prerequisites

Requirement Version Notes
Python 3.10+
Node.js 18+
Groq API Key Free Get one at console.groq.com

Step 1 — Clone and Configure

git clone https://github.com/SVSPraveen/ShipForesight.git
cd ShipForesight

Create a .env file in the project root:

GROQ_API_KEY=your_groq_api_key_here
GROQ_MODEL=llama-3.3-70b-versatile

Step 2 — Backend Setup

# Install Python dependencies
pip install -r requirements.txt

# Start the FastAPI backend server
uvicorn src.api.main:app --host 0.0.0.0 --port 8000

Backend ready at: http://localhost:8000 Interactive API docs: http://localhost:8000/docs

Step 3 — Frontend Setup

Open a second terminal and run:

cd frontend
npm install
npm run dev

Dashboard ready at: http://localhost:5173

Step 4 — First Prediction

  1. Open http://localhost:5173 in your browser.
  2. Type your Origin City (e.g. Noida) — the Country Code auto-fills to IN.
  3. Type your Destination City (e.g. Dubai) — Country Code auto-fills to AE.
  4. Check the blue "AI SMART DEFAULT" banner and click Apply Smart Default.
  5. Optionally add Pin Codes for street-level precision.
  6. Click Predict Delay Risk.
  7. View the live route on the satellite map, the delay probability, the AI explanation, and the prescriptive actions.

Step 5 — Simulate Live Tracking (Optional)

python scripts/simulate_live_traffic.py

This sends periodic GPS pings to the /webhook/shipment_update endpoint, moving the transport icon along the route in real time.


Environment Variables

Variable Required Default Description
GROQ_API_KEY Yes — API key for LLM explanations
GROQ_MODEL No llama-3.3-70b-versatile LLM model name
FEATURE_STORE_DIR No data/feature_store Path to the DuckDB feature store
MODELS_DIR No models/ Path to trained model .pkl files
HOST No 0.0.0.0 FastAPI host
PORT No 8000 FastAPI port

API Reference

POST /predict

Main prediction endpoint — runs the ML models, DuckDB enrichment, and (optionally) the LLM explanation.

Request

{
  "origin_city": "Noida",
  "destination_city": "Dubai",
  "origin_state": "Uttar Pradesh",
  "destination_state": "Dubai",
  "product_category": "Electronics",
  "supplier_name": "Maersk",
  "shipping_mode": "Ocean Freight",
  "truck_type": "MHCV",
  "month": "July",
  "quantity": 150,
  "weight_kg": 850.0,
  "value_inr": 125000.0,
  "risk_score": 0.72,
  "target_language": "English",
  "apply_enrichment": true,
  "explain": true
}

Response

{
  "prediction": {
    "will_delay": true,
    "delay_probability": 0.67,
    "estimated_delay_days": 4.2,
    "delay_reason": "Route Congestion",
    "est_transit_time": 18
  },
  "enrichment": {
    "vendor_tier": "GOOD",
    "vendor_on_time_rate": 0.612,
    "vendor_adjustment": -0.05,
    "route_historical_delay": 0.34
  },
  "recommendation": {
    "action_required": true,
    "recommendation": "Switch to Train Freight for inland leg to reduce cost by 40%.",
    "recommended_mode": "Train Freight",
    "recommended_vendor": "CONCOR",
    "transport_alternatives": [
      { "mode": "Ocean Freight", "icon": "Ship", "is_current": true, "is_recommended": false },
      { "mode": "Train Freight", "icon": "Train", "is_recommended": true, "suggested_vendor": "CONCOR" }
    ]
  },
  "explanation": "This shipment has a 67% probability of delay due to high congestion on the Noida-Dubai route..."
}

POST /fast-recommend

Pre-prediction quick recommendation (no ML models run).

Request

{ "is_ocean_crossing": true, "distance_km": 5000 }

Response

{ "mode": "Ocean Freight", "vendor": "Maersk", "reason": "Optimal cost-friendly choice for international/ocean routes." }

Other Endpoints

Endpoint Description
GET /nearest-seaport?lat=..&lon=.. Returns the nearest seaport coordinates and name
GET /nearest-airport?lat=..&lon=.. Returns the nearest airport coordinates and name
GET /searoute?origin_lat=..&origin_lon=..&dest_lat=..&dest_lon=.. Returns ocean vessel route coordinates
GET /history Returns the last 50 predictions
GET /admin/stats Returns aggregated admin KPIs (delay rates, shipment counts, vendor breakdown)
POST /webhook/shipment_update Accepts live GPS pings from carrier systems for real-time tracking
GET /health Health check endpoint

Full interactive Swagger documentation is available at http://localhost:8000/docs once the backend is running.


Model Performance

Model Metric Score
Ensemble Binary Classifier Accuracy 84.7%
Ensemble Binary Classifier AUC-ROC 0.891
LightGBM Delay Regressor MAE 1.24 days
LightGBM Delay Regressor RMSE 2.15 days
Reason Classifier Accuracy 78.2%
API Inference (no LLM) Avg. Latency ~85 ms
API Inference (with LLM) Avg. Latency ~1.8 s

Verified Test Cases

Test Origin Destination Mode Expected Result
High Risk Noida (IN) Dubai (AE) Ocean At Risk — vendor penalty applied
Low Risk Noida (IN) Mumbai (IN) Train On Track — inland station-to-station
Train Blocked Noida (IN) Dubai (AE) Train Not Viable — ocean crossing detected
Air Route Delhi (IN) New York (US) Air Arc route via IGI to JFK
Ocean Route Shanghai (CN) Hamburg (DE) Ocean Ship lane via Suez Canal

Docker Deployment

docker-compose up --build

This starts both the FastAPI backend and serves the built frontend. Add your GROQ_API_KEY to docker-compose.yml (or pass it as an environment variable) before building.


Production Roadmap

  • 🌦️ Weather-Based Re-routing — real-time OpenWeatherMap integration to dynamically recalculate delay risk and suggest alternate routes
  • 🌐 Digital Twin & Simulation — a virtual model of the full supply chain for what-if stress testing
  • 🤖 Autonomous Self-Healing — AI that auto-books backup vendors via API when a delay is predicted
  • 🌡️ IoT Cold-Chain Monitoring — temperature/humidity sensor integration for pharma and perishables
  • ⛓️ Blockchain Smart Contracts — automated SLA payments and penalties based on AI-verified delivery records
  • 🌱 Carbon Footprint (ESG) Optimizer — route optimization for minimum CO₂ emissions alongside cost and speed

Contributing

Contributions are welcome! To contribute:

  1. Fork the repository
  2. Create a new branch: git checkout -b feature/amazing-feature
  3. Commit your changes: git commit -m 'Add amazing feature'
  4. Push to the branch: git push origin feature/amazing-feature
  5. Open a Pull Request

License

This project is licensed under the MIT License. See the LICENSE file for details.


Acknowledgments

  • DataCo Smart Supply Chain dataset (Kaggle) — real-world training data
  • Groq — ultra-fast LLaMA 3 inference
  • OSRM — open-source highway routing
  • Nominatim / OpenStreetMap — free global geocoding
  • searoute — open-source ocean vessel routing
  • turf.js — geospatial analysis for great-circle arc routes
  • Leaflet.js — interactive satellite maps

About

AI-powered logistics platform that predicts shipment delays before the truck leaves — using a 3-stage ML pipeline (Ensemble Classifier → LightGBM Regressor → Reason Classifier) with async LLM explanations via Groq Qwen 2.5.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages