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
7 changes: 4 additions & 3 deletions PLAN.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# PLAN.md

Status as of 2026-11-01: research done; Gate 0 partial; Gate 1: line-F1 margin +5.6 pts (rule needs +10) but flag accuracy 100% vs 77% and 0/8 vs 4/8 false alarms; full app verified end to end on Docker; Gate 2 waived; continuing as a portfolio project. Skeleton app (FastAPI, Celery, MongoDB, MinIO, Next.js) exists but is not validated end to end, and the owner chose to build it ahead of the gates. See `docs/GATE1_RESULTS.md`.
Status as of 2026-11-28: research done; Gate 0 partial; Gate 1 re-measured after a baseline fix: the deskew baseline now leads on line F1 (0.985 vs Gemini 0.961), and Gemini's end-to-end edge is 2 of 31 cases on flags and 0/8 vs 1/8 false alarms, so AI does not clearly beat the baseline (owner to decide what this means for the project); full app verified end to end on Docker; Gate 2 waived; continuing as a portfolio project. Skeleton app (FastAPI, Celery, MongoDB, MinIO, Next.js) exists but is not validated end to end, and the owner chose to build it ahead of the gates. See `docs/GATE1_RESULTS.md`.

## Phases
1. **Research** — done. See `PRODUCT_RESEARCH.md`. 5 ideas assessed: 2 rejected, 2 on hold, 1 conditional candidate (Bill↔EOB Reconciler).
Expand All @@ -11,8 +11,9 @@ Status as of 2026-11-01: research done; Gate 0 partial; Gate 1: line-F1 margin +
6. **Publish** — repo `CodeAvk/eob-reconciler` (public) exists. Each push follows the checklist in `CLAUDE.md` plus tests and a security scan. Since 2026-11-11, GitHub Actions CI runs the backend tests, frontend build, dependency audits and a gitleaks scan on every push to `main` and every pull request.

## Next actions
- [ ] Run Gemini on the 2 unscored hard cases (case_027, case_031) when quota resets.
- [ ] Optionally fix the baseline's long-date handling and re-measure the AI margin.
- [ ] Run Gemini on the last unscored hard case (case_031) when quota resets.
- [x] Fix the baseline's long-date handling and re-measure the AI margin (2026-11-28).
- [ ] Owner decision: does the project still meet the rule that AI must beat a simpler baseline?
- [x] Synthetic generator, baseline and evaluation harness (done 2026-10-30).
- [x] Interview script drafted (`docs/INTERVIEW_SCRIPT.md`), kept as an optional path only.
- [x] End-to-end run of the full app with Docker (2026-11-01): fixed Redis port clash, CORS config and evidence citations.
Expand Down
23 changes: 13 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,20 +88,22 @@ flowchart LR

The workspace rule is that AI must beat a simpler non-AI baseline, so this was measured. Documents are synthetic with known ground truth and injected errors. The baselines use free OCR (RapidOCR) plus regex, one of them with page deskewing.

Hard set, 30 cases (tilt, blur, noise, varied date and code formats). Full detail and caveats are in [docs/GATE1_RESULTS.md](docs/GATE1_RESULTS.md).
Hard set, 31 cases (tilt, blur, noise, varied date and code formats), re-measured on 2026-11-28 after a baseline fix. Full detail and caveats are in [docs/GATE1_RESULTS.md](docs/GATE1_RESULTS.md).

| Extractor | Line F1 | Flags exactly right | Injected errors found | False alarms on clean bills |
|---|---|---|---|---|
| OCR + regex | 0.697 | 63% | 20 / 22 | 6 of 8 |
| OCR + regex + deskew | 0.914 | 77% | 21 / 22 | 4 of 8 |
| Gemini 2.5 Flash | 0.970 | 100% | 22 / 22 | 0 of 8 |
| OCR + regex | 0.791 | 74% | 22 / 23 | 4 of 8 |
| OCR + regex + deskew | **0.985** | 94% | 23 / 23 | 1 of 8 |
| Gemini 2.5 Flash | 0.961 | 100% | 23 / 23 | 0 of 8 |

