Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions .agents/skills/jarvis-docs-sync/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ Check these documentation targets:
- `docs/**/*.md`

Also check local skill docs only if they are directly affected by the change being documented.
Check linked local images or generated diagrams when their source description changed.

## Workflow

Expand All @@ -34,10 +35,18 @@ Also check local skill docs only if they are directly affected by the change bei
- `.github/workflows/*.yml`
- `.dvc/config*`
- `backend/models/*.dvc`
- Map each fact family to its documentation surface:
- `package.json` and `playwright.config.*` -> local test commands and test scope
- `.github/workflows/*.yml` -> CI-only claims
- `backend/app.py` -> endpoints, environment variables, limits, readiness, and errors
- `src/ocr/config.js` and `src/ocr/pipeline.js` -> active OCR behavior and guardrails
- dataset manifests and `assets/meter_readings.csv` -> current counts and split claims
- safety scripts under `scripts/` -> DVC, QA startup, and artifact-retention instructions

2. Compare the docs against those facts.
- Look for stale commands, ports, file paths, model names, dataset counts, workflow steps, artifact-retention rules, and benchmark expectations.
- Use `rg` to find repeated claims across docs before editing.
- Separate active claims from dated history. Keep historical benchmark snapshots intact when they are clearly dated or described as `then-current`; update wording that incorrectly presents an old snapshot as current.

3. Update only what is actually stale.
- Do not rewrite docs for style alone.
Expand All @@ -52,19 +61,31 @@ Also check local skill docs only if they are directly affected by the change bei
- Re-run `rg` for the old value to make sure stale references are gone where appropriate.
- Confirm every referenced command, path, and filename exists.
- If documentation mentions tests or benchmarks, verify the names and entry points still match the repo.
- Run `git diff --check`.
- Do not infer a passing test count by counting declarations. Execute the corresponding suite before adding or refreshing a `passes (N/N)` claim.
- Treat UI OCR metrics as verified only when a fresh **Run test set** result is available. Otherwise remove or soften the current claim instead of copying an older number forward.
- If a Markdown diagram has a checked-in rendered image, update both or leave the diagram source unchanged.

6. Report the audit boundary.
- List the documents changed and the primary facts used.
- Call out checks that remain local-only or claims that could not be re-verified.
- Do not run training, DVC push, artifact publishing, dataset ingestion, or other state-changing workflows merely to validate documentation.

## Audit Checklist

Always verify these categories when relevant:

- Dev/test commands and required environments
- Local test suites versus the subset actually run in CI
- Frontend and backend ports/endpoints
- OCR pipeline behavior and guardrails
- Model filenames and default checkpoint paths
- Dataset rebuild commands and artifact-retention process
- DVC usage and backup expectations
- CI workflows and local validation steps
- Skill-specific workflows under `.agents/skills/`
- Active baseline claims versus dated historical snapshots
- Linked generated diagrams and local documentation assets

## Useful Commands

