Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Aarogya Logo

Aarogya

Link:

https://aarogya-frontend-992540367430.asia-south1.run.app

AI-Powered Healthcare Operations Platform for India's Primary Health Centres

Gemini Cloud Run Next.js FastAPI Python TypeScript License


📋 Table of Contents


🏥 Project Overview

Aarogya (meaning health in Sanskrit) is a full-stack, AI-powered healthcare operations platform designed to digitize and optimize the management of India's public health infrastructure — specifically Primary Health Centres (PHCs) and Community Health Centres (CHCs).

The platform provides a unified operational dashboard for District Administrators, Medical Officers, Doctors, Pharmacists, Lab Technicians, Receptionists, and Data Entry operators — enabling real-time monitoring of medicine inventories, doctor attendance, patient flow, bed occupancy, and automated AI-driven audit reports.

Built during the Google Gen AI Academy APAC Edition, Aarogya leverages Google Gemini 2.0 Flash for intelligent analytics, Google Cloud Translation API for multilingual access, Google Calendar API for doctor schedule integration, Google Maps API for geospatial facility visualization, and Google Cloud Run for scalable serverless deployment.


🎯 Problem Statement

India's public healthcare system manages over 30,000 PHCs and 5,600 CHCs, serving 700+ million rural citizens. These centres face critical operational challenges:

Challenge Impact
Paper-based inventory tracking Medicine stockouts go undetected until patients are turned away
Manual attendance registers Ghost attendance, no verification mechanism, no accountability
No centralized oversight District Administrators have zero real-time visibility into PHC operations
Reactive decision-making Problems are discovered after harm, not predicted in advance
Language barriers Healthcare workers in rural areas may not be fluent in English
No AI-driven insights Monthly reports are manually compiled, delayed, and subjective

Result: Preventable deaths, medicine wastage, staff absenteeism, and systemic inefficiency in the healthcare delivery chain.


💡 Solution

Aarogya replaces fragmented, paper-based workflows with a single, intelligent, role-based platform that provides:

  1. Real-time operational visibility across all PHCs/CHCs in a district
  2. AI-powered risk analysis using Google Gemini to proactively identify critical issues
  3. Automated monthly audit reports with AI-generated executive summaries and downloadable PDFs
  4. QR + GPS dual-verified attendance to eliminate ghost attendance
  5. Smart inventory management with AI-predicted stockouts and one-click resource requests
  6. Multilingual interface (English, Hindi, Marathi) via Google Cloud Translation
  7. Google Calendar integration for doctor schedule synchronization
  8. Geospatial facility mapping using Google Maps for district-wide oversight

✨ Key Features

🏛️ District Administration

  • District-wide dashboard with live KPIs across all health centres
  • Interactive Google Maps view of all PHCs/CHCs with health score markers
  • Resource request approval/rejection with AI-generated response letters
  • PHC registration with automated admin account creation and email onboarding

💊 Inventory Management

  • Full CRUD for medicine inventory with per-PHC isolation
  • CSV bulk upload for rapid stock initialization
  • AI-powered supply chain analysis via Gemini (identifies critical shortages, drafts emergency requests)
  • Real-time stock status tracking (Stable / Low Stock / Out of Stock)
  • Distribution logs and consumption analytics

👨‍⚕️ Doctor Attendance

  • QR code-based daily check-in with cryptographic token validation
  • GPS geofencing verification (Haversine distance calculation)
  • Google Calendar OAuth2 integration for doctor availability status
  • Medical Officer dashboard with attendance percentages and streak tracking
  • Late/Present/Absent/On Leave status automation

🛏️ Bed Management

  • Real-time bed status board (Available, Occupied, Reserved, Cleaning, Maintenance, Blocked)
  • Patient admission/discharge workflow with doctor assignment
  • Ward-wise and type-wise occupancy analytics
  • District-level bed summary with criticality indicators

👤 Patient Registration

  • Unique Patient ID generation (PT-YYYYMMDD-NNNN format)
  • Complete demographic and clinical data capture
  • Priority-based queue management (Normal / Urgent / Critical)
  • Wait time tracking with consultation timeline
  • Department-wise and hourly distribution analytics