What this does and does not show:
**Short answer: not on this test.** What this does and does not show:

- On clean, uniform documents a free OCR + regex pipeline is already perfect, so AI is unnecessary there.
- On messy documents Gemini is clearly better end to end, but its lead on line F1 over a decent baseline is only +5.6 points, below the +10 the project plan asked for. A more heavily engineered baseline could close more of the gap.
- Gemini silently altered a code in 3 of 101 lines, which is why the UI asks users to verify against the original.
- The hard set was designed after seeing the easy one. Treat the numbers as a stress test, not real-world accuracy.
- On messy documents, a well-built OCR + regex baseline now reads line items slightly better than Gemini. Gemini's remaining lead is 2 of 31 cases on flags and 1 false alarm, too small to count as a real advantage.
- The first measurement (2026-11-01) showed Gemini well ahead (deskew baseline line F1 0.914). Most of that gap came from one parsing bug in the baseline, now fixed. The earlier numbers are kept in the results file.
- Gemini's possible advantage is that it needs no per-format rules; the baseline caught up only after a rule was written for these documents. That is not measured yet.
- Gemini silently altered a code in 4 of 103 lines, which is why the UI asks users to verify against the original.
- The hard set was designed after seeing the easy one, and the baseline fix after seeing its failures on the hard set. Treat the numbers as a stress test, not real-world accuracy.

## Tech stack

Expand Down Expand Up @@ -161,7 +163,7 @@ Case status moves from `queued` to `processing` to `done` or `failed`.
## Testing and security checks

