Skip to content

Latest commit

 

History

History
254 lines (191 loc) · 23.5 KB

README.md

File metadata and controls

254 lines (191 loc) · 23.5 KB

MediSense AI — Smart Health & Supply Chain Resilience

Track: Resilience — Hack2Skill "Code for Communities 2"

An AI-powered early-warning platform that predicts medicine stock-outs before they happen and recommends cross-region redistribution to prevent them. It turns fragmented health-centre data into one shared view of risk — tracking stock, bed capacity, patient footfall, and staff attendance across India's Primary Health Centres so shortages are caught before they become crises.

Live demo: https://smart-health-brics.vercel.app

Why Resilience

MediSense AI strengthens the resilience of India's primary healthcare network by giving PHC administrators real-time visibility into the four operational signals that most often fail silently until they become a crisis: medicine stock, bed capacity, patient footfall, and staff attendance. AI-generated alerts and redistribution suggestions let administrators act before a stock-out or bed shortage disrupts care, and Hindi-language output ensures the tool is usable by staff across language backgrounds, not just English-fluent administrators.

Demo Access (for judges)

Email demo@smarthealth.com
Password judge-demo-2026

The demo account is read-only. You can explore the dashboard, alerts, risk scores and redistribution suggestions. The admin pages (add PHC, stock, attendance) are restricted to the admin role and are hidden from this account on purpose, so the shared demo data stays intact.

The Problem

Public health centres (PHCs) across India's states and districts often can't see medicine shortages, bed shortages, or staffing gaps coming until it is too late. Nobody can easily tell that one region has surplus stock while a neighbouring region is critically short — and this is true at national scale, not just in a single city or state.

What It Does

  • Tracks medicine stock, daily consumption, bed capacity/occupancy, patient footfall and staff attendance across PHCs in every Indian state and district
  • Predicts how many days of stock remain for every medicine
  • Generates plain-language early-warning alerts with Gemini, in English or Hindi
  • Matches surplus stock in one state against shortages in another and recommends a transfer
  • Combines stock and attendance into a risk score per PHC, with an AI-written explanation
  • Includes a Gemini-powered chat assistant that answers admin questions using live stock and redistribution data
  • Lets admins add and remove PHCs, stock, bed counts, and attendance records through simple forms

Real / Realistic Data

Live PHC inventory and footfall APIs aren't publicly available in India, so this project uses:

  • Real Indian geography — every state and district, not a hardcoded single city
  • Simulated stock depletion — a background job models realistic daily medicine consumption over time, so the dashboard reflects real depletion dynamics rather than static numbers

How It Works

┌─────────────┐     ┌──────────────────┐     ┌──────────────────────┐
│  React app  │────▶│  Express API     │────▶│  MongoDB Atlas       │
│  (Vercel)   │ JWT │  (Render)        │     │  PHCs, stock, users  │
└─────────────┘     └───────┬──────────┘     └──────────────────────┘
                            │
              ┌─────────────┴─────────────┐
              ▼                           ▼
     ┌─────────────────┐        ┌──────────────────┐
     │ Gemini API      │        │ FastAPI service  │
     │ alert, redist,  │        │ risk score       │
     │ risk explain,   │        │ (Render)         │
     │ chat — EN/HI    │        │                  │
     └─────────────────┘        └──────────────────┘
  1. Stock, bed, footfall and attendance data lives in MongoDB.
  2. The API calculates days of stock remaining for each medicine.
  3. Gemini turns that number into a short alert for the dashboard, in English or Hindi based on the user's language toggle.
  4. The API compares stock across PHCs to find surplus-versus-shortage matches, and Gemini writes the recommendation.
  5. The Python service combines stock risk (65%) and staffing risk (35%) into a 0–100 score per PHC. Gemini then explains it. If the Python service is unreachable, the API computes the same score locally.
  6. A Gemini-powered chat assistant answers free-form admin questions using the current alerts and redistribution data as context.
  7. The dashboard shows everything live and refreshes automatically.

Google AI Studio & Gemini

All four Gemini prompts below were designed and iterated on in Google AI Studio using gemini-3.8-flash, then moved into the codebase. Production runs on gemini-3.5-flash-lite for its higher free-tier throughput; the same prompts and behavior carry over unchanged.

Alert prompt:

Write a short, urgent one-sentence alert under 25 words for a hospital admin dashboard. {medicine} stock at {phc} in {state}, India will run out in {days} days. Be direct and actionable. Output only plain text, no JSON, markdown, or bullet points. Respond in {English/Hindi}.

Redistribution prompt:

Write a short, actionable one-sentence recommendation (under 30 words) for a hospital admin dashboard. Suggest transferring {amount} units of {medicine} from {fromPhc} in {fromState} to {toPhc} in {toState}, which is critically low. Be direct. Output only plain text, no JSON, markdown, or bullet points. Respond in {English/Hindi}.

Risk explanation prompt:

Write one short sentence (under 25 words) explaining why {phc} in {state}, India has a risk score of {score}/100. Lowest stock has {days} days remaining. Staff attendance is {rate}%. Be direct and specific. Output only plain text, no JSON, markdown, or bullet points. Respond in {English/Hindi}.

Chat assistant prompt:

