Digitize physical lab reports into structured, doctor-ready clinical data — in seconds.
A full-stack healthcare workflow application that uses OCR to extract diagnostic metrics from photographed lab reports, pairs patients with doctors via QR code, and delivers real-time dashboards with trend analysis, clinical notes, and PDF export.
- Overview
- Key Features
- How It Works
- Tech Stack
- Architecture
- Getting Started
- Project Structure
- API Reference
- Database Schema
- Environment Variables
- Scripts
- Deployment
- Contributing
- License
ContextCare AI bridges the gap between physical lab reports and digital clinical workflows. In many healthcare settings — especially in emerging markets — lab results still arrive as printed or handwritten documents. Doctors manually re-enter this data, which is slow, error-prone, and impossible to trend over time.
ContextCare solves this by letting patients photograph their reports on any smartphone. The built-in OCR engine extracts key diagnostic values, which are then surfaced on a real-time doctor dashboard with historical trends, reference ranges, and clinical notes — no manual data entry required.
| Feature | Description |
|---|---|
| 📸 Smart OCR Extraction | Powered by Tesseract.js with Sharp preprocessing — extracts 6 key diagnostic metrics (FBS, Cholesterol, HDL, LDL, Triglycerides, Hemoglobin) from photographed lab reports |
| 🔗 QR Code Pairing | Patients scan a doctor-specific QR code to securely link their reports to the right physician |
| 📊 Real-time Dashboard | Doctor dashboard updates instantly via Socket.IO with metric cards, status indicators, and trend charts |
| 📈 Trend Analysis | Recharts-powered line charts with reference bands show how patient metrics evolve over multiple scans |
| 📝 Clinical Notes | Append-only notes ledger lets doctors record observations directly alongside patient data |
| 📄 PDF Export | One-click PDF report generation using @react-pdf/renderer for sharing or archival |
| 🔒 Secure Auth | PIN-based doctor authentication with encrypted session cookies via iron-session |
| ⚡ Rate Limiting | Built-in in-memory rate limiter to protect OCR and auth endpoints from abuse |
+-------------+ +--------------+ +------------+ +------------------+
| Patient | | OCR Engine | | Database | | Doctor Dashboard |
| (Phone) |---->| (Extract) |---->| (Store) |---->| (Real-time) |
+-------------+ +--------------+ +------------+ +------------------+
| | | |
1. Photo 2. Parse 3. Persist 4. Display
lab report 6 diagnostic patient data + metric cards,
metrics with extracted metrics trends, notes,
reference ranges PDF export
Step-by-step flow:
- 📸 Capture — Patient photographs their lab report using their phone's camera
- 🔍 Extract — Tesseract.js OCR engine with Sharp image preprocessing identifies and parses 6 key diagnostic metrics
- ✅ Review — Patient reviews the extracted values for accuracy before submission
- 🔗 Pair — Patient scans a doctor-specific QR code to link results to their physician
- ⚡ Notify — Socket.IO pushes a real-time event to the doctor's dashboard
- 📊 Analyze — Doctor views metric cards with normal/borderline/critical status, trend charts with reference bands, appends clinical notes, and exports PDF reports
| Layer | Technology | Purpose |
|---|---|---|
| Framework | Next.js 14 (App Router) | Full-stack React framework with server-side rendering |
| Language | TypeScript 5.6 | Type-safe development across the entire codebase |
| Styling | Tailwind CSS 3.4 | Utility-first CSS for rapid, responsive UI development |
| Database | SQLite + Prisma ORM | Zero-config embedded database with type-safe queries |
| Real-time | Socket.IO 4.8 | Bi-directional WebSocket communication for live updates |
| OCR | Tesseract.js 5 + Sharp | Client-side OCR with server-side image preprocessing |
| @react-pdf/renderer | React-based PDF document generation | |
| Auth | iron-session | Encrypted, stateless session cookies |
| Charts | Recharts | Composable charting library built on D3 |
| Icons | Lucide React | Beautiful, consistent open-source icon set |
| QR | qrcode + html5-qrcode | QR code generation and scanning |
| Server | Custom Node.js HTTP server | Unified HTTP + WebSocket server for Next.js + Socket.IO |
┌────────────────────────────────────────┐
│ Custom HTTP Server │
│ (server.ts) │
├────────────────────┬───────────────────┤
│ Next.js App │ Socket.IO │
│ (SSR + API) │ (WebSocket) │
└────────┬───────────┴────────┬──────────┘
│ │
┌───────────────────┼────────────────────┼──────────────┐
│ │ │ │
┌────────▼────────┐ ┌───────▼───────┐ ┌────────▼────────┐ │
│ Patient Flow │ │ Doctor Flow │ │ Real-time │ │
│ │ │ │ │ Events │ │
│ • Upload photo │ │ • PIN login │ │ │ │
│ • OCR extract │ │ • Dashboard │ │ • scan:created │ │
│ • Review │ │ • Notes │ │ • heartbeat │ │
│ • QR pairing │ │ • PDF export │ │ │ │
└────────┬────────┘ └───────┬───────┘ └─────────────────┘ │
│ │ │
└──────────┬───────┘ │
│ │
┌────────▼─────────┐ │
│ Prisma ORM │ │
│ + SQLite DB │ │
└──────────────────┘ │
┌───────────────────────────────────────────────────────┘
│
┌────────▼────────┐
│ Tesseract.js │
│ + Sharp │
│ (OCR Pipeline) │
└─────────────────┘
The application uses a custom Node.js HTTP server (server.ts) that mounts both the Next.js request handler and a Socket.IO instance on the same port. This enables seamless real-time communication without a separate WebSocket server.
Key architectural decisions:
- Single-process deployment — Next.js + Socket.IO share the same HTTP server, simplifying deployment and avoiding CORS complexity
- Offline-capable OCR — Ships with
eng.traineddataintessdata/, no external API calls for text extraction - Stateless auth — Encrypted cookies via
iron-sessioneliminate the need for a session store - Embedded database — SQLite requires zero setup and is perfect for single-instance deployments
| Requirement | Version |
|---|---|
| Node.js | 18+ (LTS recommended) |
| npm | 9+ |
# 1. Clone the repository
git clone https://github.com/your-username/contextcare-ai.git
cd contextcare-ai
# 2. Install dependencies
npm install
# 3. Set up environment variables
cp .env.example .env
# Edit .env and set SESSION_SECRET (min 32 characters)
# Generate one: node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
# 4. Initialize the database and seed demo data
npx prisma migrate deploy
npm run db:seed
# 5. Start the development server
npm run devThe app will be available at http://localhost:3000 🎉
Use these pre-seeded doctor accounts to explore the dashboard:
| 👨⚕️ Doctor | Specialization | 🔑 PIN |
|---|---|---|
| Dr. Ananya Sharma | General Physician | 1234 |
| Dr. Rohan Mehta | Endocrinologist | 5678 |
| Dr. Priya Nair | Internal Medicine | 9012 |
💡 Tip: Open the patient flow (
/) on your phone and the doctor dashboard (/doctor/dashboard) on your desktop to see the real-time pairing in action.
contextcare-ai/
│
├── 📂 app/ # Next.js App Router
│ ├── page.tsx # Patient upload flow (home page)
│ ├── layout.tsx # Root layout with metadata
│ ├── globals.css # Global styles
│ ├── icon.svg # App favicon
│ │
│ ├── 📂 doctor/
│ │ ├── login/page.tsx # Doctor PIN-pad login
│ │ └── dashboard/page.tsx # Real-time doctor dashboard
│ │
│ └── 📂 api/
│ ├── 📂 doctor/
│ │ ├── login/ # POST — Authenticate doctor via PIN
│ │ ├── logout/ # POST — Clear session
│ │ ├── me/ # GET — Current session info
│ │ ├── patients/ # GET — Paginated patient list with metrics
│ │ └── qr/ # GET — Generate QR pairing token
│ │
│ └── 📂 scans/
│ ├── extract/ # POST — Upload image → OCR → extract metrics
│ └── pair/ # POST — Link scan to doctor via QR token
│
├── 📂 components/
│ ├── MetricCard.tsx # Diagnostic metric display with status badge
│ ├── TrendChart.tsx # Recharts line chart with reference bands
│ ├── NotesLedger.tsx # Append-only clinical notes component
│ ├── QrPairOverlay.tsx # Doctor-side QR pairing modal
│ ├── Disclaimer.tsx # App disclaimer notice
│ └── 📂 PatientUploadFlow/ # Multi-step upload wizard components
│
├── 📂 lib/
│ ├── auth.ts # Session-based auth helper
│ ├── db.ts # Prisma client singleton
│ ├── metrics.ts # Metric definitions, reference ranges & OCR parsing
│ ├── ocr.ts # Tesseract.js + Sharp preprocessing pipeline
│ ├── pdf.ts # PDF report builder
│ ├── ratelimit.ts # In-memory rate limiter
│ ├── session.ts # iron-session configuration
│ └── socket.ts # Socket.IO helpers & room management
│
├── 📂 prisma/
│ ├── schema.prisma # Database schema (Doctor, Patient, Scan, Metric, Note)
│ └── seed.ts # Demo data seeder
│
├── 📂 scripts/
│ └── render-pdf.mjs # Standalone PDF renderer script
│
├── 📂 tessdata/
│ └── eng.traineddata # Offline English OCR language model
│
├── server.ts # Custom HTTP + Socket.IO server
├── next.config.js # Next.js configuration
├── tailwind.config.ts # Tailwind CSS configuration
├── tsconfig.json # TypeScript configuration
├── postcss.config.js # PostCSS configuration
├── .env.example # Environment variable template
├── .prettierrc # Code formatting rules
└── package.json # Dependencies & scripts
| Method | Endpoint | Description | Auth |
|---|---|---|---|
POST |
/api/doctor/login |
Authenticate via doctor name + PIN | ❌ |
POST |
/api/doctor/logout |
Clear the session cookie | ✅ |
GET |
/api/doctor/me |
Get the current logged-in doctor | ✅ |
GET |
/api/doctor/patients |
List patients with their latest metrics | ✅ |
GET |
/api/doctor/qr |
Generate a QR code token for patient pairing | ✅ |
| Method | Endpoint | Description | Auth |
|---|---|---|---|
POST |
/api/scans/extract |
Upload a lab report image → OCR → extract metrics | ❌ |
POST |
/api/scans/pair |
Link an extracted scan to a doctor via QR token | ❌ |
| Event | Direction | Description |
|---|---|---|
join |
Client → Server | Doctor dashboard joins a room to receive updates |
scan:created |
Server → Client | Pushed when a new scan is paired with a doctor |
ping:heartbeat |
Client → Server | Connection health check |
pong:heartbeat |
Server → Client | Heartbeat acknowledgment |
The application uses 5 Prisma models with the following relationships:
┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐
│ Doctor │──1:N──│ Patient │──1:N──│ Scan │──1:N──│ Metric │
└──────────┘ └──────────┘ └──────────┘ └──────────┘
│
│──1:N──┌──────────┐
│ Note │
└──────────┘
| Model | Key Fields | Description |
|---|---|---|
| Doctor | name, specialization, pinHash, qrToken |
Physician account with hashed PIN and unique QR token |
| Patient | name, phone, doctorId |
Patient linked to a doctor (unique per doctor + phone) |
| Scan | rawText, patientId |
A single lab report OCR extraction |
| Metric | key, value, unit, refMin, refMax, status |
Individual diagnostic metric with reference range and status |
| Note | content, patientId |
Append-only clinical note on a patient |
| Variable | Required | Default | Description |
|---|---|---|---|
SESSION_SECRET |
Recommended | Built-in fallback | Encryption key for session cookies (min 32 chars). Generate one with: node -e "console.log(require('crypto').randomBytes(32).toString('hex'))" |
DATABASE_URL |
No | file:./dev.db |
SQLite database connection string |
PORT |
No | 3000 |
Server port |
⚠️ Production Note: Always set a strongSESSION_SECRETin production. The built-in fallback is for development convenience only.
| Command | Description |
|---|---|
npm run dev |
Start the development server with hot reload |
npm run build |
Build the Next.js application for production |
npm start |
Run database migrations, seed data, and start the production server |
npm run db:seed |
Seed the database with demo doctors and sample data |
npx prisma studio |
Open the Prisma database browser GUI |
npx prisma migrate dev |
Create and apply a new database migration |
ContextCare AI is designed for easy single-instance deployment. The app runs on a single process with an embedded SQLite database.
- Create a new Web Service on Render
- Connect your GitHub repository
- Configure the service:
- Build Command:
npm install && npx prisma generate && npm run build - Start Command:
npm start
- Build Command:
- Add environment variables:
SESSION_SECRET— A random 64-character hex stringDATABASE_URL—file:/data/dev.db(if using a persistent disk)
- (Optional) Attach a Persistent Disk mounted at
/datafor database durability
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
RUN npx prisma generate && npm run build
ENV NODE_ENV=production
EXPOSE 3000
CMD ["npm", "start"]Contributions are welcome! Here's how to get started:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
- Follow the existing code style (Prettier config included)
- Add TypeScript types for all new code
- Test OCR changes with sample lab report images
- Ensure Socket.IO events are documented
This project is licensed under the MIT License — see the LICENSE file for details.
Built with ❤️ for better healthcare workflows