📊 AI Analytics Dashboard

  • Deterministic Health Score (0–100) computed from weighted KPIs:
    • Medicine Availability (30%), Bed Occupancy (20%), Doctor Attendance (20%), Lab Services (15%), Patient Load (10%), Alert Score (5%)
  • Gemini-powered AI insights: executive summaries, risk assessments, priority actions
  • 7-day patient footfall trend and occupancy charts

📑 AI Monthly Reports

  • Automated monthly operational audit powered by Gemini
  • Professional PDF generation with cover page, KPI tables, risk assessment
  • Executive summaries, departmental analysis, improvement roadmaps
  • Downloadable PDF reports styled as government audit documents

🌐 Multilingual Support

  • Full UI translation to Hindi (हिंदी) and Marathi (मराठी)
  • Powered by Google Cloud Translation API v2
  • Client-side caching for translated strings

🔐 Role-Based Access Control (RBAC)

  • 10 distinct roles: District Admin, PHC Admin, Medical Officer, Doctor, Receptionist, Pharmacist, Lab Technician, Data Entry, PHC Staff, Developer
  • Frontend route guarding + Backend permission enforcement
  • Multi-tenancy: users only access data from their assigned PHC

🔷 Google Technologies Used

Google technologies are the foundational backbone of Aarogya's intelligence, deployment, and user experience layers.

Google Technology Purpose Why Chosen Integration Point
Gemini 2.0 Flash (via google-genai SDK) AI-powered analytics, risk analysis, monthly report generation, inventory analysis, AI approval letters Fastest inference with structured JSON output; superior medical text understanding gemini_service.py, inventory_routes.py, district_routes.py
Google Cloud Translation API v2 Real-time UI translation to Hindi & Marathi Native support for Indic languages; high accuracy; batch translation API translate_routes.py, LanguageContext.tsx
Google Calendar API Doctor schedule sync and availability status OAuth2 integration; native Calendar read access; real-time event checking calendar_routes.py
Google Maps JavaScript API Interactive district facility map with health-score markers Best-in-class mapping; InfoWindow support; color-coded markers MapComponent.tsx
Google Cloud Run Serverless containerized deployment for both frontend and backend Zero-config scaling; Docker-native; pay-per-use; native Cloud SQL integration Dockerfile (backend), Dockerfile (frontend), cloudbuild.yaml
Google Cloud SQL (PostgreSQL) Production database on Cloud Run Managed PostgreSQL; automatic backups; Cloud SQL Python Connector for IAM auth database.py, requirements.txt
Google Cloud Build CI/CD pipeline for container image builds Native GCP integration; builds from source; pushes to Artifact Registry cloudbuild.yaml
Google Artifact Registry Docker image storage for Cloud Run deployments Regional storage; integrated with Cloud Build and Cloud Run cloudbuild.yaml
Google OAuth2 (via google-auth-oauthlib) Doctor Google Calendar linking Standard OAuth2 consent flow; refresh token persistence calendar_routes.py
Gmail SMTP Automated onboarding emails for new PHC admins Reliable email delivery; app password support email_service.py

🛠️ Complete Tech Stack

Frontend

Technology Version Purpose
Next.js 16.2.10 React framework with App Router, SSR
React 19.2.4 UI component library
TypeScript 5.x Type-safe frontend development
Tailwind CSS 4.x Utility-first CSS framework
shadcn/ui 4.13.0 Pre-built accessible UI components
Recharts 3.9.2 Charting library for analytics dashboards
Lucide React 1.23.0 Icon library
react-leaflet 5.0.0 Fallback map rendering
@react-google-maps/api 2.20.8 Google Maps React integration
html5-qrcode 2.3.8 QR code scanning for attendance
qrcode.react 4.2.0 QR code generation
sonner 2.0.7 Toast notifications
date-fns 4.4.0 Date manipulation
next-themes 0.4.6 Dark/light theme support

Backend