You are an assistant embedded in a hospital supply-chain dashboard called MediSense AI. Answer the admin's question using ONLY the data below. Be concise (under 80 words), direct, and specific. If the data doesn't cover the question, say so plainly. Respond in {English/Hindi}.

Tech Stack

Layer Technology
Frontend React 19, TypeScript, Vite, Tailwind CSS, TanStack Query, React Router
Backend Node.js, Express 5, TypeScript, MongoDB, Mongoose, JWT
AI Google Gemini — gemini-3.8-flash for prompt design in AI Studio, gemini-3.5-flash-lite in production. Powers alerts, redistribution, risk explanation, and chat, in English or Hindi
Risk scoring Python, FastAPI
Hosting Vercel (frontend), Render (API and risk service), MongoDB Atlas (database)

Project Structure

├── client/           React + Vite frontend
│   └── src/          pages, components, auth context, API helpers
├── server/           Express API
│   └── src/
│       ├── routes/       auth, phc, stock, attendance, country, risk, chat
│       ├── models/       Mongoose schemas
│       ├── middleware/   JWT auth, role checks, rate limiting
│       └── utils/        forecasting, redistribution, Gemini helpers
└── python-service/   FastAPI risk-score service

Getting Started

Prerequisites

  • Node.js 20+
  • Python 3.10+
  • A MongoDB database (local or Atlas)
  • A Gemini API key

1. Clone

git clone https://github.com/Parthwebde12/MediSense-AI.git
cd MediSense-AI

2. Risk service (optional but recommended)

cd python-service
python -m venv venv
venv\Scripts\activate        # macOS/Linux: source venv/bin/activate
pip install -r requirements.txt
uvicorn main:app --port 8001

If you skip this, the API falls back to computing the same score itself.

3. Server

cd server
npm install

Create server/.env:

PORT=5000
MONGO_URI=your_mongodb_connection_string
JWT_SECRET=a_long_random_string
GEMINI_API_KEY=your_gemini_api_key
PYTHON_SERVICE_URL=http://localhost:8001
SIMULATE_CONSUMPTION=false

Create the country record and your first admin account, then start the server:

npm run seed
npm run create-user -- --name "Your Name" --email you@example.com --password "a-strong-password" --role regional_admin
npm run dev

npm run seed deletes all PHCs, stock and attendance records before re-creating countries. Run it on a fresh database only.

4. Client

cd client
npm install

Optionally create client/.env. Without it, the client talks to http://localhost:5000/api:

VITE_API_URL=http://localhost:5000/api
npm run dev

Open http://localhost:5173 and log in with the admin account you created.

Environment Variables

Server (server/.env)

Variable Required Description
MONGO_URI Yes MongoDB connection string
JWT_SECRET Yes Secret used to sign login tokens
GEMINI_API_KEY Yes Key for alert, redistribution, risk explanation and chat text (fallback messages are used if it fails)
PORT No Defaults to 5000
PYTHON_SERVICE_URL No Risk service URL, defaults to http://localhost:8001
SIMULATE_CONSUMPTION No Set to true to drain stock over time for demos

Client (client/.env)

Variable Description
VITE_API_URL API base URL, defaults to http://localhost:5000/api
VITE_DEMO_EMAIL Shows a "Try the demo account" box on the login page
VITE_DEMO_PASSWORD Password for the demo account (public, so use a read-only account)

Roles

Role Can do
phc_staff View the dashboard, alerts, redistribution and risk scores
regional_admin Everything above, plus add and delete PHCs, stock, beds and attendance, and create users

Accounts are created by admins only. Use npm run create-user to create the first admin or to change a user's role or password.

API Overview

All routes except login and health need a Authorization: Bearer <token> header. ?lang=hi on /api/stock/alerts, /api/stock/redistribution, and /api/risk returns Hindi text; omit it (or use ?lang=en) for English.

Method Route Access Purpose
GET /api/health Public Health check
POST /api/auth/login Public Log in and receive a token
POST /api/auth/register Admin Create a user
GET /api/country Any user List countries
GET /api/phc Any user List PHCs
POST /api/phc Admin Add a PHC (with bed counts)
PATCH /api/phc/:id/beds Admin Update a PHC's bed totals/occupancy
DELETE /api/phc/:id Admin Delete a PHC and its stock and attendance
GET /api/stock Any user List stock records
POST /api/stock Admin Add a stock record
PATCH /api/stock/:id Admin Update a stock quantity
GET /api/stock/alerts Any user Top stock-out alerts
GET /api/stock/redistribution Any user Redistribution suggestions
GET /api/attendance Any user List attendance records (includes patient footfall)
POST /api/attendance Admin Add an attendance record
GET /api/risk Any user Risk scores for the highest-risk PHCs (cached for 60 seconds)
POST /api/chat Any user Ask the Gemini-powered assistant a question about current stock/alerts

Deployment

  • Frontend (Vercel): set VITE_API_URL, and optionally VITE_DEMO_EMAIL and VITE_DEMO_PASSWORD. Redeploy after changing them, because Vite reads them at build time.
  • API (Render): set the server variables above.
  • Risk service (Render): run uvicorn main:app --host 0.0.0.0 --port $PORT.
  • Database: MongoDB Atlas.

Made By

Parth Wakodikar — GitHub · LinkedIn