Expand All @@ -76,6 +97,15 @@ Always verify these categories when relevant:
- `find docs -type f -name '*.md' | sort`
- AGENTS inventory:
- `find . -type f -name 'AGENTS.md' | sort`
- Local skill inventory:
- `find .agents/skills -type f -name 'SKILL.md' | sort`
- Current corpus and ROI split facts:
- `awk 'END { print NR - 1 }' assets/meter_readings.csv`
- `backend/.venv/bin/python -c "import collections,json; data=json.load(open('backend/data/roi_dataset/splits.json'))['assignments']; print(collections.Counter(data.values()))"`
- Configured test entry points:
- `npm pkg get 'scripts.test:scripts' 'scripts.test:backend' 'scripts.test:e2e'`
- Validation:
- `git diff --check`
- Search stale values:
- `rg -n "<old-term>|<old-path>|<old-command>" AGENTS.md backend/AGENTS.md src/ocr/AGENTS.md README.md backend/README.md docs .agents/skills`
- Search current values:
Expand All @@ -86,3 +116,4 @@ Always verify these categories when relevant:
- Prefer fixing the docs in the same change set as the code change that made them stale.
- If the code is ambiguous, resolve the ambiguity from the implementation before editing docs.
- If a statement cannot be verified from the repo, remove or soften it instead of leaving a hard claim.
- Avoid bare words such as `current` next to old dates or corpus sizes; use `historical`, `then-current`, or point to the active baseline source.
2 changes: 1 addition & 1 deletion .agents/skills/jarvis-meter-to-roi-sync/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ Use `backend/.venv` for any Python step in this workflow. Do not rely on the sys
- Run `dvc add assets/<new-meter-file>` for each newly ingested canonical photo.
- For Mac/iCloud imports, DVC-track the converted `meter_YYYYMMDD.JPEG`, not the original `IMG_*.HEIC`/`IMG_*.HEIF`.
- If DVC tries to use an unwritable system cache such as `/Library/Caches/dvc`, rerun with `DVC_SITE_CACHE_DIR=/tmp/dvc-site-cache`.
- Run `scripts/dvc-push-safe.sh` if a DVC remote is configured
- Run `scripts/dvc-push-safe.sh` only with a configured off-machine remote. The guard refuses plain local paths and `file://` URLs.
- Only do this after the user has approved the ROI overlays for the new image(s).

12. Validate and summarize.
Expand Down
4 changes: 3 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
## Build, Test, and Development Commands
- `npm run serve`: Start the local web server on port `8000`.
- `npm run dev`: Alias of `npm run serve`.
- `npm run test:scripts`: Run tests for QA service guards and artifact/DVC safety scripts.
- `npm run test:backend`: Run backend API, ROI dataset, and runtime crop unit tests.
- `npm run test:e2e`: Run Playwright end-to-end tests.
- `npm run benchmark:roi-diff`: Generate ROI checkpoint diff artifacts.

Expand Down Expand Up @@ -62,7 +64,7 @@ Open `http://localhost:8000` after starting the frontend server.
- `backend/data/digit_dataset/sections_synthetic/train.dvc`
- per-file DVC tracking for promoted `backend/models/*.pt`
- After dataset ingestion or model promotion, run the relevant `dvc add ...` commands, then push with `scripts/dvc-push-safe.sh`.
- Never run raw `dvc push` directly in this repo. Always use `scripts/dvc-push-safe.sh`; it requires a configured non-local DVC remote and refuses to push to plain local paths.
- Never run raw `dvc push` directly in this repo. Always use `scripts/dvc-push-safe.sh`; it requires a configured non-local DVC remote and refuses plain local paths and `file://` URLs.
- For cloud storage, prefer Backblaze B2. Install `dvc[s3]` in `backend/.venv` and configure the DVC remote through B2's S3-compatible endpoint.
- Use `scripts/package-tier1-artifacts.sh` plus the manual `Publish Artifacts` workflow for release-style snapshots after the DVC remote is up to date.