Technology Version Purpose
FastAPI Latest Async Python web framework
Uvicorn Latest ASGI server
SQLAlchemy Latest ORM for database operations
Alembic Latest Database migration management
Pydantic Latest Data validation and serialization
python-jose Latest JWT token creation and validation
bcrypt Latest Password hashing
ReportLab Latest PDF report generation
google-genai Latest Google Gemini AI SDK
google-cloud-translate Latest Cloud Translation API client
google-auth-oauthlib Latest Google OAuth2 flows
google-api-python-client Latest Google Calendar API client
cloud-sql-python-connector Latest Cloud SQL IAM authentication

Database

Technology Purpose
SQLite Local development database
PostgreSQL (Neon) Remote development database
Google Cloud SQL (PostgreSQL 15) Production database

Infrastructure

Technology Purpose
Docker Containerization for both services
Google Cloud Run Serverless container hosting
Google Cloud Build CI/CD pipeline
Google Artifact Registry Container image storage

🏗️ Architecture Overview

graph TB
    subgraph "Frontend — Next.js 16 on Cloud Run"
        A[Browser Client] --> B[Next.js App Router]
        B --> C[AuthContext — JWT Management]
        B --> D[LanguageContext — i18n]
        B --> E[RouteGuard — RBAC]
        B --> F[shadcn/ui Components]
    end

    subgraph "Backend — FastAPI on Cloud Run"
        G[FastAPI Server] --> H[Auth Routes]
        G --> I[Analytics Routes]
        G --> J[Inventory Routes]
        G --> K[Attendance Routes]
        G --> L[Bed Routes]
        G --> M[Patient Routes]
        G --> N[Report Routes]
        G --> O[District Routes]
        G --> P[Calendar Routes]
        G --> Q[Translation Routes]
        G --> R[User Routes]
    end

    subgraph "Google AI & Cloud Services"
        S[Gemini 2.0 Flash]
        T[Cloud Translation API v2]
        U[Google Calendar API]
        V[Google Maps JS API]
        W[Google Cloud SQL]
        X[Gmail SMTP]
    end

    subgraph "Services Layer"
        G --> Y[gemini_service.py]
        G --> Z[health_score.py]
        G --> AA[pdf_generator.py]
        G --> AB[email_service.py]
    end

    A -->|REST API + JWT| G
    A -->|Maps Embed| V
    Y -->|Structured JSON| S
    Q -->|Batch Translate| T
    P -->|OAuth2 + Events| U
    G -->|SQLAlchemy ORM| W
    AB -->|SMTP TLS| X

    style S fill:#4285F4,color:#fff
    style T fill:#4285F4,color:#fff
    style U fill:#4285F4,color:#fff
    style V fill:#4285F4,color:#fff
    style W fill:#4285F4,color:#fff
    style X fill:#EA4335,color:#fff
Loading

⚙️ How It Works

1. Authentication & Authorization

A user logs in with their username, password, and PHC ID. The backend validates credentials via bcrypt, issues a JWT token (HS256, 7-day expiry), and returns the user's role and hospital assignment. The frontend stores the token in localStorage and attaches it to all API requests via Bearer header. A RouteGuard component enforces client-side route access based on the user's role.

2. Multi-Tenancy

Each user is bound to a specific hospital_id. All data queries are filtered by this ID, ensuring PHC-level data isolation. District Admins can pass ?hospital_id=X to view any PHC's data.

3. AI Pipeline

  • Live Analytics: The health_score.py service computes a deterministic Health Score from real database KPIs → this data is sent to Gemini 2.0 Flash → Gemini returns structured JSON with insights, risks, and recommendations.
  • Monthly Reports: Monthly KPIs are calculated → sent to Gemini for executive analysis → pdf_generator.py produces a professional PDF → stored on the server and linked in the database.
  • Inventory AI: Current stock levels are sent to Gemini → it identifies critical shortages and drafts emergency resource request messages.

4. Attendance Verification

Medical Officers generate a time-limited QR code (SHA-256 hashed token, 5-minute expiry). Doctors scan the QR and submit their GPS coordinates. The system validates: (a) QR token matches and hasn't expired, (b) GPS distance ≤ 50km of the PHC (relaxed for desktop testing; intended ≤ 100m). Attendance status is computed based on shift times with a 15-minute grace period.


