Skip to content

Latest commit

Β 

History

2 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ₯ Hospital AI Clinical Assistant

Production-grade, Groq-powered voice-to-prescription intelligence platform for multispeciality hospitals.

React Vite Groq TailwindCSS Framer Motion


πŸ“‹ Table of Contents

  1. Overview
  2. Core Features
  3. Tech Stack
  4. Project Architecture
  5. Module Documentation
  6. AI & Intelligence Layer
  7. Data Models
  8. Setup & Configuration
  9. Environment Variables
  10. Usage Guide
  11. UI Redesign Prompt (Stitch)

🌟 Overview

Hospital AI Clinical Assistant is a fully browser-based, zero-backend clinical documentation system designed for busy hospital doctors. It leverages Groq's LLaMA 3.1 8B Instant model to convert raw spoken doctor notes into structured, printable prescriptions β€” in real time.

The system works in two modes:

  • Online Mode (Groq AI): Doctor speaks β†’ Browser STT captures β†’ Groq AI structures β†’ Prescription generated
  • Offline Mode (Local Parser): Zero API dependency, regex+NLP-based offline fallback with 250-medicine database

All data is stored in localStorage (HIPAA-style client-only, no server uploads).


βœ… Core Features

1. 🎀 Voice-Activated Clinical Documentation

  • Uses Web Speech API (browser-native, no external SDK)
  • Language set to en-IN for Indian medical terminology
  • Continuous listening with 3-second silence detection auto-stop
  • Real-time interim transcript display while speaking
  • Stop/restart toggle with status indicators (idle / listening / processing)

2. πŸ€– Groq AI Prescription Extraction

  • Model: llama-3.1-8b-instant (ultra-fast inference)
  • Converts unstructured voice transcript β†’ full structured clinical JSON
  • Extracts: Patient Name, UHID, Age, Gender, Chief Complaint, Surgical History, Abdomen Examination, Palpable Abnormality, Radiology Impression, Provisional Diagnosis, Investigations Advised (Cardiac/Lab/Radiology), Management Plan, Medicines
  • Handles phonetic errors (e.g., "Azy" β†’ "Azithromycin", "Dolo" β†’ "Dolo 650")
  • Response format enforced as json_object for zero-parse-failure
  • Temperature: 0.1 for maximum clinical determinism

3. 🧬 Medicine Validation Engine (medicineValidator.js)

  • 250-medicine database spanning all clinical categories
  • 3-tier validation pipeline:
    1. Exact match (case-insensitive)
    2. Contains match (partial name match)
    3. Fuzzy match via Levenshtein distance (≀4 edits threshold)
  • Each medicine gets a validation badge: βœ… Verified / ⚠️ Auto-corrected / ❌ Not in DB

4. πŸ“‹ Clinical Prescription Card (PrescriptionCard.jsx)

  • Rich structured UI card with sections:
    • Patient info (Name, UHID, Age)
    • Clinical History (Chief Complaint, Surgical History)
    • Examination (Abdomen, Palpable Abnormality)
    • Radiology (Findings / Impression)
    • Assessment (Diagnosis, Management Plan)
    • Investigations (Cardiac / Lab / Radiology)
    • Prescription Table (Medicine | Dosage | Frequency | Duration)
  • Inline Edit Mode β€” doctor can edit any field directly in the card
  • Export to Word (.doc) β€” generates professional letterhead HTML β†’ .doc via Blob API
  • Print to PDF β€” browser print dialog with print-optimized CSS

5. πŸ’¬ Chat Interface (ChatInterface.jsx)

  • Dual-bubble chat (Doctor bubble right, AI bubble left)
  • Prescription cards rendered inline inside AI message thread
  • Supports text input (keyboard) and voice input (mic button)
  • File attachment button (UI ready, extendable)
  • Error display bar with auto-dismiss
  • Smooth scroll-to-latest using useRef
  • Animated typing indicator while Groq processes

6. πŸ—‚οΈ Patient Directory (PatientDirectory.jsx)

  • Aggregates all consultations into unique patient records (deduplicated by UHID or name)
  • Shows: Total Patients, Total Records, Active Today (live stat cards)
  • Searchable by patient name or UHID
  • Click "View Rx" β†’ jumps directly to that consultation's chat

7. πŸ’Š Medicine Inventory Manager (MedicineInventory.jsx)

  • Full CRUD on the medicine database:
    • Add new medicine formulation
    • Inline Edit existing medicine name
    • Delete with confirmation
  • Real-time search filter (250+ items)
  • Changes persist to localStorage
  • Toast notifications for success/error states

8. βš™οΈ Settings Panel (Settings.jsx)

  • Hospital Profile: Edit institutional name (reflected everywhere in the UI)
  • AI Integration: Securely paste/update Groq API key (masked password input)
  • Danger Zone: Factory reset β€” clears all localStorage consultation data
  • Sticky Save bar at the bottom