Expand Down
16 changes: 12 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ find assets -maxdepth 1 -type f \( -iname 'meter_*.jpg' -o -iname 'meter_*.jpeg'
scripts/dvc-push-safe.sh
```

Do not run raw `dvc push` directly in this repo. `scripts/dvc-push-safe.sh` activates `backend/.venv`, checks that a default DVC remote is configured, and refuses to push if the remote is a plain local path instead of a cloud/object-store URL.
Do not run raw `dvc push` directly in this repo. `scripts/dvc-push-safe.sh` activates `backend/.venv`, checks that a default DVC remote is configured, and refuses plain local paths and `file://` URLs instead of treating them as off-machine storage.

Configure an off-machine DVC remote once before using `scripts/dvc-push-safe.sh`.

Expand All @@ -170,6 +170,8 @@ Then create a backup archive when you want a releaseable snapshot:
scripts/package-tier1-artifacts.sh
```

The generated `.sha256` file names the archive by basename, so it can be verified from the download directory with `sha256sum -c <archive>.tar.gz.sha256`.

For GitHub-hosted retention, set the `DVC_REMOTE_URL`, `DVC_REMOTE_ACCESS_KEY_ID`, and `DVC_REMOTE_SECRET_ACCESS_KEY` repository secrets (plus optional `DVC_REMOTE_SESSION_TOKEN` if your remote uses temporary credentials), then use the manual `Publish Artifacts` workflow to `dvc pull`, package, and upload a release snapshot.

For dataset expansion/QA before retraining:
Expand Down Expand Up @@ -199,14 +201,18 @@ Check backend readiness with:
curl -s http://127.0.0.1:8001/health
```

### E2E Tests
### Tests

Run Playwright checks for neural-ROI failure handling and OCR selection guard regressions:
Run the complete local regression set from the repo root:

```bash
npm run test:scripts
npm run test:backend
npm run test:e2e
```

The script suite covers QA service/checkpoint guards plus DVC and artifact-packaging safety. The backend suite covers API image handling, ROI dataset behavior, and runtime crop geometry. Playwright covers UI state, neural-ROI failure handling, and OCR selection guard regressions.

Generate a per-image ROI checkpoint comparison report (`roi-rotaug-e30-640.pt` vs `roi.pt`) with stage `5/6` debug snapshots:

```bash
Expand Down Expand Up @@ -236,7 +242,9 @@ npm run qa:roi-geometry-audit

These write timestamped reports under `output/strip-dataset-qa/`, `output/ocr-candidate-oracle/`, `output/strip-runtime-qa/`, `output/cell-crop-failure-qa/`, and `output/roi-geometry-audit/`. Use `qa:strip-dataset` after rebuilding digit windows and before retraining, so the canonical strips can be visually accepted first.

CI runs these tests on every pull request and on pushes to `master`.
The browser-based OCR QA runners fail fast if a reused backend is not ready with the canonical promoted ROI and digit-classifier checkpoints.

CI runs the Chromium Playwright suite on every pull request and on pushes to `master`. `test:scripts` and `test:backend` are currently required local checks and are not run by `.github/workflows/e2e.yml`.

## File Overview
- `index.html`: UI layout.
Expand Down
4 changes: 3 additions & 1 deletion backend/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@
- Create the backend virtualenv with `cd backend && uv venv .venv && source .venv/bin/activate && uv pip install -r requirements.txt`.
- For any Python task that depends on computer-vision packages or image tooling (for example `ultralytics`, `opencv`, or `Pillow`), use `backend/.venv` rather than the system Python.
- Run the API with `cd backend && source .venv/bin/activate && uvicorn app:app --host 127.0.0.1 --port 8001 --reload`.
- Run backend regression tests from the repo root with `npm run test:backend`.
- In this Codex environment, if the service must be consumed by the DevTools browser, starting `uvicorn` inside the sandbox may not be reachable from the page. Prefer restarting it with escalated permissions when browser fetches to `127.0.0.1:8001` fail.

## API and Runtime Expectations
- Frontend/backend default ports are `127.0.0.1:8000` and `127.0.0.1:8001`.
- Health check: `GET /health` should report `ready: true`, `roi_ready: true`, `digit_ready: true`, `strip_digit_ready: true`, `strip_digit_23xx_ready: true`, and the expected model paths when all checkpoints are present.
- Health check: `GET /health` should report `ready: true`, `roi_ready: true`, `digit_ready: true`, `strip_digit_ready: true`, `strip_digit_23xx_ready: true`, `max_upload_bytes`, and the expected model paths when all checkpoints are present.
- Image endpoints read at most `MAX_UPLOAD_BYTES + 1` bytes per uploaded file and return HTTP `413` above the configured limit; the default limit is 20 MiB.
- Default ROI endpoint: `http://127.0.0.1:8001/roi/detect`
- Default digit endpoint: `http://127.0.0.1:8001/digit/predict-cells`
- Default strip-reader shadow endpoint: `http://127.0.0.1:8001/digit/predict-strip`
Expand Down
13 changes: 11 additions & 2 deletions backend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ python train_digit_classifier.py \
--copy-to runs/digit-classifier-finetune-runtime/digit_classifier.pt
```

May 24, 2026 recovery result: grouped CV improved from restored baseline `51.8%` per-cell accuracy to clean-only `61.6%` and clean + curated-runtime-failure `66.1%`, but the final challenger failed the then-28-image UI promotion gate (`3/28` exact, `MAE 139.11`, `1` no-read) versus the restored checkpoint with the conservative geometry ranker (`10/28` exact, `MAE 61.22`, `1` no-read). The promoted checkpoint therefore remains `backend/models/digit_classifier.pt`. The current May 29, 2026 29-image UI baseline is tracked in `src/ocr/AGENTS.md` and `docs/ocr-tuning-playbook.md`.
May 24, 2026 recovery result: grouped CV improved from restored baseline `51.8%` per-cell accuracy to clean-only `61.6%` and clean + curated-runtime-failure `66.1%`, but the final challenger failed the then-28-image UI promotion gate (`3/28` exact, `MAE 139.11`, `1` no-read) versus the restored checkpoint with the conservative geometry ranker (`10/28` exact, `MAE 61.22`, `1` no-read). The promoted checkpoint therefore remains `backend/models/digit_classifier.pt`. The active UI baseline is tracked in `src/ocr/AGENTS.md` and `docs/ocr-tuning-playbook.md`; May 2026 numbers are historical snapshots only.

## Train the whole-strip shadow reader

Expand Down Expand Up @@ -254,15 +254,23 @@ Readiness check:
curl -s http://127.0.0.1:8001/health
```

Run backend regression tests from the repo root:

```bash
npm run test:backend
```

## 4) Endpoints

- `GET /health`: model readiness (`ready`, `roi_ready`, `digit_ready`, `strip_digit_ready`, `strip_digit_23xx_ready`) + effective model/device config.
- `GET /health`: model readiness (`ready`, `roi_ready`, `digit_ready`, `strip_digit_ready`, `strip_digit_23xx_ready`) + effective model/device config and `max_upload_bytes`.
- `POST /roi/detect`: multipart upload (`image`) and returns normalized bbox + confidence.
- `POST /digit/predict`: multipart upload (`image`) and returns the predicted digit + confidence.
- `POST /digit/predict-cells`: multipart upload (`images`, repeated field) for batch cell decoding.
- `POST /digit/predict-strip`: multipart upload (`image`) for direct fixed-length 4-digit strip decoding.
- `POST /digit/predict-strip-23xx`: multipart upload (`image`) for guarded house-specific `23xx` suffix decoding.

All image fields default to a 20 MiB per-file limit and return HTTP `413` when exceeded. Override the limit with `MAX_UPLOAD_BYTES`.

Frontend integration defaults:
- ROI detection path is `http://127.0.0.1:8001/roi/detect` and is required for OCR.
- Digit classifier path is `http://127.0.0.1:8001/digit/predict-cells` and is only used when `OCR_CONFIG.digitClassifier.enabled=true`.
Expand All @@ -272,6 +280,7 @@ Frontend integration defaults:

## Environment Variables

- `MAX_UPLOAD_BYTES`: maximum bytes read from each uploaded image (default: `20971520`).
- `ROI_MODEL_PATH`: path to `.pt` weights (default: `backend/models/roi-rotaug-e30-640.pt`)
- `ROI_DEFAULT_CONFIDENCE`: detection confidence threshold (default: `0.05`)
- `ROI_DEFAULT_IOU`: NMS IoU threshold (default: `0.5`)
Expand Down
26 changes: 19 additions & 7 deletions backend/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import numpy as np
from fastapi import FastAPI, File, HTTPException, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from PIL import Image, UnidentifiedImageError
from PIL import Image, ImageOps, UnidentifiedImageError

try:
from .detector import DetectorUnavailableError, RoiDetector
Expand Down Expand Up @@ -58,6 +58,7 @@ def _env_int(name: str, default: int) -> int:
DEFAULT_CONFIDENCE = _env_float("ROI_DEFAULT_CONFIDENCE", 0.05)
DEFAULT_IOU = _env_float("ROI_DEFAULT_IOU", 0.5)
DEFAULT_IMGSZ = _env_int("ROI_DEFAULT_IMGSZ", 960)
MAX_UPLOAD_BYTES = max(1, _env_int("MAX_UPLOAD_BYTES", 20 * 1024 * 1024))
DEFAULT_DIGIT_MODEL_PATH = BASE_DIR / "models" / "digit_classifier.pt"
DIGIT_MODEL_PATH = Path(os.getenv("DIGIT_MODEL_PATH", str(DEFAULT_DIGIT_MODEL_PATH))).expanduser().resolve()
DIGIT_MIN_CONFIDENCE = _env_float("DIGIT_MIN_CONFIDENCE", 0.0)
Expand Down Expand Up @@ -185,11 +186,21 @@ def get_strip_digit_reader_23xx() -> StripDigitReader23xx:
def _load_rgb_image(file_bytes: bytes) -> np.ndarray:
try:
with Image.open(io.BytesIO(file_bytes)) as image:
rgb = image.convert("RGB")
rgb = ImageOps.exif_transpose(image).convert("RGB")
return np.array(rgb)
except UnidentifiedImageError as error:
raise HTTPException(status_code=400, detail="Unsupported image format.") from error


async def _read_upload_bytes(upload: UploadFile, max_bytes: int = MAX_UPLOAD_BYTES) -> bytes:
file_bytes = await upload.read(max_bytes + 1)
if len(file_bytes) > max_bytes:
raise HTTPException(
status_code=413,
detail=f"Upload too large; limit is {max_bytes} bytes."
)
return file_bytes

@app.get("/health")
def health() -> dict:
roi_model_exists = MODEL_PATH.exists()
Expand Down Expand Up @@ -253,6 +264,7 @@ def health() -> dict:
"default_confidence": DEFAULT_CONFIDENCE,
"default_iou": DEFAULT_IOU,
"default_imgsz": DEFAULT_IMGSZ,
"max_upload_bytes": MAX_UPLOAD_BYTES,
"digit_min_confidence": DIGIT_MIN_CONFIDENCE,
"digit_top_k": DIGIT_TOP_K,
"strip_digit_min_confidence": STRIP_DIGIT_MIN_CONFIDENCE,
Expand All @@ -273,7 +285,7 @@ async def detect_roi(image: UploadFile = File(...)) -> dict:
except DetectorUnavailableError as error:
raise HTTPException(status_code=503, detail=str(error)) from error

file_bytes = await image.read()
file_bytes = await _read_upload_bytes(image)
if not file_bytes:
raise HTTPException(status_code=400, detail="Empty upload.")

Expand Down Expand Up @@ -317,7 +329,7 @@ async def predict_digit(image: UploadFile = File(...)) -> dict:
except DigitClassifierUnavailableError as error:
raise HTTPException(status_code=503, detail=str(error)) from error

file_bytes = await image.read()
file_bytes = await _read_upload_bytes(image)
if not file_bytes:
raise HTTPException(status_code=400, detail="Empty upload.")

Expand Down Expand Up @@ -353,7 +365,7 @@ async def predict_digit_cells(images: list[UploadFile] = File(...)) -> dict:
predictions = []
accepted_count = 0
for upload in images:
file_bytes = await upload.read()
file_bytes = await _read_upload_bytes(upload)
if not file_bytes:
predictions.append({
"ok": False,
Expand Down Expand Up @@ -397,7 +409,7 @@ async def predict_digit_strip(image: UploadFile = File(...)) -> dict:
except StripDigitReaderUnavailableError as error:
raise HTTPException(status_code=503, detail=str(error)) from error

file_bytes = await image.read()
file_bytes = await _read_upload_bytes(image)
if not file_bytes:
raise HTTPException(status_code=400, detail="Empty upload.")

Expand Down Expand Up @@ -428,7 +440,7 @@ async def predict_digit_strip_23xx(image: UploadFile = File(...)) -> dict:
except StripDigitReader23xxUnavailableError as error:
raise HTTPException(status_code=503, detail=str(error)) from error

file_bytes = await image.read()
file_bytes = await _read_upload_bytes(image)
if not file_bytes:
raise HTTPException(status_code=400, detail="Empty upload.")

Expand Down
Loading
Loading