🔄 Project Workflow

sequenceDiagram
    actor DA as District Admin
    actor MO as Medical Officer
    actor Doc as Doctor
    participant FE as Frontend (Next.js)
    participant BE as Backend (FastAPI)
    participant DB as Database
    participant AI as Google Gemini

    DA->>FE: Login (username + password)
    FE->>BE: POST /api/v1/auth/login
    BE->>DB: Validate credentials
    DB-->>BE: User + Role
    BE-->>FE: JWT Token + User info
    FE->>FE: Store token, redirect to dashboard

    DA->>FE: View District Overview
    FE->>BE: GET /api/v1/district/overview
    BE->>DB: Aggregate KPIs across all PHCs
    DB-->>BE: KPI data
    BE-->>FE: Dashboard data

    MO->>FE: View AI Analytics
    FE->>BE: GET /api/v1/analytics/
    BE->>DB: Calculate Health Score
    BE->>AI: Send KPIs to Gemini
    AI-->>BE: Structured JSON insights
    BE-->>FE: Score + AI Insights

    MO->>FE: Generate Monthly Report
    FE->>BE: POST /api/v1/reports/generate
    BE->>DB: Calculate monthly KPIs
    BE->>AI: Generate executive analysis
    AI-->>BE: Detailed report JSON
    BE->>BE: Generate PDF (ReportLab)
    BE->>DB: Save report record
    BE-->>FE: PDF download URL

    Doc->>FE: Scan QR for attendance
    FE->>BE: POST /api/v1/attendance/scan
    BE->>DB: Validate QR + GPS + Mark attendance
    BE-->>FE: Attendance status
Loading

🔄 System Flow

flowchart LR
    A[User Login] --> B{Role?}
    B -->|District Admin| C[District Dashboard]
    B -->|PHC Admin| D[Manage Roles]
    B -->|Medical Officer| E[Inventory/Analytics]
    B -->|Doctor| F[Attendance]
    B -->|Receptionist| G[Patients]
    B -->|Pharmacist| H[Inventory]
    B -->|Data Entry| I[Patients/Beds/Inventory]

    C --> J[View Map & KPIs]
    C --> K[Manage Resource Requests]
    C --> L[Register New PHC]

    E --> M[AI Analytics + Health Score]
    E --> N[Generate AI Reports]
    E --> O[Manage Inventory with AI]

    F --> P[QR Scan + GPS Check-in]
    F --> Q[Google Calendar Sync]
Loading

📁 Folder Structure

