Commit ·
df033d6
0
Parent(s):
Deploy Vision AI to Hugging Face Space
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributesAdded+1
- .gitignoreAdded+49
- README.mdAdded+346
- app.pyAdded+19
- backend/.dockerignoreAdded+7
- backend/.env.exampleAdded+21
- backend/DockerfileAdded+22
- backend/app/__init__.pyAdded
- backend/app/config.pyAdded+54
- backend/app/dependencies.pyAdded+53
- backend/app/main.pyAdded+53
- backend/app/routes/__init__.pyAdded
- backend/app/routes/caption.pyAdded+48
- backend/app/routes/health.pyAdded+40
- backend/app/routes/plant.pyAdded+54
- backend/app/routes/prescription.pyAdded+25
- backend/app/routes/product_label.pyAdded+45
- backend/app/schemas/__init__.pyAdded+29
- backend/app/schemas/plant.pyAdded+57
- backend/app/schemas/prescription.pyAdded+15
- backend/app/schemas/product_label.pyAdded+11
- backend/app/services/__init__.pyAdded
- backend/app/services/caption_service.pyAdded+105
- backend/app/services/captioners/blip.pyAdded+127
- backend/app/services/captioners/catr.pyAdded+207
- backend/app/services/captioners/common.pyAdded+63
- backend/app/services/captioners/sat.pyAdded+276
- backend/app/services/plant_service.pyAdded+32
- backend/app/services/prescription_service.pyAdded+44
- backend/app/services/product_label_service.pyAdded+80
- backend/app_gradio.pyAdded+336
- backend/configs.yamlAdded+31
- backend/data/eval/eval_after.jsonAdded+339
- backend/data/eval/eval_before.jsonAdded+292
- backend/data/eval/prescriptions/README.mdAdded+56
- backend/data/eval/product_labels/README.mdAdded+39
- backend/data/medicines/known_brands.jsonAdded+887
- backend/data/medicines/updated_indian_medicine_data.csvAdded+3
- backend/data/medicines/uses_by_ingredient.jsonAdded
- backend/data/product_label/additives.jsonAdded
- backend/data/product_label/allergens.jsonAdded+349
- backend/data/product_label/nutriscore_thresholds.jsonAdded+392
- backend/model/__init__.pyAdded
- backend/model/captioning/__init__.pyAdded+7
- backend/model/captioning/catr/LICENSEAdded+201
- backend/model/captioning/catr/__init__.pyAdded+6
- backend/model/captioning/catr/backbone.pyAdded+116
- backend/model/captioning/catr/caption.pyAdded+57
- backend/model/captioning/catr/configuration.pyAdded+44
- backend/model/captioning/catr/position_encoding.pyAdded+85
1backend/data/medicines/updated_indian_medicine_data.csv filter=lfs diff=lfs merge=lfs -text12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849# Secrets.env*.env!.env.example
# OS / editor.DS_Store.vscode/.idea/
# Pythonvenv/.venv/__pycache__/*.pyc*.egg-info/.ipynb_checkpoints/.pytest_cache/
# Frontendnode_modules/frontend/dist/
# Model weights (large; see backend/README.md to recreate)backend/weights/ocr/backend/weights/*.pthbackend/weights/*.pth.tar*.pth
# Generated outputsbackend/experiments/results/*.log
# Local backups and private notesarchive/project_review/
# Medicine index cache (rebuilt from the CSV) and labelled eval prescriptions (patient data)backend/data/cache/backend/data/eval/prescriptions/*!backend/data/eval/prescriptions/README.md
# Product label: labelled eval photosbackend/data/eval/product_labels/*!backend/data/eval/product_labels/README.md
# 250k Medicines Usage, Side Effects and Substitutes (CC BY-SA 4.0): raw download, 89 MB, not committed.# The small derived lookup data/medicines/uses_by_ingredient.json IS committed (CC BY-SA 4.0).backend/data/medicines/250k_raw/123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346---title: Vision AI - Image Captioning & Analysisemoji: 👁️colorFrom: bluecolorTo: indigosdk: gradiosdk_version: 4.44.0app_file: app.pypinned: falselicense: mit---
# 🖼️ Vision AI Backend: captioning, prescriptions, food labels, plants
FastAPI backend with four features:
- **Image captioning:** three pretrained models, chosen per request (`?model=`), each returning one attention map per word, which shows where the model looked:
| `model` | Architecture | Trained on | Attention grid | |---|---|---|---| | `blip` (**configured default**) | ViT-B/16 + BERT-style text decoder | COCO (fine-tuned) | 24×24 | | `sat` | ResNet-101 + soft attention + LSTM ("Show, Attend and Tell", the PRD architecture) | COCO 2014 | 14×14 | | `catr` | ResNet-101 + 6-layer transformer | COCO 2017 | follows image aspect |
On our test photos BLIP was the most accurate (for example "a woman in a suit leaning on a railing", where SAT and CATR both said "talking on a cell phone"). `configs.yaml` therefore sets `blip` as the default; SAT and CATR remain available with `?model=sat` and `?model=catr`. `deploy/deploy_ec2.sh` pre-caches BLIP so no visitor waits for the download. All three still say "a dog running with a ball in its mouth" for a dog with the ball at its paws.- **Prescription reader:** photo → OpenCV preprocessing → RapidOCR (PaddleOCR models, English + Hindi) on this machine → patient/doctor lines removed → a free AI text model structures the medicine lines → checked against the Indian Medicine Dataset, with "What it's for" by ingredient.- **Food label checker:** photo → the same preprocessing and OCR → regex parser (AI only for values the parser missed) → allergen rules and Nutri-Score 2023, plus a guarded explanation.- **Plant identification:** 1–5 photos → PlantNet API → candidates plus a small local medicinal guide; medicinal uses are written by the text AI from the **name only** (never the photo), in English, Hindi or Kannada.
The prescription and label pipelines are described in `../project_review/ADR-005-simplified-pipelines.md` (a local, git-ignored design document).
The React app lives in `../frontend/`.
---
## 📁 Structure
```backend/├── run.py # starts the API + built web app on one port (uvicorn)├── configs.yaml # captioning inference settings (default model, weights, beam size)├── requirements.txt # FastAPI, torch, transformers, openai, rapidfuzz, OpenCV (2-step install)├── requirements-ocr.txt # RapidOCR + onnxruntime, pinned; installed with --no-deps├── Dockerfile # Linux image; OCR models downloaded at build time├── .dockerignore # keeps venv, .env, weights, eval data out of the image├── .env.example # up-to-date template: OPENROUTER_*, GROQ_*, PLANTNET_API_KEY├── app/ # FastAPI service layer│ ├── main.py # app, CORS, routers; 4 services created once at startup│ ├── config.py # env-overridable settings (.env)│ ├── dependencies.py # image upload validation (type, size, EXIF)│ ├── schemas/ # API response models: __init__ (health, caption), prescription.py,│ │ # product_label.py, plant.py│ ├── routes/ # health.py, caption.py, prescription.py, product_label.py, plant.py│ └── services/ # caption_service.py (+ captioners/), prescription_service.py,│ # product_label_service.py, plant_service.py├── model/│ ├── captioning/ # SAT model + converter, CATR architecture; BLIP is loaded│ │ # via HuggingFace transformers in app/services/captioners/blip.py│ ├── common/ # preprocess.py, ocr.py (RapidOCR), llm.py (OpenRouter + Groq), redact.py│ ├── prescription/ # pipeline, extract, layout, medicine_db, uses, schemas│ ├── product_label/ # pipeline, parser, allergens, nutriscore, additives, sanity, explain, schemas│ └── plant/ # identify.py (PlantNet + local guide), uses.py (AI-written, cached)├── weights/ # model files (git-ignored): captioning weights + word map; ocr/ from│ # setup_ocr_models.py; catr_tokenizer/├── scripts/ # setup_ocr_models.py, compare_ocr.py, eval_*.py, build_*.py,│ # matcher_cases*.json├── tests/ # unittest; no network, OCR and AI are fakes├── data/medicines/ # Indian Medicine Dataset CSV (MIT), known_brands.json,│ # uses_by_ingredient.json (CC BY-SA 4.0), 250k_raw/, Images/├��─ data/product_label/ # allergens.json, additives.json, nutriscore_thresholds.json├── data/cache/ # medicine_index.pkl (built from the CSV) + ai_eval_rx/ eval caches (git-ignored)├── data/samples/ # prescription_test.jpeg└── data/eval/ # eval photos and ground truth (git-ignored), eval_before.json / eval_after.json```
### Caption request flow
```POST /api/caption?model=sat|catr|blip (image) # sat = configs.yaml default → dependencies.read_image validate type/size, fix EXIF rotation, RGB → CaptionService.caption picks the engine (default: configs.yaml inference.model) blip BlipProcessor 384×384 → generate (beam 3, no repeated word pairs) → cross-attention of each word over 24×24 patches, minus the caption's average (removes ViT "attention sink" patches so each word shows its own region) sat 256×256, ImageNet norm → ResNet-101 → (1, 14, 14, 2048) → beam 5 with the gated soft-attention LSTM → 14×14 map per word catr longest side 299 → ResNet-101 + transformer encoder once → beam 3 over the decoder → cross-attention (mean of heads and layers) on an H×W grid per word → { model, caption, words, alphas, grid_shape, grid_size, generation_time_ms, inference_ms }```
`alphas` always contains **one map per word**, scaled 0–1, but the shape depends on the engine:**14×14** for SAT, **24×24** for BLIP and **H×W** (image aspect ratio) for CATR. The exact shape isreturned as `grid_shape`; the older square-only `grid_size` field is kept for older clients.Beam size defaults come from `configs.yaml`: SAT 5, CATR 3, BLIP 3 (overridable with `?beam_size=`).
---
## 🛠 Installation
```bashcd backendpython3 -m venv venvsource venv/bin/activate # macOS/Linuxpython -m pip install --upgrade pippython -m pip install -r requirements.txtpython -m pip install --no-deps -r requirements-ocr.txt # RapidOCR + onnxruntime, pinned; uses our one OpenCVpython scripts/setup_ocr_models.py # OCR models -> weights/ocr/ (once, ~364 MB, SHA-256 checked)cp .env.example .env # then add OPENROUTER_API_KEY (and GROQ_API_KEY as backup)```
The app never downloads OCR models while running; without them the prescription and label pages report"not available" and point to `setup_ocr_models.py`. Docker: `docker build -t vision-ai-backend .` does all of this(headless OpenCV on Linux).
Put the captioning weights in `weights/`. They are git-ignored. To recreate them:
1. Download `BEST_checkpoint_coco_5_cap_per_img_5_min_word_freq.pth.tar` and `WORDMAP_coco_5_cap_per_img_5_min_word_freq.json` from the project's model assets.2. Copy both into `weights/`.3. Run: ```bash python -m model.captioning.convert_checkpoint # writes weights/sat_resnet101_coco.pth ```
The converter loads the pickled checkpoint through a `models` → `sat_models` alias and drops the optimizer state. It then checks that the converted model gives bit-identical outputs. After that, the `.pth.tar` is no longer needed (this copy's is kept in `../archive/weights/`; copy it back into `weights/` only to re-run the converter).
---
## 🚀 Usage
```bashcd backendvenv/bin/python run.py # http://127.0.0.1:8000/docs```
### Starting the backend and frontend
Start the servers from **your own terminal**. A server started by a tool or an assistant session stops when that session ends.
**Option A: one port (simplest).** `run.py` serves the API and the built web app together:
```bashcd frontend && npm install && npm run build # once, and again after any UI changecd ../backend && venv/bin/python run.py # open http://127.0.0.1:8000 (#/product-label for the label tab)```
**Option B: while editing the UI (two terminals, hot reload):**
```bash# terminal 1: API on :8000cd backend && venv/bin/python run.py# terminal 2: Vite dev server on :5173, forwards /api to :8000cd frontend && npm run dev # open http://localhost:5173```
Vite listens on `localhost`. If `http://127.0.0.1:5173` refuses the connection, use `http://localhost:5173`.
- **Stop:** press `Ctrl+C` in each terminal. If port 8000 or 5173 is still in use, find the process with `lsof -iTCP:8000 -sTCP:LISTEN` and stop it with `kill <PID>`.- **Check:** `curl http://127.0.0.1:8000/api/health` should report `"product_label": "ready"`.- **Keys:** copy `.env.example` to `backend/.env` and set `OPENROUTER_API_KEY` (free model), `GROQ_API_KEY` (backup) and `PLANTNET_API_KEY` (plant identification). Without the AI keys the prescription and label features still work: prescriptions show dataset-matched names with "AI busy: details not extracted", labels use the parser only. Without the PlantNet key the plant endpoints return 503.- **Installing packages:** use `venv/bin/python -m pip install …`, not `venv/bin/pip`. The venv was moved, so its `pip` script points at an old interpreter path.- **Keeping it running:** to keep the server running after you close the terminal, use `nohup venv/bin/python run.py > server.log 2>&1 &` (stop it with `kill`).
Run the server from the venv. Different Pillow/torch versions resize images slightly differently, and that can change some captions.
| Method | Endpoint | Body | Response ||---|---|---|---|| GET | `/api/health` | — | status, device, vocab_size, checkpoint, modes || POST | `/api/caption` | `file` (JPEG/PNG/WebP ≤ 10 MB); optional `model` (`sat` default, `catr`, `blip`), `beam_size` (1–10, default 5) and `max_len` | `{model, caption, inference_ms, words, alphas, grid_shape, grid_size, generation_time_ms}`. `alphas` has one map per word, scaled 0–1; shape is 14×14 (SAT), 24×24 (BLIP) or H×W (CATR), given by `grid_shape` (`grid_size` is kept for older clients) || POST | `/api/prescription` | `file` (image) | structured prescription JSON (`status`: ok / unreadable / ai_busy) || POST | `/api/product-label/interpret` | `image`; optional `product_name` (≤ 100 chars, titles the result and is given to the explanation AI, never used for values or the score) | food label result (`status`: ok / unreadable) || GET | `/api/product-label/{id}/explanation` | – | guarded explanation (AI) or the template || POST | `/api/plant/identify` | `images` (1–5 photos of one plant), `organ` (auto / leaf / flower / fruit / bark) | PlantNet candidates + medicinal-use context for plants in the local guide (`status`: ok / no_match). Needs `PLANTNET_API_KEY`; photos are sent to Pl@ntNet || POST | `/api/plant/uses` | `{scientific_name, common_names}` | medicinal uses (with evidence level), parts used, safety notes, `toxic` flag, written by the AI from the name only; doses are removed (`status`: ok / busy / unavailable) |
The React dev server proxies `/api` to the backend (`frontend/vite.config.js`).
Captioning settings live in `configs.yaml` → `inference:` (`weights`, `image_size`, `beam_size` (default 5), `no_repeat_ngram` (default 2), `max_caption_len`).At startup the model runs one short warm-up pass (a second or two on Apple MPS). This keeps the first real request fast (about 0.1–0.7 s).
### Tests
```bashcd backendvenv/bin/python -m unittest discover -s tests -v```
The tests check:- the encoder output is `(1, 14, 14, 2048)`- attention weights add up to 1 at every decoding step- 14×14 maps scaled 0–1, with special tokens removed- the vocabulary is the COCO word map (9,490 entries)- beam size and length limits- the API response shape and error codes
The 7 test files are: `test_captioning.py`, `test_layout_rows.py`, `test_ocr_candidates.py`,`test_prescription.py`, `test_prescription_uses.py`, `test_product_label.py` and `test_plant.py`.They use fake OCR engines and fake AI clients, so no network or model weights are needed(except `test_captioning.py`, which needs `weights/sat_resnet101_coco.pth`).
### Prescription reader (`model/prescription/`, ADR-005)
```POST /api/prescription (image) 1. preprocess common/preprocess.py: EXIF rotation, resize (steps chosen by scripts/compare_ocr.py) 2. OCR common/ocr.py: RapidOCR detection + recognition; every box is also read by the Devanagari model and the more confident reading is kept (printed Hindi, "रात"); sideways/upside-down photos are turned upright. No text -> "Couldn't read this photo. Try a flatter, brighter photo." 3. redact common/redact.py: only lines from the first medicine marker (Rx / Tab / 1)) on, without name, age, weight, phone, address or registration lines, ever leave this machine 4. AI extract.py: one text request (OpenRouter free model, Groq as backup) -> medicines (name as written, alternatives, strength, form) + already taking. Identification only (2026-11-17): how often, how long, dose counts, dates and follow-up are not extracted. Both busy -> each word of the medicine lines is looked up in the dataset instead, and the result says "AI busy: details not extracted. Try again in a few minutes." 5. rules names not found in the OCR text are flagged; a strength on a low-confidence line or not in the text is marked "check". Schedule marks (1-0-1, BD, "x 5 days") are only used as evidence that a row is a medicine line 6. dataset medicine_db.py + uses.py (below)```
The feature **identifies medicines only**: chat, date parsing, dose counts and follow-up were removed in the2026-11 simplification (the old `chat.py`, `dates.py` and line-cropping modules are gone). No image is sentto the AI — only the redacted medicine rows, as text.
#### Medicine matching (local, step 6)
- **Data:** - Indian Medicine Dataset (`data/medicines/updated_indian_medicine_data.csv`, MIT licence as provided with the file; add the exact source URL here, 45 MB, 253,973 rows). Discontinued rows (7,905) and duplicate names are dropped: **241,867 medicines, 116,502 brands**. - **"What it's for" (by ingredient):** derived from a public medicines-usage dataset, licensed **CC BY-SA 4.0**. The raw CSV (89 MB) goes in `data/medicines/250k_raw/` and is git-ignored; `scripts/build_medicine_uses.py` joins it to the Indian Medicine Dataset by name and writes the committed lookup `data/medicines/uses_by_ingredient.json` (0.57 MB, 2,896 ingredient keys), which is **itself CC BY-SA 4.0** (ShareAlike: keep this licence if you redistribute it). Where it has no uses, the Indian Medicine Dataset's own description is the fallback. Names are normalised (dothiepin = dosulepin, acetaminophen = paracetamol, …); combinations without their own entry combine each ingredient's uses. No AI ever writes these lines; with no data the app says "No description available. Ask your pharmacist what this medicine is for." - The cleaned index is cached in `data/cache/medicine_index.pkl`. It's built in about 10 s the first time, loads in about 1 s afterwards, loads once at startup, and rebuilds automatically if the CSV changes.- **Per extracted medicine:** 1. **Company names never count as medicines.** Exact company names without digits are rejected first ("Cipla"; "Pan 40" is still a medicine). 2. **Brand similarity (rapidfuzz) decides the status:** - **matched:** ≥ 90 and ≥ 5 points ahead of the best *different* brand - **verify:** 75–89, or a close different brand - **unmatched:** < 75 3. **Within the winning brand, strength and form pick the variant** ("Dolo 650" → Dolo 650 Tablet). Strengths come from the name *and* the composition. A written strength with no matching product means **verify**; no written strength means no strength is shown. 4. **Identification guards (2026-11-17):** - the brand word is chosen past an OCR-misread "Tab" ("Td SERTA" → Serta, not the brand "TD"); - a misspelt brand is **matched** only if the written strength or a variant word ("PT", "Plus") confirms it, otherwise **verify**; - a written word the product doesn't have ("Colgate Plax") or a form it doesn't come in ("gum paint" vs tablets) means **verify**; - oral-care products and devices (Colgate, toothbrush, Sensodyne ...) are reported as not a medicine; - "Ativan (Lorazepam)" is matched as the brand Ativan with Lorazepam as an alternative name. 5. **Confidence level and strength (2026-11-18):** strength written and in the product → good; written and in no product of the brand → Low; not written and the written variant comes in one strength only ("Hexigel", "Sizodon Plus") → neutral "not applicable"; not written and it comes in 2–3 strengths → Medium, 4 or more → Low. A strength inside the name ("Dolo 650") counts as written. High needs every factor good or neutral, no other brand within 5 points, and, when the strength can't confirm it, a name match of exactly 100. A gum paint counts as the same kind of product as a mouth gel, cream or ointment. 6. **Measured with** `scripts/eval_matcher.py`: 115 cases used while writing the rules and 123 held-out cases generated afterwards (written name → expected ingredient, checked against the dataset). Tuning cases: wrong confident matches 4 → 0, correct or offered for confirmation 107 → 115 of 115. Held-out cases: wrong 0 → 0, correct or offered 96 → 121 of 123 (mostly misread "Tab" prefixes such as "Tub" or "Ta6"). `scripts/eval_prescription.py` scores whole photos the same way (identified / to confirm / wrong). 7. **Not in the dataset → `data/medicines/known_brands.json`** → **known_brand** (e.g. Zincovit, Electral; never counted as matched). 8. **The name as read is never overwritten:** `read_as` keeps it, `suggested_name` gives the database name, and a review note explains the difference.- **Top-3 candidates** (distinct brands first) are returned for the UI's "verify" dropdown.- **`db_info`** ("From medicine database") holds composition, manufacturer, pack, type, and description, side effects and interactions **only when the dataset has them** (about 2.8% of medicines). Empty fields are omitted. The LLM never adds medical facts.- **Confidence** = reader confidence × match score/100 × status weight (matched 1.0, verify 0.8, known brand 0.7, unmatched 0.5), all 0–1. Names not found in the text that was read stay **capped at 0.30**.
> **Not medical advice:** handwriting OCR is error-prone. The UI shows a disclaimer, and every result must be checked by a doctor or pharmacist.
### Food label checker (`model/product_label/`, ADR-005)
```POST /api/product-label/interpret imageGET /api/product-label/{session_id}/explanation explanation, fetched after the results (never blocks them)
1. preprocess + OCR same modules as prescriptions (no Hindi pass); no text -> "Couldn't read this photo ..." 2. parser regex, per 100 g / 100 mL (per serving converted with the serving size); nutrient names in English, French, German, Spanish, Italian, Dutch, Portuguese, Polish, Czech 3. AI (only if needed) a nutrient whose name is printed but whose value wasn't parsed, or values that fail the sanity check: the OCR TEXT (never the photo) goes to the AI, which may only copy numbers that are in that text; anything else is rejected. AI busy -> parsed values + a note 4. analysis sanity checks, allergens (rules; "unknown" when the ingredients weren't read, never "none"), additives, Nutri-Score 2023 (official tables), tips (rules) 5. explanation AI from the parsed values only, guarded (numbers, recommendations, allergen claims); template when no AI answers```
- **Health score (Nutri-Score):** the updated algorithm from Santé publique France, *Conditions of Use*, version 26 June 2024, Exhibit 1-B. All thresholds are in `data/product_label/nutriscore_thresholds.json`, with the source recorded. Category: beverage when the table is per 100 mL, otherwise general food (approximate).- **Sanity checks:** energy ≈ 4·protein + 4·carbs + 9·fat (±20 %); kJ ≈ kcal × 4.184 (±10 %); nothing above 100 g/100 g; sugars and fibre ≤ carbohydrate; saturated + trans fat ≤ fat; added sugars ≤ sugars. A failure adds "values may be misread".- **Data files:** `allergens.json` (incl. Indian terms; sulphites per FSSAI Labelling Regulations 2020, clause 5(14)(viii)) and `additives.json` (Open Food Facts additives taxonomy, ODbL, pinned commit).- **Evaluation:** `scripts/eval_product_label.py --all` scores the verified photos (7 values within ±5 %); `--ai-cache DIR` keeps AI answers between runs so repeated evals don't use the free allowance. `scripts/compare_ocr.py` compares OCR models and preprocessing steps (no AI). `scripts/build_label_eval_set.py` builds the set from the Hugging Face dataset and keeps your own photos separate.
### Plant identification (`model/plant/`)
```POST /api/plant/identify 1-5 photos of one plant + organ (auto / leaf / flower / fruit / bark)POST /api/plant/uses {scientific_name, common_names, lang} -> medicinal uses
identify.py 1-5 photos -> PlantNet API (PLANTNET_API_KEY) -> candidates + confidence; adds context from a small hand-written local guide, with Hindi/Kannada text uses.py AI writes uses from the NAME ONLY (never the photo); JSON-validated, any dose is removed, cached in memory per scientific name. A second AI call translates the checked English answer to hi/kn and validates script and structure; if translation fails the English answer is returned```
- Photos are sent to **Pl@ntNet** (France); the free tier allows 500 identifications/day.- Without `PLANTNET_API_KEY` the endpoints return 503 and `/api/health` reports `"plant": "unavailable"`.- This feature does not use the OCR models or the medicine database. See `tests/test_plant.py` (network mocked).
### AI (`model/common/llm.py`)- **One free OpenRouter text model** (`OPENROUTER_MODEL`, must end in `:free`), **Groq as the single backup** (`GROQ_MODEL`). The official `openai` SDK talks to both. One try per provider, plus **one short wait-and-retry** only for an HTTP 429 whose `retry-after` is ≤ 10 s. No budget files and no caches in the app. Keys are never logged.- **Text only:** no image is ever sent to an AI.- **Configuration:** `.env.example` is the up-to-date template. Older variable names sometimes left in a local `.env` (`TROCR_*`, `LLM_PROVIDER_ORDER`, `OPENROUTER_*_MODELS`, `PRESCRIPTION_*`) are no longer read by any code.
> **Where data goes** (the app shows the same text, with the configured model names):> - **Caption a photo:** read on this machine. Nothing is sent anywhere else.> - **Read a prescription:** the photo is read on this machine. Only the medicine lines (no patient, doctor or clinic details) are sent as **text** to OpenRouter, or Groq if OpenRouter is busy.> - **Check a food label:** the photo is read on this machine. Only if a printed value couldn't be parsed is the label's **text** sent to the AI; explanations send the parsed values.> - **Identify a plant:** the photos are sent to **Pl@ntNet**. The medicinal-uses AI receives only the plant's name, never a photo.> - OpenRouter is used with **free models only**, and free models may use what they receive for training.>> **Disclaimer:** informational only — not a substitute for a dietitian. Always check the printed label if you have an allergy.
---
## 🏋️ Pretrained weights
| | ||---|---|| Architecture | ResNet-101 encoder → 14×14×2048 features; additive soft attention with sigmoid gate; LSTMCell decoder (attention/embed/decoder dim 512) || Training data | MS-COCO 2014, Karpathy split, 5 captions/image, min word freq 5 (vocabulary 9,490) || Checkpoint | `BEST_checkpoint_coco_5_cap_per_img_5_min_word_freq.pth.tar`, epoch 18, validation BLEU-4 0.2429 || Reported test BLEU-4 | ≈ 0.33 at beam size 3 (not re-measured here) |
`model/captioning/sat_models.py` defines the network. Its local changes are marked `LOCAL CHANGE`:- `resnet101(weights=None)`, so nothing downloads- an MPS-aware `device`- a CPU fallback for the 14×14 adaptive pool on Apple MPS
> **History:** this project originally trained its own Show-Attend-Tell model on Flickr8k. That model was replaced on 2026-11-12. Its local "test" split overlapped the images it was trained on, so its reported BLEU-4 of 0.485 wasn't reproducible. The old code is backed up in `../archive/flickr8k_legacy.zip` (git-ignored).
---
### CATR and BLIP weights
- **CATR**: model code in `model/captioning/catr/`, weights `weight493084032.pth` (v3). Local changes, marked `LOCAL CHANGE`: `weights=None` for the backbone (no ImageNet download), and the device is chosen by the service. The service encodes each image once and decodes incrementally; on our tests its greedy output was identical to the reference implementation.- **BLIP**: loaded through Hugging Face `transformers` (about 1 GB in the HF cache). The deploy script downloads it once during setup, so the first caption request is fast.
---
### Data licences
- Indian Medicine Dataset: MIT (as provided with the file).- `data/medicines/uses_by_ingredient.json`: CC BY-SA 4.0; credited in the app wherever the descriptions appear and on the About page.- Open Food Facts additives taxonomy (`data/product_label/additives.json`): ODbL.- OCR models (`weights/ocr/`, downloaded by `scripts/setup_ocr_models.py`): Apache-2.0.
## 🧩 LicenseThis project is licensed under the [MIT License](LICENSE)12345678910111213141516171819"""Entrypoint for Hugging Face Spaces Gradio deployment."""from __future__ import annotations
import sysfrom pathlib import Path
# Add backend directory to sys.path so app and model packages resolve cleanlyROOT_DIR = Path(__file__).resolve().parentBACKEND_DIR = ROOT_DIR / "backend"
if str(BACKEND_DIR) not in sys.path: sys.path.insert(0, str(BACKEND_DIR))
from backend.app_gradio import demo
if __name__ == "__main__": demo.launch(server_name="0.0.0.0", server_port=7860)1234567venv/.env**/__pycache__/data/cache/data/eval/data/medicines/250k_raw/weights/ocr/123456789101112131415161718192021# Copy to `.env` (never commit real keys). Read at API start-up.
# --- AI (text only): one free OpenRouter model, Groq as the single backup (ADR-005) ---# OpenRouter key from openrouter.ai/keys. Only a model id ending in ":free" is ever used.OPENROUTER_API_KEY=OPENROUTER_MODEL=nvidia/nemotron-3-ultra-550b-a55b:free# Backup when OpenRouter is busy or fails.GROQ_API_KEY=GROQ_MODEL=qwen/qwen3.8-27b# Without any key the app still reads photos: prescriptions show the medicine names matched from the text# ("AI busy: details not extracted"), food labels use the parser only.
# --- Plant identification: PlantNet API key from my.plantnet.org (free tier: 500 identifications/day) ---# Photos are sent to PlantNet (Pl@ntNet, France) for identification.PLANTNET_API_KEY=
# --- OCR (RapidOCR, models in weights/ocr/ from scripts/setup_ocr_models.py) ---# Model set: v6-small (default) | v6-medium | v5-mobile | v5-server. See project_review/ADR-005.# OCR_MODELS=v6-small# Devanagari (Hindi) second reading for prescriptions: 1 (default) | 0# OCR_HINDI=112345678910111213141516171819202122# Backend image (Linux). OCR models are downloaded and checksum-verified at BUILD time by# scripts/setup_ocr_models.py, never at request time. On Linux requirements.txt installs the headless OpenCV# (no GUI libraries needed), which is also what rapidocr expects.# docker build -t vision-ai-backend backend/# docker run -p 8000:8000 --env-file backend/.env vision-ai-backendFROM python:3.14-slim
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 PIP_NO_CACHE_DIR=1# onnxruntime needs the OpenMP runtimeRUN apt-get update && apt-get install -y --no-install-recommends libgomp1 && rm -rf /var/lib/apt/lists/*
WORKDIR /appCOPY requirements.txt requirements-ocr.txt ./# CPU-only PyTorch wheels keep the image small; captioning runs on CPU in the container.RUN pip install --extra-index-url https://download.pytorch.org/whl/cpu -r requirements.txt \ && pip install --no-deps -r requirements-ocr.txt
COPY . .RUN python scripts/setup_ocr_models.py
EXPOSE 8000CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354"""Central configuration. Every value can be overridden with an env var.Loads configuration from .env.It contains things like:- File paths- Maximum upload size- Allowed image types- CORS settings"""import osfrom dataclasses import dataclassfrom pathlib import Path
# backend/app/config.py -> parents[0]=app, [1]=backendBACKEND_ROOT = Path(__file__).resolve().parents[1]
# Load backend/.env before Settings reads the environment. Optional: the API# still works without python-dotenv, it just ignores the .env file.try: from dotenv import load_dotenv
load_dotenv(BACKEND_ROOT / ".env")except ImportError: # pragma: no cover - python-dotenv is optional pass
@dataclass(frozen=True)class Settings: # Captioning settings (weights path, beam size, ...) live in the # `inference:` section of this YAML file; see app/services/caption_service.py. config_path: Path = Path( os.getenv("CONFIG_PATH", str(BACKEND_ROOT / "configs.yaml")) )
# Optional: serve the built React app from FastAPI (frontend/dist). frontend_dist: Path = Path( os.getenv("FRONTEND_DIST", str(BACKEND_ROOT.parent / "frontend" / "dist")) )
max_upload_mb: int = int(os.getenv("MAX_UPLOAD_MB", "10")) allowed_types: tuple = ("image/jpeg", "image/png", "image/webp")
# Prescriptions and food labels: OCR models (weights/ocr/, see scripts/setup_ocr_models.py) and the AI # (OPENROUTER_API_KEY / OPENROUTER_MODEL, backup GROQ_API_KEY / GROQ_MODEL) are read by # model/common/ocr.py and model/common/llm.py directly from the environment. cors_origins: tuple = tuple( o.strip() for o in os.getenv( "CORS_ORIGINS", "http://localhost:5173,http://127.0.0.1:5173" ).split(",") if o.strip() )
settings = Settings()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253"""Shared FastAPI dependencies (image upload validation).Common image validation.
read_image():- Checks image type- Checks file size- Reads image safely- Fixes EXIF orientation- Converts image to RGB- Creates SHA-256 hash"""import hashlibimport io
from fastapi import HTTPException, UploadFilefrom PIL import Image, ImageOps, UnidentifiedImageError
from .config import settings
# Large enough for PrescriptionReader OCR (it works at ~1200 px); captioning uses 256 px.MAX_DECODE_SIDE = 2048
def read_image(file: UploadFile) -> Image.Image: """Validate an uploaded image and return an EXIF-corrected RGB PIL image.""" if file.content_type not in settings.allowed_types: raise HTTPException( status_code=415, detail=f"Unsupported image type '{file.content_type}'. " f"Allowed: {', '.join(settings.allowed_types)}.", )
max_bytes = settings.max_upload_mb * 1024 * 1024 data = file.file.read(max_bytes + 1) if len(data) > max_bytes: raise HTTPException( status_code=413, detail=f"Image is larger than the {settings.max_upload_mb} MB limit.", )
try: image = Image.open(io.BytesIO(data)) # JPEG only: decode directly at 1/2, 1/4 or 1/8 scale while keeping both sides # >= MAX_DECODE_SIDE. Huge camera photos then decode in a fraction of the time. image.draft("RGB", (MAX_DECODE_SIDE, MAX_DECODE_SIDE)) image = ImageOps.exif_transpose(image).convert("RGB") except (UnidentifiedImageError, OSError, Image.DecompressionBombError): raise HTTPException(status_code=400, detail="Could not decode the uploaded image.")
# Key for the in-memory reader cache: the same photo uploaded again is never re-sent to Groq. image.info["upload_sha256"] = hashlib.sha256(data).hexdigest()
return image1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253"""FastAPI application entry point."""import loggingfrom contextlib import asynccontextmanager
from fastapi import FastAPIfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.staticfiles import StaticFiles
from .config import settingsfrom .routes import caption, health, plant, prescription, product_labelfrom .services.caption_service import CaptionServicefrom .services.plant_service import PlantServicefrom .services.prescription_service import PrescriptionServicefrom .services.product_label_service import ProductLabelService
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
@asynccontextmanagerasync def lifespan(app: FastAPI): app.state.caption_service = CaptionService() app.state.prescription_service = PrescriptionService() app.state.product_label_service = ProductLabelService() app.state.plant_service = PlantService() yield
app = FastAPI( title="Image Captioning API", version="1.0.0", description="Show, Attend and Tell captioning (pretrained ResNet-101 / COCO 2014 weights), prescription reader, food labels and plant identification (PlantNet).", lifespan=lifespan,)
app.add_middleware( CORSMiddleware, allow_origins=list(settings.cors_origins), allow_credentials=True, allow_methods=["GET", "POST"], allow_headers=["*"],)
app.include_router(health.router)app.include_router(health.root_router) # GET /health aliasapp.include_router(caption.router)app.include_router(prescription.router)app.include_router(product_label.router)app.include_router(plant.router)
# Serve the built React app if `frontend/dist` exists (production mode).if settings.frontend_dist.is_dir(): app.mount("/", StaticFiles(directory=settings.frontend_dist, html=True), name="frontend")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748"""Caption endpoint: upload an image, get a caption plus per-word attention maps."""import loggingimport time
from fastapi import APIRouter, Depends, HTTPException, Query, Requestfrom PIL import Image
from ..dependencies import read_imagefrom ..schemas import CaptionResponse
router = APIRouter(prefix="/api", tags=["caption"])log = logging.getLogger("backend.caption")
@router.post("/caption", response_model=CaptionResponse)def create_caption( request: Request, image: Image.Image = Depends(read_image), max_len: int | None = Query(None, ge=1, le=60, description="Maximum caption length in words"), beam_size: int | None = Query( None, ge=1, le=10, description="Beam search width (default from configs.yaml inference.beam_size)", ), model: str | None = Query( None, pattern="^(sat|catr|blip)$", description="sat = Show-Attend-Tell, catr = CATR transformer, blip = BLIP-base. " "Default: configs.yaml inference.model", ),) -> CaptionResponse: service = request.app.state.caption_service try: engine = service.get(model) except Exception: log.exception("Could not load caption model %s", model) raise HTTPException(status_code=503, detail="Caption model could not be loaded.") if not engine.ready: log.error("Caption model %s unavailable: %s", engine.name, engine.error) raise HTTPException(status_code=503, detail=f"Caption model '{engine.name}' is not available.")
started = time.perf_counter() try: result = service.caption(image, beam_size=beam_size, max_len=max_len, model=model) except Exception: log.exception("Caption generation failed") raise HTTPException(status_code=500, detail="Caption generation failed.")
elapsed_ms = round((time.perf_counter() - started) * 1000) return CaptionResponse(mode="caption", inference_ms=elapsed_ms, **result)12345678910111213141516171819202122232425262728293031323334353637383940"""Health / readiness endpoint."""from fastapi import APIRouter, Request
from ..schemas import HealthResponsefrom model.common.llm import default_llmfrom ..services.caption_service import LABELS
router = APIRouter(prefix="/api", tags=["health"])
@router.get("/health", response_model=HealthResponse)def health(request: Request) -> HealthResponse: service = request.app.state.caption_service prescription = getattr(request.app.state, "prescription_service", None) return HealthResponse( status="ok" if service.ready else "degraded", device=str(service.device), vocab_size=service.vocab_size, checkpoint=str(service.checkpoint_path), caption_model=service.default_model, caption_models=service.status(), caption_model_labels=LABELS, modes={ "caption": "ready" if service.ready else "unavailable", "prescription": prescription.status if prescription else "unavailable", "medicine_db": getattr(prescription, "medicine_db", "unavailable"), "product_label": getattr(getattr(request.app.state, "product_label_service", None), "status", "unavailable"), "plant": getattr(getattr(request.app.state, "plant_service", None), "status", "unavailable"), }, ai={"providers": default_llm().describe()}, # provider order and models (never keys) )
# Alias without the /api prefix: some tools (and the reference app) poll GET /health.root_router = APIRouter(tags=["health"])
@root_router.get("/health", response_model=HealthResponse, include_in_schema=False)def health_alias(request: Request) -> HealthResponse: return health(request)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354"""Plant identification endpoint.
POST /api/plant/identify 1-5 photos of the same plant (+ organ) -> PlantNet candidates and guide contextPOST /api/plant/uses {scientific_name, common_names, lang} -> medicinal uses written by the AI (name only, no photo), in English, Hindi (hi) or Kannada (kn)"""import loggingfrom typing import List
from fastapi import APIRouter, File, Form, HTTPException, Request, UploadFile
from ..dependencies import read_imagefrom ..schemas.plant import PlantResult, PlantUsesRequest, PlantUsesResponsefrom model.plant.identify import MAX_IMAGES, ORGANS, PlantNetError
router = APIRouter(prefix="/api/plant", tags=["plant"])log = logging.getLogger("backend.plant")
@router.post("/identify", response_model=PlantResult)def identify(request: Request, images: List[UploadFile] = File(..., description=f"1-{MAX_IMAGES} photos of the same plant"), organ: str = Form("auto", description=f"What the photos show: {', '.join(ORGANS)}")) -> PlantResult: if organ not in ORGANS: raise HTTPException(status_code=422, detail=f"organ must be one of: {', '.join(ORGANS)}.") if len(images) > MAX_IMAGES: raise HTTPException(status_code=422, detail=f"Send at most {MAX_IMAGES} photos of the same plant.") service = request.app.state.plant_service if not service.ready: raise HTTPException(status_code=503, detail="Plant identification isn't set up (PLANTNET_API_KEY missing).") pils = [read_image(f) for f in images] try: return service.identify(pils, organ) except PlantNetError as exc: log.warning("PlantNet failed: %s", exc) if exc.status == 429: raise HTTPException(status_code=429, detail="PlantNet's daily limit is reached. Try again tomorrow.") if exc.status in (401, 403): raise HTTPException(status_code=502, detail="PlantNet rejected the API key.") raise HTTPException(status_code=502, detail="PlantNet couldn't be reached. Please try again.") except Exception: log.exception("Plant identification failed") raise HTTPException(status_code=500, detail="Plant identification failed.")
@router.post("/uses", response_model=PlantUsesResponse)def uses(body: PlantUsesRequest, request: Request) -> PlantUsesResponse: try: return request.app.state.plant_service.medicinal_uses(body.scientific_name, body.common_names, body.lang) except ValueError as exc: raise HTTPException(status_code=422, detail=str(exc)) except Exception: log.exception("Plant uses failed") raise HTTPException(status_code=500, detail="Medicinal uses couldn't be loaded.")12345678910111213141516171819202122232425"""Prescription endpoint: read a photo."""import loggingfrom fastapi import APIRouter, Depends, HTTPException, Requestfrom PIL import Image
from ..dependencies import read_imagefrom ..schemas.prescription import PrescriptionResult
router = APIRouter(prefix="/api", tags=["prescription"])log = logging.getLogger("backend.prescription")
@router.post("/prescription", response_model=PrescriptionResult)def analyze_prescription(request: Request, image: Image.Image = Depends(read_image)) -> PrescriptionResult: service = request.app.state.prescription_service if not service.ready: log.error("Prescription reader unavailable: %s", service.error) raise HTTPException(status_code=503, detail="The prescription reader is not available right now. " "Check the server logs (OCR models installed?).") try: return service.analyze(image) except Exception: log.exception("Prescription analysis failed") # details only in the server log raise HTTPException(status_code=500, detail="Prescription analysis failed.")
123456789101112131415161718192021222324252627282930313233343536373839404142434445"""Food label endpoints.
POST /api/product-label/interpret label photo (+ optional product_name) -> result (no AI for values that were read)GET /api/product-label/{session_id}/explanation explanation, fetched after the results"""import logging
from typing import Optional
from fastapi import APIRouter, File, Form, HTTPException, Request, UploadFile
from ..dependencies import read_imagefrom ..schemas.product_label import ExplanationResponse, ProductLabelResult
router = APIRouter(prefix="/api/product-label", tags=["product-label"])log = logging.getLogger("backend.product_label")
@router.post("/interpret", response_model=ProductLabelResult)def interpret(request: Request, image: UploadFile = File(..., description="Label photo (ingredients + nutrition table)"), product_name: Optional[str] = Form(None, description="Optional product name typed by the user") ) -> ProductLabelResult: pil = read_image(image) service = request.app.state.product_label_service if not service.ready: raise HTTPException(status_code=503, detail="The label reader is not available right now (OCR models installed?).") try: return service.interpret(pil, product_name) except Exception: log.exception("Product label interpretation failed") raise HTTPException(status_code=500, detail="Product label interpretation failed.")
@router.get("/{session_id}/explanation", response_model=ExplanationResponse)def explanation(session_id: str, request: Request) -> ExplanationResponse: try: r = request.app.state.product_label_service.explanation(session_id) except KeyError: raise HTTPException(status_code=404, detail="Session not found or expired. Check the label again.") except Exception: log.exception("Product label explanation failed") raise HTTPException(status_code=500, detail="Explanation failed.") return ExplanationResponse(session_id=session_id, status=r["explanation_status"], explanation=r["explanation"], source=r["explanation_source"], note=r.get("explanation_note"))
1234567891011121314151617181920212223242526272829"""API response models: health and captioning here; prescription.py and product_label.py re-export the feature models."""from typing import Any, Dict, List
from pydantic import BaseModel
class HealthResponse(BaseModel): status: str device: str vocab_size: int checkpoint: str modes: Dict[str, str] caption_model: str = "sat" # default captioning model caption_models: Dict[str, str] = {} # name -> ready | unavailable | not_loaded caption_model_labels: Dict[str, str] = {} ai: Dict[str, Any] = {} # AI providers and models in order (no keys)
class CaptionResponse(BaseModel): mode: str = "caption" caption: str inference_ms: int # wall-clock time of the whole request handler model: str = "sat" # which captioning model produced this caption # Attention: one grid_shape[0] x grid_shape[1] map per word, scaled 0-1. words: List[str] = [] alphas: List[List[List[float]]] = [] grid_size: int = 0 # rows (kept for older clients; maps may be non-square, see grid_shape) grid_shape: List[int] = [0, 0] generation_time_ms: float = 0.0 # preprocessing + encoder + decoding123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657"""API models for plant identification."""from typing import Dict, List, Optional
from pydantic import BaseModel
class PlantCandidate(BaseModel): scientific_name: str author: str = "" common_names: List[str] = [] family: str = "" genus: str = "" score: float # PlantNet confidence 0-1
class PlantGuide(BaseModel): in_guide: bool # True only for the few plants in the app's local guide common_name: str use: str safety: str translations: Dict[str, Dict[str, str]] = {} # "hi"/"kn" -> {common_name, use, safety}, hand-written
class PlantResult(BaseModel): status: str # ok | no_match organ: str images: int best: Optional[PlantCandidate] = None candidates: List[PlantCandidate] = [] low_confidence: bool = True # best score below 60 % guide: Optional[PlantGuide] = None
class PlantUsesRequest(BaseModel): scientific_name: str common_names: List[str] = [] lang: str = "en" # en | hi | kn
class PlantUse(BaseModel): use: str detail: str = "" evidence: str = "traditional" # traditional | limited | moderate
class PlantUsesResponse(BaseModel): status: str # ok | busy (AI limit or error) | unavailable (no AI key) scientific_name: str known_medicinal: bool = False summary: str = "" uses: List[PlantUse] = [] parts_used: List[str] = [] safety: List[str] = [] toxic: bool = False source: Optional[dict] = None # {"provider", "model"} that wrote it lang: str = "en" # language of the text; "en" when a translation wasn't available local_name: str = "" # the plant's name in that language (translations only)123456789101112131415"""API response models for the perception/prescription feature.
Kept separate from ``app/schemas/__init__.py`` so the captioning schemas stayuntouched. The canonical models live in ``model.prescription.schemas``."""import sys
from ..config import BACKEND_ROOT
if str(BACKEND_ROOT) not in sys.path: sys.path.insert(0, str(BACKEND_ROOT))
from model.prescription.schemas import MedicineItem, OcrLine, PrescriptionResult # noqa: E402
__all__ = ["MedicineItem", "OcrLine", "PrescriptionResult"]1234567891011"""API models for the Product Label Interpreter (canonical models in model.product_label.schemas)."""import sys
from ..config import BACKEND_ROOT
if str(BACKEND_ROOT) not in sys.path: sys.path.insert(0, str(BACKEND_ROOT))
from model.product_label.schemas import ExplanationResponse, ProductLabelResult # noqa: E402
__all__ = ["ExplanationResponse", "ProductLabelResult"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105"""CaptionService: one entry point for all captioning models.
sat Show, Attend and Tell, ResNet-101 + LSTM, COCO 2014 -> 14x14 attention catr CATR, ResNet-101 + transformer, COCO 2017 -> H x W attention blip BLIP-base, ViT-B/16 + text decoder, COCO fine-tuned -> 24x24 attention
`configs.yaml` -> `inference.model` picks the default (loaded at startup);the others load on first use (``?model=`` on the API). Every model returns thesame shape: caption, words, one attention map per word (0-1), grid_shape."""from __future__ import annotations
import loggingimport threading
import yamlfrom PIL import Image
from ..config import settingsfrom .captioners.blip import BLIPCaptionerfrom .captioners.catr import CATRCaptionerfrom .captioners.sat import SATCaptioner
log = logging.getLogger("backend.caption")
ENGINES = {"sat": SATCaptioner, "catr": CATRCaptioner, "blip": BLIPCaptioner}LABELS = {name: cls.label for name, cls in ENGINES.items()}
def load_inference_cfg() -> dict: try: with open(settings.config_path, "r") as f: return (yaml.safe_load(f) or {}).get("inference", {}) or {} except FileNotFoundError: return {}
class CaptionService: def __init__(self) -> None: self.cfg = load_inference_cfg() default = str(self.cfg.get("model", "sat")).lower() self.default_model = default if default in ENGINES else "sat" self._engines: dict = {} self._lock = threading.Lock() self.get(self.default_model)
# --- engine registry ------------------------------------------------ def get(self, name: str | None = None): name = (name or self.default_model).lower() if name not in ENGINES: raise KeyError(name) engine = self._engines.get(name) if engine is None: with self._lock: engine = self._engines.get(name) if engine is None: log.info("Loading caption model '%s'", name) engine = ENGINES[name](self.cfg) self._engines[name] = engine return engine
def status(self) -> dict: """name -> ready | unavailable | not_loaded.""" out = {} for name in ENGINES: engine = self._engines.get(name) out[name] = "not_loaded" if engine is None else ("ready" if engine.ready else "unavailable") return out
# --- attributes the health route reads (from the default model) ------- @property def _default(self): return self._engines[self.default_model]
@property def ready(self) -> bool: return self._default.ready
@property def error(self): return self._default.error
@property def device(self): return self._default.device
@property def vocab_size(self) -> int: return self._default.vocab_size
@property def checkpoint_path(self): return self._default.checkpoint_path
# --- inference ---------------------------------------------------------- def caption(self, image: Image.Image, beam_size: int | None = None, max_len: int | None = None, model: str | None = None) -> dict: engine = self.get(model) if not engine.ready: raise RuntimeError(engine.error or f"Caption model '{engine.name}' is not available.") return engine.caption(image, beam_size=beam_size, max_len=max_len)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127"""BLIPCaptioner: BLIP image captioning, base model.
ViT-B/16 image encoder + BERT-style text decoder with cross-attention,fine-tuned for captioning on COCO.
Per request: 1. BlipProcessor: resize to 384 x 384, CLIP-style normalisation. 2. model.generate with beam search and repeat blocking. 3. One extra text-decoder pass on the final caption with output_attentions=True: cross-attention of each token over the 24 x 24 image patches (mean over heads and layers; the [CLS] image token is dropped)."""from __future__ import annotations
import loggingimport mathimport threadingimport time
import numpy as npimport torchfrom PIL import Image
from .common import merge_wordpieces, normalise_map, select_device
log = logging.getLogger("backend.caption.blip")
class BLIPCaptioner: name = "blip" label = "BLIP-base (ViT-B/16 + text decoder, COCO fine-tuned)"
def __init__(self, cfg: dict) -> None: own = cfg.get("blip") or {} self.model_id = own.get("model_id", "Salesforce/blip-image-captioning-base") self.checkpoint_path = f"huggingface:{self.model_id}" self.default_beam_size = int(own.get("beam_size", cfg.get("beam_size", 3))) self.max_caption_len = int(own.get("max_caption_len", min(int(cfg.get("max_caption_len", 30)), 40))) self.no_repeat_ngram = int(own.get("no_repeat_ngram", cfg.get("no_repeat_ngram", 2))) self.repetition_penalty = float(own.get("repetition_penalty", 1.0))
self.device = select_device() self.lock = threading.Lock() self.ready = False self.error: str | None = None self.vocab_size = 0 self.model = None self.processor = None self._load()
def _load(self) -> None: try: from transformers import BlipForConditionalGeneration, BlipProcessor
try: # use the local cache without a network round-trip when possible processor = BlipProcessor.from_pretrained(self.model_id, local_files_only=True) model = BlipForConditionalGeneration.from_pretrained(self.model_id, local_files_only=True) except OSError: log.info("Downloading %s (~1 GB, first run only)", self.model_id) processor = BlipProcessor.from_pretrained(self.model_id) model = BlipForConditionalGeneration.from_pretrained(self.model_id) self.processor = processor self.model = model.to(self.device).eval() self.vocab_size = processor.tokenizer.vocab_size self.ready = True self.caption(Image.new("RGB", (384, 384), (128, 128, 128)), max_len=8) # warm-up log.info("BLIP loaded on %s", self.device) except Exception as exc: self.ready = False self.error = f"Failed to load BLIP: {exc}" log.exception(self.error)
@torch.no_grad() def caption(self, image: Image.Image, beam_size: int | None = None, max_len: int | None = None) -> dict: if not self.ready: raise RuntimeError(self.error or "BLIP is not loaded.") started = time.perf_counter() beam = int(beam_size or self.default_beam_size) limit = int(max_len or self.max_caption_len) tok = self.processor.tokenizer with self.lock: inputs = self.processor(images=image.convert("RGB"), return_tensors="pt").to(self.device) out = self.model.generate(**inputs, num_beams=beam, max_new_tokens=limit, no_repeat_ngram_size=self.no_repeat_ngram or 0, repetition_penalty=self.repetition_penalty) seq = out[0] special = set(tok.all_special_ids) # Skip special tokens, including BLIP's decoder-start token, which # is outside the tokenizer vocabulary (it maps to None). pieces_all = tok.convert_ids_to_tokens(seq.tolist()) keep_pos = [i for i, (t, p) in enumerate(zip(seq.tolist(), pieces_all)) if i > 0 and t not in special and p is not None] ids = [int(seq[i]) for i in keep_pos] maps: list[np.ndarray] = [] side = 0 if ids: image_embeds = self.model.vision_model(pixel_values=inputs["pixel_values"])[0] dec = self.model.text_decoder( input_ids=seq.unsqueeze(0), attention_mask=torch.ones_like(seq).unsqueeze(0), encoder_hidden_states=image_embeds, output_attentions=True, return_dict=True, ) cross = torch.stack(list(dec.cross_attentions)) # (layers, 1, heads, T, 1+P) att = cross.mean(dim=(0, 2))[0][:, 1:] # (T, P), drop the [CLS] image token # ViT "attention sinks": a few patches take most of the attention for # EVERY token, so raw maps all peak at the same spot. Keep only what is # specific to each word: its attention above the caption's average. att = (att - att[keep_pos].mean(0, keepdim=True) if keep_pos else att).clamp(min=0) side = int(math.isqrt(att.shape[-1])) # the token at position i was predicted from position i-1 maps = [att[i - 1].reshape(side, side).float().cpu().numpy() for i in keep_pos] words, word_maps = merge_wordpieces(tok.convert_ids_to_tokens(ids), maps) keep = [i for i, wd in enumerate(words) if any(ch.isalnum() for ch in wd)] words = [words[i] for i in keep] return { "caption": " ".join(words), "words": words, "alphas": [normalise_map(word_maps[i]) for i in keep], "grid_size": side, "grid_shape": [side, side], "generation_time_ms": round((time.perf_counter() - started) * 1000, 1), "model": self.name, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207"""CATRCaptioner: CAption TRansformer.
ResNet-101 (dilated, stride 16) + 6-layer transformer encoder/decoder,BERT word-piece vocabulary, trained on COCO 2017.Model code: model/captioning/catr/. Weights: weights/catr_v3_coco.pth.
Per request: 1. Resize so the longest side is 299 px (keeps aspect ratio), normalise to [-1, 1]. 2. Backbone + transformer encoder run ONCE -> memory over an H x W grid. 3. Beam search over the decoder (the reference greedy path re-runs the whole network every step; this gives the same greedy result much faster). 4. One extra decoder pass on the final caption with hooks on every decoder layer's cross-attention -> one H x W map per word (mean over heads/layers)."""from __future__ import annotations
import loggingimport sysimport threadingimport timefrom pathlib import Path
import numpy as npimport torchimport torch.nn.functional as Ffrom PIL import Image
from ...config import BACKEND_ROOTfrom .common import block_repeated_ngrams, merge_wordpieces, normalise_map, select_device
if str(BACKEND_ROOT) not in sys.path: sys.path.insert(0, str(BACKEND_ROOT))
from model.captioning.catr import caption as catr_caption # noqa: E402from model.captioning.catr.configuration import Config as CATRConfig # noqa: E402from model.captioning.catr.transformer import generate_square_subsequent_mask # noqa: E402from model.captioning.catr.utils import nested_tensor_from_tensor_list # noqa: E402
log = logging.getLogger("backend.caption.catr")
class CATRCaptioner: name = "catr" label = "CATR (ResNet-101 + Transformer, COCO 2017)"
def __init__(self, cfg: dict) -> None: own = cfg.get("catr") or {} weights = Path(own.get("weights", "weights/catr_v3_coco.pth")) tok_dir = Path(own.get("tokenizer", "weights/catr_tokenizer")) self.checkpoint_path = weights if weights.is_absolute() else BACKEND_ROOT / weights self.tokenizer_dir = tok_dir if tok_dir.is_absolute() else BACKEND_ROOT / tok_dir self.max_side = int(own.get("max_image_side", 299)) self.default_beam_size = int(own.get("beam_size", cfg.get("beam_size", 3))) self.max_caption_len = int(own.get("max_caption_len", cfg.get("max_caption_len", 50))) self.no_repeat_ngram = int(own.get("no_repeat_ngram", cfg.get("no_repeat_ngram", 2))) self.length_alpha = float(own.get("length_alpha", 0.7))
self.device = select_device() self.lock = threading.Lock() self.ready = False self.error: str | None = None self.vocab_size = 0 self.model = None self.tokenizer = None self._load()
# ------------------------------------------------------------------ def _load(self) -> None: if not self.checkpoint_path.exists(): self.error = (f"CATR weights not found: {self.checkpoint_path}. Download " "https://github.com/saahiluppal/catr/releases/download/0.2/weight493084032.pth") log.warning(self.error) return try: from transformers import BertTokenizer
model, _ = catr_caption.build_model(CATRConfig()) ckpt = torch.load(self.checkpoint_path, map_location="cpu", weights_only=True) model.load_state_dict(ckpt["model"] if "model" in ckpt else ckpt, strict=True) if self.tokenizer_dir.exists(): tokenizer = BertTokenizer.from_pretrained(str(self.tokenizer_dir)) else: # first run: fetch bert-base-uncased vocab (~230 KB) and keep a local copy tokenizer = BertTokenizer.from_pretrained("bert-base-uncased") tokenizer.save_pretrained(str(self.tokenizer_dir)) self.model = model.to(self.device).eval() self.tokenizer = tokenizer self.vocab_size = tokenizer.vocab_size self.ready = True self.caption(Image.new("RGB", (self.max_side, self.max_side), (128, 128, 128)), beam_size=self.default_beam_size, max_len=8) # warm-up log.info("CATR loaded on %s", self.device) except Exception as exc: self.ready = False self.error = f"Failed to load CATR: {exc}" log.exception(self.error)
# ------------------------------------------------------------------ def _preprocess(self, image: Image.Image) -> torch.Tensor: img = image.convert("RGB") w, h = img.size scale = self.max_side / max(w, h) img = img.resize((max(1, int(w * scale)), max(1, int(h * scale))), Image.BICUBIC, reducing_gap=3.0) arr = (np.asarray(img, dtype=np.float32) / 255.0 - 0.5) / 0.5 return torch.from_numpy(arr).permute(2, 0, 1).to(self.device)
def _encode(self, x: torch.Tensor): model = self.model samples = nested_tensor_from_tensor_list([x]) feats, pos = model.backbone(samples) src, mask = feats[-1].decompose() src = model.input_proj(src) h, w = src.shape[-2:] src = src.flatten(2).permute(2, 0, 1) pos = pos[-1].flatten(2).permute(2, 0, 1) mask = mask.flatten(1) memory = model.transformer.encoder(src, src_key_padding_mask=mask, pos=pos) return memory, mask, pos, (int(h), int(w))
def _decode(self, memory, mask, pos, tokens: torch.Tensor) -> torch.Tensor: """tokens (n, t) -> decoder output (t, n, C).""" T = self.model.transformer n, t = tokens.shape tgt = T.embeddings(tokens).permute(1, 0, 2) query = T.embeddings.position_embeddings.weight[:t].unsqueeze(1).repeat(1, n, 1) return T.decoder(tgt, memory.expand(-1, n, -1), memory_key_padding_mask=mask.expand(n, -1), pos=pos.expand(-1, n, -1), query_pos=query, tgt_mask=generate_square_subsequent_mask(t).to(tokens.device))
def _beam_search(self, memory, mask, pos, beam: int, max_len: int): tok = self.tokenizer cls_id, sep_id = tok.cls_token_id, tok.sep_token_id banned = [tok.pad_token_id, tok.unk_token_id, cls_id, tok.mask_token_id] seqs = [[cls_id]] scores = torch.zeros(1, device=self.device) done: list[tuple[float, list[int]]] = [] for _ in range(max_len): tokens = torch.tensor(seqs, device=self.device) hs = self._decode(memory, mask, pos, tokens) logp = F.log_softmax(self.model.mlp(hs[-1]), dim=-1) # (n, V) logp[:, banned] = float("-inf") block_repeated_ngrams(logp, seqs, self.no_repeat_ngram, skip=1) total = (scores[:, None] + logp).view(-1) top, idx = total.topk(min(beam, total.numel())) V = logp.shape[1] new_seqs, new_scores = [], [] for score, flat in zip(top.tolist(), idx.tolist()): parent, word = divmod(flat, V) seq = seqs[parent] + [word] if word == sep_id: length = len(seq) - 2 # without CLS / SEP done.append((score / max(length, 1) ** self.length_alpha, seq[1:-1])) else: new_seqs.append(seq) new_scores.append(score) if not new_seqs or len(done) >= beam: break seqs, scores = new_seqs, torch.tensor(new_scores, device=self.device) if not done: # length limit reached: take the best unfinished beam done = [(float(s) / max(len(q) - 1, 1) ** self.length_alpha, q[1:]) for s, q in zip(scores.tolist(), seqs)] return max(done, key=lambda d: d[0])[1]
def _attention(self, memory, mask, pos, ids: list[int], hw) -> list[np.ndarray]: """Cross-attention of each generated token over the H x W grid (mean of heads and layers).""" captured = [] hooks = [layer.multihead_attn.register_forward_hook(lambda m, i, o: captured.append(o[1])) for layer in self.model.transformer.decoder.layers] try: tokens = torch.tensor([[self.tokenizer.cls_token_id] + ids], device=self.device) self._decode(memory, mask, pos, tokens) finally: for hook in hooks: hook.remove() att = torch.stack([a[0] for a in captured if a is not None]).mean(0) # (t, S) h, w = hw # position i (input token i) predicts token i+1 -> rows 0..len(ids)-1 return [att[i].reshape(h, w).float().cpu().numpy() for i in range(len(ids))]
# ------------------------------------------------------------------ @torch.no_grad() def caption(self, image: Image.Image, beam_size: int | None = None, max_len: int | None = None) -> dict: if not self.ready: raise RuntimeError(self.error or "CATR is not loaded.") started = time.perf_counter() beam = int(beam_size or self.default_beam_size) limit = int(max_len or self.max_caption_len) with self.lock: memory, mask, pos, hw = self._encode(self._preprocess(image)) ids = self._beam_search(memory, mask, pos, beam, limit) maps = self._attention(memory, mask, pos, ids, hw) if ids else [] pieces = self.tokenizer.convert_ids_to_tokens(ids) words, word_maps = merge_wordpieces(pieces, maps) keep = [i for i, wd in enumerate(words) if any(ch.isalnum() for ch in wd)] words = [words[i] for i in keep] alphas = [normalise_map(word_maps[i]) for i in keep] return { "caption": " ".join(words), "words": words, "alphas": alphas, "grid_size": hw[0], "grid_shape": [hw[0], hw[1]], "generation_time_ms": round((time.perf_counter() - started) * 1000, 1), "model": self.name, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263"""Helpers shared by the captioning engines."""from __future__ import annotations
from typing import List, Sequence, Tuple
import numpy as npimport torch
def select_device() -> torch.device: """CUDA, then Apple MPS, then CPU.""" if torch.cuda.is_available(): return torch.device("cuda") mps = getattr(torch.backends, "mps", None) if mps is not None and mps.is_available(): return torch.device("mps") return torch.device("cpu")
def normalise_map(grid: np.ndarray) -> List[List[float]]: """Scale one attention map to 0-1 (max = 1) and round for JSON.""" grid = np.asarray(grid, dtype=np.float32) grid = grid / (grid.max() + 1e-8) return np.round(grid, 3).tolist()
def merge_wordpieces( pieces: Sequence[str], maps: Sequence[np.ndarray]) -> Tuple[List[str], List[np.ndarray]]: """Join BERT word-pieces ("fr", "##is", "##bee") into words.
The attention map of a merged word is the mean of its pieces' maps. """ words: List[str] = [] word_maps: List[List[np.ndarray]] = [] for piece, grid in zip(pieces, maps): if piece.startswith("##") and words: words[-1] += piece[2:] word_maps[-1].append(grid) else: words.append(piece) word_maps.append([grid]) return words, [np.mean(group, axis=0) for group in word_maps]
def block_repeated_ngrams(scores: torch.Tensor, seqs: List[List[int]], n: int, skip: int = 1) -> None: """Set -inf for every next token that would repeat an n-gram already in each sequence.
``skip`` leading tokens (e.g. the start token) are ignored. """ if n <= 0: return for i, seq in enumerate(seqs): if len(seq) - skip < n - 1: continue prefix = tuple(seq[len(seq) - n + 1:]) if n > 1 else () banned = { seq[j + n - 1] for j in range(skip, len(seq) - n + 1) if tuple(seq[j:j + n - 1]) == prefix } if banned: scores[i, list(banned)] = float("-inf")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276"""SATCaptioner: pretrained Show, Attend and Tell (ResNet-101, COCO 2014).
Model code : model/captioning/sat_models.pyWeights : weights/sat_resnet101_coco.pth (converted once by `python -m model.captioning.convert_checkpoint`)
Per request: 1. Resize to 256x256, ImageNet mean/std normalisation. 2. Encoder (ResNet-101 + adaptive pool) -> (1, 14, 14, 2048). 3. Beam search (default width 3) with the gated soft-attention LSTM decoder. 4. Return caption, words and one 14x14 attention map per word (scaled 0-1)."""from __future__ import annotations
import loggingimport sysimport threadingimport timefrom pathlib import Path
import numpy as npimport torchimport torch.nn.functional as Fimport yamlfrom PIL import Image
from ...config import BACKEND_ROOT, settings
if str(BACKEND_ROOT) not in sys.path: sys.path.insert(0, str(BACKEND_ROOT))
from model.captioning.sat_models import DecoderWithAttention, Encoder # noqa: E402
log = logging.getLogger("backend.caption")
IMAGENET_MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32)IMAGENET_STD = np.array([0.229, 0.224, 0.225], dtype=np.float32)SPECIAL_TOKENS = {"<start>", "<end>", "<pad>", "<unk>"}
def _select_device() -> torch.device: if torch.cuda.is_available(): return torch.device("cuda") mps = getattr(torch.backends, "mps", None) if mps is not None and mps.is_available(): return torch.device("mps") return torch.device("cpu")
def _load_inference_cfg() -> dict: try: with open(settings.config_path, "r") as f: return (yaml.safe_load(f) or {}).get("inference", {}) or {} except FileNotFoundError: return {}
class SATCaptioner: """Loads the converted COCO model once and serves beam-search captions."""
name = "sat" label = "Show, Attend and Tell (ResNet-101 + LSTM, COCO 2014)"
def __init__(self, cfg: dict | None = None) -> None: cfg = dict(cfg if cfg is not None else _load_inference_cfg()) cfg.update(cfg.get("sat") or {}) # model-specific keys override shared ones weights = Path(cfg.get("weights", "weights/sat_resnet101_coco.pth")) self.checkpoint_path = weights if weights.is_absolute() else BACKEND_ROOT / weights self.image_size = int(cfg.get("image_size", 256)) self.default_beam_size = int(cfg.get("beam_size", 5)) self.max_caption_len = int(cfg.get("max_caption_len", 50)) # Forbid repeating any word n-gram within a caption (0 = off). Stops loops # like "a dog sitting in the grass next to a dog". self.no_repeat_ngram = int(cfg.get("no_repeat_ngram", 2))
self.device = _select_device() self.lock = threading.Lock() self.ready = False self.error: str | None = None self.vocab_size = 0 self.meta: dict = {}
self.encoder: Encoder | None = None self.decoder: DecoderWithAttention | None = None self.word_map: dict[str, int] = {} self.rev_word_map: dict[int, str] = {}
self._load()
# ------------------------------------------------------------------ def _load(self) -> None: path = self.checkpoint_path if not path.exists(): self.error = (f"Weights not found: {path}. " "Run `python -m model.captioning.convert_checkpoint` from backend/.") log.warning(self.error) return try: ckpt = torch.load(path, map_location="cpu", weights_only=True) meta = ckpt.get("meta", {}) word_map = ckpt["word_map"]
encoder = Encoder(encoded_image_size=int(meta.get("encoded_image_size", 14))) decoder = DecoderWithAttention( attention_dim=int(meta.get("attention_dim", 512)), embed_dim=int(meta.get("embed_dim", 512)), decoder_dim=int(meta.get("decoder_dim", 512)), vocab_size=len(word_map), encoder_dim=int(meta.get("encoder_dim", 2048)), ) encoder.load_state_dict(ckpt["encoder_state"], strict=True) decoder.load_state_dict(ckpt["decoder_state"], strict=True)
self.encoder = encoder.to(self.device).eval() self.decoder = decoder.to(self.device).eval() self.word_map = word_map self.rev_word_map = {v: k for k, v in word_map.items()} self.vocab_size = len(word_map) self.meta = meta self.ready = True
# Warm-up pass so the first real request doesn't pay kernel setup. # Uses the default beam width: GPU (MPS/CUDA) kernels are shape-specific, # so a beam-1 warm-up does not warm the beam-3 path. started = time.perf_counter() noise = np.random.default_rng(0).integers(0, 256, (self.image_size, self.image_size, 3), dtype=np.uint8) self.caption(Image.fromarray(noise), beam_size=self.default_beam_size, max_len=12) log.info("Caption model warm-up done in %.0f ms", (time.perf_counter() - started) * 1000) log.info("SAT caption model loaded: vocab %d on %s (epoch %s, val BLEU-4 %s)", self.vocab_size, self.device, meta.get("epoch"), meta.get("val_bleu4")) except Exception as exc: self.error = f"Failed to load caption model: {exc}" log.exception(self.error)
# ------------------------------------------------------------------ def _preprocess(self, image: Image.Image) -> torch.Tensor: # reducing_gap: shrink in cheap integer steps first, then bicubic, so very large # photos (e.g. 14000x9000) resize in milliseconds instead of ~1.5 s. img = image.convert("RGB").resize((self.image_size, self.image_size), Image.BICUBIC, reducing_gap=3.0) arr = (np.asarray(img, dtype=np.float32) / 255.0 - IMAGENET_MEAN) / IMAGENET_STD return torch.from_numpy(arr).permute(2, 0, 1).unsqueeze(0).to(self.device)
@torch.no_grad() def caption(self, image: Image.Image, beam_size: int | None = None, max_len: int | None = None) -> dict: """Caption a PIL image. Returns caption, words, per-word alphas (0-1), timing.""" if not self.ready: raise RuntimeError(self.error or "Caption model is not loaded.")
started = time.perf_counter() beam = int(beam_size or self.default_beam_size) limit = int(max_len or self.max_caption_len) tensor = self._preprocess(image)
with self.lock: seq, alphas = self._beam_search(tensor, beam, limit)
words: list[str] = [] word_alphas: list[list[list[float]]] = [] for t in range(1, len(seq)): # index 0 is <start> word = self.rev_word_map.get(seq[t], "<unk>") if word in ("<end>", "<pad>"): break if word in SPECIAL_TOKENS: continue # drop <unk> (and any stray <start>) together with its map a = np.asarray(alphas[t], dtype=np.float32) a = a / (a.max() + 1e-8) words.append(word) word_alphas.append(np.round(a, 3).tolist())
return { "caption": " ".join(words), "words": words, "alphas": word_alphas, "grid_size": len(word_alphas[0]) if word_alphas else 0, "grid_shape": [len(word_alphas[0]), len(word_alphas[0][0])] if word_alphas else [0, 0], "model": self.name, "generation_time_ms": round((time.perf_counter() - started) * 1000, 1), }
# ------------------------------------------------------------------ @staticmethod def _block_repeated_ngrams(scores: torch.Tensor, seqs: list[list[int]], n: int) -> None: """Set -inf for every next token that would repeat an n-gram already in the beam.""" for i, seq in enumerate(seqs): prefix = tuple(seq[len(seq) - n + 1:]) # last n-1 tokens banned = { seq[j + n - 1] for j in range(1, len(seq) - n + 1) # skip <start> at index 0 if tuple(seq[j:j + n - 1]) == prefix } if banned: scores[i, list(banned)] = float("-inf")
def _beam_search(self, image: torch.Tensor, beam_size: int, max_len: int): """Keep the best partial captions at every decoding step.""" k = beam_size vocab_size = len(self.word_map) decoder = self.decoder start_idx, end_idx = self.word_map["<start>"], self.word_map["<end>"] unk_idx = self.word_map.get("<unk>") n = self.no_repeat_ngram
encoder_out = self.encoder(image) # (1, 14, 14, 2048) enc_size = encoder_out.size(1) encoder_dim = encoder_out.size(3) encoder_out = encoder_out.view(1, -1, encoder_dim) num_pixels = encoder_out.size(1) encoder_out = encoder_out.expand(k, num_pixels, encoder_dim)
k_prev_words = torch.full((k, 1), start_idx, dtype=torch.long, device=self.device) seqs = k_prev_words top_k_scores = torch.zeros(k, 1, device=self.device) seqs_alpha = torch.ones(k, 1, enc_size, enc_size, device=self.device)
complete_seqs, complete_alphas, complete_scores = [], [], [] h, c = decoder.init_hidden_state(encoder_out) step = 1
while True: embeddings = decoder.embedding(k_prev_words).squeeze(1) awe, alpha = decoder.attention(encoder_out, h) alpha = alpha.view(-1, enc_size, enc_size) gate = decoder.sigmoid(decoder.f_beta(h)) awe = gate * awe h, c = decoder.decode_step(torch.cat([embeddings, awe], dim=1), (h, c))
scores = F.log_softmax(decoder.fc(h), dim=1) if unk_idx is not None: scores[:, unk_idx] = float("-inf") # never emit <unk> if n > 0 and seqs.size(1) >= n: self._block_repeated_ngrams(scores, seqs.tolist(), n) scores = top_k_scores.expand_as(scores) + scores
if step == 1: top_k_scores, top_k_words = scores[0].topk(k, 0, True, True) else: top_k_scores, top_k_words = scores.view(-1).topk(k, 0, True, True)
prev_inds = torch.div(top_k_words, vocab_size, rounding_mode="floor") next_inds = top_k_words % vocab_size
seqs = torch.cat([seqs[prev_inds], next_inds.unsqueeze(1)], dim=1) seqs_alpha = torch.cat([seqs_alpha[prev_inds], alpha[prev_inds].unsqueeze(1)], dim=1)
incomplete = [i for i, w in enumerate(next_inds.tolist()) if w != end_idx] complete = [i for i in range(len(next_inds)) if i not in incomplete]
if complete: complete_seqs.extend(seqs[complete].tolist()) complete_alphas.extend(seqs_alpha[complete].tolist()) complete_scores.extend(top_k_scores[complete].tolist()) k -= len(complete)
if k == 0 or step >= max_len: break
seqs = seqs[incomplete] seqs_alpha = seqs_alpha[incomplete] h = h[prev_inds[incomplete]] c = c[prev_inds[incomplete]] encoder_out = encoder_out[prev_inds[incomplete]] top_k_scores = top_k_scores[incomplete].unsqueeze(1) k_prev_words = next_inds[incomplete].unsqueeze(1) step += 1
if not complete_seqs: # length limit reached before any beam produced <end> best = int(top_k_scores.view(-1).argmax()) return seqs[best].tolist(), seqs_alpha[best].tolist()
best = complete_scores.index(max(complete_scores)) return complete_seqs[best], complete_alphas[best]1234567891011121314151617181920212223242526272829303132"""PlantService: PlantNet identification (needs PLANTNET_API_KEY) and AI-written medicinal uses (model.plant.uses)."""from __future__ import annotations
import sysfrom typing import Any, Dict, Sequence
from ..config import BACKEND_ROOT
if str(BACKEND_ROOT) not in sys.path: sys.path.insert(0, str(BACKEND_ROOT))
from model.plant import identify as plant # noqa: E402from model.plant.uses import PlantUses # noqa: E402
class PlantService: def __init__(self, uses: PlantUses | None = None) -> None: self.uses = uses or PlantUses()
@property def ready(self) -> bool: return bool(plant.api_key())
@property def status(self) -> str: return "ready" if self.ready else "unavailable"
def identify(self, images: Sequence, organ: str) -> Dict[str, Any]: return plant.identify(images, organ)
def medicinal_uses(self, scientific_name: str, common_names: Sequence[str] = (), lang: str = "en") -> Dict[str, Any]: return self.uses.get(scientific_name, common_names, lang)1234567891011121314151617181920212223242526272829303132333435363738394041424344"""PrescriptionService: runs the prescription pipeline, one photo at a time."""from __future__ import annotations
import loggingimport sysimport threadingfrom typing import Optional
from PIL import Image
from ..config import BACKEND_ROOT
if str(BACKEND_ROOT) not in sys.path: sys.path.insert(0, str(BACKEND_ROOT))
from model.prescription.medicine_db import get_index # noqa: E402from model.prescription.pipeline import PrescriptionPipeline # noqa: E402from model.prescription.schemas import PrescriptionResult # noqa: E402
log = logging.getLogger("backend.prescription")
class PrescriptionService: def __init__(self, pipeline: Optional[PrescriptionPipeline] = None) -> None: index = get_index() # medicine dataset, loaded once (cached index, ~1 s) self.medicine_db = f"{len(index.rows)} medicines, {len(index.known)} known brands" if index else "unavailable" self.pipeline = pipeline or PrescriptionPipeline() self._run_lock = threading.Lock()
@property def ready(self) -> bool: return self.pipeline.ocr.available
@property def status(self) -> str: return "ready" if self.ready else "unavailable"
@property def error(self) -> Optional[str]: return self.pipeline.ocr.error
def analyze(self, image: Image.Image) -> PrescriptionResult: with self._run_lock: # one OCR run at a time return self.pipeline.run(image)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980"""ProductLabelService: runs the label pipeline and keeps each result for an hour (for the explanation)."""from __future__ import annotations
import loggingimport reimport sysimport threadingimport timefrom collections import OrderedDictfrom typing import Any, Dict, Optional
from ..config import BACKEND_ROOT
if str(BACKEND_ROOT) not in sys.path: sys.path.insert(0, str(BACKEND_ROOT))
from model.product_label.pipeline import ProductLabelPipeline # noqa: E402
log = logging.getLogger("backend.product_label")
SESSION_TTL_S = 3600MAX_SESSIONS = 200MAX_NAME_CHARS = 100
def clean_product_name(name: Optional[str]) -> Optional[str]: """The product name the user typed: control characters removed, spaces collapsed, at most 100 characters.""" value = re.sub(r"\s+", " ", re.sub(r"[\x00-\x1f\x7f]", " ", name or "")).strip()[:MAX_NAME_CHARS] return value or None
class ProductLabelService: def __init__(self, pipeline: Optional[ProductLabelPipeline] = None) -> None: self.pipeline = pipeline or ProductLabelPipeline() self._sessions: "OrderedDict[str, Dict[str, Any]]" = OrderedDict() self._lock = threading.Lock() self._run_lock = threading.Lock()
@property def ready(self) -> bool: return self.pipeline.ocr.available
@property def status(self) -> str: return "ready" if self.ready else "unavailable"
def interpret(self, image, product_name: Optional[str] = None) -> Dict[str, Any]: with self._run_lock: result = self.pipeline.run(image) # Typed by the user: a title for the result and context for the explanation. result["product_name"] = clean_product_name(product_name) if result["status"] == "ok": with self._lock: self._sessions[result["session_id"]] = {"created": time.time(), "result": result} self._prune() return result
def _get(self, session_id: str) -> Dict[str, Any]: with self._lock: self._prune() entry = self._sessions.get(session_id) if entry is None: raise KeyError(session_id) return entry
def explanation(self, session_id: str) -> Dict[str, Any]: entry = self._get(session_id) with self._lock: lock = entry.setdefault("explain_lock", threading.Lock()) with lock: # generated once per session self.pipeline.add_explanation(entry["result"]) return entry["result"]
def _prune(self) -> None: now = time.time() for sid in [s for s, e in self._sessions.items() if now - e["created"] > SESSION_TTL_S]: self._sessions.pop(sid, None) while len(self._sessions) > MAX_SESSIONS: self._sessions.popitem(last=False)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336"""Gradio app for Hugging Face Spaces deployment.
Wraps the existing FastAPI backend services into a Gradio interface,so the entire backend (captioning, prescription reader, product label,plant identification) runs as a single Hugging Face Space.
Launch: python app_gradio.pyOr via Spaces: set this as `app_file: app_gradio.py` in README.md metadata."""from __future__ import annotations
import jsonimport loggingimport osimport sysimport timefrom pathlib import Pathfrom typing import Optional
import gradio as grimport numpy as npimport torchfrom PIL import Image
# ZeroGPU support for Hugging Face Spaces free tiertry: import spacesexcept ImportError: class spaces: @staticmethod def GPU(fn=None, duration=None): if fn is None: return lambda f: f return fn
# huggingface_hub is used to download weights at startup (see download_weights())try: import huggingface_hub # noqa: F401except ImportError: pass
# ---------------------------------------------------------------------------# Ensure the backend root is on sys.path so internal imports work.# ---------------------------------------------------------------------------BACKEND_ROOT = Path(__file__).resolve().parentif str(BACKEND_ROOT) not in sys.path: sys.path.insert(0, str(BACKEND_ROOT))
# Load .env if present (optional, Spaces uses Secrets instead)try: from dotenv import load_dotenv load_dotenv(BACKEND_ROOT / ".env")except ImportError: pass
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")log = logging.getLogger("gradio_app")
# ---------------------------------------------------------------------------# Download CATR / SAT model weights if not already present.# - If HF_WEIGHTS_REPO is set, downloads from your Hugging Face model repo.# - Otherwise, automatically downloads the official CATR v3 checkpoint (~322 MB).# ---------------------------------------------------------------------------HF_WEIGHTS_REPO = os.getenv("HF_WEIGHTS_REPO", "")CATR_OFFICIAL_URL = "https://github.com/saahiluppal/catr/releases/download/0.2/weight493084032.pth"
def download_weights(): """Ensure CATR checkpoint is available, downloading if necessary.""" weights_dir = BACKEND_ROOT / "weights" weights_dir.mkdir(exist_ok=True) catr_pth = weights_dir / "catr_v3_coco.pth"
if catr_pth.exists() and catr_pth.stat().st_size > 100_000_000: log.info("CATR model checkpoint already present (%s).", catr_pth.name) return
# 1. Try Hugging Face Hub if HF_WEIGHTS_REPO is specified if HF_WEIGHTS_REPO and HF_WEIGHTS_REPO != "YOUR_USERNAME/vision-ai-weights": try: from huggingface_hub import hf_hub_download log.info("Downloading CATR checkpoint from Hugging Face Hub: %s ...", HF_WEIGHTS_REPO) hf_hub_download( repo_id=HF_WEIGHTS_REPO, filename="catr_v3_coco.pth", local_dir=str(weights_dir), repo_type="model", ) if catr_pth.exists() and catr_pth.stat().st_size > 100_000_000: log.info("CATR weights successfully downloaded from Hugging Face Hub.") return except Exception as exc: log.warning("Could not download CATR from HF Hub (%s): %s", HF_WEIGHTS_REPO, exc)
# 2. Download from official CATR release log.info("Downloading CATR v3 weights (~322 MB) from official release URL...") try: import urllib.request req = urllib.request.Request( CATR_OFFICIAL_URL, headers={"User-Agent": "VisionAI-Spaces/1.0"} ) with urllib.request.urlopen(req) as response, open(catr_pth, "wb") as out_file: total_size = int(response.info().get("Content-Length", 0)) chunk_size = 2 * 1024 * 1024 # 2 MB chunks downloaded = 0 while True: chunk = response.read(chunk_size) if not chunk: break out_file.write(chunk) downloaded += len(chunk) if total_size > 0 and (downloaded % (20 * 1024 * 1024) < chunk_size): pct = (downloaded / total_size) * 100 log.info("CATR download progress: %d MB / %d MB (%.1f%%)", downloaded // (1024 * 1024), total_size // (1024 * 1024), pct) log.info("CATR weights downloaded successfully to %s", catr_pth) except Exception as exc: log.error("Failed to download CATR weights: %s", exc) if catr_pth.exists(): catr_pth.unlink()
download_weights()
# ---------------------------------------------------------------------------# Run OCR model setup if weights/ocr/ is missing# ---------------------------------------------------------------------------ocr_dir = BACKEND_ROOT / "weights" / "ocr"if not ocr_dir.exists() or not list(ocr_dir.glob("*.onnx")): import subprocess log.info("Running OCR model setup...") try: subprocess.run([sys.executable, str(BACKEND_ROOT / "scripts" / "setup_ocr_models.py")], check=True) except Exception as exc: log.error("OCR model setup encountered an error: %s", exc)
# ---------------------------------------------------------------------------# Load services (same objects the FastAPI app uses)# ---------------------------------------------------------------------------from app.services.caption_service import CaptionServicefrom app.services.prescription_service import PrescriptionServicefrom app.services.product_label_service import ProductLabelServicefrom app.services.plant_service import PlantService
log.info("Loading services...")caption_service = CaptionService()prescription_service = PrescriptionService()product_label_service = ProductLabelService()plant_service = PlantService()
# Pre-load BOTH BLIP and CATR models so both are warm and ready immediatelyfor model_name in ["blip", "catr"]: try: engine = caption_service.get(model_name) log.info("Caption model '%s' ready: %s", model_name, engine.ready) except Exception as exc: log.warning("Could not pre-warm caption model '%s': %s", model_name, exc)
log.info("All services loaded.")
# ======================================================================# 1. IMAGE CAPTIONING# ======================================================================@spaces.GPU(duration=60)def caption_image(image: Image.Image, model: str = "blip", beam_size: int = 3, max_len: int = 30) -> str: """Generate a caption for an uploaded image.""" if image is None: return "⚠️ Please upload an image." image = image.convert("RGB") try: engine = caption_service.get(model) # On ZeroGPU, ensure model is mapped to active CUDA context if torch.cuda.is_available() and hasattr(engine, "device") and str(engine.device) == "cpu": try: engine.device = torch.device("cuda") if hasattr(engine, "model") and engine.model is not None: engine.model = engine.model.to("cuda") except Exception as e: log.warning("Could not dynamically move %s to CUDA: %s", model, e) if not engine.ready: return f"⚠️ Caption model '{model}' is not available: {engine.error}" started = time.perf_counter() result = caption_service.caption(image, beam_size=beam_size, max_len=max_len, model=model) elapsed = round((time.perf_counter() - started) * 1000) caption_text = result["caption"] model_used = result.get("model", model) return ( f"**Caption:** {caption_text}\n\n" f"*Model: {model_used} · Beam size: {beam_size} · " f"Inference: {elapsed} ms*" ) except Exception as exc: log.exception("Caption generation failed") return f"❌ Error: {exc}"
# ======================================================================# 2. PRESCRIPTION READER# ======================================================================def read_prescription(image: Image.Image) -> str: """Read a prescription photo and extract medicines.""" if image is None: return "⚠️ Please upload a prescription image." image = image.convert("RGB") if not prescription_service.ready: return f"⚠️ Prescription reader is not available: {prescription_service.error}" try: result = prescription_service.analyze(image) # result is a PrescriptionResult pydantic model return json.dumps(result.model_dump() if hasattr(result, "model_dump") else result.dict(), indent=2, ensure_ascii=False, default=str) except Exception as exc: log.exception("Prescription analysis failed") return f"❌ Error: {exc}"
# ======================================================================# 3. PRODUCT LABEL INTERPRETER# ======================================================================def interpret_label(image: Image.Image, product_name: str = "") -> str: """Read a food/product label photo and interpret it.""" if image is None: return "⚠️ Please upload a label image." image = image.convert("RGB") if not product_label_service.ready: return "⚠️ Label reader is not available (OCR models installed?)." try: result = product_label_service.interpret(image, product_name or None) return json.dumps(result if isinstance(result, dict) else (result.model_dump() if hasattr(result, "model_dump") else result.dict()), indent=2, ensure_ascii=False, default=str) except Exception as exc: log.exception("Product label interpretation failed") return f"❌ Error: {exc}"
# ======================================================================# 4. PLANT IDENTIFICATION# ======================================================================def identify_plant(image: Image.Image, organ: str = "auto") -> str: """Identify a plant from a photo (requires PLANTNET_API_KEY).""" if image is None: return "⚠️ Please upload a plant image." image = image.convert("RGB") if not plant_service.ready: return "⚠️ Plant identification is not available (PLANTNET_API_KEY not set)." try: result = plant_service.identify([image], organ) return json.dumps(result if isinstance(result, dict) else (result.model_dump() if hasattr(result, "model_dump") else result.dict()), indent=2, ensure_ascii=False, default=str) except Exception as exc: log.exception("Plant identification failed") return f"❌ Error: {exc}"
# ======================================================================# BUILD THE GRADIO APP# ======================================================================with gr.Blocks(title="Vision AI – Image Captioning & Analysis", theme=gr.themes.Soft()) as demo: gr.Markdown( """ # 🧠 Vision AI — Image Captioning & Analysis Upload an image and choose a feature below. Runs captioning models (BLIP / SAT / CATR), prescription reading, food-label interpretation, and plant identification. """ )
# Available models: BLIP and CATR both supported; SAT if weights file is present caption_models = ["blip", "catr"] if (BACKEND_ROOT / "weights" / "sat_resnet101_coco.pth").exists(): caption_models.append("sat")
# --- Tab 1: Caption --------------------------------------------------- with gr.Tab("📝 Image Caption"): with gr.Row(): with gr.Column(): cap_image = gr.Image(type="pil", label="Upload an image") cap_model = gr.Radio( choices=caption_models, value="blip", label="Captioning model (BLIP or CATR)", info="BLIP: Vision Transformer + Text Decoder (COCO fine-tuned) | CATR: ResNet-101 + Transformer", ) cap_beam = gr.Slider(1, 10, value=3, step=1, label="Beam size") cap_maxlen = gr.Slider(5, 60, value=30, step=1, label="Max caption length") cap_btn = gr.Button("Generate Caption", variant="primary") with gr.Column(): cap_output = gr.Markdown(label="Caption") cap_btn.click( caption_image, inputs=[cap_image, cap_model, cap_beam, cap_maxlen], outputs=cap_output, )
# --- Tab 2: Prescription ----------------------------------------------- with gr.Tab("💊 Prescription Reader"): with gr.Row(): with gr.Column(): rx_image = gr.Image(type="pil", label="Upload a prescription photo") rx_btn = gr.Button("Read Prescription", variant="primary") with gr.Column(): rx_output = gr.Code(label="Result (JSON)", language="json") rx_btn.click(read_prescription, inputs=[rx_image], outputs=rx_output)
# --- Tab 3: Product Label ----------------------------------------------- with gr.Tab("🏷️ Product Label"): with gr.Row(): with gr.Column(): pl_image = gr.Image(type="pil", label="Upload a label photo") pl_name = gr.Textbox(label="Product name (optional)", placeholder="e.g. Maggi Noodles") pl_btn = gr.Button("Interpret Label", variant="primary") with gr.Column(): pl_output = gr.Code(label="Result (JSON)", language="json") pl_btn.click(interpret_label, inputs=[pl_image, pl_name], outputs=pl_output)
# --- Tab 4: Plant ID --------------------------------------------------- with gr.Tab("🌿 Plant Identification"): with gr.Row(): with gr.Column(): plant_image = gr.Image(type="pil", label="Upload a plant photo") plant_organ = gr.Dropdown( choices=["auto", "flower", "leaf", "fruit", "bark", "habit"], value="auto", label="Organ shown in photo", ) plant_btn = gr.Button("Identify Plant", variant="primary") with gr.Column(): plant_output = gr.Code(label="Result (JSON)", language="json") plant_btn.click(identify_plant, inputs=[plant_image, plant_organ], outputs=plant_output)
if __name__ == "__main__": demo.launch(server_name="0.0.0.0", server_port=7860)12345678910111213141516171819202122232425262728293031# Image captioning (served by the API, read by app/services/caption_service.py).# Pretrained Show, Attend and Tell from github.com/sgrvinod/a-PyTorch-Tutorial-to-Image-Captioning:# ResNet-101 encoder, 14x14 soft attention with gating, LSTMCell decoder, COCO 2014.inference: model: blip # default model: blip | sat | catr (others load on first use, ?model=). # blip = most accurate on our photos; SAT remains the PRD architecture # and is available with ?model=sat. BLIP is pre-cached at deploy time. weights: "weights/sat_resnet101_coco.pth" # SAT; created by: python -m model.captioning.convert_checkpoint image_size: 256 # SAT input size (image_size x image_size) beam_size: 5 # default beam width (API ?beam_size= overrides, 1-10). 5 avoided # loops/vague captions that 3 produced (e.g. "a dog ... next to a dog") no_repeat_ngram: 2 # forbid repeating any word pair within a caption (0 = off) max_caption_len: 50 # hard cap on generated words
# CATR: ResNet-101 + transformer, COCO 2017 (github.com/saahiluppal/catr, Apache-2.0) catr: weights: "weights/catr_v3_coco.pth" # release 0.2 / weight493084032.pth tokenizer: "weights/catr_tokenizer" # bert-base-uncased vocab, saved on first load max_image_side: 299 beam_size: 3
# BLIP-base: ViT-B/16 + text decoder, COCO fine-tuned (Salesforce, BSD-3-Clause) blip: model_id: "Salesforce/blip-image-captioning-base" # Hugging Face cache beam_size: 3 max_caption_len: 30 # Repeat control (tested 2026-11-12 on 7 photos): no_repeat_ngram 2 + repetition_penalty 1.2 # stopped "sri ... sri ... sri" loops without changing good captions; no_repeat_ngram 3 let # "sri sri sri" through, so the stricter 2 stays. no_repeat_ngram: 2 repetition_penalty: 1.2123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339{ "when": "2026-11-13, simplified pipelines (ADR-005)", "label": { "photos": 16, "values_within_5pct": "106/112", "accuracy": 0.9464, "per_field": { "energy_kcal": "16/16", "sugars_g": "16/16", "fat_g": "15/16", "saturated_fat_g": "15/16", "carbohydrate_g": "16/16", "protein_g": "14/16", "salt_g": "14/16" }, "latency_ms_mean": 2996, "latency_ms_p95": 5816, "ai_requests": 9, "ai_requests_per_photo": 0.56, "notes": "RapidOCR v6-small, steps exif+resize+perspective+clahe; AI (OCR text only) for missing values", "per_photo": [ { "image": "ndl/06174988_13.jpg", "latency_ms": 5816, "ai_values": [ "fat_g", "saturated_fat_g" ], "fields": { "energy_kcal": true, "sugars_g": true, "fat_g": true, "saturated_fat_g": true, "carbohydrate_g": true, "protein_g": true, "salt_g": true } }, { "image": "ndl/7613379505774_2.jpg", "latency_ms": 3699, "ai_values": [], "fields": { "energy_kcal": true, "sugars_g": true, "fat_g": true, "saturated_fat_g": true, "carbohydrate_g": true, "protein_g": true, "salt_g": false } }, { "image": "ndl/2642824003775_2.jpg", "latency_ms": 3169, "ai_values": [ "protein_g", "saturated_fat_g", "sugars_g" ], "fields": { "energy_kcal": true, "sugars_g": true, "fat_g": true, "saturated_fat_g": true, "carbohydrate_g": true, "protein_g": true, "salt_g": false } }, { "image": "ndl/3760027470152_1.jpg", "latency_ms": 3156, "ai_values": [], "fields": { "energy_kcal": true, "sugars_g": true, "fat_g": true, "saturated_fat_g": true, "carbohydrate_g": true, "protein_g": true, "salt_g": true } }, { "image": "ndl/3576620008209_4.jpg", "latency_ms": 3471, "ai_values": [ "carbohydrate_g" ], "fields": { "energy_kcal": true, "sugars_g": true, "fat_g": true, "saturated_fat_g": true, "carbohydrate_g": true, "protein_g": true, "salt_g": true } }, { "image": "ndl/5400210432861_2.jpg", "latency_ms": 1761, "ai_values": [ "energy_kj" ], "fields": { "energy_kcal": true, "sugars_g": true, "fat_g": false, "saturated_fat_g": true, "carbohydrate_g": true, "protein_g": true, "salt_g": true } }, { "image": "ndl/3760251820143_3.jpg", "latency_ms": 1357, "ai_values": [ "protein_g", "salt_g", "saturated_fat_g" ], "fields": { "energy_kcal": true, "sugars_g": true, "fat_g": true, "saturated_fat_g": true, "carbohydrate_g": true, "protein_g": true, "salt_g": true } }, { "image": "ndl/3760054405448_2.jpg", "latency_ms": 5022, "ai_values": [ "carbohydrate_g", "fat_g", "saturated_fat_g" ], "fields": { "energy_kcal": true, "sugars_g": true, "fat_g": true, "saturated_fat_g": true, "carbohydrate_g": true, "protein_g": true, "salt_g": true } }, { "image": "ndl/3266191064178_3.jpg", "latency_ms": 1454, "ai_values": [], "fields": { "energy_kcal": true, "sugars_g": true, "fat_g": true, "saturated_fat_g": true, "carbohydrate_g": true, "protein_g": true, "salt_g": true } }, { "image": "ndl/3560071284305_2.jpg", "latency_ms": 2820, "ai_values": [], "fields": { "energy_kcal": true, "sugars_g": true, "fat_g": true, "saturated_fat_g": true, "carbohydrate_g": true, "protein_g": true, "salt_g": true } }, { "image": "ndl/3263859892982_2.jpg", "latency_ms": 6096, "ai_values": [], "fields": { "energy_kcal": true, "sugars_g": true, "fat_g": true, "saturated_fat_g": false, "carbohydrate_g": true, "protein_g": false, "salt_g": true } }, { "image": "ndl/7610198012537_3.jpg", "latency_ms": 1234, "ai_values": [ "fat_g", "salt_g" ], "fields": { "energy_kcal": true, "sugars_g": true, "fat_g": true, "saturated_fat_g": true, "carbohydrate_g": true, "protein_g": true, "salt_g": true } }, { "image": "ndl/3425471120052_4.jpg", "latency_ms": 1415, "ai_values": [], "fields": { "energy_kcal": true, "sugars_g": true, "fat_g": true, "saturated_fat_g": true, "carbohydrate_g": true, "protein_g": true, "salt_g": true } }, { "image": "ndl/2910833010368_4.jpg", "latency_ms": 3275, "ai_values": [], "fields": { "energy_kcal": true, "sugars_g": true, "fat_g": true, "saturated_fat_g": true, "carbohydrate_g": true, "protein_g": true, "salt_g": true } }, { "image": "ndl/8437013754477_2.jpg", "latency_ms": 2803, "ai_values": [], "fields": { "energy_kcal": true, "sugars_g": true, "fat_g": true, "saturated_fat_g": true, "carbohydrate_g": true, "protein_g": false, "salt_g": true } }, { "image": "ndl/8901808004943_2.jpg", "latency_ms": 1387, "ai_values": [], "fields": { "energy_kcal": true, "sugars_g": true, "fat_g": true, "saturated_fat_g": true, "carbohydrate_g": true, "protein_g": true, "salt_g": true } } ] }, "prescription_p5": { "status": "ok", "latency_ms": 5723, "timings": { "preprocess_ms": 14, "ocr_ms": 4864, "ai_ms": 793, "match_ms": 41, "total_ms": 5719 }, "ai_calls": 1, "already_taking": [ "Ecosprin AV" ], "date": null, "score": { "medicines_found": "3/3", "found": [ "dothepin", "clonazepam", "zocalm" ], "extra_medicines": 0, "fields_correct": "5/8", "already_taking_ok": true, "per_medicine": [ { "read_as": "Dothepin / Prothiaden 75mg", "match": "dothepin", "status": "matched", "strength": "75mg", "dosage": "1 tablet", "frequency": "at night", "checks": [], "what_for": "Anxiety disorder and depression", "strength_ok": true, "dose_ok": true, "when_ok": true }, { "read_as": "Clonazepam", "match": "clonazepam", "status": "known_brand", "strength": null, "dosage": "2 tablets", "frequency": null, "checks": [], "what_for": "Anxiety disorder and epilepsy/Seizures", "strength_ok": false, "dose_ok": false, "when_ok": false }, { "read_as": "Zocalm 5mg", "match": "zocalm", "status": "matched", "strength": "5mg", "dosage": null, "frequency": "SOS (when needed)", "checks": [], "what_for": "Insomnia", "strength_ok": true, "dose_ok": null, "when_ok": true } ] }, "ai_requests_note": "1 text request per scan; this run reused the eval cache. Live run: AI 6.9 s on OpenRouter free (total 12.1 s)." }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292{ "when": "2026-11-13, commit pre-simplification (1e7d65b)", "label": { "photos": 16, "values_within_5pct": "109/112", "accuracy": 0.9732, "per_field": { "energy_kcal": "16/16", "sugars_g": "16/16", "fat_g": "15/16", "saturated_fat_g": "16/16", "carbohydrate_g": "16/16", "protein_g": "16/16", "salt_g": "14/16" }, "latency_ms_mean": 4170, "latency_ms_p95": 8377, "ai_reads": 10, "ai_requests_counted": 20, "notes": "Apple Vision first, vision AI for gaps (10 of 16 photos), reader cache on, Open Food Facts off", "per_photo": [ { "image": "ndl/06174988_13.jpg", "latency_ms": 2302, "fields": { "energy_kcal": true, "sugars_g": true, "fat_g": true, "saturated_fat_g": true, "carbohydrate_g": true, "protein_g": true, "salt_g": true } }, { "image": "ndl/7613379505774_2.jpg", "latency_ms": 285, "fields": { "energy_kcal": true, "sugars_g": true, "fat_g": true, "saturated_fat_g": true, "carbohydrate_g": true, "protein_g": true, "salt_g": true } }, { "image": "ndl/2642824003775_2.jpg", "latency_ms": 2734, "fields": { "energy_kcal": true, "sugars_g": true, "fat_g": true, "saturated_fat_g": true, "carbohydrate_g": true, "protein_g": true, "salt_g": true } }, { "image": "ndl/3760027470152_1.jpg", "latency_ms": 1275, "fields": { "energy_kcal": true, "sugars_g": true, "fat_g": true, "saturated_fat_g": true, "carbohydrate_g": true, "protein_g": true, "salt_g": true } }, { "image": "ndl/3576620008209_4.jpg", "latency_ms": 530, "fields": { "energy_kcal": true, "sugars_g": true, "fat_g": true, "saturated_fat_g": true, "carbohydrate_g": true, "protein_g": true, "salt_g": true } }, { "image": "ndl/5400210432861_2.jpg", "latency_ms": 13880, "fields": { "energy_kcal": true, "sugars_g": true, "fat_g": true, "saturated_fat_g": true, "carbohydrate_g": true, "protein_g": true, "salt_g": true } }, { "image": "ndl/3760251820143_3.jpg", "latency_ms": 8243, "fields": { "energy_kcal": true, "sugars_g": true, "fat_g": true, "saturated_fat_g": true, "carbohydrate_g": true, "protein_g": true, "salt_g": false } }, { "image": "ndl/3760054405448_2.jpg", "latency_ms": 4304, "fields": { "energy_kcal": true, "sugars_g": true, "fat_g": false, "saturated_fat_g": true, "carbohydrate_g": true, "protein_g": true, "salt_g": false } }, { "image": "ndl/3266191064178_3.jpg", "latency_ms": 890, "fields": { "energy_kcal": true, "sugars_g": true, "fat_g": true, "saturated_fat_g": true, "carbohydrate_g": true, "protein_g": true, "salt_g": true } }, { "image": "ndl/3560071284305_2.jpg", "latency_ms": 281, "fields": { "energy_kcal": true, "sugars_g": true, "fat_g": true, "saturated_fat_g": true, "carbohydrate_g": true, "protein_g": true, "salt_g": true } }, { "image": "ndl/3263859892982_2.jpg", "latency_ms": 583, "fields": { "energy_kcal": true, "sugars_g": true, "fat_g": true, "saturated_fat_g": true, "carbohydrate_g": true, "protein_g": true, "salt_g": true } }, { "image": "ndl/7610198012537_3.jpg", "latency_ms": 8377, "fields": { "energy_kcal": true, "sugars_g": true, "fat_g": true, "saturated_fat_g": true, "carbohydrate_g": true, "protein_g": true, "salt_g": true } }, { "image": "ndl/3425471120052_4.jpg", "latency_ms": 7433, "fields": { "energy_kcal": true, "sugars_g": true, "fat_g": true, "saturated_fat_g": true, "carbohydrate_g": true, "protein_g": true, "salt_g": true } }, { "image": "ndl/2910833010368_4.jpg", "latency_ms": 718, "fields": { "energy_kcal": true, "sugars_g": true, "fat_g": true, "saturated_fat_g": true, "carbohydrate_g": true, "protein_g": true, "salt_g": true } }, { "image": "ndl/8437013754477_2.jpg", "latency_ms": 7489, "fields": { "energy_kcal": true, "sugars_g": true, "fat_g": true, "saturated_fat_g": true, "carbohydrate_g": true, "protein_g": true, "salt_g": true } }, { "image": "ndl/8901808004943_2.jpg", "latency_ms": 7393, "fields": { "energy_kcal": true, "sugars_g": true, "fat_g": true, "saturated_fat_g": true, "carbohydrate_g": true, "protein_g": true, "salt_g": true } } ] }, "prescription_p5": { "reader": "device_text_ai", "latency_ms": 3562, "ai_requests": 0, "already_taking": [ "Ecosprin" ], "general_instructions": "Course: 3 months (check)", "date": null, "score": { "medicines_found": "3/3", "found": [ "dothepin", "clonazepam", "zocalm" ], "extra_medicines": 0, "fields_correct": "4/8", "already_taking_ok": true, "per_medicine": [ { "read_as": "Dothepin Protheaden 75mg", "match": "dothepin", "status": "matched", "strength": "75mg", "dosage": "1 tab", "frequency": null, "what_for": "Anxiety disorder and depression", "strength_ok": true, "dose_ok": true, "when_ok": false }, { "read_as": "Clonazepam / Lonazep / Clonotril", "match": "clonazepam", "status": "matched", "strength": null, "dosage": "1 tab", "frequency": null, "what_for": "Anxiety disorder and epilepsy/Seizures", "strength_ok": false, "dose_ok": true, "when_ok": false }, { "read_as": "Xocalm", "match": "zocalm", "status": "verify", "strength": null, "dosage": "1 tab", "frequency": "SOS", "what_for": null, "strength_ok": false, "dose_ok": null, "when_ok": true } ] }, "ai_requests_note": "0 because the text-AI answer was cached; uncached = 1 text request" }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556# Prescription evaluation set
Put labelled prescription photos here (`.jpg`, `.jpeg` or `.png`) plus a `ground_truth.json`:
```json{ "p5.jpg": { "image": "/absolute/path/to/p5.jpg", "split": "tuned", "filled": true, "medicines": [ {"aliases": ["dothepin", "prothiaden", "dosulepin"], "strength": "75mg"}, {"aliases": ["pantop", "pantoprazole"], "strength": "40mg"} ], "already_taking": ["ecosprin av"] }}```
- `image` (optional) — defaults to the photo next to `ground_truth.json`.- `split` — `tuned` (rules were developed on it) or `unseen` (default, held out).- `filled` — `false` means the ground truth isn't written yet; the row is skipped.- `aliases` — the brand as written, other brands of it, and the ingredient (generic) name. Other keys such as dose, timing or duration are ignored: the feature **identifies medicines only**.
List every medicine **as written on the prescription** (brand + strength is enough). Then run, from`backend/`:
```bashvenv/bin/python scripts/eval_prescription.py # all prescriptionsvenv/bin/python scripts/eval_prescription.py --only p5.jpg # one photovenv/bin/python scripts/eval_prescription.py --json report.jsonvenv/bin/python scripts/eval_prescription.py --no-ai # OCR + dataset onlyvenv/bin/python scripts/eval_prescription.py --ai-cache DIR # reuse AI answers between runs```
Per prescription the script reports:
| Metric | Meaning ||---|---|| found | a listed medicine whose name matches an alias (one-to-one, fuzzy ≥ 0.8) || identified | found **and** Matched / Known brand to a product whose name or ingredients contain an alias || to confirm | found **and** Verify, with an alias among the candidates (the person can pick it) || **WRONG** | Matched / Known brand to a product containing **no** alias — the dangerous outcome || junk rows | listed medicines that match nothing in the truth || strength | written strength read correctly |
It also reports precision/recall/F1, match-status counts and latency. `--ai-cache` is for repeatevaluation runs only; the app itself never caches AI answers.
The pipeline reads the photo **on this machine** (OpenCV + RapidOCR), strips patient/doctor lines, andsends only the medicine rows as text to the configured AI provider (OpenRouter free model, Groq backup).No image and no patient details are sent anywhere. See `scripts/eval_prescription.py` and ADR-005 in`project_review/` for the full flow.
Images here contain patient data: the photos and `ground_truth.json` are git-ignored.123456789101112131415161718192021222324252627282930313233343536373839# Product label evaluation set
Real photos only (no synthetic images). Ground truth NEVER comes from this app's own output.Everything here except this README is git-ignored.
| folder | what | ground truth | counts in eval ||---|---|---|---|| `ndl/` | nutrition-table photos from the Hugging Face dataset `openfoodfacts/nutrient-detection-layout` (CC BY-SA 3.0) | per-100 g values tagged by the dataset's professional annotators, converted strictly (OCR noise is skipped, not guessed) | yes if the conversion was clean and passes the sanity check; otherwise after your review || `off_india/` | Indian products from Open Food Facts: a nutrition photo + an ingredients photo each | OFF volunteer values, marked `open_food_facts (volunteer, UNVERIFIED)` | only after you tick **verified** || `my_photos/` | your own photos | empty skeleton for you to fill in | only after you tick **verified** |
Build / update (run from `backend/`):
venv/bin/python scripts/build_label_eval_set.py build # downloads ndl + off_india (pauses between requests) venv/bin/python scripts/build_label_eval_set.py skeleton # adds new files in my_photos/ with empty values venv/bin/python scripts/build_label_eval_set.py review # review page at http://127.0.0.1:8765/
On the review page, compare every value with the photo, fix or clear it, then tick **verified** and press Save.Save writes `ground_truth.json` (the previous version is kept as `ground_truth.json.bak`).
Evaluate the verified entries:
venv/bin/python scripts/eval_product_label.py --json product_label_eval.json
`ground_truth.json` (version 2), one entry per product:
"off_india/8904156707320": { "source": "open_food_facts (volunteer, UNVERIFIED)", "licence": "...", "verified": false, "images": {"nutrition": "off_india/8904156707320_nutrition.jpg", "ingredients": "off_india/..._ingredients.jpg"}, "barcode": "8904156707320", "product_name": "...", "allergens": ["milk", "wheat_gluten"], // CONTAINS only; [] = none; null = not scored "nutrients_per_100": {"energy_kcal": 520, "sugars_g": 3.1, ...}, "origin": {...}, "notes": [...] }
Allergen names: milk, wheat_gluten, soy, peanut, tree_nuts, sesame, egg, fish, crustaceans, mustard, sulphites.Scored nutrients (±5 %): energy (kcal, or kJ ÷ 4.184), sugars, fat, saturated fat, carbohydrate, protein, salt (or sodium × 2.5).Products with two photos are scored as follows: nutrition values come from the nutrition photo and allergens from the ingredients photo.Each photo is sent to Groq (label reading).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887{ "_source": "Curated list of common Indian medicine brands and generics, ported from the reference PrescriptionReader project and extended (Zincovit, Rabemac, Rablet, Electral, ORS). Used only as a FALLBACK when a name is not in the Indian Medicine Dataset; a hit is shown as 'known_brand', never 'matched'. Compositions are general (no strengths) and only filled where well established.", "brands": [ { "name": "aceclofenac", "composition": "Aceclofenac" }, { "name": "actrapid", "composition": null }, { "name": "alex", "composition": null }, { "name": "allegra", "composition": "Fexofenadine" }, { "name": "alprazolam", "composition": "Alprazolam" }, { "name": "ambroxol", "composition": "Ambroxol" }, { "name": "amitriptyline", "composition": "Amitriptyline" }, { "name": "amlodipine", "composition": "Amlodipine" }, { "name": "amoxicillin", "composition": "Amoxicillin" }, { "name": "amoxyclav", "composition": null }, { "name": "amphotericin", "composition": "Amphotericin" }, { "name": "ampicillin", "composition": "Ampicillin" }, { "name": "aripiprazole", "composition": "Aripiprazole" }, { "name": "ascoril", "composition": null }, { "name": "aspirin", "composition": "Aspirin" }, { "name": "atenolol", "composition": "Atenolol" }, { "name": "atorvastatin", "composition": "Atorvastatin" }, { "name": "augmentin", "composition": "Amoxicillin + clavulanic acid" }, { "name": "azithral", "composition": "Azithromycin" }, { "name": "b complex", "composition": "B complex" }, { "name": "bambuterol", "composition": "Bambuterol" }, { "name": "becosules", "composition": "Vitamin B-complex with vitamin C" }, { "name": "benadryl", "composition": null }, { "name": "betnovate", "composition": null }, { "name": "brimonidine", "composition": "Brimonidine" }, { "name": "bromhexine", "composition": "Bromhexine" }, { "name": "brufen", "composition": "Ibuprofen" }, { "name": "calamine", "composition": "Calamine" }, { "name": "calcirol", "composition": null }, { "name": "calcium", "composition": "Calcium" }, { "name": "calpol", "composition": "Paracetamol" }, { "name": "carbimazole", "composition": "Carbimazole" }, { "name": "cefalexin", "composition": "Cefalexin" }, { "name": "cefixime", "composition": "Cefixime" }, { "name": "celecoxib", "composition": "Celecoxib" }, { "name": "cetrizine", "composition": null }, { "name": "chlorpheniramine", "composition": "Chlorpheniramine" }, { "name": "cifran", "composition": "Ciprofloxacin" }, { "name": "ciplox", "composition": "Ciprofloxacin" }, { "name": "ciprofloxacin", "composition": "Ciprofloxacin" }, { "name": "clarithromycin", "composition": "Clarithromycin" }, { "name": "clindamycin", "composition": "Clindamycin" }, { "name": "clomipramine", "composition": "Clomipramine" }, { "name": "clonazepam", "composition": "Clonazepam" }, { "name": "clopidogrel", "composition": "Clopidogrel" }, { "name": "clotrimazole", "composition": "Clotrimazole" }, { "name": "cod liver oil", "composition": "Cod liver oil" }, { "name": "combiflam", "composition": "Ibuprofen + paracetamol" }, { "name": "corex", "composition": null }, { "name": "crocin", "composition": "Paracetamol" }, { "name": "desloratadine", "composition": "Desloratadine" }, { "name": "dexamethasone", "composition": "Dexamethasone" }, { "name": "dextromethorphan", "composition": "Dextromethorphan" }, { "name": "diazepam", "composition": "Diazepam" }, { "name": "diclofenac", "composition": "Diclofenac" }, { "name": "digene", "composition": null }, { "name": "digoxin", "composition": "Digoxin" }, { "name": "diltiazem", "composition": "Diltiazem" }, { "name": "disprin", "composition": null }, { "name": "dolo", "composition": "Paracetamol" }, { "name": "dolo 650", "composition": "Paracetamol (650mg)" }, { "name": "domperidone", "composition": "Domperidone" }, { "name": "doxycycline", "composition": "Doxycycline" }, { "name": "electral", "composition": "Oral rehydration salts (WHO formula)" }, { "name": "electrolyte", "composition": "Oral rehydration salts / electrolytes" }, { "name": "eltroxin", "composition": "Thyroxine (levothyroxine)" }, { "name": "enalapril", "composition": "Enalapril" }, { "name": "eno", "composition": null }, { "name": "erythromycin", "composition": "Erythromycin" }, { "name": "escitalopram", "composition": "Escitalopram" }, { "name": "esomeprazole", "composition": "Esomeprazole" }, { "name": "etoricoxib", "composition": "Etoricoxib" }, { "name": "famotidine", "composition": "Famotidine" }, { "name": "fenofibrate", "composition": "Fenofibrate" }, { "name": "fepanil", "composition": null }, { "name": "fexofenadine", "composition": "Fexofenadine" }, { "name": "fluconazole", "composition": "Fluconazole" }, { "name": "fluoxetine", "composition": "Fluoxetine" }, { "name": "folic acid", "composition": "Folic acid" }, { "name": "furosemide", "composition": "Furosemide" }, { "name": "fusidic acid", "composition": null }, { "name": "galvus", "composition": null }, { "name": "gelusil", "composition": null }, { "name": "gemfibrozil", "composition": "Gemfibrozil" }, { "name": "gentamicin", "composition": "Gentamicin" }, { "name": "gliclazide", "composition": "Gliclazide" }, { "name": "glimepiride", "composition": "Glimepiride" }, { "name": "glipizide", "composition": "Glipizide" }, { "name": "glucobay", "composition": null }, { "name": "glycomet", "composition": "Metformin" }, { "name": "grilinctus", "composition": null }, { "name": "griseofulvin", "composition": "Griseofulvin" }, { "name": "guaifenesin", "composition": "Guaifenesin" }, { "name": "haloperidol", "composition": "Haloperidol" }, { "name": "heparin", "composition": "Heparin" }, { "name": "humalog", "composition": null }, { "name": "hydrochlorothiazide", "composition": "Hydrochlorothiazide" }, { "name": "hydrocortisone", "composition": "Hydrocortisone" }, { "name": "hydroxyzine", "composition": "Hydroxyzine" }, { "name": "ibuprofen", "composition": "Ibuprofen" }, { "name": "imipramine", "composition": "Imipramine" }, { "name": "indomethacin", "composition": "Indomethacin" }, { "name": "insulin", "composition": "Insulin" }, { "name": "iron", "composition": "Iron" }, { "name": "isosorbide", "composition": "Isosorbide" }, { "name": "itraconazole", "composition": "Itraconazole" }, { "name": "januvia", "composition": null }, { "name": "ketoconazole", "composition": "Ketoconazole" }, { "name": "ketorolac", "composition": "Ketorolac" }, { "name": "lacto calamine", "composition": null }, { "name": "lansoprazole", "composition": "Lansoprazole" }, { "name": "lantus", "composition": null }, { "name": "latanoprost", "composition": "Latanoprost" }, { "name": "levocetirizine", "composition": "Levocetirizine" }, { "name": "levofloxacin", "composition": "Levofloxacin" }, { "name": "levothyroxine", "composition": "Levothyroxine" }, { "name": "lincomycin", "composition": "Lincomycin" }, { "name": "liothyronine", "composition": "Liothyronine" }, { "name": "lisinopril", "composition": "Lisinopril" }, { "name": "lithium", "composition": "Lithium" }, { "name": "loratadine", "composition": "Loratadine" }, { "name": "lorazepam", "composition": "Lorazepam" }, { "name": "losartan", "composition": "Losartan" }, { "name": "magnesium", "composition": "Magnesium" }, { "name": "metacin", "composition": null }, { "name": "metformin", "composition": "Metformin" }, { "name": "methimazole", "composition": "Methimazole" }, { "name": "metoprolol", "composition": "Metoprolol" }, { "name": "metronidazole", "composition": "Metronidazole" }, { "name": "miconazole", "composition": "Miconazole" }, { "name": "mixtard", "composition": null }, { "name": "montair", "composition": "Montelukast" }, { "name": "montelukast", "composition": "Montelukast" }, { "name": "moxifloxacin", "composition": "Moxifloxacin" }, { "name": "multivitamin", "composition": "Multivitamin" }, { "name": "mupirocin", "composition": "Mupirocin" }, { "name": "naproxen", "composition": "Naproxen" }, { "name": "neosporin", "composition": null }, { "name": "neurobion", "composition": null }, { "name": "nifedipine", "composition": "Nifedipine" }, { "name": "nimesulide", "composition": "Nimesulide" }, { "name": "nitroglycerin", "composition": "Nitroglycerin" }, { "name": "norflox", "composition": "Norfloxacin" }, { "name": "novomix", "composition": null }, { "name": "nystatin", "composition": "Nystatin" }, { "name": "ofloxacin", "composition": "Ofloxacin" }, { "name": "olanzapine", "composition": "Olanzapine" }, { "name": "omega 3", "composition": "Omega 3" }, { "name": "omeprazole", "composition": "Omeprazole" }, { "name": "omez", "composition": "Omeprazole" }, { "name": "ondansetron", "composition": "Ondansetron" }, { "name": "ornidazole", "composition": "Ornidazole" }, { "name": "ors", "composition": "Oral rehydration salts" }, { "name": "pacimol", "composition": null }, { "name": "pan 40", "composition": "Pantoprazole (40mg)" }, { "name": "panderm", "composition": null }, { "name": "pantop", "composition": "Pantoprazole" }, { "name": "pantoprazole", "composition": "Pantoprazole" }, { "name": "paracetamol", "composition": "Paracetamol" }, { "name": "paracip", "composition": null }, { "name": "paroxetine", "composition": "Paroxetine" }, { "name": "pheniramine", "composition": "Pheniramine" }, { "name": "pioglitazone", "composition": "Pioglitazone" }, { "name": "piroxicam", "composition": "Piroxicam" }, { "name": "pravastatin", "composition": "Pravastatin" }, { "name": "prednisolone", "composition": "Prednisolone" }, { "name": "propranolol", "composition": "Propranolol" }, { "name": "propylthiouracil", "composition": "Propylthiouracil" }, { "name": "pyrigesic", "composition": null }, { "name": "quadriderm", "composition": null }, { "name": "quetiapine", "composition": "Quetiapine" }, { "name": "rabemac", "composition": "Rabeprazole" }, { "name": "rabeprazole", "composition": "Rabeprazole" }, { "name": "rablet", "composition": "Rabeprazole" }, { "name": "ramipril", "composition": "Ramipril" }, { "name": "ranitidine", "composition": "Ranitidine" }, { "name": "razo", "composition": "Rabeprazole" }, { "name": "revital", "composition": null }, { "name": "risperidone", "composition": "Risperidone" }, { "name": "rosuvastatin", "composition": "Rosuvastatin" }, { "name": "salbutamol", "composition": "Salbutamol" }, { "name": "saridon", "composition": null }, { "name": "secnidazole", "composition": "Secnidazole" }, { "name": "sertraline", "composition": "Sertraline" }, { "name": "shelcal", "composition": "Calcium carbonate + vitamin D3" }, { "name": "simethicone", "composition": "Simethicone" }, { "name": "simvastatin", "composition": "Simvastatin" }, { "name": "sitagliptin", "composition": "Sitagliptin" }, { "name": "soframycin", "composition": null }, { "name": "stamlo", "composition": "Amlodipine" }, { "name": "streptokinase", "composition": "Streptokinase" }, { "name": "sucralfate", "composition": "Sucralfate" }, { "name": "sumo", "composition": null }, { "name": "telma", "composition": "Telmisartan" }, { "name": "telmisartan", "composition": "Telmisartan" }, { "name": "terbinafine", "composition": "Terbinafine" }, { "name": "terbutaline", "composition": "Terbutaline" }, { "name": "tetracycline", "composition": "Tetracycline" }, { "name": "theophylline", "composition": "Theophylline" }, { "name": "thyronorm", "composition": "Thyroxine (levothyroxine)" }, { "name": "thyroxine", "composition": "Thyroxine" }, { "name": "timolol", "composition": "Timolol" }, { "name": "tinidazole", "composition": "Tinidazole" }, { "name": "tobramycin", "composition": "Tobramycin" }, { "name": "tramadol", "composition": "Tramadol" }, { "name": "verapamil", "composition": "Verapamil" }, { "name": "vildagliptin", "composition": "Vildagliptin" }, { "name": "vitamin c", "composition": "Vitamin c" }, { "name": "vitamin d3", "composition": "Vitamin d3" }, { "name": "vitamin e", "composition": "Vitamin e" }, { "name": "voveran", "composition": "Diclofenac" }, { "name": "warfarin", "composition": "Warfarin" }, { "name": "zinc", "composition": "Zinc" }, { "name": "zincovit", "composition": "Multivitamin + multimineral with zinc" }, { "name": "zithromax", "composition": null }, { "name": "zolpidem", "composition": "Zolpidem" }, { "name": "zopiclone", "composition": "Zopiclone" } ], "companies": [ "alkem", "aurobindo", "cadila", "cipla", "dr reddy", "glenmark", "intas", "lupin", "mankind", "ranbaxy", "sun pharma", "torrent" ]}123version https://git-lfs.github.com/spec/v1oid sha256:1032846aa3e96db07631d1229ec3ec364e03cd505c1dcbd094f1ecd3f3fe75f5size 44953149123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349{ "_source": "Project rule set (Product Label Interpreter spec, 2026-11-12). Deterministic keyword rules with English and common Indian terms. Matches whole words/phrases, case-insensitive. This is a screening aid, NOT a substitute for the printed allergen declaration.", "_matching": { "keywords": "whole-word / whole-phrase match in the ingredients text, the 'contains' statement and the 'may contain' statement", "exclude_phrases": "if a keyword only occurs inside one of these phrases it does not count (e.g. 'peanut butter' is not milk)", "may_contain": "keywords found in the 'may contain' statement, or after a may-contain marker inside the ingredients text, go to may_contain instead of contains", "negation": "a keyword directly preceded by a negation marker ('free from milk', 'no added egg', 'non-dairy') or written as '<keyword>-free' / '<keyword> free' does not count" }, "allergens": { "milk": { "label": "Milk", "keywords": [ "milk", "milk solids", "milk powder", "skimmed milk", "skimmed milk powder", "whole milk powder", "whey", "whey powder", "whey protein", "casein", "caseinate", "sodium caseinate", "lactose", "butter", "butter oil", "ghee", "cream", "cheese", "paneer", "khoya", "khoa", "curd", "yoghurt", "yogurt", "dahi", "milk fat", "dairy" ], "exclude_phrases": [ "coconut milk", "coconut milk powder", "almond milk", "soy milk", "soya milk", "oat milk", "rice milk", "peanut butter", "cocoa butter", "shea butter", "nut butter", "kokum butter", "cream of tartar", "coconut cream", "dairy free", "dairy-free", "non-dairy", "non dairy" ] }, "wheat_gluten": { "label": "Wheat / gluten", "keywords": [ "wheat", "wheat flour", "whole wheat", "maida", "atta", "sooji", "suji", "semolina", "rava", "gluten", "wheat gluten", "barley", "barley malt", "malt extract", "rye", "oats", "oat", "oat flour", "durum" ], "exclude_phrases": [ "gluten free", "gluten-free", "buckwheat" ], "notes": { "oats": "Oats are often cross-contaminated with wheat; listed as a possible gluten source.", "oat": "Oats are often cross-contaminated with wheat; listed as a possible gluten source.", "oat flour": "Oats are often cross-contaminated with wheat; listed as a possible gluten source." } }, "soy": { "label": "Soy", "keywords": [ "soy", "soya", "soybean", "soybeans", "soya bean", "soya beans", "soy lecithin", "soya lecithin", "soy protein", "soya protein", "soy sauce", "tofu" ], "patterns": [ "lecithin\\s*\\(\\s*(?:from\\s+)?soya?\\b[^)]*\\)", "(?:ins|e)\\s*-?\\s*322\\s*\\(\\s*(?:from\\s+)?soya?\\b[^)]*\\)", "soya?\\s*(?:-|\\s)?\\s*(?:ins|e)\\s*-?\\s*322" ], "exclude_phrases": [ "soy free", "soy-free" ], "notes": { "lecithin": "Lecithin / INS 322 counts as soy only when the label says it comes from soy." } }, "peanut": { "label": "Peanut", "keywords": [ "peanut", "peanuts", "groundnut", "groundnuts", "ground nut", "ground nuts", "moongphali", "mungfali", "peanut butter", "peanut oil", "groundnut oil", "arachis oil" ], "exclude_phrases": [ "peanut free", "peanut-free" ] }, "tree_nuts": { "label": "Tree nuts", "keywords": [ "almond", "almonds", "badam", "cashew", "cashews", "cashew nut", "kaju", "pistachio", "pistachios", "pista", "walnut", "walnuts", "akhrot", "hazelnut", "hazelnuts", "pecan", "macadamia", "brazil nut", "tree nuts", "nuts", "nut" ], "exclude_phrases": [ "nutmeg", "coconut", "peanut", "peanuts", "groundnut", "groundnuts", "ground nut", "ground nuts", "doughnut", "butternut", "nut free", "nut-free", "nuts free" ], "notes": { "nuts": "A generic 'nuts' is treated as tree nuts; it may also mean peanuts.", "nut": "A generic 'nut' is treated as tree nuts; it may also mean peanuts." } }, "sesame": { "label": "Sesame", "keywords": [ "sesame", "sesame seeds", "sesame oil", "til", "til seeds", "til oil", "gingelly", "gingelly oil", "tahini" ], "exclude_phrases": [ "sesame free", "sesame-free" ] }, "egg": { "label": "Egg", "keywords": [ "egg", "eggs", "egg powder", "egg white", "egg yolk", "whole egg", "albumin", "albumen", "egg albumin" ], "exclude_phrases": [ "eggless", "egg free", "egg-free", "eggplant" ] }, "fish": { "label": "Fish", "keywords": [ "fish", "fish sauce", "fish oil", "fish extract", "anchovy", "anchovies", "tuna", "salmon", "sardine", "sardines", "mackerel" ], "exclude_phrases": [ "shellfish" ] }, "crustaceans": { "label": "Crustaceans (shellfish)", "keywords": [ "crustacean", "crustaceans", "shellfish", "prawn", "prawns", "shrimp", "shrimps", "crab", "lobster" ], "exclude_phrases": [] }, "mustard": { "label": "Mustard", "keywords": [ "mustard", "mustard seeds", "mustard oil", "mustard powder", "rai", "sarson", "sarson oil" ], "exclude_phrases": [ "mustard free", "mustard-free" ] }, "sulphites": { "label": "Sulphites", "keywords": [ "sulphite", "sulphites", "sulfite", "sulfites", "sulphur dioxide", "sulfur dioxide", "sodium metabisulphite", "sodium metabisulfite", "potassium metabisulphite", "potassium metabisulfite", "metabisulphite", "metabisulfite", "sodium sulphite", "sodium sulfite", "sodium bisulphite", "sodium bisulfite", "potassium bisulphite", "potassium bisulfite" ], "patterns": [ "(?:ins|e)\\s*-?\\s*22[0-8](?![0-9])", "(?:preservatives?|antioxidants?|class\\s*ii\\s*preservatives?)\\s*[:(]?\\s*\\(?\\s*(?:ins\\s*)?22[0-8](?![0-9])" ], "pattern_keyword": "sulphite", "exclude_phrases": [ "sulphite free", "sulphite-free", "sulfite free", "sulfite-free" ], "notes": { "sulphite": "FSSAI requires sulphites to be declared only at 10 mg/kg (as sulphur dioxide) or more; an ingredient list can't show the amount, so a listed sulphite (INS 220-228) means 'present', not 'above the threshold'." }, "source": { "rule": "FSS (Labelling and Display) Regulations, 2020, clause 5(14)(viii): sulphite to be declared when present at 10 mg/kg or more", "verified_from": "FSSAI, 'Frequently Asked Questions (FAQs) on FSS (Labelling & Display) Regulations, 2020', Q23", "url": "https://fssai.gov.in/upload/uploadfiles/files/FAQ_Labelling_Display_23_06_2022.pdf", "sha256": "b8548c58e9e90c2304956d8f40c71bba95fad900cdf04cfe9cc2cec5dccc1576", "checked": "2026-11-12", "caveat": "The full regulation text was not available here; the FAQ (official FSSAI) confirms clause 5(14)(viii) and the 10 mg/kg threshold." } } }, "may_contain_markers": [ "may contain", "may also contain", "may contain traces of", "traces of", "may have traces", "manufactured in a facility", "processed in a facility", "manufactured in a factory", "produced in a factory", "same facility", "shared equipment", "same line" ], "negation_markers": [ "free from", "free of", "no added", "does not contain", "doesn't contain", "without", "non", "no" ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392{ "_source": { "title": "Conditions of Use of the trademark « Nutri-Score » — EXHIBIT 1-B: Specifications of the Updated Algorithm", "publisher": "Santé publique France", "version": "Version dated 26 June 2024, approved by Santé publique France (Updated Algorithm: foods revised 2022, beverages revised 2023)", "pages": "28-32 (Tables 5-10, sections 1-a, 1-b, 2-a, 2-b, 2-c)", "official_url": "https://www.santepubliquefrance.fr/content/download/150258/file/24042023CoU_EN.pdf", "copy_used": "https://www.blv.admin.ch/dam/fr/sd-web/HGZNnGi-OQON/benutzerreglement-nutri-score-en.pdf (official copy hosted by the Swiss Federal Food Safety and Veterinary Office; the santepubliquefrance.fr download aborted)", "copy_sha256": "c8146b9fad26ede0526ebe95a36501b2c97961188657ff65d9f98d49fb73de93", "transcribed": "2026-11-12, by hand from the PDF text of Exhibit 1-B", "not_in_this_document": "Which products count as cheese, red meat, animal/vegetable fats-nuts-seeds, beverages, waters, fruits/vegetables/legumes and non-nutritive sweeteners is defined in the separate Nutri-Score 'Questions & Answers' document (not used here); the app approximates categories (see product category rules in nutriscore.py)." }, "_interpretation": { "thresholds": "Each 'points' list gives the threshold for 1, 2, 3, ... points. Unless stated otherwise points = number of thresholds STRICTLY exceeded (the tables read '0: <= x or < x', 'n: > x').", "boundary_note": "Table 5 lists energy 0 points as '< 335' and 1 point as '> 335' (likewise saturates '< 1' / '> 1', FVL '< 40' / '> 40'); a value exactly on the threshold is given the lower score here.", "fats_ratio_rule": "Table 7 'Saturates/Lipids' is a percentage with '<' bounds (0: < 10, 1: < 16, ... 9: < 64, 10: >= 64), so points = number of thresholds the ratio is GREATER THAN OR EQUAL TO.", "salt": "Tables use salt (g/100 g). When only sodium is printed: salt = sodium x 2.5 (Regulation (EU) No 1169/2011, Annex I, definition 11 — not part of Exhibit 1-B).", "energy": "Tables use kJ. When only kcal is printed: kJ = kcal x 4.184 (not part of Exhibit 1-B)." }, "general": { "table": "Tables 5 and 6, section 1-a", "negative": { "energy_kj": [ 335, 670, 1005, 1340, 1675, 2010, 2345, 2680, 3015, 3350 ], "saturated_fat_g": [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ], "sugars_g": [ 3.4, 6.8, 10, 14, 17, 20, 24, 27, 31, 34, 37, 41, 44, 48, 51 ], "salt_g": [ 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0, 3.2, 3.4, 3.6, 3.8, 4.0 ] }, "positive": { "protein_g": [ 2.4, 4.8, 7.2, 9.6, 12, 14, 17 ], "fibre_g": [ 3.0, 4.1, 5.2, 6.3, 7.4 ], "fvl_percent": { "thresholds": [ 40, 60, 80 ], "points": [ 1, 2, 5 ] } }, "protein_rule": { "exclude_protein_when_n_at_least": 11, "except": [ "cheese" ], "text": "If N < 11 or the product is cheese: score = N - P. If N >= 11: score = N - fibre points - FVL points." }, "red_meat_protein_max_points": 2, "grades": [ { "max": 0, "grade": "A" }, { "max": 2, "grade": "B" }, { "max": 10, "grade": "C" }, { "max": 18, "grade": "D" }, { "max": null, "grade": "E" } ] }, "fats_nuts_seeds": { "table": "Tables 7 and 8, sections 1-b and 2-b", "negative": { "energy_from_saturates_kj": [ 120, 240, 360, 480, 600, 720, 840, 960, 1080, 1200 ], "energy_from_saturates_formula": "saturates (g/100 g) x 37", "sugars_g": [ 3.4, 6.8, 10, 14, 17, 20, 24, 27, 31, 34, 37, 41, 44, 48, 51 ], "saturates_to_lipids_percent": [ 10, 16, 22, 28, 34, 40, 46, 52, 58, 64 ], "salt_g": [ 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0, 3.2, 3.4, 3.6, 3.8, 4.0 ] }, "positive": { "protein_g": [ 2.4, 4.8, 7.2, 9.6, 12, 14, 17 ], "fibre_g": [ 3.0, 4.1, 5.2, 6.3, 7.4 ], "fvl_percent": { "thresholds": [ 40, 60, 80 ], "points": [ 1, 2, 5 ] } }, "protein_rule": { "exclude_protein_when_n_at_least": 7, "except": [], "text": "If N < 7: score = N - P. If N >= 7: score = N - fibre points - FVL points." }, "grades": [ { "max": -6, "grade": "A" }, { "max": 2, "grade": "B" }, { "max": 10, "grade": "C" }, { "max": 18, "grade": "D" }, { "max": null, "grade": "E" } ] }, "beverages": { "table": "Tables 9 and 10, sections 1-b and 2-c (per 100 mL)", "negative": { "energy_kj": [ 30, 90, 150, 210, 240, 270, 300, 330, 360, 390 ], "sugars_g": [ 0.5, 2, 3.5, 5, 6, 7, 8, 9, 10, 11 ], "saturated_fat_g": [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ], "salt_g": [ 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0, 3.2, 3.4, 3.6, 3.8, 4.0 ], "non_nutritive_sweeteners_points": 4 }, "positive": { "protein_g": [ 1.2, 1.5, 1.8, 2.1, 2.4, 2.7, 3.0 ], "fibre_g": [ 3, 4.1, 5.2, 6.3, 7.4 ], "fvl_percent": { "thresholds": [ 40, 60, 80 ], "points": [ 2, 4, 6 ] } }, "protein_rule": { "exclude_protein_when_n_at_least": null, "except": [], "text": "Score = N - P (protein always counted)." }, "waters_grade": "A", "grades": [ { "max": 2, "grade": "B" }, { "max": 6, "grade": "C" }, { "max": 9, "grade": "D" }, { "max": null, "grade": "E" } ] }}1234567"""Image captioning model: pretrained Show, Attend and Tell (ResNet-101, COCO 2014).
- sat_models.py model definitions- convert_checkpoint.py one-time conversion of the .pth.tar to weights/sat_resnet101_coco.pth
Served by app/services/caption_service.py."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.123456"""CATR (CAption TRansformer) model code.
ResNet-101 (dilated) encoder + 6-layer transformer encoder/decoder, BERTword-piece vocabulary, trained on COCO 2017.Served by app/services/caption_service.py when `inference.model: catr`."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116from collections import OrderedDict
import torchimport torch.nn.functional as Fimport torchvisionfrom torch import nnfrom torchvision.models._utils import IntermediateLayerGetterfrom typing import Dict, List
from .utils import NestedTensor
from .position_encoding import build_position_encoding
class FrozenBatchNorm2d(torch.nn.Module): """ BatchNorm2d where the batch statistics and the affine parameters are fixed. Copy-paste from torchvision.misc.ops with added eps before rqsrt, without which any other models than torchvision.models.resnet[18,34,50,101] produce nans. """
def __init__(self, n): super(FrozenBatchNorm2d, self).__init__() self.register_buffer("weight", torch.ones(n)) self.register_buffer("bias", torch.zeros(n)) self.register_buffer("running_mean", torch.zeros(n)) self.register_buffer("running_var", torch.ones(n))
def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs): num_batches_tracked_key = prefix + 'num_batches_tracked' if num_batches_tracked_key in state_dict: del state_dict[num_batches_tracked_key]
super(FrozenBatchNorm2d, self)._load_from_state_dict( state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
def forward(self, x): # move reshapes to the beginning # to make it fuser-friendly w = self.weight.reshape(1, -1, 1, 1) b = self.bias.reshape(1, -1, 1, 1) rv = self.running_var.reshape(1, -1, 1, 1) rm = self.running_mean.reshape(1, -1, 1, 1) eps = 1e-5 scale = w * (rv + eps).rsqrt() bias = b - rm * scale return x * scale + bias
class BackboneBase(nn.Module):
def __init__(self, backbone: nn.Module, train_backbone: bool, num_channels: int, return_interm_layers: bool): super().__init__() for name, parameter in backbone.named_parameters(): if not train_backbone or 'layer2' not in name and 'layer3' not in name and 'layer4' not in name: parameter.requires_grad_(False) if return_interm_layers: return_layers = {"layer1": "0", "layer2": "1", "layer3": "2", "layer4": "3"} else: return_layers = {'layer4': "0"} self.body = IntermediateLayerGetter(backbone, return_layers=return_layers) self.num_channels = num_channels
def forward(self, tensor_list: NestedTensor): xs = self.body(tensor_list.tensors) out: Dict[str, NestedTensor] = {} for name, x in xs.items(): m = tensor_list.mask assert m is not None mask = F.interpolate(m[None].float(), size=x.shape[-2:]).to(torch.bool)[0] out[name] = NestedTensor(x, mask) return out
class Backbone(BackboneBase): """ResNet backbone with frozen BatchNorm.""" def __init__(self, name: str, train_backbone: bool, return_interm_layers: bool, dilation: bool): # LOCAL CHANGE: weights=None (no ImageNet download; the trained CATR # checkpoint provides every weight). torchvision removed `pretrained=`. backbone = getattr(torchvision.models, name)( replace_stride_with_dilation=[False, False, dilation], weights=None, norm_layer=FrozenBatchNorm2d) num_channels = 512 if name in ('resnet18', 'resnet34') else 2048 super().__init__(backbone, train_backbone, num_channels, return_interm_layers)
class Joiner(nn.Sequential): def __init__(self, backbone, position_embedding): super().__init__(backbone, position_embedding)
def forward(self, tensor_list: NestedTensor): xs = self[0](tensor_list) out: List[NestedTensor] = [] pos = [] for name, x in xs.items(): out.append(x) # position encoding pos.append(self[1](x).to(x.tensors.dtype))
return out, pos
def build_backbone(config): position_embedding = build_position_encoding(config) train_backbone = config.lr_backbone > 0 return_interm_layers = False backbone = Backbone(config.backbone, train_backbone, return_interm_layers, config.dilation) model = Joiner(backbone, position_embedding) model.num_channels = backbone.num_channels return model123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657import torchfrom torch import nnimport torch.nn.functional as F
from .utils import NestedTensor, nested_tensor_from_tensor_listfrom .backbone import build_backbonefrom .transformer import build_transformer
class Caption(nn.Module): def __init__(self, backbone, transformer, hidden_dim, vocab_size): super().__init__() self.backbone = backbone self.input_proj = nn.Conv2d( backbone.num_channels, hidden_dim, kernel_size=1) self.transformer = transformer self.mlp = MLP(hidden_dim, 512, vocab_size, 3)
def forward(self, samples, target, target_mask): if not isinstance(samples, NestedTensor): samples = nested_tensor_from_tensor_list(samples)
features, pos = self.backbone(samples) src, mask = features[-1].decompose()
assert mask is not None
hs = self.transformer(self.input_proj(src), mask, pos[-1], target, target_mask) out = self.mlp(hs.permute(1, 0, 2)) return out
class MLP(nn.Module): """ Very simple multi-layer perceptron (also called FFN)"""
def __init__(self, input_dim, hidden_dim, output_dim, num_layers): super().__init__() self.num_layers = num_layers h = [hidden_dim] * (num_layers - 1) self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))
def forward(self, x): for i, layer in enumerate(self.layers): x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x) return x
def build_model(config): backbone = build_backbone(config) transformer = build_transformer(config)
model = Caption(backbone, transformer, config.hidden_dim, config.vocab_size) criterion = torch.nn.CrossEntropyLoss()
return model, criterion1234567891011121314151617181920212223242526272829303132333435363738394041424344
class Config(object): def __init__(self):
# Learning Rates self.lr_backbone = 1e-5 self.lr = 1e-4
# Epochs self.epochs = 30 self.lr_drop = 20 self.start_epoch = 0 self.weight_decay = 1e-4
# Backbone self.backbone = 'resnet101' self.position_embedding = 'sine' self.dilation = True # Basic self.device = 'cpu' # LOCAL CHANGE: device is chosen by the service self.seed = 42 self.batch_size = 32 self.num_workers = 8 self.checkpoint = './checkpoint.pth' self.clip_max_norm = 0.1
# Transformer self.hidden_dim = 256 self.pad_token_id = 0 self.max_position_embeddings = 128 self.layer_norm_eps = 1e-12 self.dropout = 0.1 self.vocab_size = 30522
self.enc_layers = 6 self.dec_layers = 6 self.dim_feedforward = 2048 self.nheads = 8 self.pre_norm = True
# Dataset self.dir = '../coco' self.limit = -112345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485import mathimport torchfrom torch import nn
from .utils import NestedTensor
class PositionEmbeddingSine(nn.Module): """ This is a more standard version of the position embedding, very similar to the one used by the Attention is all you need paper, generalized to work on images. """ def __init__(self, num_pos_feats=64, temperature=10000, normalize=False, scale=None): super().__init__() self.num_pos_feats = num_pos_feats self.temperature = temperature self.normalize = normalize if scale is not None and normalize is False: raise ValueError("normalize should be True if scale is passed") if scale is None: scale = 2 * math.pi self.scale = scale
def forward(self, tensor_list: NestedTensor): x = tensor_list.tensors mask = tensor_list.mask assert mask is not None not_mask = ~mask y_embed = not_mask.cumsum(1, dtype=torch.float32) x_embed = not_mask.cumsum(2, dtype=torch.float32) if self.normalize: eps = 1e-6 y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale
dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device) dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats)
pos_x = x_embed[:, :, :, None] / dim_t pos_y = y_embed[:, :, :, None] / dim_t pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).flatten(3) pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3) pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2) return pos
class PositionEmbeddingLearned(nn.Module): """ Absolute pos embedding, learned. """ def __init__(self, num_pos_feats=256): super().__init__() self.row_embed = nn.Embedding(50, num_pos_feats) self.col_embed = nn.Embedding(50, num_pos_feats) self.reset_parameters()
def reset_parameters(self): nn.init.uniform_(self.row_embed.weight) nn.init.uniform_(self.col_embed.weight)
def forward(self, tensor_list: NestedTensor): x = tensor_list.tensors h, w = x.shape[-2:] i = torch.arange(w, device=x.device) j = torch.arange(h, device=x.device) x_emb = self.col_embed(i) y_emb = self.row_embed(j) pos = torch.cat([ x_emb.unsqueeze(0).repeat(h, 1, 1), y_emb.unsqueeze(1).repeat(1, w, 1), ], dim=-1).permute(2, 0, 1).unsqueeze(0).repeat(x.shape[0], 1, 1, 1) return pos
def build_position_encoding(config): N_steps = config.hidden_dim // 2 if config.position_embedding in ('v2', 'sine'): # TODO find a better way of exposing other arguments position_embedding = PositionEmbeddingSine(N_steps, normalize=True) elif config.position_embedding in ('v3', 'learned'): position_embedding = PositionEmbeddingLearned(N_steps) else: raise ValueError(f"not supported {config.position_embedding}")
return position_embedding.gitattributesAdded+1
.gitignoreAdded+49
README.mdAdded+346
app.pyAdded+19
backend/.dockerignoreAdded+7
backend/.env.exampleAdded+21
backend/DockerfileAdded+22
backend/app/__init__.pyAdded
backend/app/config.pyAdded+54
backend/app/dependencies.pyAdded+53
backend/app/main.pyAdded+53
backend/app/routes/__init__.pyAdded
backend/app/routes/caption.pyAdded+48
backend/app/routes/health.pyAdded+40
backend/app/routes/plant.pyAdded+54
backend/app/routes/prescription.pyAdded+25
backend/app/routes/product_label.pyAdded+45
backend/app/schemas/__init__.pyAdded+29
backend/app/schemas/plant.pyAdded+57
backend/app/schemas/prescription.pyAdded+15
backend/app/schemas/product_label.pyAdded+11
backend/app/services/__init__.pyAdded
backend/app/services/caption_service.pyAdded+105
backend/app/services/captioners/blip.pyAdded+127
backend/app/services/captioners/catr.pyAdded+207
backend/app/services/captioners/common.pyAdded+63
backend/app/services/captioners/sat.pyAdded+276
backend/app/services/plant_service.pyAdded+32
backend/app/services/prescription_service.pyAdded+44
backend/app/services/product_label_service.pyAdded+80
backend/app_gradio.pyAdded+336
backend/configs.yamlAdded+31
backend/data/eval/eval_after.jsonAdded+339
backend/data/eval/eval_before.jsonAdded+292
backend/data/eval/prescriptions/README.mdAdded+56
backend/data/eval/product_labels/README.mdAdded+39
backend/data/medicines/known_brands.jsonAdded+887
backend/data/medicines/updated_indian_medicine_data.csvAdded+3
backend/data/medicines/uses_by_ingredient.jsonAdded
backend/data/product_label/additives.jsonAdded
backend/data/product_label/allergens.jsonAdded+349
backend/data/product_label/nutriscore_thresholds.jsonAdded+392
backend/model/__init__.pyAdded
backend/model/captioning/__init__.pyAdded+7
backend/model/captioning/catr/LICENSEAdded+201
backend/model/captioning/catr/__init__.pyAdded+6
backend/model/captioning/catr/backbone.pyAdded+116
backend/model/captioning/catr/caption.pyAdded+57
backend/model/captioning/catr/configuration.pyAdded+44
backend/model/captioning/catr/position_encoding.pyAdded+85