Spaces:
Running on Zero

SmartWareHouseAI / README.md
Pro-Coder's picture
Upload 44 files
4c8ed45 verified
|
Raw History Blame
9.57 kB
---
title: Smart Warehouse AI Assistant
emoji: 🏭
colorFrom: blue
colorTo: indigo
sdk: gradio
sdk_version: 5.9.1
app_file: app.py
pinned: false
license: agpl-3.0
short_description: LLM warehouse copilot, predictive maintenance & CV
---
# 🏭 Smart Warehouse AI Assistant
An LLM-powered, retrieval-grounded AI copilot for automated warehouse
operations -- built as a portfolio / application project. Combines an
**LLM assistant (RAG)**, an **intent classifier**, an **inventory/order
query layer**, and an **Isolation-Forest predictive-maintenance model**,
with a full **Model Evaluation** tab reporting real accuracy/F1/ROC-AUC
metrics on held-out test data.
πŸ‘‰ **Live demo:** add your Space URL here once deployed, e.g.
`https://huggingface.co/spaces/<your-username>/smart-warehouse-ai`
## Tabs
1. **πŸ’¬ AI Assistant** β€” free-text warehouse-ops Q&A. Intent classification β†’ TF-IDF retrieval over a
17-article knowledge base (RAG) β†’ hosted LLM, with **multi-turn memory** (follow-ups like
*"what about Zone D instead?"* work), a multi-model fallback chain, a retrieval-only fallback, and a
"Test LLM connection" diagnostics button.
2. **πŸ“¦ Inventory & Order Query** β€” natural-language queries over synthetic inventory / order tables.
3. **⚠️ Predictive Maintenance** β€” Isolation Forest anomaly detector (calibrated threshold). Single
readings via sliders, **CSV batch scoring** (sample file provided), and optional **Slack alerts**
(real if `SLACK_WEBHOOK_URL` is set, otherwise a clearly-labelled preview β€” never claimed as sent).
4. **πŸ“· Visual Inventory Scan** β€” two sub-tabs:
- **Real photos (YOLO):** upload a warehouse photo (or load an openly-licensed Wikimedia Commons
example, fetched at runtime with author/licence shown). *Standard* mode = COCO-pretrained YOLOv8
(finds people/vehicles; COCO has **no** pallet/forklift/box class). *Find by name* mode =
open-vocabulary **YOLOE** β€” type "pallet, cardboard box, forklift…" and it searches zero-shot.
- **Synthetic rack (classical-CV baseline):** the original OpenCV pipeline on synthetic racks with
known ground truth, so accuracy *can* be measured.
5. **πŸ“Š Model Evaluation** β€” graphical, held-out metrics for every component, including the vision
pipeline's accuracy-vs-noise curve.
6. **ℹ️ About** β€” dataset provenance, model function table, architecture, how to test.
A **🌐 Language / 言θͺž** selector switches the explanatory text between English and ζ—₯本θͺž.
## Quick start (local)
```bash
git clone <this-repo>
cd smart-warehouse-ai
pip install -r requirements.txt
# (re)generate datasets, train models, produce evaluation plots/metrics
python build_artifacts.py
# run the app
python app.py
```
Open the printed local URL (usually `http://127.0.0.1:7860`).
## Enabling full LLM responses
The app works out of the box in **retrieval-only fallback mode** (no external API calls). For real
LLM-generated answers it needs an API key for any **OpenAI-compatible** chat endpoint. The simplest free
option is Groq:
1. Create a free API key at https://console.groq.com
2. Set it as a Space secret (or env var) named `GROQ_API_KEY`. The default model is `llama-3.1-8b-instant`;
override with `LLM_MODEL` if Groq retires or renames it.
Other options (checked in this order; the first that answers wins):
| Secrets | Backend |
|---|---|
| `LLM_API_KEY` + `LLM_BASE_URL` + `LLM_MODEL` | any OpenAI-compatible API (OpenRouter, Together, Cerebras, …) |
| `GROQ_API_KEY` | Groq (free plan) |
| `HF_TOKEN` | Hugging Face Inference Providers router β€” **needs credits**; free accounts get almost none, which shows up as `402 Payment Required` |
```bash
export GROQ_API_KEY=gsk_xxxxxxxxxxxx
python app.py
```
The **Test LLM connection** button (AI Assistant tab) shows exactly what each backend returned.
## Deploying to Hugging Face Spaces
See [`DEPLOY.md`](./DEPLOY.md) for full step-by-step instructions.
## Project structure
```
smart-warehouse-ai/
β”œβ”€β”€ app.py # Gradio app (5 tabs)
β”œβ”€β”€ build_artifacts.py # generates data, trains models, evaluates, saves plots
β”œβ”€β”€ requirements.txt
β”œβ”€β”€ src/
β”‚ β”œβ”€β”€ vision_model.py # classical-CV rack scanner (+ synthetic scene generator)
β”‚ β”œβ”€β”€ real_vision.py # real-photo detection: YOLOv8 (COCO) + YOLOE (open-vocabulary)
β”‚ β”œβ”€β”€ alerting.py # Slack alert (real webhook or preview) + email preview
β”‚ β”œβ”€β”€ data_generation.py # synthetic intent / inventory / sensor datasets
β”‚ β”œβ”€β”€ knowledge_base.py # warehouse-ops knowledge base (RAG source docs)
β”‚ β”œβ”€β”€ retriever.py # TF-IDF retriever
β”‚ β”œβ”€β”€ intent_model.py # intent classifier (train/predict)
β”‚ β”œβ”€β”€ anomaly_model.py # Isolation Forest anomaly detector
β”‚ β”œβ”€β”€ llm_client.py # OpenAI-compatible LLM client (Groq / custom / HF router) + fallback
β”‚ └── inventory_db.py # NL -> structured query helpers
β”œβ”€β”€ models/ # trained model artifacts (.joblib)
β”œβ”€β”€ data/ # generated datasets + evaluation JSON
└── assets/ # evaluation plots (confusion matrices, ROC curve)
```
## Evaluation summary
See the in-app **Model Evaluation** tab for full details (confusion
matrices, per-class precision/recall, retrieval hit-rate table, latency
benchmark). Headline numbers from the included run:
| Component | Metric | Score |
|---|---|---|
| Intent classifier | Accuracy | ~98% |
| Intent classifier | Macro F1 | ~97% |
| Anomaly detector | Precision | 100% |
| Anomaly detector | Recall | ~97% |
| Anomaly detector | F1 | ~98% |
| Anomaly detector | ROC-AUC | ~1.00 |
| RAG retriever | Hit-rate@1 / @2 | 88% / 100% |
| Synthetic-rack CV baseline (noise 0.4) | Exact box-count match | ~88% (100% clean β†’ ~77% at max noise) |
| Real-photo YOLO / YOLOE | β€” | **Not benchmarked** (no labelled warehouse photos available) |
*(Computed on synthetic, held-out test data β€” see the Evaluation tab for
methodology notes.)*
**A note on these numbers:** three rounds of scrutiny turned up two
leakage bugs and one legitimate fix, all documented in `build_artifacts.py`:
1. **Train/test leakage (intent classifier).** Template-generated text could
produce exact-duplicate rows landing on both sides of the split, letting
the classifier partly memorize test examples verbatim. Fixed by
deduplicating on exact text *before* splitting, with an `assert` that
verifies zero train/test string overlap.
2. **Threshold leakage (anomaly detector).** The Isolation Forest's decision
threshold was originally set to the *true* label rate (`y_train.mean()`)
β€” not available in a real unsupervised deployment. Switching to
scikit-learn's label-blind `"auto"` heuristic removed the leak, but
dropped precision to 67% (F1 80%) β€” an honest but mediocre result.
3. **The actual fix: calibrated threshold.** The model is still fit fully
unsupervised (no labels touched during `.fit()`). Its decision threshold
is then calibrated by maximizing F1 on a small, separate *labelled
calibration split* (140 examples, 14 confirmed anomalies) β€” analogous to
tuning an alert threshold against a handful of confirmed historical
incidents in production, a standard real-world practice. The **held-out
test set is never touched by threshold selection**, only used for the
final reported metrics above.
ROC-AUC staying at 1.00 throughout all three versions is the most telling
number: it's threshold-independent by construction, so it confirms the
model's *ranking* of anomalies was always excellent β€” the entire story here
is about honestly picking the cutoff, not about detection ability.
## Real-photo detection: what was and wasn't verified
| | Status |
|---|---|
| YOLOv8n / YOLOv8s (COCO) on a real photo | βœ… run end-to-end; detections visually checked |
| YOLOE open-vocabulary on a real photo | βœ… run end-to-end through the app's API; one duplicate-box over-count observed, hence the user-facing IoU slider |
| Accuracy on **warehouse** photos | ❌ **Not measured** β€” no labelled warehouse images were available |
| Wikimedia example photos | ⚠️ Fetched at runtime on the Space; my development sandbox couldn't reach Wikimedia, so these were *not* run through the detector before delivery (the failure path *was* tested) |
| YOLO-World / OWLv2 / Grounding DINO | Not shipped β€” their weights are hosted where I couldn't verify them |
Photos are processed in memory and never stored; Ultralytics' anonymous usage sync is switched off.
First use downloads weights from the official Ultralytics GitHub releases (β‰ˆ630 MB for open-vocabulary
mode, once per container).
## Image attributions
Example photos are **not bundled**; they're fetched from Wikimedia Commons when selected, and shown with
author and licence:
- *Modern warehouse with pallet rack storage system.jpg* β€” Axisadman, CC BY-SA 3.0
- *Allentown Project 042.jpg* β€” Chrisking, CC BY-SA 3.0
- *576 CHEP pallets.jpg* β€” train_photos (Flickr), CC BY-SA 2.0
## License
**AGPL-3.0.** The real-photo detector uses Ultralytics YOLO, whose code and pretrained weights are
AGPL-3.0; serving them as a network app means the combined project is distributed under the same terms
(source is available in this repository). If you want to reuse the project in a closed-source product,
Ultralytics sells a commercial licence, or you can swap in a differently-licensed detector.