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
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,4 @@ Intel i5-1334U, ~31.7 GB RAM, no NVIDIA GPU. No local LLMs are used (owner decis
- One feature per commit, pushed only when that feature is finished, tested and verified. Do not push several features in one session just to catch up.
- Take time on each step; quality over speed. New projects are started one at a time, after the current one meets its gates.
- Never backdate commits, fake timestamps, or create filler commits to shape the contribution graph. History must match the real work.
- Push method: token in the git-ignored `.env` as `GITHUB_TOKEN`, passed per command via `http.extraheader`; never printed or stored. Token expires about 2026-11-28, so remind the owner before then.
- Push method: token in the git-ignored `.env` as `GITHUB_TOKEN`, passed per command via `http.extraheader`; never printed or stored. The token is fine-grained, limited to the CodeAvk repo, and expires on 2026-12-28 (renewed 2026-11-28), so remind the owner before then. Open-source contributions to other projects use the `gh` CLI keyring login, not this token.
5 changes: 3 additions & 2 deletions PLAN.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# PLAN.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`.
Status as of 2026-11-30: research done; Gate 0 partial; Gate 1 re-measured after a baseline fix: on known layouts the deskew baseline leads on line F1 (0.985 vs Gemini 0.961) and Gemini's end-to-end edge is 2 of 31 cases; on 20 cases in three unseen layouts (frozen before any run) Gemini scores line F1 0.963 with all flags right and the unchanged baseline 0, so the AI's measured value is handling new layouts without new rules (owner to decide whether that meets the AI-must-beat-baseline rule); 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 @@ -13,7 +13,8 @@ Status as of 2026-11-28: research done; Gate 0 partial; Gate 1 re-measured after
## Next actions
- [ ] 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] Test both extractors on unseen layouts (2026-11-30).
- [ ] Owner decision: does the project still meet the rule that AI must beat a simpler baseline? (Known layouts: no. Unseen layouts: yes.)
- [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
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,12 +96,12 @@ Hard set, 31 cases (tilt, blur, noise, varied date and code formats), re-measure
| OCR + regex + deskew | **0.985** | 94% | 23 / 23 | 1 of 8 |
| Gemini 2.5 Flash | 0.961 | 100% | 23 / 23 | 0 of 8 |

**Short answer: not on this test.** What this does and does not show:
**Short answer: not on known layouts; yes on unseen ones.** 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, 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's advantage is that it needs no per-format rules. On 20 cases in three new layouts, frozen before either extractor ran, Gemini scored line F1 0.963 with every flag right; the unchanged baseline read nothing (F1 0). The baseline's zero is expected, since its rules don't cover those layouts; the point is that Gemini needed no changes. How long new rules would take is not measured.
- 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.

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

```
cd backend && python -m pytest -q # 45 tests
cd backend && python -m pytest -q # 59 tests
cd frontend && npx tsc --noEmit # type check
cd backend && python -m pip_audit -r requirements.txt
cd frontend && npm audit
Expand All @@ -189,7 +189,7 @@ 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.
- [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.
- [x] Test both extractors on unseen layouts (2026-11-30: Gemini line F1 0.963, unchanged baseline 0).
- [ ] UI polish and clearer error states.
- [ ] Add a screenshot or short demo recording.

Expand Down
94 changes: 84 additions & 10 deletions backend/app/synthetic.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,13 @@
real CPT codes) and amounts. Each case can inject one known error so that
extraction and checks can be scored against exact expectations.

CLI: python -m app.synthetic OUT_DIR [COUNT] [SEED] [hard]
Unseen layouts (styles 3-5) are a held-out test: they were written on
2026-11-30 and frozen before either extractor was run on them, and neither the
baseline rules nor the Gemini prompt may be tuned against them. They change
the row structure, date format and total labels, the things a rule-based
parser is written for and a model is not.

CLI: python -m app.synthetic OUT_DIR [COUNT] [SEED] [hard|unseen]
"""
import io
import json
Expand All @@ -27,6 +33,10 @@
DESCRIPTIONS = ("Office visit", "Lab panel", "Imaging study", "Procedure supplies",
"Consultation", "Therapy session", "Facility fee")
FONT_FILES = ("arial.ttf", "calibri.ttf", "segoeui.ttf")
# Unseen layouts: style -> (total label, amount-owed label, EOB responsibility label)
UNSEEN_LABELS = {3: ("Total billed", "Balance due", "Patient responsibility"),
4: ("Statement total", "Please pay", "You may owe"),
5: ("Sum of charges", "Patient balance", "What you owe")}


@dataclass
Expand All @@ -38,6 +48,7 @@ class Case:
style: int
injected: str
hard: bool = False
unseen: bool = False
extra: list = field(default_factory=list) # distractor rows: (label, date, amount)


Expand All @@ -51,6 +62,8 @@ def _print_date(iso: str, style: int) -> str:
return f"{m}/{d}/{y}"
if style == 2:
return f"{MONTHS[int(m) - 1]} {int(d)}, {y}"
if style == 3: # day first, unseen layouts only
return f"{int(d)} {MONTHS[int(m) - 1]} {y}"
return iso


Expand All @@ -72,13 +85,15 @@ def _hard_extra(rng, date_style):
return rows


def make_case(rng: random.Random, injected=None, hard=False) -> Case:
def make_case(rng: random.Random, injected=None, hard=False, unseen=None) -> Case:
"""unseen: None for the trained-on layouts, or an unseen layout style 3-5."""
n = rng.randint(2, 6)
lines, descs = [], []
date_style = rng.randint(0, 2) if hard else 0
style = unseen
date_style = {3: 1, 4: 3, 5: 0}[style] if unseen else (rng.randint(0, 2) if hard else 0)
for i in range(n):
iso = f"2026-{rng.randint(1, 9):02d}-{rng.randint(1, 28):02d}"
code = _hard_code(rng) if hard else f"SYN-{rng.randint(1000, 9999)}"
code = _hard_code(rng) if hard or unseen else f"SYN-{rng.randint(1000, 9999)}"
amount = _money(rng, 20, 4000) if hard else _money(rng, 20, 900)
lines.append(Line(_print_date(iso, date_style), code, amount, f"row{i}"))
descs.append(rng.choice(LONG_DESCRIPTIONS if hard else DESCRIPTIONS))
Expand All @@ -93,9 +108,12 @@ def make_case(rng: random.Random, injected=None, hard=False) -> Case:
if injected == "eob_mismatch":
responsibility = max(Decimal("0"), owed - _money(rng, 5, 60))
bill = Bill(lines, stated, owed)
if unseen:
return Case(bill, Eob([], responsibility), descs, f"Sample Clinic {rng.choice('ABCDEFG')}",
style, injected or "none", False, True, _hard_extra(rng, date_style))
return Case(bill, Eob([], responsibility), descs,
f"Sample Clinic {rng.choice('ABCDEFG')}", rng.randint(0, 2),
injected or "none", hard, _hard_extra(rng, date_style) if hard else [])
injected or "none", hard, False, _hard_extra(rng, date_style) if hard else [])


def expected_flags(case: Case):
Expand Down Expand Up @@ -145,7 +163,60 @@ def _wrap(text: str, width: int = 24):
return rows + [cur]


def _render_unseen_bill(case: Case, rng: random.Random) -> Image.Image:
"""Styles 3-5. 3: two-line rows (code on its own line below the charge).
4: columns Amount, Code, Date, Description with day-first dates.
5: each charge as a labelled block of three lines."""
per_line = {3: 2, 4: 1, 5: 3}[case.style]
rows = per_line * len(case.bill.lines) + len(case.extra)
img = Image.new("RGB", (900, 330 + 44 * rows + 30 * len(case.bill.lines) + 140), "white")
d, f, fb = ImageDraw.Draw(img), _font(22), _font(26)
d.text((40, 30), case.provider, font=fb, fill="black")
d.text((40, 70), "STATEMENT - SYNTHETIC SAMPLE, NOT A REAL BILL", font=f, fill="#555")
y = 130
if case.style == 3:
heads = (("Service", 40), ("Description", 220), ("Charge", 700))
elif case.style == 4:
heads = (("Amount", 40), ("Code", 200), ("Date", 340), ("Description", 540))
else:
heads = (("Charges", 40),)
for h, x in heads:
d.text((x, y), h, font=fb, fill="black")
d.line((40, y + 36, 860, y + 36), fill="black")
y += 52
for line, desc in zip(case.bill.lines, case.descriptions):
amt = f"${line.billed:,.2f}"
if case.style == 3:
d.text((40, y), line.date, font=f, fill="black")
d.text((220, y), desc, font=f, fill="black")
d.text((700, y), amt, font=f, fill="black")
d.text((220, y + 34), f"Procedure code: {line.code}", font=f, fill="#333")
y += 44 + 34
elif case.style == 4:
for v, x in zip((amt, line.code, line.date, desc), (40, 200, 340, 540)):
d.text((x, y), v, font=f, fill="black")
y += 44
else:
for k, v in (("Service date", line.date), ("Code", f"{line.code} ({desc})"),
("Charge", amt)):
d.text((60, y), f"{k}:", font=f, fill="black")
d.text((260, y), v, font=f, fill="black")
y += 34
y += 30
for label, date, amount in case.extra: # payments/adjustments: no code, not charges
d.text((40, y), f"{date} {label} {amount}", font=f, fill="#222")
y += 44
y += 20
total_label, owe_label, _ = UNSEEN_LABELS[case.style]
d.line((40, y, 860, y), fill="black")
d.text((40, y + 20), f"{total_label}: ${case.bill.stated_total:,.2f}", font=fb, fill="black")
d.text((40, y + 62), f"{owe_label}: ${case.bill.patient_owes:,.2f}", font=fb, fill="black")
return _scan_effect(img, rng)


def render_bill(case: Case, rng: random.Random) -> Image.Image:
if case.unseen:
return _render_unseen_bill(case, rng)
wrapped = [_wrap(desc) if case.hard else [desc] for desc in case.descriptions]
body_rows = sum(max(len(w), 1) for w in wrapped) + len(case.extra)
img = Image.new("RGB", (900, 330 + 44 * body_rows + 140), "white")
Expand Down Expand Up @@ -196,7 +267,8 @@ def render_eob(case: Case, rng: random.Random) -> Image.Image:
d.text((40, 140), f"Amount billed by provider: ${total:,.2f}", font=f, fill="black")
plan = total - case.eob.patient_responsibility
d.text((40, 190), f"Plan paid: ${plan:,.2f}", font=f, fill="black")
d.text((40, 260), f"Your responsibility: ${case.eob.patient_responsibility:,.2f}",
label = UNSEEN_LABELS[case.style][2] if case.unseen else "Your responsibility"
d.text((40, 260), f"{label}: ${case.eob.patient_responsibility:,.2f}",
font=fb, fill="black")
return _scan_effect(img, rng, case.hard)

Expand All @@ -205,6 +277,8 @@ def truth_dict(case: Case) -> dict:
return {
"injected": case.injected,
"hard": case.hard,
"unseen": case.unseen,
"style": case.style,
"expected_flags": expected_flags(case),
"bill": {"lines": [{"date": l.date, "code": l.code, "amount": str(l.billed)}
for l in case.bill.lines],
Expand All @@ -214,12 +288,12 @@ def truth_dict(case: Case) -> dict:
}


def generate(out_dir: Path, count=12, seed=1, hard=False):
def generate(out_dir: Path, count=12, seed=1, hard=False, unseen=False):
out_dir = Path(out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
rng = random.Random(seed)
for i in range(count):
case = make_case(rng, ERRORS[i % len(ERRORS)], hard)
case = make_case(rng, ERRORS[i % len(ERRORS)], hard, 3 + i % 3 if unseen else None)
stem = out_dir / f"case_{i:03d}"
render_bill(case, rng).save(f"{stem}_bill.png")
render_eob(case, rng).save(f"{stem}_eob.png")
Expand All @@ -231,5 +305,5 @@ def generate(out_dir: Path, count=12, seed=1, hard=False):
target = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("data/generated")
n = int(sys.argv[2]) if len(sys.argv) > 2 else 12
s = int(sys.argv[3]) if len(sys.argv) > 3 else 1
is_hard = len(sys.argv) > 4 and sys.argv[4] == "hard"
print(f"wrote {generate(target, n, s, is_hard)} cases to {target}")
mode = sys.argv[4] if len(sys.argv) > 4 else ""
print(f"wrote {generate(target, n, s, mode == 'hard', mode == 'unseen')} cases to {target}")
22 changes: 22 additions & 0 deletions backend/tests/test_synthetic.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,25 @@ def test_hard_images_render(tmp_path):
assert generate(tmp_path, count=4, seed=2, hard=True) == 4
truth = json.loads((tmp_path / "case_000_truth.json").read_text())
assert truth["hard"] is True


@pytest.mark.parametrize("injected", ERRORS)
@pytest.mark.parametrize("style", (3, 4, 5))
def test_unseen_layouts_keep_exact_ground_truth(injected, style):
for seed in range(10):
case = make_case(random.Random(seed), injected, unseen=style)
want = [] if injected is None else [injected]
assert expected_flags(case) == want, (seed, injected, style)
assert case.unseen and case.style == style and not case.hard


def test_unseen_day_first_dates_only_in_style_4():
case = make_case(random.Random(3), None, unseen=4)
assert all(l.date.split()[1].isalpha() for l in case.bill.lines) # "11 Jul 2026"


def test_unseen_set_cycles_layouts(tmp_path):
assert generate(tmp_path, count=6, seed=2, unseen=True) == 6
styles = [json.loads((tmp_path / f"case_{i:03d}_truth.json").read_text())["style"]
for i in range(6)]
assert styles == [3, 4, 5, 3, 4, 5]
Loading