Aarogya/
├── backend/
│   ├── app/
│   │   ├── api/
│   │   │   ├── dependencies.py          # Auth dependencies, role checkers, hospital resolver
│   │   │   └── routes/
│   │   │       ├── analytics_routes.py   # AI analytics + health score endpoint
│   │   │       ├── attendance_routes.py  # QR generation, scanning, MO dashboard
│   │   │       ├── auth_routes.py        # Login endpoint with JWT issuance
│   │   │       ├── bed_routes.py         # Bed CRUD, admission/discharge, analytics
│   │   │       ├── calendar_routes.py    # Google Calendar OAuth2 + events
│   │   │       ├── district_routes.py    # District overview, map data, requests
│   │   │       ├── inventory_routes.py   # Inventory CRUD, CSV upload, AI analysis
│   │   │       ├── notification_routes.py# Notification read/fetch
│   │   │       ├── patient_routes.py     # Patient registration, queue, analytics
│   │   │       ├── phc_routes.py         # PHC registration, update, delete
│   │   │       ├── report_routes.py      # AI monthly report generation
│   │   │       ├── translate_routes.py   # Google Cloud Translation endpoint
│   │   │       └── user_routes.py        # User CRUD, role management
│   │   ├── core/
│   │   │   ├── config.py                 # Pydantic Settings (env vars)
│   │   │   └── security.py              # JWT, bcrypt, RBAC permissions
│   │   ├── db/
│   │   │   └── database.py              # SQLAlchemy engine + Cloud SQL connector
│   │   ├── models/                       # SQLAlchemy ORM models
│   │   │   ├── attendance.py             # Doctor, AttendanceRecord, DailyQRSession
│   │   │   ├── bed.py                    # Bed model
│   │   │   ├── district.py              # District model
│   │   │   ├── health_centre.py         # HealthCentre model (PHC/CHC)
│   │   │   ├── inventory.py             # InventoryItem, InventoryLog
│   │   │   ├── notification.py          # Notification model
│   │   │   ├── patient.py               # Patient model
│   │   │   ├── report.py                # Report model
│   │   │   ├── resource_request.py      # ResourceRequest model
│   │   │   └── user.py                  # User model
│   │   ├── schemas/                      # Pydantic request/response schemas
│   │   │   ├── health_centre.py
│   │   │   ├── inventory.py
│   │   │   └── user.py                  # Role enum definition
│   │   └── services/                     # Business logic services
│   │       ├── email_service.py          # Gmail SMTP onboarding emails
│   │       ├── gemini_service.py         # Gemini AI integration
│   │       ├── health_score.py           # Deterministic health score calculator
│   │       └── pdf_generator.py          # ReportLab PDF report builder
│   ├── alembic/                          # Database migration scripts
│   ├── scripts/                          # Utility seed scripts
│   ├── static/reports/                   # Generated PDF reports
│   ├── Dockerfile                        # Backend container (Cloud Run)
│   ├── requirements.txt                  # Python dependencies
│   └── .env                              # Environment variables
│
├── frontend/
│   ├── src/
│   │   ├── app/                          # Next.js App Router pages
│   │   │   ├── ai-audit/                 # AI analytics dashboard page
│   │   │   ├── analytics/                # Analytics page
│   │   │   ├── attendance/               # Attendance management page
│   │   │   ├── beds/                     # Bed management page
│   │   │   ├── district-admin/           # District admin dashboard
│   │   │   ├── health-centre/            # Health centre listing
│   │   │   ├── inventory/                # Inventory management page
│   │   │   ├── login/                    # Login page
│   │   │   ├── manage-roles/             # PHC Admin role management
│   │   │   ├── patients/                 # Patient registration & queue
│   │   │   ├── phc/                      # PHC details
│   │   │   ├── reports/                  # Report generation & viewing
│   │   │   ├── layout.tsx                # Root layout with providers
│   │   │   ├── globals.css               # Global styles
│   │   │   └── page.tsx                  # Home redirect
│   │   ├── components/
│   │   │   ├── layout/
│   │   │   │   ├── ClientLayout.tsx      # App shell with sidebar + header
│   │   │   │   ├── Header.tsx            # Top bar with notifications, hospital selector
│   │   │   │   ├── RouteGuard.tsx        # RBAC route protection
│   │   │   │   └── Sidebar.tsx           # Role-filtered navigation
│   │   │   ├── MapComponent.tsx          # Google Maps integration
│   │   │   └── ui/                       # shadcn/ui component library
│   │   ├── contexts/
│   │   │   ├── AuthContext.tsx            # JWT + user state management
│   │   │   └── LanguageContext.tsx        # i18n with Google Translation
│   │   └── lib/
│   │       ├── api.ts                    # Centralized API client with auth headers
│   │       ├── permissions.ts            # Route-level RBAC permissions map
│   │       ├── translations.ts           # Translation key definitions
│   │       └── utils.ts                  # Utility functions
│   ├── Dockerfile                        # Frontend container (Cloud Run)
│   ├── cloudbuild.yaml                   # Google Cloud Build config
│   ├── package.json                      # Node.js dependencies
│   └── .env.local                        # Frontend environment variables
│
├── aarogya_logo.png                      # Project logo
└── .gitignore

🚀 Installation

Prerequisites

  • Python 3.11+
  • Node.js 20+
  • npm 10+
  • Google Cloud Account (for Gemini API, Cloud Translation, Maps, Calendar)
  • Git

Backend Setup

# Clone the repository
git clone https://github.com/your-username/Aarogya.git
cd Aarogya/backend