9. πŸ”‘ API Key Modal (ApiKeyModal.jsx)

  • Accessible from the Chat header Settings icon
  • Key format validation (gsk_ prefix check)
  • Key stored in localStorage only (never sent to any server except Groq's own endpoint)
  • Show/hide password toggle
  • Links directly to console.groq.com/keys

10. πŸ—ƒοΈ Consultation History & Persistence

  • All consultations stored in localStorage as JSON (hospital_consultations)
  • Sidebar groups consultations as Today vs Previous
  • Click any consultation β†’ restores full chat + prescriptions
  • New Consultation button starts a fresh session
  • Hospital name and API key also persist across page reloads

11. πŸ“„ Offline Prescription Parser (prescriptionParser.js)

  • Zero-dependency fallback when no API key is configured
  • Extracts via regex patterns:
    • Patient name (supports Mr/Mrs/Miss/Dr prefixes)
    • UHID from "UHID:", "Patient ID:", "PID:"
    • Age from "age 45", "45 years old"
    • Gender from gendered pronouns & keywords
    • Symptoms from 35+ keyword dictionary
    • Medicines directly from 250-medicine database scan
    • Dosage (mg/ml/mcg/tab/cap), Frequency, Duration
  • generateDocument() creates plain-text formatted prescription

12. πŸ“± Responsive Layout

  • Sidebar hidden on mobile, slides in via transform/translate
  • Mobile hamburger menu toggles sidebar
  • Backdrop blur overlay on mobile sidebar open
  • All views (Chat, Directory, Inventory, Settings) fully mobile-responsive

πŸ› οΈ Tech Stack

Layer Technology Purpose
Framework React 18.2 + Vite 5.2 SPA, fast HMR dev
Styling TailwindCSS 3.4 Utility-first responsive design
Animation Framer Motion 11 Page transitions, card animations
Icons Lucide React Consistent medical + UI icons
AI Engine Groq Cloud (LLaMA 3.1 8B) Voice→JSON prescription extraction
STT Web Speech API (browser native) Real-time voice transcription
Storage localStorage Client-only data persistence
Build Vite + @vitejs/plugin-react Fast build + JSX transform
Linting ESLint + react-hooks plugin Code quality

πŸ“ Project Architecture

hospital-assistant/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ App.jsx                    # Root β€” state, routing, persistence
β”‚   β”œβ”€β”€ main.jsx                   # React DOM entry
β”‚   β”œβ”€β”€ index.css                  # Global styles + Tailwind directives
β”‚   β”‚
β”‚   β”œβ”€β”€ components/
β”‚   β”‚   β”œβ”€β”€ Sidebar.jsx            # Left nav: consultations + module links
β”‚   β”‚   β”œβ”€β”€ ChatInterface.jsx      # Main doctor-AI chat + voice input
β”‚   β”‚   β”œβ”€β”€ PrescriptionCard.jsx   # Rich clinical report card + export
β”‚   β”‚   β”œβ”€β”€ PatientDirectory.jsx   # Patient list with stats + search
β”‚   β”‚   β”œβ”€β”€ MedicineInventory.jsx  # CRUD medicine database manager
β”‚   β”‚   β”œβ”€β”€ Settings.jsx           # Hospital config + API key + danger zone
β”‚   β”‚   └── ApiKeyModal.jsx        # Groq key input modal
β”‚   β”‚
β”‚   β”œβ”€β”€ utils/
β”‚   β”‚   β”œβ”€β”€ groqApi.js             # Groq API calls (extract + document gen)
β”‚   β”‚   β”œβ”€β”€ medicineValidator.js   # 3-tier fuzzy medicine validation
β”‚   β”‚   └── prescriptionParser.js  # Offline regex-based transcript parser
β”‚   β”‚
β”‚   └── data/
β”‚       └── medicines.js           # 250-medicine curated database
β”‚
β”œβ”€β”€ public/
β”œβ”€β”€ vite.config.js
β”œβ”€β”€ tailwind.config.js
β”œβ”€β”€ package.json
└── README.md

πŸ“¦ Module Documentation

App.jsx β€” State Orchestrator

  • Manages top-level state: apiKey, hospitalInfo, medicines, consultations, currentConsultationId, view
  • All state persists to localStorage via useEffect
  • Routes between 4 views: chat, directory, medicines, settings
  • Passes onUpdateConsultation handler to ChatInterface for history sync

ChatInterface.jsx β€” Core Interaction Engine

  • State: micStatus, transcript, inputText, prescriptions, messages, metadata, errorMsg
  • Web Speech API lifecycle: startListening() β†’ onresult (interim) β†’ 3s silence β†’ stopListening() β†’ processAndSend()
  • processAndSend(text):
    1. Appends doctor message to thread
    2. Calls extractPrescriptionFromSpeech() (Groq) or parseTranscript() (offline)
    3. Appends AI reply + PrescriptionCard to thread
    4. Updates metadata (patient name, diagnosis)
    5. Syncs back to history via onUpdateHistory()

groqApi.js β€” AI Communication Layer

  • groqRequest(apiKey, system, user) β€” generic Groq fetch with JSON response format
  • extractPrescriptionFromSpeech(transcript, apiKey, medicineList) β€” primary extraction
    • Injects hospital medicine list into system prompt for phonetic correction
    • Validates returned medicines via validateMedicines()
  • generatePrescriptionDocument(structuredData, hospitalName, apiKey) β€” formats plain text document

medicineValidator.js β€” Fuzzy Match Engine

  • levenshtein(a, b) β€” O(mΓ—n) DP string distance
  • validateMedicine(input) β€” 3-tier: exact β†’ contains β†’ Levenshtein (≀4)
  • validateMedicines(array) β€” maps validation over AI medicine array

prescriptionParser.js β€” Zero-Dependency Fallback

  • parseTranscript(transcript) β€” full offline extraction pipeline
  • generateDocument(data, hospitalName) β€” plain text prescription formatter

🧠 AI & Intelligence Layer

Groq API Configuration

Endpoint : https://api.groq.com/openai/v1/chat/completions
Model    : llama-3.1-8b-instant
Temp     : 0.1 (deterministic for medical accuracy)
Format   : json_object (guaranteed JSON output)

Prompt Engineering (System)

The system prompt instructs the model to:

  1. Output ONLY valid JSON (no markdown, no prose)
  2. Use null for missing fields
  3. Fix phonetic errors by mapping to the injected medicine list
  4. Extract comprehensive clinical fields from single voice input

Output JSON Schema

{
  "patient_name": "string | null",
  "age": "number | null",
  "gender": "string | null",
  "uhid": "string | null",
  "chief_complaint": "string",
  "past_history": {
    "surgical_history": "string",
    "duration": "string"
  },
  "clinical_examination": {
    "abdomen": "string",
    "palpable_abnormality": "string"
  },
  "radiology": {
    "findings": "string",
    "impression": "string"
  },
  "provisional_diagnosis": "string",
  "investigations_advised": {
    "cardiac": ["string"],
    "laboratory": ["string"],
    "radiology": ["string"]
  },
  "plan": "string",
  "medicines": [
    {
      "name": "string",
      "dosage": "string",
      "frequency": "string",
      "duration": "string"
    }
  ]
}

πŸ“Š Data Models

Consultation Object (localStorage)

{
  id: 1712345678901,          // timestamp as unique ID
  patient_name: "Ramesh Patel",
  diagnosis: "Acute Appendicitis",
  messages: [
    { role: "doctor" | "ai", content: "...", type?: "prescription", prescriptionData?: {} }
  ],
  prescriptions: [
    { id: 1712345678902, data: { ...prescriptionJSON } }
  ]
}

Medicine Validation Object

{
  name: "Dolo",                        // raw AI output
  dosage: "650mg",
  frequency: "Twice Daily",
  duration: "5 days",
  validation: {
    matched: "Dolo 650",               // corrected name from DB
    status: "fuzzy",                   // valid | fuzzy | invalid
    original: "Dolo"
  }
}

πŸš€ Setup & Configuration

Prerequisites

Installation

# Clone / open project
cd hospital-assistant

# Install dependencies
npm install

# Start development server
npm run dev

# Production build
npm run build

First Run

  1. App runs at http://localhost:5173
  2. Click the βš™οΈ Settings icon in the chat header
  3. Enter your Groq API key (gsk_...)
  4. Start speaking! Press the 🎀 microphone button

πŸ” Environment Variables

Create a .env file in the project root (optional):

# If set, this key is pre-loaded (user can still override via UI)
VITE_GROQ_API_KEY=gsk_your_key_here

Note: Without a key, the app automatically falls back to the offline regex parser. No functionality is broken β€” the offline mode still extracts medicines, patient details, and generates prescriptions.


πŸ“– Usage Guide

Starting a Consultation

  1. Click "New Consultation" in the sidebar
  2. Press the 🎀 microphone button (turns red when listening)
  3. Speak naturally: "Patient Ramesh Patel, age 58, male, UHID 12345. Chief complaint chest pain for 3 days. Past surgical history appendectomy 2 years ago. Abdomen soft. No palpable abnormality. USG shows impression of kidney stone. Provisional diagnosis acute cholecystitis. Advise CBC, LFT, USG abdomen. Prescribe Pantoprazole 40mg once daily for 7 days, Buscopan twice daily for 5 days."
  4. Stop talking β†’ 3-second silence auto-submits
  5. Prescription card appears instantly

Editing a Prescription

  • Click "Edit Report" on any prescription card
  • All fields become editable inline
  • Click "Finish Editing" to save

Exporting

  • Word (.doc): Generates professional letterhead document
  • Print PDF: Browser print dialog with clinic-ready layout

Managing Medicines

  • Go to Medicine Inventory from the sidebar
  • Search, add, edit, or remove medicines
  • Changes immediately affect AI phonetic correction


πŸ“Œ Notes

  • All data is client-side only β€” no server, no database, no cloud storage
  • The Groq API key is stored in localStorage β€” remind users this is their own browser
  • The offline parser is a robust fallback but Groq AI provides far superior accuracy
  • The medicine database can be expanded by adding entries to src/data/medicines.js
  • For production deployment, consider adding HTTPS + CSP headers for security

Built with ❀️ for clinical excellence

Releases

Packages

Contributors

Languages