Inspiration
Three moments look unrelated on the surface: coming home from a hospital, getting sick in another country, and receiving donated relief packs in a disaster blackout zone. All three share one clinical hazard. Different labels hide the exact same chemical molecule, with no doctor on speed dial.
My dad is a cardiologist. Relatives and friends call him often for a second opinion, and almost every time it is for a non-cardiac reason after a hospital discharge, an urgent-care visit, or a new prescription. Before he reads a single lab report, he spreads every bottle and discharge paper across the table and checks the active ingredients and daily totals. Almost every time, his first move is catching overlapping active ingredients or mismatched daily doses and telling them to pause and confirm the dose with their prescribing doctor.
I wanted to know if this pattern shows up outside hospital discharges. It does. When you travel across borders, a common painkiller or antibiotic carries an unfamiliar brand name and a different tablet strength. When people receive donated medical aid in disaster and blackout zones with zero network coverage, unfamiliar foreign packs can stack dangerously against chronic prescriptions. Clinical data backs this up:
- One in two hospital discharges contains a medication discrepancy. Systematic reviews indexed on NIH PubMed Central report a median ~50% rate of unintentional medication discrepancies after hospital discharge. Roughly 1 in 5 discharged patients suffers an adverse drug event, according to the AHRQ Patient Safety Network.
- Medication errors drive 1.5 million U.S. ER visits and $42 billion in annual global costs. The CDC tracks about 1.5 million U.S. emergency department visits and 500,000 hospitalizations each year from adverse drug events, including over 600,000 ER visits among adults 65 and older. Worldwide, the World Health Organization (WHO) estimates medication errors cost $42 billion every year, nearly 1% of global health expenditure.
A typical consumer app or cloud vision chatbot fails here for three reasons:
- Identity leaks on every label. Prescription bottles and discharge sheets print patient names, dates of birth, phone numbers, and regional medical IDs that leak if uploaded raw to a cloud API.
- Cloud-only tools stop working when signal drops. On an international flight, in a hurricane or earthquake shelter after cell towers go down, in a rural home, or in a hospital basement, a cloud wrapper breaks.
- Probabilistic LLMs should not own dosage math. A language model can parse messy text, but deterministic code must calculate daily milligram ceilings and trigger overdose alerts.
These constraints led me to build MedLedger, an offline-first medication safety checker that performs deterministic double-dosage and cross-border equivalence checks without sending personal data to the cloud. It does not replace a doctor or prescribe dose changes. It puts a fast, private first-pass ingredient and overlap check in anyone's pocket so they know the exact conflict to confirm with a physician or pharmacist.
What it does
MedLedger is a dual-platform Chrome web app and native SwiftUI iOS app (iOS 17.0 to 27.2) with Offline Available privacy built in by default.
- Works offline in zero-Wi-Fi disaster and blackout zones. Scanning, redaction, and reconciliation run locally in under
100 mswhile queuing zero-PII handoff writes in local Cloud Firestore disk cache until connectivity returns. - Masks personal data locally across 7 jurisdictions before any model runs. On-device OCR and optical masking scrub patient names, dates of birth, addresses, phone numbers, and regional medical IDs across the U.S., India, the UK, the EU, China, Bangladesh, and Singapore, while refusing blurry captures and loose unlabeled pills.
- Supports flexible single-sheet or multi-photo capture. You can photograph a single multi-drug handwritten prescription (such as a diabetes and hypertension regimen with
1+0+1,OD,BD,TDS, orHSdosing notation) or add extra bottles and blister strips side by side. - Extracts structured medications on-device through Firebase AI Logic (
FirebaseAILogicandfirebase/ai). Apple Foundation Models on Apple Intelligence iPhones (iOS 26+) and Chrome Built-in AI Gemini Nano on Chrome Desktop (139+) parse redacted label text into canonical drug entries offline. When a device lacks local weights or encounters hard-to-read handwriting, selective cloud fallback uses schema-enforced Firebase AI Logic JSON output over redacted text or top-header-masked images. - Computes exact 24-hour active-ingredient totals and 7-jurisdiction equivalents deterministically. Non-AI Swift and TypeScript code maps
76active ingredients,170brand and fixed-dose combination products across7jurisdictions,46FDA and EMA interaction pairs, and13duplicate-class rules. It catches hidden double doses across discharge sheets, home bottles, and foreign blister packs (such asIbuprofen + Naproxendouble NSAIDs,Norco + Tylenolacetaminophen stacking, or red foilFimoxyl 500Amoxicillin equivalents across 7 regions), visualizes every shared ingredient, and recalculates the 24-hour curve immediately on 1-tap Hold with instant Undo. - Streams live FDA guidance and speaks 5-language neural audio (
ONLY_IN_CLOUD). Only when the user taps Check FDA guidance or Listen does MedLedger send anonymous generic ingredient names togemini-3.5-flash-litefor streamed official FDA safety context andgemini-3.8-flash-ttsfor spoken caregiver alerts in 5 languages (EN,ES,中文,বাংলা,VI), falling back offline to native device speech (AVSpeechSynthesizerand Web Speech).
Scope note (Apple App Store Guideline 1.4.2): MedLedger is an informational label-discrepancy and caregiver-handoff tool. It does not diagnose medical conditions or prescribe dosing changes and directs users to confirm every flagged overlap with a licensed physician or pharmacist.
How we built it
I spent about 2 days chatting with Gemini to evaluate whether this clinical gap had real-world impact. After that assessment, I wrote markdown specification documents covering the product idea, feature scope, hackathon constraints, and required Firebase and iOS capabilities.
I handed those markdown documents to Antigravity CLI, which built the codebase across a 2.5-day sprint using Neon xhigh as orchestrator with Hydrogen and Neon agents in an agent swarm, routing tasks by complexity. I instructed Antigravity to apply official Firebase AI skills and harden the backend against the Firebase General and Production Launch checklist. On the client side, I used open-source UI skills to build the React 19 web frontend and native SwiftUI iOS frontend.
Here is how the backend and clinical stack break down across platforms and datasets.
iOS
- apple-foundation-models: Acts as the primary local LLM on iPhone inside Firebase AI Logic's
HybridModel. On Apple Intelligence iPhones (iOS 26+),SystemLanguageModel.defaultextracts structured medications strictly on-device with zero tools attached. On older hardware (iOS 17to25, such as a compact iPhone SE), MedLedger runs the deterministic offline RxNorm parser and optional redacted cloud fallback. - apple-vision: Runs 100% on-device Neural Engine OCR on iPhone and powers the reproducible 68-real-photo stress-test binary. It returns exact pixel bounding boxes for every word on a pill bottle, foil strip, or discharge sheet so CoreGraphics blacks out names, dates of birth, NHS numbers, UHIDs, and Chinese IDs in RAM before any language model runs. Apple Vision makes the
0 Braw photo egress claim physically verifiable in Airplane Mode and blackout shelters. - avfoundation (Apple AVFoundation): Powers two core iOS features. First, live AR camera capture streams
AVCaptureSessionframes to Apple Vision for real-time on-screen black-box redaction over patient identifiers as you point your iPhone at a bottle. Second, caregiver voice playback and offline fallback configuresAVAudioSession(.playback)to play Cloud Gemini TTS WAV audio in 5 languages (EN,ES,中文,বাংলা,VI) and falls back to on-deviceAVSpeechSynthesizerwhen Wi-Fi and cell service disappear. An older adult or blackout-shelter volunteer who cannot read small English print can tap Listen and hear a clear alert offline.
Web
- firebase-ai-logic (
firebase/aion Web andFirebaseAILogicon iOS): Forms the central routing spine of the entire app. One unified SDK runs on-device primary inference on both iOS and Web alongside selectiveONLY_IN_CLOUDcalls togemini-3.5-flash-lite(streaming live FDA citations, resolving unknown foreign brands, and reading header-masked handwritten prescriptions) andgemini-3.8-flash-tts(5-language neural audio). Firebase App Check protects cloud calls and Firebase Remote Config governs thresholds and model versions over the air. - gemini-nano: Acts as the primary local LLM on Chrome Web through Firebase AI Logic. On Chrome Desktop with Gemini Nano enabled, MedLedger parses pre-redacted bottle text into structured medication JSON directly on the laptop. On browsers without Gemini Nano, a 3-layer fail-open guard prevents unredacted data from leaving the device while deterministic RxNorm and optional sanitized cloud fallback keep the app fully functional.
Deterministic clinical datasets
No LLM is ever allowed to calculate final daily milligram totals or suppress an overdose alert. To keep every clinical calculation deterministic and offline, I sourced and bundled local JSON versions of three pharmaceutical standards inside the app:
- rxnorm: Powers the deterministic safety engine. Every drug maps to a standard RxCUI (for example,
161for Acetaminophen and Paracetamol) across76active ingredients,170brand and fixed-dose combination products in7jurisdictions,46FDA and EMA interaction pairs, and13duplicate-class rules. It computes exact 24-hour milligram math, parses South Asian and Commonwealth schedules (1+0+1,OD,BD,TDS,HS), recovers noisy handwritten OCR tokens with bounded edit-distance matching, and maps cross-border equivalents offline. - openfda: Pulls real, messy FDA drug labels from
api.fda.gov/drug/label.json, including 15 out-of-corpus holdout drugs. This dataset gave me verifiable, non-cherry-picked validation against live government labels. - fhir: Generates a downloadable zero-PII HL7 FHIR R4 JSON
BundlecontainingMedicationStatementandDetectedIssueresources plus a printable QR handoff sheet. This output connects consumer scans to real pharmacy and hospital EHR workflows (such as Epic and Cerner) while staying strictly non-diagnostic under Apple App Store Guideline 1.4.2.
How all five layers work together
Instead of forcing a cloud-only or edge-only compromise, each stage runs on the plane its privacy, latency, and freshness requirements demand:
| Layer | Role | Web (firebase/ai) |
Native iOS (FirebaseAILogic) |
Wire PHI |
|---|---|---|---|---|
| Layer 1 | Optical and text PII firewall | HTML5 Canvas, tesseract.js WASM, 7-region regex firewall, top-11% Rx header mask, and < 15-char blur refusal |
Fast bilingual Apple Vision (Latin, EU, and Chinese), CoreGraphics masking, and < 12-char blur refusal |
0 B |
| Layer 2 | On-device structured extraction | InferenceMode.ONLY_ON_DEVICE and PREFER_ON_DEVICE (window.LanguageModel Gemini Nano) plus Schema.object cloud fallback |
FirebaseAI.SystemLanguageModel.default, HybridModel(primary:secondary:), and iOS 17 to 25 Schema.array plus SafetySetting fallback |
0 B |
| Layer 3 | Deterministic clinical commit gate | Offline TypeScript RxNorm and 7-region WHO INN (76 ingredients, 170 brands), 21 CFR 201.66 Drug Facts state machine, fuzzy OCR recovery, and pack-count guard |
Parity Swift RxNorm and 7-region WHO INN, 21 CFR 201.66 Drug Facts state machine, fuzzy OCR recovery, and 24h PK timeline | 0 B |
| Layer 4 | Live FDA grounding, long-tail brands, header-masked handwriting, and 5-language voice | InferenceMode.ONLY_IN_CLOUD (generateContentStream gemini-3.5-flash-lite, FOREIGN_BRAND_SCHEMA, and gemini-3.8-flash-tts with 44-byte RIFF/WAV normalizer) |
Dedicated cloud GenerativeModel (tools: [.googleSearch()], SafetySetting, and gemini-3.8-flash-tts RIFF/WAV) |
0 B PHI (generic names or header-masked Rx only) |
| Layer 5 | Proof, sync, and governance | SHA-256 audit chain, persistentLocalCache Firestore, App Check Fraud Defense, and Remote Config v3 |
Parity SHA-256 chain, .task(id:) Firestore listeners, App Attest, and real-time addOnConfigUpdateListener |
0 B PHI |
Challenges we ran into
FDA 21 CFR 201.66 multi-line Drug Facts warnings caused cross-drug false positives. Real OTC cartons print interacting drug names like
warfarininsideWarningsand excipients insideInactive Ingredients. I built a deterministic Drug Facts section state machine in TypeScript and Swift that isolatesActive Ingredientsbefore drug matching, reducing warning false positives to0.Capsule ink triggered
5/100false matches against bare"potassium"on live openFDA labels. Realapi.fda.govlabels listed trace"potassium hydroxide"inside capsule imprint ink. Replacing bare"potassium"matching with clinical salt terms across Web and iOS dropped false matches from5/100to0/100, lifted in-corpus recall to85/85 (100%), and held out-of-corpus holdout refusals at15/15 (100%).Real handwritten prescriptions and reflective metallic foil packs broke naive OCR. Testing a real 6-drug handwritten cardiologist prescription split tablet strengths across lines (
IBUPROFENfollowed on the next line by800mg), used shorthand schedules (1+0+1,(T.D.S),(B:I.D)), and produced OCR typos (AMLODIFNE), while red metallic antibiotic strips (Fimoxyl 500Amoxycillin BP) created glare. I added split-line strength attachment, regional dosing parsers, bounded Levenshtein fuzzy recovery (<= 2edits with a locked 3-letter prefix), British-spelling INN aliases (amoxycillintoamoxicillin), and an automatic top-11% header-masked handwriting fallback.Firestore security rules and Web PCM audio gaps caught by official Firebase Agent Skills. Auditing
firestore.rulessurfaced missing server-side PHI denylist rules and mutable audit entries, while Web playback required wrapping raw 24 kHz linear PCM fromgemini-3.8-flash-ttsin a 44-byte RIFF/WAV header. Adding a 30-key server-side PHI denylist and append-only SHA-256 hash-chain rules raised the security audit score from3/5to5/5, and adding the RIFF/WAV normalizer enabled clean 5-language playback on Chrome and Safari.
Accomplishments that we're proud of
Inspect the reproducible real-photo OCR test results in the repository.
- Offline reproducible 68-photo real packaging Apple Vision OCR pipeline (
tests/ocr-pipeline/): The repository ships 68 attributed real packaging photographs (50 CC-licensed Wikimedia Commons international packs and 18 U.S. NIH DailyMed FDA labels) with the compiled Apple Vision runner. It achieves51/56 (91.1%)exact labeled match at232 ms/photo,12/12 (100%)loose-pill and bare-blister refusals,27/27pack-count traps blocked, and68/68zero-byte PII verification. - Unfakeable live physical iPhone test on real handwritten Rx and metallic antibiotic strips: Check Demo on YoutubeOn a physical iPhone SE running offline, MedLedger decodes a real 6-drug handwritten cardiologist prescription (flagging critical
Ibuprofen + Naproxendouble-NSAID stacking alongside diabetes and blood pressure drugs and speaking the alert aloud) and reads a red metallicFimoxyl 500(Amoxycillin BP 500 mg) blister strip to display equivalents across all 7 jurisdictions. - Verified clinical recall and clean cross-platform builds: MedLedger passes
54/54automated Vitest tests on Web, achieves0/100false matches and85/85 (100%)in-corpus recall on liveapi.fda.govlabels, compiles on Xcode foriOS 17.0to27.2with0errors and0warnings, and passes8/8automated secret-hygiene checks. - Hybrid speedup and Firebase Spark unit economics: Layers 1 through 3 run locally in
413 ms(5.8xfaster than a ~2,400 ms cloud vision round-trip) at$0.00marginal cost. Selective Layer 4 cloud calls send about 650 tokens of anonymous generic names on demand ($0.0004paid-tier equivalent,$0.00within Firebase Spark free quotas) compared to the$206.00AJMC/JAPhA manual pharmacist reconciliation baseline.
What we learned
Live benchmarks on real packaging and real prescriptions are the only tests that matter. Taking photos of bottles in my own medicine cabinet produced encouraging early demos, but pushing the app through 68 royalty-free international packaging photos, 100 live openFDA labels, a handwritten cardiologist prescription, and a reflective antibiotic foil strip exposed failure modes that synthetic mocks hid. Those tests surfaced regional drug spelling differences (such as paracetamol, acetaminophen, amoxycillin, and amoxicillin), capsule-ink potassium false matches, FDA warning-section traps, and split-line handwritten dosing syntax. Solving every one of those bugs in deterministic code made the safety gate reliable before any cloud call runs.
What's next for MedLedger
Expand clinical specialties and global jurisdictions: Add formularies for other fields (e.g nephrology, neurology, and gastroenterology etc), and expand regional brand tables beyond the current 7 jurisdictions to cover Brazil and Latin America, MENA, Australia, Southeast Asia, Eastern Europe, and Africa.
Native Kotlin Android companion and outpatient clinical pilot: Add a third synced surface using
firebase-ai-ondeviceand ML Kit AICore for on-device bottle scanning on budget Android phones, and pilot zero-PII FHIR R4 handoff bundles with outpatient clinics.Scheduled cron dataset sync: Run automated scheduled jobs to pull updated openFDA, RxNorm, and WHO INN datasets and ship refreshed JSON bundles over the air so offline drug tables stay current.
Multigenerational immigrant and elderly polypharmacy homes: Expand shared zero-PII Caregiver Sync Rooms with multi-shift caregiver handoffs across languages so families can reconcile home-country medicines brought back by relatives beside local specialist prescriptions.
Maritime, aviation, and remote expedition crews: Support shipboard, offshore rig, and remote expedition medical kits where satellite connectivity is limited and supplies come from multiple countries.
Built With
- antigravity
- apple-foundation-model
- apple-vision
- fhir
- firebase
- firebase-ai-logic
- firebase-hosting
- gemini
- gemini-nano
- google-cloud
- openfda
- react
- rxnorm
- swift
- tailwind
- typescript
- vite
- xcode