Files
pfm-ocr/CLAUDE.md
T
Rafhan Mazaya FathurrahmanandClaude Fable 5 721dea41dc fix(backend): date-parser fixes + extract cascade into date_extract.py; note global graphify install
Split the expiry-date extraction cascade out of classify_ocr_server.py into
config/date_extract.py (pure regex, importable/testable without loading
models). Three behavioral fixes, offline-regressed against all 79 captured
OCR line-sets and sanity-verified live on the two target images:

- Guard the 012/112 month-misrecognition cleanup rules: they fired on
  perfectly valid dates too (BB 01122026 = 01/12/2026 matches 0+112+2026)
  and mangled them into 7-digit junk that parsed as 00/22/26. Skipped when
  the line already contains a valid date. Fixes image 11.
- Exclude store price-tag lines (Printed:.., Rp...) from the keyword-less
  stages so a shelf label's print timestamp can't shadow the real date
  printed on the package. Fixes image 71 (09/04/2027).
- Validity-gate the lenient stage (day<=31, month<=12, year 2020-2039) so
  garbled digit runs return empty instead of junk like 1/3/06 or 11/1/01.

Also: clamp /probe-ocr crop box to image bounds (PIL pads out-of-bounds
crops into a gigapixel canvas -> DecompressionBombError), and update
CLAUDE.md's Graphify section - the global Claude Code skill integration was
installed 2026-07-15 at the user's explicit request.

Full-batch measurement of these fixes (expected 79.7% -> ~80.6%) is still
pending - the run was stopped twice at the user's end; re-run
scripts/accuracy-check-scan.mts next session before building on this.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gr6HH7JrdsXX8AARejQboM
2026-07-14 22:20:22 +07:00

122 lines
8.6 KiB
Markdown

# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## What this repo is
An on-premise, GPU-accelerated OCR system that turns a Prima Fresh Mart store staff member's phone photo of a Delivery Order (DO) into structured, database-backed data. The app's users are **store staff (petugas toko) on duty at each store**, not delivery drivers — each login account is bound to exactly one store (`accounts.role = 'store'`). A **Flutter mobile app** (this root) is the store-facing client; a **Dockerized backend** (`backend/`) runs the Next.js API gateway, the PaddleOCR/vLLM pipeline, and Postgres.
Read `README.md` first for the full architecture (mermaid diagrams, tech stack, accuracy numbers). Read `backend/CLAUDE.md` before touching anything under `backend/` — it documents backend-specific history, gotchas, and confidentiality notes not repeated here.
## Repository structure
```
lib/ # Flutter app (this is the root Dart package)
config/ app_config.dart — theme + dynamic API base URL resolution
core/ Dio client, Hive storage, geolocation, go_router
features/ auth, camera, documents, editor, splash — one folder per feature
models/
test/ # Flutter widget/unit tests (flat, not mirrored to lib/)
backend/ # Next.js gateway + Python OCR pipeline + Postgres (see backend/CLAUDE.md)
docs/ # Deep-dive workflow & extraction-rule docs
docker-compose.yml # Canonical backend stack — always run from repo root, not backend/
docker-compose.demo.yml # Production-mode override (npm start instead of npm run dev)
start-dev-tunnel.ps1 # Syncs LAN IP into app_config.dart + starts ngrok
```
**Two `docker-compose.yml` files exist** (`./docker-compose.yml` and `backend/docker-compose.yml`, a legacy standalone duplicate with a different Compose project name). Always run `docker compose` from the repo root — running it from inside `backend/` causes container-name conflicts with anything already started from root.
## Commands
### Flutter app (repo root)
```bash
flutter pub get # install deps
flutter run # run on connected device/emulator
flutter test # run all tests in test/
flutter test test/blur_detector_test.dart # run a single test file
flutter analyze lib # static analysis (flutter_lints)
flutter build apk --release # release APK -> build/app/outputs/flutter-apk/app-release.apk
./start-dev-tunnel.ps1 # detect LAN IP, patch app_config.dart, start ngrok
```
The release APK is currently debug-signed (`android/app/build.gradle.kts` has a TODO for a real signing config) — fine for internal installs, not Play Store distribution.
### Backend (from repo root)
```bash
cp backend/.env.example backend/.env # first-time setup; set CUDA_VISIBLE_DEVICES
docker compose up --build # full stack (dev mode, hot-reloads pfm-web-app)
docker compose -f docker-compose.yml -f docker-compose.demo.yml up -d --build # production mode, rebuild before every demo
```
**Policy for Demo vs. Development:**
- **Local Development**: ALWAYS use `docker compose up` (`npm run dev`). It enables hot-reloading for rapid iteration.
- **Demos / Field Testing**: YOU MUST use the `.demo.yml` override shown above (`npm start`). The development server has a known throughput ceiling and will bottleneck if multiple devices upload simultaneously. Do not run client demonstrations using the dev server.
See `backend/CLAUDE.md` for the Next.js app commands (`npm run dev/build/lint`), the accuracy regression harness, and the uv/vLLM Python service commands.
## Architecture notes for the Flutter client
- **API base URL is resolved dynamically at startup**, not hardcoded to one value: `AppConfig.initializeApiBaseUrl()` in `lib/config/app_config.dart` tries a hardcoded LAN IP first, falling back to a fixed ngrok domain. If login/upload fails on a device, this is the first thing to check — re-run `start-dev-tunnel.ps1` if the host machine's LAN IP or ngrok tunnel has gone stale.
- **Upload flow**: capture → Laplacian-variance blur check → GPS tag → multipart upload → the app polls `GET /documents` every 2s (up to ~4.3 min, 130 retries) until the backend's OCR pass sets `parsed=true` → operator reviews/corrects on-device → `PUT /documents/:id` saves final data → PDF receipt generated/printed locally.
- **Pending-upload queue is persisted to a Hive box** (`lib/features/documents/pending_documents_provider.dart`, `lib/core/storage/local_storage.dart`) — an OS-level app kill mid-upload no longer loses the document; on next launch the queue reloads and resumes anything left non-terminal (fixed 2026-07-08, see `plans/next-enhancements.md` §3.1).
- Auth (`lib/features/auth/`) performs real token verification against the backend `api/v1/auth/login` endpoint. Do not treat it as a demo stub anymore.
## Confidentiality
`backend/` contains real client business data committed to source (SKU/vendor/customer master data, scanned DO photos, hand-labeled ground truth) — see `backend/CLAUDE.md`'s Confidentiality section before exporting, logging, or sharing anything from `backend/sources/` or `backend/uploads/`.
## Code structure queries (Graphify)
An AST-derived knowledge graph of this repo lives in `graphify-out/` (gitignored;
rebuilt automatically by `.git/hooks/post-commit`/`post-checkout`). It is pure
tree-sitter AST + local graph algorithms — no LLM/API key involved (clustering was
run with `--no-label` to skip the optional LLM community-naming step).
- **Prefer it for structural/relationship questions** — "what calls X", "what
breaks if Y is renamed", "where is Z used" — via `graphify query "..."` /
`graphify explain "X"` / `graphify affected "X"` against `graphify-out/graph.json`.
These return a small, token-budgeted slice of the graph, which is usually cheaper
than Grep-then-Read across several files for broad/architectural questions.
- **Still Read the actual file** before editing it, or whenever the question
depends on exact logic/values — the graph captures structure (nodes/edges/call
relationships), not full source text.
- The global Claude Code integration (`graphify install --platform claude`) **was
installed 2026-07-15 at the user's explicit request** (it had previously been
deferred). It wrote `~/.claude/skills/graphify/SKILL.md` (678 lines, auto-loads
across all projects, fires on codebase/architecture questions and `/graphify`) and
a 3-line `~/.claude/CLAUDE.md` pointer. Content comes from the third-party
`graphify` pip package — re-review after any `pip install -U graphify`.
- `graphify.exe` is not on PATH (Windows user pip install) — invoke via full path
`%APPDATA%\Roaming\Python\Python312\Scripts\graphify.exe` or add that dir to PATH.
## Agents Settings Kit
@AGENTS.md
The rules above are the shared, cross-tool source of truth for the `e`/`enhance` and
`n`/`next` enhancement workflow — kept in `AGENTS.md`, not duplicated here, so
Cursor/Copilot/other agents stay in sync (see `docs/vibe-coding/` if that directory
is added later). Roles referenced above are defined in `SKILLS.md`. The workflow's
backlog and shipped-feature log live in `plans/next-enhancements.md` and
`docs/feature-list.md` respectively — see `AGENTS.md`'s Adaptation Notes for how
those coexist with this repo's pre-existing `.agents/AGENTS.md` (OCR parsing rules)
and `plans/next-enhancement-plan.md` (a separate, already-`[DONE]` QA checklist).
**Scope: this kit excludes `backend/`.** `AGENTS.md`'s "Scope" section (top of the
file) is authoritative — the `e`/`n` workflow, its §3 file-size enforcement, and its
§5/§6 Demo-Live/Cloud-Local switches apply to the Flutter app only. `backend/` keeps
its own pre-existing `backend/CLAUDE.md` + `backend/AGENTS.md`; don't run `e`/`n`
against backend modules or apply this kit's generic rules there unless the user
explicitly asks for a backend-scoped run.
Claude-specific notes:
- **Role subagents**: when a task benefits from a fresh, unbiased pass — code review,
QA verification, architecture check — spawn the relevant `SKILLS.md` role via the
`Agent` tool instead of continuing in the current context. This mirrors the
"review in a fresh context window" practice: a context that has been implementing
a feature is a worse reviewer of that same feature.
- **Clarifying questions** (AGENTS.md §2a): use `AskUserQuestion` for the one-at-a-time
grilling step, not free-text questions buried in a longer response.
- **Plan mode**: for any `n`/`next` task that touches multiple files or has more than
one reasonable implementation approach, use `EnterPlanMode` before writing code.