```
cd backend && python -m pytest -q # 43 tests
cd backend && python -m pytest -q # 45 tests
cd frontend && npx tsc --noEmit # type check
cd backend && python -m pip_audit -r requirements.txt
cd frontend && npm audit
Expand All @@ -186,7 +188,8 @@ The free Gemini tier may retain and human-review submitted content, and Google's

- [ ] Score the last two hard cases and a second Gemini model (flash-lite) on the same 32 cases when free quota allows.
- [ ] Redact personal data before any API call, with tests.
- [ ] Improve the baseline's long-date handling and re-measure the AI margin.
- [x] Improve the baseline's long-date handling and re-measure the AI margin (2026-11-28: the baseline now leads on line F1).
- [ ] Test both extractors on unseen layouts to measure whether Gemini's lack of per-format rules is a real advantage.
- [ ] UI polish and clearer error states.
- [ ] Add a screenshot or short demo recording.

Expand Down
28 changes: 25 additions & 3 deletions backend/app/baseline.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,22 @@
anywhere in a row. Generic patterns cover ISO, US and long dates and three code
shapes (SYN-dddd, letter+4 digits, 5 digits). One bounded round of tuning was
done after the easy-set run; it was not tuned against individual failures.
A second, documented change (2026-11-28) handles two OCR effects found on the
hard set: a long date merged with the code next to it, and a long date with no
space after the comma. See docs/GATE1_RESULTS.md.
"""
import io
import re
from decimal import Decimal

from app.core.checks import Bill, Eob, Line

DATE = re.compile(r"\d{4}-\d{2}-\d{2}|\d{1,2}/\d{1,2}/\d{4}|[A-Z][a-z]{2} \d{1,2}, \d{4}")
DATE = re.compile(r"\d{4}-\d{2}-\d{2}|\d{1,2}/\d{1,2}/\d{4}|[A-Z][a-z]{2} \d{1,2}, ?\d{4}")
LONG_DATE = re.compile(r"([A-Z][a-z]{2}) (\d{1,2}), ?(\d{4})")
CODE = re.compile(r"\bSYN-\d{4}\b|\b[A-Z]\d{4}\b|\b\d{5}\b")
# The code column follows the date column in every layout. OCR often merges the
# two boxes ("Apr 28, 2026G5213"), so after the date only a right boundary is required.
CODE_AFTER_DATE = re.compile(r"\s*(SYN-\d{4}|[A-Z]\d{4}|\d{5})(?![\dA-Za-z])")
AMOUNT = re.compile(r"\$?\s?(\d[\d,]*\.\d{2})")
TOTAL = re.compile(r"total\s+charges", re.I)
OWES = re.compile(r"amount\s+you\s+owe", re.I)
Expand Down Expand Up @@ -78,6 +85,20 @@ def _amount(text):
return Decimal(m.group(1).replace(",", "")) if m else None


def _normalise_date(text: str) -> str:
"""OCR can drop the space after the comma in a long date; print it the standard way."""
m = LONG_DATE.fullmatch(text)
return f"{m.group(1)} {m.group(2)}, {m.group(3)}" if m else text


def _find_code(row: str, date_match):
m = CODE_AFTER_DATE.match(row, date_match.end())
if m:
return m.group(1)
m = CODE.search(row)
return m.group() if m else None


def parse_bill_rows(rows) -> Bill:
lines, total, owes = [], Decimal("0"), Decimal("0")
for row in rows:
Expand All @@ -86,11 +107,12 @@ def parse_bill_rows(rows) -> Bill:
elif OWES.search(row):
owes = _amount(row) or owes
else:
d, c = DATE.search(row), CODE.search(row)
d = DATE.search(row)
c = _find_code(row, d) if d else None
amounts = AMOUNT.findall(row)
if d and c and amounts:
# the code's digits can be read as an amount-like token; take the last decimal amount
lines.append(Line(d.group(), c.group(),
lines.append(Line(_normalise_date(d.group()), c,
Decimal(amounts[-1].replace(",", "")), row))
return Bill(lines, total, owes)

Expand Down
24 changes: 24 additions & 0 deletions backend/tests/test_evaluate_baseline.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,30 @@ def test_parse_bill_rows_other_formats_and_distractors():
assert bill.stated_total == D("3467.28")


def test_parse_bill_rows_date_merged_with_code():
# The first four rows are OCR output for synthetic hard-set bills (case_004, case_018);
# the last two are made-up variants: a merged US date, and the amount-first layout.
rows = ["Apr 28, 2026G5213 $3,601.65 Physical thera",
"May 5,202680603 $1,720.14 Physical thera)",
"Mar 5,2026 SYN-2553 $2,101.21 Follow-up eval",
"Apr 26, 2026SYN-1399 $1,122.20 Physical theraj",
"03/20/202689585 $151.10 Physical theraj",
"$573.26 Jul 22, 202626971 Consultation"]
bill = parse_bill_rows(rows)
assert [(l.date, l.code, l.billed) for l in bill.lines] == [
("Apr 28, 2026", "G5213", D("3601.65")),
("May 5, 2026", "80603", D("1720.14")),
("Mar 5, 2026", "SYN-2553", D("2101.21")),
("Apr 26, 2026", "SYN-1399", D("1122.20")),
("03/20/2026", "89585", D("151.10")),
("Jul 22, 2026", "26971", D("573.26"))]


def test_parse_bill_rows_does_not_guess_a_misread_code():
# OCR read "SYN" as "6YN" and merged it with the date; no code shape matches, so skip the row.
assert parse_bill_rows(["Mar 23, 20266YN-5332 $3,132.62 Outpatient ima"]).lines == []


def test_group_rows_orders_by_x_and_splits_on_y():
from app.baseline import group_rows
items = [(100.0, 300.0, "B"), (101.0, 50.0, "A"), (160.0, 10.0, "C")]
Expand Down
45 changes: 26 additions & 19 deletions docs/GATE1_RESULTS.md
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
# Gate 1 results: does AI beat the simple solution?

Last updated: 2026-11-01. Task: extract bill line items, totals and the EOB patient amount, then run the deterministic checks. All documents are synthetic (`backend/app/synthetic.py`). Reproduce with the commands at the bottom.
Last updated: 2026-11-28 (baseline fix and re-run; first version 2026-11-01). Task: extract bill line items, totals and the EOB patient amount, then run the deterministic checks. All documents are synthetic (`backend/app/synthetic.py`). Reproduce with the commands at the bottom.

## Verdict: line-extraction criterion NOT met; end-to-end accuracy clearly better
## Verdict: AI does NOT beat the improved baseline on extraction; a small end-to-end edge remains

The plan required AI to reach line F1 >= 0.90 **and** beat the baseline by >= 10 points.

- **Line F1:** Gemini 0.970 vs 0.914 for a deskewed OCR + regex baseline, a margin of **+5.6 points**. Below the +10 the plan asked for, so the strict criterion is not met.
- **End-to-end flags:** Gemini gets the flags exactly right in 100% of cases vs 76.7% for the stronger baseline (+23 points), finds 22/22 injected errors vs 21/22, and raises **0 false alarms on 8 clean bills vs 4 of 8**. False alarms are the costly failure in this product, and a missed line makes a clean bill look wrong.
- **Line F1:** after the 2026-11-28 baseline fix, the deskewed OCR + regex baseline scores **0.985** and Gemini **0.961** on the same 31 hard cases. The baseline is now ahead by 2.4 points, so the criterion is clearly not met.
- **End-to-end flags:** Gemini gets the flags exactly right in 31 of 31 cases vs 29 of 31 for the baseline. Both find all 23 injected errors. Gemini raises 0 false alarms on 8 clean bills, the baseline 1. Those are differences of one or two synthetic cases, too few to call a real advantage.

So AI adds a real but moderate advantage. It is mostly robustness: it handles varied dates, codes, tilt and noise without per-format rules. A more heavily engineered baseline could narrow the gap.
So on this synthetic test, a carefully built non-AI pipeline matches or beats Gemini. What Gemini still offers is that it needs no per-format rules: the baseline only caught up after a rule was written for an OCR effect seen in these exact documents, and a new layout could break it again. That is a plausible benefit, but it is **not measured** here.

### How the verdict changed

On 2026-11-01 the deskew baseline scored line F1 0.914 and Gemini looked clearly better end to end (flags exact 100% vs 77%, false alarms 0/8 vs 4/8). Most of the baseline's misses had one cause: OCR merged a long date with the code next to it (`Apr 28, 2026G5213`) or dropped the space after the comma (`Mar 5,2026`), so the code pattern failed. Fixing that one parsing problem (2026-11-28) moved the baseline to the numbers above. The earlier gap reflected a weak baseline, not an AI advantage.

The owner chose to continue as a portfolio project (2026-10-31) and waived user interviews. Demand is **not validated**.

Expand All @@ -22,23 +26,25 @@ The owner chose to continue as a portfolio project (2026-10-31) and waived user

Clean, uniform documents are fully solved by free OCR + regex. No AI needed here.

## Hard set (seed 21): the same 30 cases for all three extractors
## Hard set (seed 21): the same 31 cases for all extractors

Hard mode adds three date formats, three code formats, thousands separators, wrapped descriptions, payment and adjustment rows, page tilt, blur, noise and JPEG damage. Gemini completed 30 of 32 cases; two failed (one transient HTTP 503, one daily-quota 429). All three extractors are scored on the same 30.
Hard mode adds three date formats, three code formats, thousands separators, wrapped descriptions, payment and adjustment rows, page tilt, blur, noise and JPEG damage. Gemini completed 31 of 32 cases (case_027 was scored after the first report; case_031 is still unscored). All extractors are scored on the same 31, with 103 bill lines.

| Extractor | Line precision | Line recall | Line F1 | Flags exact | Injected found | False alarms (clean) |
|---|---|---|---|---|---|---|
| OCR + regex (plain) | 1.000 | 0.535 | 0.697 | 0.633 | 20/22 | 6/8 |
| OCR + regex + deskew | 1.000 | 0.842 | 0.914 | 0.767 | 21/22 | 4/8 |
| Gemini 2.5 Flash | 0.970 | 0.970 | 0.970 | 1.000 | 22/22 | 0/8 |
| OCR + regex (plain), 2026-11-01 | 1.000 | 0.524 | 0.688 | 0.613 | 21/23 | 6/8 |
| OCR + regex (plain), 2026-11-28 | 0.986 | 0.660 | 0.791 | 0.742 | 22/23 | 4/8 |
| OCR + regex + deskew, 2026-11-01 | 1.000 | 0.825 | 0.904 | 0.742 | 22/23 | 4/8 |
| **OCR + regex + deskew, 2026-11-28** | 0.990 | 0.981 | **0.985** | 0.935 | 23/23 | 1/8 |
| Gemini 2.5 Flash | 0.961 | 0.961 | 0.961 | 1.000 | 23/23 | 0/8 |

Amounts and totals: Gemini got the stated total, amount owed and EOB amount right in every one of the 30 cases. No amount was invented by any extractor.
The 2026-11-01 rows are kept for comparison; they are the same OCR output parsed by the earlier rules. No extractor invented an amount.

### What each approach gets wrong

- **Plain baseline:** page tilt pushes amounts out of line with their dates, so lines are dropped, totals look wrong, and clean bills get false "sum mismatch" flags.
- **Deskew baseline:** it still misses lines, mostly those with long-format dates (such as "Mar 23, 2026") and varied code shapes. These look fixable with more rules.
- **Gemini:** 3 of 101 lines had altered codes: a dropped letter prefix twice (`A9326` became `9326`) and a leading zero added once (`80603` became `080603`). Amounts were correct, but silently changed values are a real risk, so the UI tells users to verify against the original.
- **Plain baseline:** page tilt pushes amounts out of line with their dates, so lines are still dropped, totals look wrong, and clean bills get false "sum mismatch" flags.
- **Deskew baseline (2026-11-28):** 101 of 103 lines right. One line was missed because OCR read `SYN` as `6YN` and merged it with the date; that missing line caused the one false alarm (case_004). One code was read as `19243` instead of `J9243`. No rule was added for these, to avoid fitting the baseline to single failures.
- **Gemini:** 99 of 103 lines right. 4 lines had altered codes: a dropped letter prefix three times (`A9326` became `9326`) and a leading zero added once (`80603` became `080603`). Amounts were correct, but silently changed values are a real risk, so the UI tells users to verify against the original.

## End-to-end check on the real stack (2026-11-01)

Expand All @@ -53,16 +59,17 @@ One synthetic pair with a known duplicate charge went through upload, MinIO, Mon

- All data is synthetic and written by me. Real bills vary more.
- I built the hard set after seeing the baseline score 100% on the easy set, which risks favouring AI. The deskew baseline was also added after seeing the plain baseline fail. Both were one-pass changes made in the open, but treat the numbers as a stress test, not an estimate of real-world accuracy.
- Small samples: 30 cases, 8 of them clean. The first 18 Gemini results were produced before the evidence-citation fix. That change touched only the `source` text, not the extracted values.
- Two hard cases (case_027, case_031) were not scored for Gemini because of API errors.
- Small samples: 31 cases, 8 of them clean. The first 18 Gemini results were produced before the evidence-citation fix. That change touched only the `source` text, not the extracted values.
- One hard case (case_031) is not scored for Gemini because of an API error.
- The 2026-11-28 baseline fix was written after looking at the baseline's failures on this same hard set. It is a general parsing rule (a code may follow a date with no space), not a per-case patch, but it still favours the baseline on these documents, just as the hard set was built after seeing the easy one.
- No real documents were used. Free-tier terms say not to send personal or health data.
- User demand is not validated (Gate 2 waived).

## Next steps

1. Run Gemini on case_027 and case_031 when the quota resets.
2. Optionally improve the baseline's long-date handling and re-measure the margin.
3. Report these numbers, including the sub-10-point line-F1 margin, in the README.
1. Run Gemini on case_031 when the quota allows.
2. Measure the "no per-format rules" claim directly: a fresh synthetic set with layouts neither extractor has seen, scored without changing the baseline first.
3. Decide, as the owner, whether the project still meets the workspace rule that AI must beat a simpler baseline.

## Reproduce

Expand Down