# Create virtual environment
python -m venv .venv
source .venv/bin/activate  # Linux/Mac
.venv\Scripts\activate     # Windows

# Install dependencies
pip install -r requirements.txt

# Configure environment variables
cp .env.example .env
# Edit .env with your actual values (see Environment Variables section)

# Seed the database (optional — for demo data)
python seed_real_world.py

# Start the backend server
uvicorn app.main:app --reload --port 8000

Frontend Setup

cd Aarogya/frontend

# Install dependencies
npm install

# Configure environment variables
cp .env.example .env.local
# Edit .env.local with your values

# Start the development server
npm run dev

Environment Variables

Backend (backend/.env)

Variable Description Required
GEMINI_API_KEY Google Gemini API key from AI Studio
DATABASE_URL SQLAlchemy database URL
SECRET_KEY JWT signing secret
ALLOWED_ORIGINS Comma-separated CORS origins
SMTP_EMAIL Gmail address for sending emails Optional
SMTP_PASSWORD Gmail app password Optional
INSTANCE_CONNECTION_NAME Cloud SQL instance (for Cloud Run) Production only

Frontend (frontend/.env.local)

Variable Description Required
NEXT_PUBLIC_API_URL Backend API URL
NEXT_PUBLIC_GOOGLE_MAPS_API_KEY Google Maps JavaScript API key

📡 API Endpoints

Authentication

Method Endpoint Description
POST /api/v1/auth/login Login with username, password, PHC ID

Users

Method Endpoint Description
GET /api/v1/users/ List users in PHC
POST /api/v1/users/ Create new user
PUT /api/v1/users/{id} Update user
DELETE /api/v1/users/{id} Delete user

Health Centres (PHC)

Method Endpoint Description
GET /api/v1/phc/ List all health centres
POST /api/v1/phc/ Register new PHC
PUT /api/v1/phc/{id} Update PHC
DELETE /api/v1/phc/{id} Delete PHC

Inventory

Method Endpoint Description
GET /api/v1/inventory/ List inventory items
POST /api/v1/inventory/ Add inventory item
PUT /api/v1/inventory/{id} Update item
DELETE /api/v1/inventory/{id} Delete item
GET /api/v1/inventory/logs View distribution logs
GET /api/v1/inventory/analytics Inventory analytics
POST /api/v1/inventory/bulk-upload CSV bulk upload
GET /api/v1/inventory/ai-analysis AI-powered stock analysis
POST /api/v1/inventory/requests Submit resource request
GET /api/v1/inventory/requests View PHC's requests

Attendance

Method Endpoint Description
GET /api/v1/attendance/mo/dashboard MO attendance dashboard
GET /api/v1/attendance/mo/records Attendance records
POST /api/v1/attendance/qr/generate Generate QR code
POST /api/v1/attendance/scan Scan QR for check-in
GET /api/v1/attendance/doctor/dashboard Doctor personal dashboard

Beds

Method Endpoint Description
GET /api/v1/beds/ List beds
POST /api/v1/beds/ Create bed
POST /api/v1/beds/{id}/admit Admit/reserve patient
POST /api/v1/beds/{id}/discharge Discharge patient
PUT /api/v1/beds/{id}/status Update bed status
GET /api/v1/beds/analytics Bed analytics
GET /api/v1/beds/district/summary District bed summary

Patients

Method Endpoint Description
GET /api/v1/patients/ List patients
POST /api/v1/patients/ Register patient
PUT /api/v1/patients/{id} Update patient
GET /api/v1/patients/analytics Patient analytics
GET /api/v1/patients/doctors List hospital doctors

Analytics & Reports

Method Endpoint Description
GET /api/v1/analytics/ AI-powered analytics
GET /api/v1/reports/ Hospital reports
GET /api/v1/reports/monthly All monthly reports
POST /api/v1/reports/generate Generate AI monthly report

District Admin

Method Endpoint Description
GET /api/v1/district/overview District KPI overview
GET /api/v1/district/map-data Map data for all centres
GET /api/v1/district/requests All resource requests
POST /api/v1/district/requests/{id}/approve Approve with AI letter
POST /api/v1/district/requests/{id}/reject Reject request

Google Calendar

Method Endpoint Description
GET /api/v1/calendar/auth Initiate OAuth2 flow
GET /api/v1/calendar/callback OAuth2 callback
GET /api/v1/calendar/events Fetch doctor's calendar events

Translation

Method Endpoint Description
POST /api/v1/translate Batch translate text

Notifications

Method Endpoint Description
GET /api/v1/notifications/ Get notifications
POST /api/v1/notifications/{id}/read Mark notification as read

🔐 Authentication

  • Mechanism: JWT (JSON Web Tokens) with HS256 signing
  • Token Lifetime: 7 days
  • Password Hashing: bcrypt with random salt
  • Multi-Tenancy: PHC ID verification during login for non-admin roles
  • Transport: Bearer token in Authorization header
  • Frontend: Token stored in localStorage, attached via apiFetch() wrapper
  • RBAC: 10 roles with both frontend route guarding and backend dependency injection

🗄️ Database

Schema Overview

erDiagram
    districts ||--o{ health_centres : contains
    districts ||--o{ users : manages
    health_centres ||--o{ users : employs
    health_centres ||--o{ inventory_items : stocks
    health_centres ||--o{ beds : has
    health_centres ||--o{ patients : treats
    health_centres ||--o{ doctors : staffs
    health_centres ||--o{ reports : generates
    health_centres ||--o{ daily_qr_sessions : creates
    doctors ||--o{ attendance_records : has
    doctors ||--o{ patients : treats
    doctors ||--o{ beds : assigned_to
    inventory_items ||--o{ inventory_logs : tracks
    users {
        int id PK
        int hospital_id FK
        int district_id FK
        string username UK
        string password_hash
        string role
        string email UK
        boolean is_active
    }
    health_centres {
        int id PK
        int district_id FK
        string name
        string type
        string phc_id UK
        int health_score
        float latitude
        float longitude
    }
    inventory_items {
        int id PK
        int hospital_id FK
        string name
        int total_qty
        int qty_sold
        int min_threshold
        string status
    }
    patients {
        int id PK
        int hospital_id FK
        string patient_uid UK
        string full_name
        string visit_type
        string status
        string priority
    }
    beds {
        int id PK
        int hospital_id FK
        string bed_number
        string ward
        string bed_type
        string status
    }
    doctors {
        int id PK
        int phc_id FK
        int user_id FK
        string name
        string specialization
        boolean calendar_linked
    }
    reports {
        int id PK
        int hospital_id FK
        float health_score
        string risk_level
        string pdf_url
    }
Loading

🤖 AI Components

1. Live Analytics Insights (Gemini 2.0 Flash)

  • Input: Real-time KPIs (medicine counts, bed occupancy, doctor attendance, patient footfall)
  • Output: Structured JSON with executive summary, strengths, weaknesses, risk assessment, priority actions
  • Fallback: Mock insights if Gemini API is unavailable

2. Monthly Report Generation (Gemini 2.0 Flash)

  • Input: Monthly aggregated KPIs
  • Output: Comprehensive audit report with departmental analysis, risk assessment, improvement roadmap
  • Artifact: PDF document generated via ReportLab

3. Inventory AI Analysis (Gemini Flash)

  • Input: Current stock levels with critical status flags
  • Output: Supply chain health summary + auto-drafted emergency resource request messages
  • Schema Enforcement: Uses Pydantic model as Gemini's response_schema

4. AI Approval Letters (Gemini 2.5 Flash)

  • Input: Approved resource request details + admin custom note
  • Output: Professional approval letter text

5. Deterministic Health Score

  • Not AI-based — a weighted mathematical formula:
    • Medicine Score (30%) + Bed Score (20%) + Doctor Score (20%) + Lab Score (15%) + Patient Score (10%) + Alert Score (5%)
  • Risk Classification: Critical (<50), Moderate (50–74), Low Risk (≥75)

☁️ Google Cloud Components

graph LR
    subgraph "Google Cloud Platform"
        CR_BE["Cloud Run<br/>(Backend API)"]
        CR_FE["Cloud Run<br/>(Frontend)"]
        CSQL["Cloud SQL<br/>(PostgreSQL 15)"]
        CB["Cloud Build"]
        AR["Artifact Registry"]
        GEM["Gemini API"]
        TRANS["Cloud Translation"]
        CAL["Calendar API"]
        MAPS["Maps JS API"]
    end

    CB --> AR
    AR --> CR_BE
    AR --> CR_FE
    CR_BE --> CSQL
    CR_BE --> GEM
    CR_BE --> TRANS
    CR_BE --> CAL
    CR_FE --> MAPS
    CR_FE --> CR_BE

    style GEM fill:#4285F4,color:#fff
    style TRANS fill:#4285F4,color:#fff
    style CAL fill:#4285F4,color:#fff
    style MAPS fill:#4285F4,color:#fff
    style CSQL fill:#4285F4,color:#fff
    style CR_BE fill:#4285F4,color:#fff
    style CR_FE fill:#4285F4,color:#fff
    style CB fill:#4285F4,color:#fff
    style AR fill:#4285F4,color:#fff
Loading

🔮 Future Improvements

  • Predictive Analytics: ML-based demand forecasting for medicine consumption
  • WhatsApp Bot Integration: Alerts for critical stockouts and attendance failures
  • Telemedicine Module: Video consultation integration
  • Aadhaar-Based Patient Identity: Link patients to national ID
  • Inter-PHC Medicine Transfer: Automated redistribution of surplus stock
  • Offline Mode: Service worker-based offline data entry for low-connectivity areas
  • Voice-Based Data Entry: Speech-to-text for illiterate healthcare workers using Google Speech API
  • Automated Scheduling: AI-powered doctor shift scheduling
  • Epidemic Detection: Anomaly detection in patient symptom patterns
  • Government API Integration: Direct reporting to HMIS/NHM portals

📈 Scalability

  • Horizontal Scaling: Cloud Run auto-scales from 0 to N instances based on request volume
  • Database Scaling: Cloud SQL supports read replicas and vertical scaling
  • Stateless Backend: No server-side session state; all auth via JWT
  • CDN-Ready Frontend: Next.js static assets can be served via Cloud CDN
  • Multi-District Support: Architecture supports multiple districts with district-level isolation
  • Batch Translation Caching: Translated strings cached in localStorage to avoid redundant API calls

🔒 Security

  • Password Security: bcrypt with random salt per user
  • JWT Tokens: HS256 signed, 7-day expiry, validated on every request
  • RBAC: Both frontend (RouteGuard) and backend (RequireRole dependency) enforcement
  • Multi-Tenancy Isolation: Users can only access data from their assigned hospital_id
  • CORS: Configurable allowed origins with regex support
  • SQL Injection Prevention: SQLAlchemy ORM with parameterized queries
  • Input Validation: Pydantic schemas with type checking and constraints
  • Secure Attendance: SHA-256 hashed QR tokens with 5-minute expiry + GPS verification

⚡ Performance Optimizations

  • Gemini JSON Mode: response_mime_type="application/json" eliminates post-processing
  • Pydantic Schema as Response Schema: Direct structured output from Gemini (inventory AI)
  • Database Indexing: All foreign keys and frequently queried columns are indexed
  • Lazy Client Initialization: Google Cloud Translation client is lazily initialized
  • Frontend Code Splitting: Next.js App Router provides automatic code splitting per route
  • Translation Caching: Browser localStorage caching of translated strings per locale
  • Efficient Queries: Batch queries with filter and join instead of N+1 patterns

👥 Contributors

Name Role
Mitansh Jadhav AI Developer

📄 License

This project is licensed under the MIT License — see the LICENSE file for details.

Built with ❤️ for India's public healthcare system

About

Aarogya (meaning health in Sanskrit) is a full-stack, AI-powered healthcare operations platform designed to digitize and optimize the management of India's public health infrastructure — specifically Primary Health Centres (PHCs) and Community Health Centres (CHCs).

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages