Upload folder using huggingface_hub
Browse files- .gitignore +6 -0
- README.md +25 -6
- agent.py +241 -0
- app.py +481 -0
- mock_data.py +208 -0
- requirements.txt +2 -0
.gitignore
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.pyc
|
| 3 |
+
*.pyo
|
| 4 |
+
.gradio/
|
| 5 |
+
.env
|
| 6 |
+
*.json
|
README.md
CHANGED
|
@@ -1,12 +1,31 @@
|
|
| 1 |
---
|
| 2 |
-
title: Nurse
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version:
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
|
|
|
| 10 |
---
|
| 11 |
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Nurse-Rostering-AI-Agent
|
| 3 |
+
emoji: π₯
|
| 4 |
+
colorFrom: green
|
| 5 |
+
colorTo: blue
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: "5.23.0"
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
+
short_description: AI agent that fills nursing shift gaps automatically
|
| 11 |
---
|
| 12 |
|
| 13 |
+
# π₯ Nurse Rostering AI Agent Demo
|
| 14 |
+
|
| 15 |
+
An AI-powered scheduling assistant that analyses a 14-day nursing roster, identifies unfilled shifts, and fills gaps through simulated outreach.
|
| 16 |
+
|
| 17 |
+
## Tabs
|
| 18 |
+
|
| 19 |
+
| Tab | Description |
|
| 20 |
+
|-----|-------------|
|
| 21 |
+
| π€ AI Manager | Chat with the agent β it analyses gaps and fills them step by step |
|
| 22 |
+
| π Roster View | Visual 14-day grid (green = filled, red = unfilled) |
|
| 23 |
+
| π Insights | KPIs, gap analysis by shift type and week |
|
| 24 |
+
| π©ββοΈ Nurse Availability | Search and filter nurses by name, week, and capacity |
|
| 25 |
+
|
| 26 |
+
## How it works
|
| 27 |
+
|
| 28 |
+
1. A mock roster of **20 nurses** over **14 days** is generated with **8 intentional gaps**
|
| 29 |
+
2. Click **"Run AI Agent"** in the AI Manager tab
|
| 30 |
+
3. The agent streams its 5-step process: Analyse β Filter β Outreach β Resolve β Update
|
| 31 |
+
4. All tabs update live as shifts are filled
|
agent.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
agent.py β Simulated AI Rostering Agent
|
| 3 |
+
|
| 4 |
+
Implements the 5-step agent flow:
|
| 5 |
+
1. Analyze β identify unfilled shifts
|
| 6 |
+
2. Filter β find eligible nurses with capacity
|
| 7 |
+
3. Outreach β simulate SMS/WhatsApp messages (mock Twilio)
|
| 8 |
+
4. Resolve β simulate nurse responses
|
| 9 |
+
5. Update β fill the roster and report back
|
| 10 |
+
|
| 11 |
+
In production, replace the clearly-marked simulation blocks with:
|
| 12 |
+
β’ LLM API calls (OpenAI / Anthropic / Gemini) for natural-language reasoning
|
| 13 |
+
β’ Twilio / WhatsApp Business API for real outreach
|
| 14 |
+
β’ Database writes for persistence
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import random
|
| 20 |
+
import time
|
| 21 |
+
from dataclasses import dataclass
|
| 22 |
+
from datetime import date
|
| 23 |
+
from typing import Generator
|
| 24 |
+
|
| 25 |
+
from mock_data import (
|
| 26 |
+
Nurse,
|
| 27 |
+
ShiftSlot,
|
| 28 |
+
eligible_nurses_for_slot,
|
| 29 |
+
get_unfilled_slots,
|
| 30 |
+
week_number,
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
# ββ Agent response streaming βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 35 |
+
|
| 36 |
+
@dataclass
|
| 37 |
+
class AgentStep:
|
| 38 |
+
"""One chunk of the agent's thought process, streamed to the UI."""
|
| 39 |
+
phase: str # e.g. "π Analyze", "π² Outreach"
|
| 40 |
+
message: str # markdown-formatted content
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def run_agent(
|
| 44 |
+
roster: list[ShiftSlot],
|
| 45 |
+
nurses: list[Nurse],
|
| 46 |
+
user_prompt: str,
|
| 47 |
+
) -> Generator[AgentStep, None, list[ShiftSlot]]:
|
| 48 |
+
"""Generator that yields AgentSteps and mutates the roster in-place.
|
| 49 |
+
|
| 50 |
+
The caller iterates over yielded steps to build the chat log,
|
| 51 |
+
then collects the final roster state.
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 55 |
+
# STEP 1 β ANALYZE
|
| 56 |
+
# In production: send the roster + prompt to an LLM to identify intent
|
| 57 |
+
# and extract which gaps to fill.
|
| 58 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 59 |
+
unfilled = get_unfilled_slots(roster)
|
| 60 |
+
|
| 61 |
+
if not unfilled:
|
| 62 |
+
yield AgentStep(
|
| 63 |
+
phase="β
Complete",
|
| 64 |
+
message="All shifts are fully staffed β no action needed.",
|
| 65 |
+
)
|
| 66 |
+
return roster
|
| 67 |
+
|
| 68 |
+
yield AgentStep(
|
| 69 |
+
phase="π Step 1 β Analyze",
|
| 70 |
+
message=_format_gap_analysis(unfilled, roster),
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 74 |
+
# STEP 2 β FILTER ELIGIBLE NURSES
|
| 75 |
+
# In production: query the HR database / BQ for nurse availability,
|
| 76 |
+
# leave balance, skills match, etc.
|
| 77 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 78 |
+
fill_plan: list[tuple[ShiftSlot, list[Nurse]]] = []
|
| 79 |
+
for slot in unfilled:
|
| 80 |
+
eligible = eligible_nurses_for_slot(slot, nurses, roster)
|
| 81 |
+
fill_plan.append((slot, eligible))
|
| 82 |
+
|
| 83 |
+
yield AgentStep(
|
| 84 |
+
phase="π― Step 2 β Filter Eligible Nurses",
|
| 85 |
+
message=_format_eligibility(fill_plan, roster),
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 89 |
+
# STEP 3 β OUTREACH (MOCKED)
|
| 90 |
+
# In production: call Twilio REST API or WhatsApp Business API here.
|
| 91 |
+
# Example:
|
| 92 |
+
# from twilio.rest import Client
|
| 93 |
+
# client = Client(ACCOUNT_SID, AUTH_TOKEN)
|
| 94 |
+
# client.messages.create(body=msg, from_=TWILIO_NUM, to=nurse.phone)
|
| 95 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 96 |
+
outreach_log = _simulate_outreach(fill_plan)
|
| 97 |
+
|
| 98 |
+
yield AgentStep(
|
| 99 |
+
phase="π² Step 3 β Outreach (Simulated SMS/WhatsApp)",
|
| 100 |
+
message=outreach_log,
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 104 |
+
# STEP 4 β RESOLVE RESPONSES
|
| 105 |
+
# In production: poll for incoming webhook responses from Twilio,
|
| 106 |
+
# or use an async callback handler.
|
| 107 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 108 |
+
assignments, resolution_log = _simulate_responses(fill_plan)
|
| 109 |
+
|
| 110 |
+
yield AgentStep(
|
| 111 |
+
phase="π© Step 4 β Nurse Responses",
|
| 112 |
+
message=resolution_log,
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 116 |
+
# STEP 5 β UPDATE ROSTER
|
| 117 |
+
# In production: write to BigQuery / Postgres, notify the manager,
|
| 118 |
+
# update the calendar system.
|
| 119 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 120 |
+
for slot, nurse in assignments:
|
| 121 |
+
if nurse not in slot.assigned:
|
| 122 |
+
slot.assigned.append(nurse)
|
| 123 |
+
|
| 124 |
+
remaining = get_unfilled_slots(roster)
|
| 125 |
+
|
| 126 |
+
yield AgentStep(
|
| 127 |
+
phase="β
Step 5 β Roster Updated",
|
| 128 |
+
message=_format_completion(assignments, remaining),
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
return roster
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
# ββ Formatting helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 135 |
+
|
| 136 |
+
def _format_gap_analysis(unfilled: list[ShiftSlot], roster: list[ShiftSlot]) -> str:
|
| 137 |
+
lines = [f"Found **{len(unfilled)} unfilled shift(s)** across the 2-week roster:\n"]
|
| 138 |
+
lines.append("| # | Date | Day | Shift | Hours | Vacancies |")
|
| 139 |
+
lines.append("|---|------|-----|-------|-------|-----------|")
|
| 140 |
+
for i, s in enumerate(unfilled, 1):
|
| 141 |
+
day_name = s.day.strftime("%A")
|
| 142 |
+
lines.append(
|
| 143 |
+
f"| {i} | {s.day.strftime('%d %b')} | {day_name} "
|
| 144 |
+
f"| {s.shift_name} | {s.shift_hours} | {s.vacancies} |"
|
| 145 |
+
)
|
| 146 |
+
return "\n".join(lines)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def _format_eligibility(
|
| 150 |
+
fill_plan: list[tuple[ShiftSlot, list[Nurse]]],
|
| 151 |
+
roster: list[ShiftSlot],
|
| 152 |
+
) -> str:
|
| 153 |
+
lines = ["Searching the 20-nurse pool for availabilityβ¦\n"]
|
| 154 |
+
for slot, eligible in fill_plan:
|
| 155 |
+
day_name = slot.day.strftime("%A")
|
| 156 |
+
lines.append(
|
| 157 |
+
f"**{slot.day.strftime('%d %b')} ({day_name}) β {slot.shift_name}** "
|
| 158 |
+
f"β {len(eligible)} eligible nurses"
|
| 159 |
+
)
|
| 160 |
+
top3 = eligible[:3]
|
| 161 |
+
for n in top3:
|
| 162 |
+
week = week_number(slot, roster)
|
| 163 |
+
from mock_data import nurse_shifts_in_week
|
| 164 |
+
current = nurse_shifts_in_week(n, roster, week)
|
| 165 |
+
lines.append(f" - {n.name} β {current}/5 shifts this week")
|
| 166 |
+
if len(eligible) > 3:
|
| 167 |
+
lines.append(f" - β¦ and {len(eligible) - 3} more\n")
|
| 168 |
+
else:
|
| 169 |
+
lines.append("")
|
| 170 |
+
return "\n".join(lines)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def _simulate_outreach(fill_plan: list[tuple[ShiftSlot, list[Nurse]]]) -> str:
|
| 174 |
+
"""Mock SMS/WhatsApp outreach to top-3 eligible nurses per gap."""
|
| 175 |
+
lines = ["Sending shift-cover requestsβ¦\n"]
|
| 176 |
+
lines.append("```")
|
| 177 |
+
for slot, eligible in fill_plan:
|
| 178 |
+
top3 = eligible[:3]
|
| 179 |
+
day_str = slot.day.strftime("%d %b (%A)")
|
| 180 |
+
for n in top3:
|
| 181 |
+
lines.append(
|
| 182 |
+
f"π± β {n.name} ({n.phone})\n"
|
| 183 |
+
f' "Hi {n.name.replace("Nurse ", "")}, '
|
| 184 |
+
f"can you cover {slot.shift_name} shift on {day_str} "
|
| 185 |
+
f'({slot.shift_hours})? Reply YES to confirm."'
|
| 186 |
+
)
|
| 187 |
+
lines.append("")
|
| 188 |
+
lines.append("```")
|
| 189 |
+
lines.append(f"\nβ
**{sum(min(3, len(e)) for _, e in fill_plan)} messages sent** β awaiting responsesβ¦")
|
| 190 |
+
return "\n".join(lines)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def _simulate_responses(
|
| 194 |
+
fill_plan: list[tuple[ShiftSlot, list[Nurse]]],
|
| 195 |
+
) -> tuple[list[tuple[ShiftSlot, Nurse]], str]:
|
| 196 |
+
"""Simulate nurse replies β first eligible nurse always says YES."""
|
| 197 |
+
rng = random.Random(99)
|
| 198 |
+
assignments: list[tuple[ShiftSlot, Nurse]] = []
|
| 199 |
+
lines = ["Responses received:\n"]
|
| 200 |
+
lines.append("```")
|
| 201 |
+
|
| 202 |
+
for slot, eligible in fill_plan:
|
| 203 |
+
filled = False
|
| 204 |
+
top3 = eligible[:3]
|
| 205 |
+
for i, n in enumerate(top3):
|
| 206 |
+
# Simulate: first nurse accepts, others may decline
|
| 207 |
+
if not filled and (i == 0 or rng.random() > 0.5):
|
| 208 |
+
lines.append(f"β
{n.name}: \"YES β I'll take it!\"")
|
| 209 |
+
assignments.append((slot, n))
|
| 210 |
+
filled = True
|
| 211 |
+
else:
|
| 212 |
+
lines.append(f"β {n.name}: \"Sorry, can't make it.\"")
|
| 213 |
+
|
| 214 |
+
if not filled:
|
| 215 |
+
lines.append(f"β οΈ No confirmation yet for {slot.day.strftime('%d %b')} {slot.shift_name}")
|
| 216 |
+
lines.append("")
|
| 217 |
+
|
| 218 |
+
lines.append("```")
|
| 219 |
+
return assignments, "\n".join(lines)
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def _format_completion(
|
| 223 |
+
assignments: list[tuple[ShiftSlot, Nurse]],
|
| 224 |
+
remaining: list[ShiftSlot],
|
| 225 |
+
) -> str:
|
| 226 |
+
lines = [f"**{len(assignments)} shift(s) filled successfully!**\n"]
|
| 227 |
+
lines.append("| Date | Shift | Assigned To |")
|
| 228 |
+
lines.append("|------|-------|-------------|")
|
| 229 |
+
for slot, nurse in assignments:
|
| 230 |
+
lines.append(
|
| 231 |
+
f"| {slot.day.strftime('%d %b (%a)')} | {slot.shift_name} | {nurse.name} |"
|
| 232 |
+
)
|
| 233 |
+
lines.append("")
|
| 234 |
+
if remaining:
|
| 235 |
+
lines.append(
|
| 236 |
+
f"β οΈ **{len(remaining)} shift(s) still unfilled** β "
|
| 237 |
+
"consider extending outreach to part-time or agency staff."
|
| 238 |
+
)
|
| 239 |
+
else:
|
| 240 |
+
lines.append("π **All shifts are now fully covered!** Roster is complete.")
|
| 241 |
+
return "\n".join(lines)
|
app.py
ADDED
|
@@ -0,0 +1,481 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
app.py β Nurse Rostering AI Agent Demo (Gradio)
|
| 3 |
+
|
| 4 |
+
4-Tab Dashboard:
|
| 5 |
+
Tab 1 β AI Chat (agent fills gaps)
|
| 6 |
+
Tab 2 β Roster View (white background, readable)
|
| 7 |
+
Tab 3 β Insights (macro gap analysis)
|
| 8 |
+
Tab 4 β Nurse Availability (search & filter)
|
| 9 |
+
|
| 10 |
+
Deploy: gradio deploy
|
| 11 |
+
Local: python app.py
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import gradio as gr
|
| 17 |
+
import pandas as pd
|
| 18 |
+
from collections import defaultdict
|
| 19 |
+
|
| 20 |
+
from mock_data import (
|
| 21 |
+
MAX_SHIFTS_PER_WEEK,
|
| 22 |
+
NUM_NURSES,
|
| 23 |
+
NURSES_PER_SHIFT,
|
| 24 |
+
SHIFTS,
|
| 25 |
+
generate_nurses,
|
| 26 |
+
generate_roster,
|
| 27 |
+
get_unfilled_slots,
|
| 28 |
+
week_number,
|
| 29 |
+
nurse_shifts_in_week,
|
| 30 |
+
nurse_works_on_day,
|
| 31 |
+
eligible_nurses_for_slot,
|
| 32 |
+
ShiftSlot,
|
| 33 |
+
Nurse,
|
| 34 |
+
)
|
| 35 |
+
from agent import run_agent
|
| 36 |
+
|
| 37 |
+
# ββ Global state ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 38 |
+
nurses: list[Nurse] = []
|
| 39 |
+
roster: list[ShiftSlot] = []
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def init_state():
|
| 43 |
+
global nurses, roster
|
| 44 |
+
nurses = generate_nurses()
|
| 45 |
+
roster = generate_roster(nurses)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
init_state()
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 52 |
+
# TAB 2 β ROSTER VIEW (white background, high contrast)
|
| 53 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 54 |
+
|
| 55 |
+
def roster_to_html(roster: list[ShiftSlot]) -> str:
|
| 56 |
+
days: dict[str, list[ShiftSlot]] = {}
|
| 57 |
+
for slot in roster:
|
| 58 |
+
days.setdefault(slot.day.isoformat(), []).append(slot)
|
| 59 |
+
all_days = sorted(days.keys())
|
| 60 |
+
|
| 61 |
+
total_slots = len(roster)
|
| 62 |
+
unfilled_count = len(get_unfilled_slots(roster))
|
| 63 |
+
filled_count = total_slots - unfilled_count
|
| 64 |
+
total_assignments = sum(len(s.assigned) for s in roster)
|
| 65 |
+
|
| 66 |
+
html = """
|
| 67 |
+
<style>
|
| 68 |
+
.r-wrap { font-family: 'Inter', -apple-system, sans-serif; }
|
| 69 |
+
.r-stats { display: flex; gap: 24px; padding: 14px 20px; background: #f0f4f8; border-radius: 10px; margin-bottom: 16px; font-size: 14px; color: #1a1a2e; flex-wrap: wrap; }
|
| 70 |
+
.r-stat { display: flex; align-items: center; gap: 6px; }
|
| 71 |
+
.r-dot { width: 10px; height: 10px; border-radius: 50%; }
|
| 72 |
+
.r-dot-green { background: #16a34a; }
|
| 73 |
+
.r-dot-red { background: #dc2626; }
|
| 74 |
+
.r-table { border-collapse: collapse; width: 100%; font-size: 13px; }
|
| 75 |
+
.r-table th { background: #1e293b; color: #fff; padding: 10px 8px; text-align: center; border: 1px solid #cbd5e1; }
|
| 76 |
+
.r-table td { padding: 8px 10px; border: 1px solid #cbd5e1; vertical-align: top; min-width: 150px; line-height: 1.6; }
|
| 77 |
+
.r-filled { background: #f0fdf4; color: #14532d; }
|
| 78 |
+
.r-unfilled { background: #fef2f2; color: #7f1d1d; }
|
| 79 |
+
.r-week { background: #e2e8f0 !important; color: #0f172a; font-size: 14px; font-weight: 700; text-align: left; padding: 8px 14px; }
|
| 80 |
+
.r-day { font-weight: 600; background: #f8fafc; color: #1e293b; text-align: center; white-space: nowrap; }
|
| 81 |
+
.r-name { display: block; padding: 1px 0; font-size: 12.5px; }
|
| 82 |
+
.r-gap { display: inline-block; background: #dc2626; color: #fff; padding: 2px 8px; border-radius: 4px; font-size: 11px; font-weight: 600; margin-top: 4px; }
|
| 83 |
+
</style>
|
| 84 |
+
<div class="r-wrap">
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
html += f"""
|
| 88 |
+
<div class="r-stats">
|
| 89 |
+
<div class="r-stat"><b>π₯ ICU Roster</b> Β· 2-Week Schedule</div>
|
| 90 |
+
<div class="r-stat"><span class="r-dot r-dot-green"></span> Filled: {filled_count}/{total_slots}</div>
|
| 91 |
+
<div class="r-stat"><span class="r-dot r-dot-red"></span> Unfilled: {unfilled_count}</div>
|
| 92 |
+
<div class="r-stat">π©ββοΈ {NUM_NURSES} nurses Β· {total_assignments} assignments</div>
|
| 93 |
+
</div>
|
| 94 |
+
"""
|
| 95 |
+
|
| 96 |
+
html += '<table class="r-table"><tr><th>Date</th>'
|
| 97 |
+
for sn, sh in SHIFTS:
|
| 98 |
+
html += f"<th>{sn}<br><small>{sh}</small></th>"
|
| 99 |
+
html += "</tr>"
|
| 100 |
+
|
| 101 |
+
for i, dk in enumerate(all_days):
|
| 102 |
+
if i == 0:
|
| 103 |
+
html += '<tr><td colspan="4" class="r-week">π
Week 1</td></tr>'
|
| 104 |
+
elif i == 7:
|
| 105 |
+
html += '<tr><td colspan="4" class="r-week">π
Week 2</td></tr>'
|
| 106 |
+
|
| 107 |
+
slots = days[dk]
|
| 108 |
+
label = slots[0].day.strftime("%a %d %b")
|
| 109 |
+
html += f'<tr><td class="r-day">{label}</td>'
|
| 110 |
+
|
| 111 |
+
for slot in slots:
|
| 112 |
+
cls = "r-unfilled" if slot.vacancies > 0 else "r-filled"
|
| 113 |
+
cell = ""
|
| 114 |
+
for n in slot.assigned:
|
| 115 |
+
cell += f'<span class="r-name">π©ββοΈ {n.name.replace("Nurse ", "")}</span>'
|
| 116 |
+
if slot.vacancies > 0:
|
| 117 |
+
cell += f'<span class="r-gap">β οΈ NEED {slot.vacancies}</span>'
|
| 118 |
+
html += f'<td class="{cls}">{cell}</td>'
|
| 119 |
+
html += "</tr>"
|
| 120 |
+
|
| 121 |
+
html += "</table></div>"
|
| 122 |
+
return html
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 126 |
+
# TAB 3 β INSIGHTS
|
| 127 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 128 |
+
|
| 129 |
+
def build_insights_html(roster: list[ShiftSlot]) -> str:
|
| 130 |
+
unfilled = get_unfilled_slots(roster)
|
| 131 |
+
total = len(roster)
|
| 132 |
+
filled = total - len(unfilled)
|
| 133 |
+
fill_pct = filled / total * 100 if total else 0
|
| 134 |
+
|
| 135 |
+
# Gaps by shift type
|
| 136 |
+
gap_by_shift: dict[str, int] = defaultdict(int)
|
| 137 |
+
for s in unfilled:
|
| 138 |
+
gap_by_shift[s.shift_name] += s.vacancies
|
| 139 |
+
|
| 140 |
+
# Gaps by week
|
| 141 |
+
gap_by_week: dict[int, int] = defaultdict(int)
|
| 142 |
+
for s in unfilled:
|
| 143 |
+
w = week_number(s, roster)
|
| 144 |
+
gap_by_week[w] += s.vacancies
|
| 145 |
+
|
| 146 |
+
# Nurse utilisation
|
| 147 |
+
nurse_load: dict[int, dict[int, int]] = defaultdict(lambda: defaultdict(int))
|
| 148 |
+
for s in roster:
|
| 149 |
+
w = week_number(s, roster)
|
| 150 |
+
for n in s.assigned:
|
| 151 |
+
nurse_load[n.id][w] += 1
|
| 152 |
+
|
| 153 |
+
at_max = sum(1 for nw in nurse_load.values() for c in nw.values() if c >= MAX_SHIFTS_PER_WEEK)
|
| 154 |
+
|
| 155 |
+
bar_col = "#16a34a" if fill_pct >= 95 else "#f59e0b" if fill_pct >= 85 else "#dc2626"
|
| 156 |
+
|
| 157 |
+
html = """
|
| 158 |
+
<style>
|
| 159 |
+
.ins { font-family: 'Inter', -apple-system, sans-serif; color: #1e293b; }
|
| 160 |
+
.kpi-row { display: flex; gap: 16px; flex-wrap: wrap; margin-bottom: 24px; }
|
| 161 |
+
.kpi { flex: 1; min-width: 160px; background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 12px; padding: 20px; text-align: center; }
|
| 162 |
+
.kpi-val { font-size: 32px; font-weight: 800; margin-bottom: 4px; }
|
| 163 |
+
.kpi-label { font-size: 13px; color: #64748b; }
|
| 164 |
+
.bar-outer { width: 100%; height: 14px; background: #e2e8f0; border-radius: 7px; overflow: hidden; margin-top: 8px; }
|
| 165 |
+
.bar-inner { height: 100%; border-radius: 7px; }
|
| 166 |
+
.section { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 12px; padding: 20px; margin-bottom: 16px; }
|
| 167 |
+
.section h3 { margin: 0 0 12px; font-size: 15px; color: #334155; }
|
| 168 |
+
.gap-table { width: 100%; border-collapse: collapse; font-size: 13px; }
|
| 169 |
+
.gap-table th { background: #f1f5f9; padding: 8px 12px; text-align: left; border-bottom: 2px solid #e2e8f0; color: #475569; }
|
| 170 |
+
.gap-table td { padding: 8px 12px; border-bottom: 1px solid #f1f5f9; }
|
| 171 |
+
.badge-red { background: #fee2e2; color: #991b1b; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: 600; }
|
| 172 |
+
.badge-green { background: #dcfce7; color: #166534; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: 600; }
|
| 173 |
+
</style>
|
| 174 |
+
<div class="ins">
|
| 175 |
+
"""
|
| 176 |
+
|
| 177 |
+
html += f"""
|
| 178 |
+
<div class="kpi-row">
|
| 179 |
+
<div class="kpi">
|
| 180 |
+
<div class="kpi-val" style="color:{bar_col}">{fill_pct:.0f}%</div>
|
| 181 |
+
<div class="kpi-label">Fill Rate</div>
|
| 182 |
+
<div class="bar-outer"><div class="bar-inner" style="width:{fill_pct}%;background:{bar_col}"></div></div>
|
| 183 |
+
</div>
|
| 184 |
+
<div class="kpi">
|
| 185 |
+
<div class="kpi-val" style="color:#dc2626">{len(unfilled)}</div>
|
| 186 |
+
<div class="kpi-label">Unfilled Shifts</div>
|
| 187 |
+
</div>
|
| 188 |
+
<div class="kpi">
|
| 189 |
+
<div class="kpi-val" style="color:#0ea5e9">{total}</div>
|
| 190 |
+
<div class="kpi-label">Total Shifts (2 weeks)</div>
|
| 191 |
+
</div>
|
| 192 |
+
<div class="kpi">
|
| 193 |
+
<div class="kpi-val" style="color:#8b5cf6">{at_max}</div>
|
| 194 |
+
<div class="kpi-label">Nurse-Weeks at Max (5/5)</div>
|
| 195 |
+
</div>
|
| 196 |
+
</div>
|
| 197 |
+
"""
|
| 198 |
+
|
| 199 |
+
# Gaps by shift type
|
| 200 |
+
html += '<div class="section"><h3>π Gaps by Shift Type</h3><table class="gap-table"><tr><th>Shift</th><th>Unfilled Slots</th></tr>'
|
| 201 |
+
for sn, _ in SHIFTS:
|
| 202 |
+
cnt = gap_by_shift.get(sn, 0)
|
| 203 |
+
badge = f'<span class="badge-red">{cnt}</span>' if cnt > 0 else '<span class="badge-green">0</span>'
|
| 204 |
+
html += f"<tr><td>{sn}</td><td>{badge}</td></tr>"
|
| 205 |
+
html += "</table></div>"
|
| 206 |
+
|
| 207 |
+
# Gaps by week
|
| 208 |
+
html += '<div class="section"><h3>π
Gaps by Week</h3><table class="gap-table"><tr><th>Week</th><th>Unfilled Slots</th></tr>'
|
| 209 |
+
for w in sorted(gap_by_week.keys()):
|
| 210 |
+
cnt = gap_by_week[w]
|
| 211 |
+
badge = f'<span class="badge-red">{cnt}</span>' if cnt > 0 else '<span class="badge-green">0</span>'
|
| 212 |
+
html += f"<tr><td>Week {w}</td><td>{badge}</td></tr>"
|
| 213 |
+
if not gap_by_week:
|
| 214 |
+
html += '<tr><td colspan="2">β
No gaps</td></tr>'
|
| 215 |
+
html += "</table></div>"
|
| 216 |
+
|
| 217 |
+
# Unfilled shift detail
|
| 218 |
+
if unfilled:
|
| 219 |
+
html += '<div class="section"><h3>π΄ Unfilled Shift Details</h3><table class="gap-table"><tr><th>#</th><th>Date</th><th>Day</th><th>Shift</th><th>Vacancies</th></tr>'
|
| 220 |
+
for i, s in enumerate(unfilled, 1):
|
| 221 |
+
html += f'<tr><td>{i}</td><td>{s.day.strftime("%d %b %Y")}</td><td>{s.day.strftime("%A")}</td><td>{s.shift_name} ({s.shift_hours})</td><td><span class="badge-red">{s.vacancies}</span></td></tr>'
|
| 222 |
+
html += "</table></div>"
|
| 223 |
+
else:
|
| 224 |
+
html += '<div class="section"><h3>β
All shifts are fully covered!</h3></div>'
|
| 225 |
+
|
| 226 |
+
html += "</div>"
|
| 227 |
+
return html
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 231 |
+
# TAB 4 β NURSE AVAILABILITY (search / filter)
|
| 232 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 233 |
+
|
| 234 |
+
def build_nurse_table(name_filter: str, week_filter: str, availability_filter: str) -> str:
|
| 235 |
+
"""Build an HTML table of nurses with their weekly loads and availability."""
|
| 236 |
+
|
| 237 |
+
week_num = None
|
| 238 |
+
if week_filter and week_filter != "All":
|
| 239 |
+
week_num = int(week_filter.replace("Week ", ""))
|
| 240 |
+
|
| 241 |
+
only_available = availability_filter == "Has Capacity"
|
| 242 |
+
|
| 243 |
+
rows = []
|
| 244 |
+
for n in nurses:
|
| 245 |
+
if name_filter and name_filter.lower() not in n.name.lower():
|
| 246 |
+
continue
|
| 247 |
+
|
| 248 |
+
w1 = nurse_shifts_in_week(n, roster, 1)
|
| 249 |
+
w2 = nurse_shifts_in_week(n, roster, 2)
|
| 250 |
+
cap1 = MAX_SHIFTS_PER_WEEK - w1
|
| 251 |
+
cap2 = MAX_SHIFTS_PER_WEEK - w2
|
| 252 |
+
|
| 253 |
+
days_w1 = sorted(set(
|
| 254 |
+
s.day for s in roster
|
| 255 |
+
if week_number(s, roster) == 1 and n in s.assigned
|
| 256 |
+
))
|
| 257 |
+
days_w2 = sorted(set(
|
| 258 |
+
s.day for s in roster
|
| 259 |
+
if week_number(s, roster) == 2 and n in s.assigned
|
| 260 |
+
))
|
| 261 |
+
|
| 262 |
+
if week_num == 1 and only_available and cap1 <= 0:
|
| 263 |
+
continue
|
| 264 |
+
if week_num == 2 and only_available and cap2 <= 0:
|
| 265 |
+
continue
|
| 266 |
+
if week_num is None and only_available and cap1 <= 0 and cap2 <= 0:
|
| 267 |
+
continue
|
| 268 |
+
|
| 269 |
+
rows.append({
|
| 270 |
+
"nurse": n,
|
| 271 |
+
"w1": w1, "w2": w2,
|
| 272 |
+
"cap1": cap1, "cap2": cap2,
|
| 273 |
+
"days_w1": days_w1, "days_w2": days_w2,
|
| 274 |
+
})
|
| 275 |
+
|
| 276 |
+
html = """
|
| 277 |
+
<style>
|
| 278 |
+
.na { font-family: 'Inter', -apple-system, sans-serif; color: #1e293b; }
|
| 279 |
+
.na-count { font-size: 14px; color: #64748b; margin-bottom: 12px; }
|
| 280 |
+
.na-table { width: 100%; border-collapse: collapse; font-size: 13px; }
|
| 281 |
+
.na-table th { background: #f1f5f9; padding: 10px 12px; text-align: left; border-bottom: 2px solid #e2e8f0; color: #475569; font-weight: 600; }
|
| 282 |
+
.na-table td { padding: 10px 12px; border-bottom: 1px solid #f1f5f9; vertical-align: top; }
|
| 283 |
+
.na-table tr:hover { background: #f8fafc; }
|
| 284 |
+
.cap-full { color: #dc2626; font-weight: 700; }
|
| 285 |
+
.cap-has { color: #16a34a; font-weight: 700; }
|
| 286 |
+
.day-chip { display: inline-block; background: #e0f2fe; color: #0c4a6e; padding: 1px 6px; border-radius: 4px; font-size: 11px; margin: 1px 2px; }
|
| 287 |
+
.phone-txt { color: #64748b; font-size: 12px; }
|
| 288 |
+
</style>
|
| 289 |
+
<div class="na">
|
| 290 |
+
"""
|
| 291 |
+
|
| 292 |
+
html += f'<div class="na-count">Showing {len(rows)} of {NUM_NURSES} nurses</div>'
|
| 293 |
+
html += """
|
| 294 |
+
<table class="na-table">
|
| 295 |
+
<tr>
|
| 296 |
+
<th>Nurse</th>
|
| 297 |
+
<th>Phone</th>
|
| 298 |
+
<th>Week 1 Shifts</th>
|
| 299 |
+
<th>Week 1 Capacity</th>
|
| 300 |
+
<th>Week 1 Days</th>
|
| 301 |
+
<th>Week 2 Shifts</th>
|
| 302 |
+
<th>Week 2 Capacity</th>
|
| 303 |
+
<th>Week 2 Days</th>
|
| 304 |
+
</tr>
|
| 305 |
+
"""
|
| 306 |
+
|
| 307 |
+
for r in rows:
|
| 308 |
+
n = r["nurse"]
|
| 309 |
+
name_short = n.name.replace("Nurse ", "")
|
| 310 |
+
|
| 311 |
+
cap1_cls = "cap-full" if r["cap1"] <= 0 else "cap-has"
|
| 312 |
+
cap2_cls = "cap-full" if r["cap2"] <= 0 else "cap-has"
|
| 313 |
+
|
| 314 |
+
days1_html = " ".join(f'<span class="day-chip">{d.strftime("%a %d")}</span>' for d in r["days_w1"]) or "β"
|
| 315 |
+
days2_html = " ".join(f'<span class="day-chip">{d.strftime("%a %d")}</span>' for d in r["days_w2"]) or "β"
|
| 316 |
+
|
| 317 |
+
html += f"""
|
| 318 |
+
<tr>
|
| 319 |
+
<td><b>π©ββοΈ {name_short}</b></td>
|
| 320 |
+
<td><span class="phone-txt">{n.phone}</span></td>
|
| 321 |
+
<td>{r['w1']}/5</td>
|
| 322 |
+
<td class="{cap1_cls}">{r['cap1']} left</td>
|
| 323 |
+
<td>{days1_html}</td>
|
| 324 |
+
<td>{r['w2']}/5</td>
|
| 325 |
+
<td class="{cap2_cls}">{r['cap2']} left</td>
|
| 326 |
+
<td>{days2_html}</td>
|
| 327 |
+
</tr>"""
|
| 328 |
+
|
| 329 |
+
html += "</table></div>"
|
| 330 |
+
return html
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 334 |
+
# TAB 1 β AI CHAT
|
| 335 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 336 |
+
|
| 337 |
+
def handle_chat(user_message: str, history: list[dict]) -> tuple:
|
| 338 |
+
"""Process user message β agent steps β update roster + all tabs."""
|
| 339 |
+
global roster
|
| 340 |
+
|
| 341 |
+
full_response = ""
|
| 342 |
+
for step in run_agent(roster, nurses, user_message):
|
| 343 |
+
full_response += f"### {step.phase}\n\n{step.message}\n\n---\n\n"
|
| 344 |
+
|
| 345 |
+
history.append({"role": "user", "content": user_message})
|
| 346 |
+
history.append({"role": "assistant", "content": full_response})
|
| 347 |
+
|
| 348 |
+
return (
|
| 349 |
+
history,
|
| 350 |
+
"", # clear textbox
|
| 351 |
+
roster_to_html(roster), # tab 2
|
| 352 |
+
build_insights_html(roster), # tab 3
|
| 353 |
+
build_nurse_table("", "All", "All"), # tab 4
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def reset_demo():
|
| 358 |
+
global nurses, roster
|
| 359 |
+
init_state()
|
| 360 |
+
return (
|
| 361 |
+
[], # chat
|
| 362 |
+
roster_to_html(roster),
|
| 363 |
+
build_insights_html(roster),
|
| 364 |
+
build_nurse_table("", "All", "All"),
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 369 |
+
# GRADIO APP
|
| 370 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 371 |
+
|
| 372 |
+
def create_app() -> gr.Blocks:
|
| 373 |
+
with gr.Blocks(title="π₯ Nurse Rostering AI Agent") as app:
|
| 374 |
+
|
| 375 |
+
gr.Markdown(
|
| 376 |
+
"""
|
| 377 |
+
# π₯ Nurse Rostering AI Agent β ICU Department
|
| 378 |
+
**AI-Powered Workforce Scheduling Demo** Β· 20 Nurses Β· 3 Shifts / Day Β· 2-Week Roster
|
| 379 |
+
"""
|
| 380 |
+
)
|
| 381 |
+
|
| 382 |
+
with gr.Tabs():
|
| 383 |
+
# ββ Tab 1: AI Chat ββββββββββββββββββββββββββββββββββββββββββββ
|
| 384 |
+
with gr.Tab("π€ AI Manager"):
|
| 385 |
+
gr.Markdown(
|
| 386 |
+
"> π‘ Type **\"Fill the unfilled shifts\"** to watch the AI agent "
|
| 387 |
+
"analyze gaps, find available nurses, send outreach, and update the roster."
|
| 388 |
+
)
|
| 389 |
+
chatbot = gr.Chatbot(
|
| 390 |
+
type="messages",
|
| 391 |
+
value=[{
|
| 392 |
+
"role": "assistant",
|
| 393 |
+
"content": (
|
| 394 |
+
"π Hi! I'm your AI Roster Manager for the **ICU department**.\n\n"
|
| 395 |
+
"I can see there are **unfilled shifts** in the 2-week roster. "
|
| 396 |
+
"How can I help?\n\n"
|
| 397 |
+
"**Try asking:**\n"
|
| 398 |
+
'- *"Fill the unfilled shifts"*\n'
|
| 399 |
+
'- *"Show me the gaps for this week"*\n'
|
| 400 |
+
'- *"Find nurses for the night shift"*'
|
| 401 |
+
),
|
| 402 |
+
}],
|
| 403 |
+
height=520,
|
| 404 |
+
)
|
| 405 |
+
with gr.Row():
|
| 406 |
+
msg_input = gr.Textbox(
|
| 407 |
+
placeholder="e.g. Fill the unfilled shifts for this weekβ¦",
|
| 408 |
+
show_label=False,
|
| 409 |
+
scale=5,
|
| 410 |
+
container=False,
|
| 411 |
+
)
|
| 412 |
+
send_btn = gr.Button("Send", variant="primary", scale=1)
|
| 413 |
+
reset_btn = gr.Button("π Reset Demo", variant="secondary", size="sm")
|
| 414 |
+
|
| 415 |
+
# ββ Tab 2: Roster View ββββββββββββββββββββββββββββββββββββββββ
|
| 416 |
+
with gr.Tab("π Roster View"):
|
| 417 |
+
roster_display = gr.HTML(value=roster_to_html(roster))
|
| 418 |
+
|
| 419 |
+
# ββ Tab 3: Insights βββββββββββββββββββββββββββββββββββββββββββ
|
| 420 |
+
with gr.Tab("π Insights"):
|
| 421 |
+
insights_display = gr.HTML(value=build_insights_html(roster))
|
| 422 |
+
|
| 423 |
+
# ββ Tab 4: Nurse Availability βββββββββββββββββββββββββββββββββ
|
| 424 |
+
with gr.Tab("π©ββοΈ Nurse Availability"):
|
| 425 |
+
with gr.Row():
|
| 426 |
+
name_search = gr.Textbox(
|
| 427 |
+
label="π Search by name",
|
| 428 |
+
placeholder="e.g. Priya, Mei Lingβ¦",
|
| 429 |
+
scale=3,
|
| 430 |
+
)
|
| 431 |
+
week_dd = gr.Dropdown(
|
| 432 |
+
label="Week",
|
| 433 |
+
choices=["All", "Week 1", "Week 2"],
|
| 434 |
+
value="All",
|
| 435 |
+
scale=1,
|
| 436 |
+
)
|
| 437 |
+
avail_dd = gr.Dropdown(
|
| 438 |
+
label="Availability",
|
| 439 |
+
choices=["All", "Has Capacity"],
|
| 440 |
+
value="All",
|
| 441 |
+
scale=1,
|
| 442 |
+
)
|
| 443 |
+
filter_btn = gr.Button("Apply Filter", variant="primary", scale=1)
|
| 444 |
+
|
| 445 |
+
nurse_display = gr.HTML(value=build_nurse_table("", "All", "All"))
|
| 446 |
+
|
| 447 |
+
# ββ Event wiring ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 448 |
+
chat_outputs = [chatbot, msg_input, roster_display, insights_display, nurse_display]
|
| 449 |
+
|
| 450 |
+
send_btn.click(
|
| 451 |
+
fn=handle_chat,
|
| 452 |
+
inputs=[msg_input, chatbot],
|
| 453 |
+
outputs=chat_outputs,
|
| 454 |
+
)
|
| 455 |
+
msg_input.submit(
|
| 456 |
+
fn=handle_chat,
|
| 457 |
+
inputs=[msg_input, chatbot],
|
| 458 |
+
outputs=chat_outputs,
|
| 459 |
+
)
|
| 460 |
+
reset_btn.click(
|
| 461 |
+
fn=reset_demo,
|
| 462 |
+
outputs=[chatbot, roster_display, insights_display, nurse_display],
|
| 463 |
+
)
|
| 464 |
+
filter_btn.click(
|
| 465 |
+
fn=build_nurse_table,
|
| 466 |
+
inputs=[name_search, week_dd, avail_dd],
|
| 467 |
+
outputs=nurse_display,
|
| 468 |
+
)
|
| 469 |
+
name_search.submit(
|
| 470 |
+
fn=build_nurse_table,
|
| 471 |
+
inputs=[name_search, week_dd, avail_dd],
|
| 472 |
+
outputs=nurse_display,
|
| 473 |
+
)
|
| 474 |
+
|
| 475 |
+
return app
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
# ββ Entry point βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 479 |
+
if __name__ == "__main__":
|
| 480 |
+
app = create_app()
|
| 481 |
+
app.launch(show_error=True)
|
mock_data.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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2 |
+
mock_data.py β Mock data generator for Nurse Rostering Demo
|
| 3 |
+
|
| 4 |
+
Generates:
|
| 5 |
+
β’ 20 ICU nurses with realistic Singaporean names
|
| 6 |
+
β’ A 2-week (14-day) roster with 3 shifts/day, 4 nurses/shift
|
| 7 |
+
β’ Exactly 80 of 84 shifts filled per week (4 unfilled/week β 8 total gaps)
|
| 8 |
+
β’ No nurse exceeds 5 shifts/week or is double-booked on the same day
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import random
|
| 14 |
+
from dataclasses import dataclass, field
|
| 15 |
+
from datetime import date, timedelta
|
| 16 |
+
from typing import Optional
|
| 17 |
+
|
| 18 |
+
# ββ Constants βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 19 |
+
SHIFTS = [
|
| 20 |
+
("Morning", "08:00β16:00"),
|
| 21 |
+
("Afternoon", "16:00β00:00"),
|
| 22 |
+
("Night", "00:00β08:00"),
|
| 23 |
+
]
|
| 24 |
+
NURSES_PER_SHIFT = 4
|
| 25 |
+
MAX_SHIFTS_PER_WEEK = 5
|
| 26 |
+
NUM_NURSES = 20
|
| 27 |
+
NUM_DAYS = 14
|
| 28 |
+
SHIFTS_PER_DAY = 3
|
| 29 |
+
TOTAL_SLOTS_PER_WEEK = NURSES_PER_SHIFT * SHIFTS_PER_DAY * 7 # 84
|
| 30 |
+
UNFILLED_PER_WEEK = 4 # intentionally leave 4 gaps per week
|
| 31 |
+
|
| 32 |
+
# Realistic Singaporean nurse names
|
| 33 |
+
NURSE_NAMES = [
|
| 34 |
+
"Nurse Priya Nair",
|
| 35 |
+
"Nurse Mei Ling Tan",
|
| 36 |
+
"Nurse Aisha Binte Hassan",
|
| 37 |
+
"Nurse Siti Nurhaliza",
|
| 38 |
+
"Nurse Rachel Lim",
|
| 39 |
+
"Nurse Kavitha Devi",
|
| 40 |
+
"Nurse Nurul Izzah",
|
| 41 |
+
"Nurse Chen Wei Ting",
|
| 42 |
+
"Nurse Fatimah Zahra",
|
| 43 |
+
"Nurse Amanda Koh",
|
| 44 |
+
"Nurse Dewi Sari",
|
| 45 |
+
"Nurse Jasmine Teo",
|
| 46 |
+
"Nurse Lakshmi Rao",
|
| 47 |
+
"Nurse Hazel Ong",
|
| 48 |
+
"Nurse Nadiah Ismail",
|
| 49 |
+
"Nurse Ying Xuan Lee",
|
| 50 |
+
"Nurse Deepa Menon",
|
| 51 |
+
"Nurse Sarah Tan",
|
| 52 |
+
"Nurse Farah Abdullah",
|
| 53 |
+
"Nurse Grace Wong",
|
| 54 |
+
]
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@dataclass
|
| 58 |
+
class Nurse:
|
| 59 |
+
id: int
|
| 60 |
+
name: str
|
| 61 |
+
phone: str # mock SG number
|
| 62 |
+
|
| 63 |
+
def __hash__(self):
|
| 64 |
+
return self.id
|
| 65 |
+
|
| 66 |
+
def __eq__(self, other):
|
| 67 |
+
return isinstance(other, Nurse) and self.id == other.id
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@dataclass
|
| 71 |
+
class ShiftSlot:
|
| 72 |
+
"""One shift on one day."""
|
| 73 |
+
day: date
|
| 74 |
+
shift_name: str # Morning / Afternoon / Night
|
| 75 |
+
shift_hours: str # e.g. "08:00β16:00"
|
| 76 |
+
assigned: list[Nurse] = field(default_factory=list)
|
| 77 |
+
|
| 78 |
+
@property
|
| 79 |
+
def is_filled(self) -> bool:
|
| 80 |
+
return len(self.assigned) >= NURSES_PER_SHIFT
|
| 81 |
+
|
| 82 |
+
@property
|
| 83 |
+
def vacancies(self) -> int:
|
| 84 |
+
return max(0, NURSES_PER_SHIFT - len(self.assigned))
|
| 85 |
+
|
| 86 |
+
@property
|
| 87 |
+
def key(self) -> str:
|
| 88 |
+
return f"{self.day.isoformat()}|{self.shift_name}"
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def generate_nurses() -> list[Nurse]:
|
| 92 |
+
"""Create 20 nurses with mock phone numbers."""
|
| 93 |
+
nurses = []
|
| 94 |
+
for i, name in enumerate(NURSE_NAMES[:NUM_NURSES]):
|
| 95 |
+
phone = f"659{random.randint(1000_0000, 9999_9999)}"
|
| 96 |
+
nurses.append(Nurse(id=i, name=name, phone=phone))
|
| 97 |
+
return nurses
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def generate_roster(
|
| 101 |
+
nurses: list[Nurse],
|
| 102 |
+
start_date: date | None = None,
|
| 103 |
+
seed: int = 42,
|
| 104 |
+
) -> list[ShiftSlot]:
|
| 105 |
+
"""Build a 14-day roster with exactly 8 intentional gaps.
|
| 106 |
+
|
| 107 |
+
Strategy per week (7 days):
|
| 108 |
+
1. Create all 21 shift-slots (7 days Γ 3 shifts).
|
| 109 |
+
2. Need to fill 84 nurse-slots (21 Γ 4 nurses each).
|
| 110 |
+
3. Fill only 80 β leave 4 random slots with 3 nurses instead of 4.
|
| 111 |
+
4. Distribute using round-robin so no nurse > 5 shifts / week
|
| 112 |
+
and no nurse works two shifts on the same day.
|
| 113 |
+
"""
|
| 114 |
+
rng = random.Random(seed)
|
| 115 |
+
|
| 116 |
+
if start_date is None:
|
| 117 |
+
# Next Monday
|
| 118 |
+
today = date.today()
|
| 119 |
+
start_date = today + timedelta(days=(7 - today.weekday()) % 7 or 7)
|
| 120 |
+
|
| 121 |
+
all_slots: list[ShiftSlot] = []
|
| 122 |
+
|
| 123 |
+
for week_offset in range(2):
|
| 124 |
+
week_start = start_date + timedelta(weeks=week_offset)
|
| 125 |
+
|
| 126 |
+
# Build empty slots for this week
|
| 127 |
+
week_slots: list[ShiftSlot] = []
|
| 128 |
+
for d in range(7):
|
| 129 |
+
day = week_start + timedelta(days=d)
|
| 130 |
+
for shift_name, shift_hours in SHIFTS:
|
| 131 |
+
week_slots.append(ShiftSlot(day=day, shift_name=shift_name, shift_hours=shift_hours))
|
| 132 |
+
|
| 133 |
+
# Pick 4 slots that will be intentionally short-staffed (3 nurses instead of 4)
|
| 134 |
+
gap_indices = set(rng.sample(range(len(week_slots)), UNFILLED_PER_WEEK))
|
| 135 |
+
|
| 136 |
+
# Target nurse-slots to fill
|
| 137 |
+
# full slot = 4, gap slot = 3
|
| 138 |
+
target_per_slot = [
|
| 139 |
+
NURSES_PER_SHIFT - 1 if i in gap_indices else NURSES_PER_SHIFT
|
| 140 |
+
for i in range(len(week_slots))
|
| 141 |
+
]
|
| 142 |
+
|
| 143 |
+
# Track per-nurse constraints
|
| 144 |
+
nurse_week_count = {n.id: 0 for n in nurses}
|
| 145 |
+
nurse_day_set: dict[int, set[date]] = {n.id: set() for n in nurses}
|
| 146 |
+
|
| 147 |
+
# Fill each slot
|
| 148 |
+
for slot_idx, slot in enumerate(week_slots):
|
| 149 |
+
needed = target_per_slot[slot_idx]
|
| 150 |
+
eligible = [
|
| 151 |
+
n for n in nurses
|
| 152 |
+
if nurse_week_count[n.id] < MAX_SHIFTS_PER_WEEK
|
| 153 |
+
and slot.day not in nurse_day_set[n.id]
|
| 154 |
+
]
|
| 155 |
+
rng.shuffle(eligible)
|
| 156 |
+
chosen = eligible[:needed]
|
| 157 |
+
slot.assigned = chosen
|
| 158 |
+
for n in chosen:
|
| 159 |
+
nurse_week_count[n.id] += 1
|
| 160 |
+
nurse_day_set[n.id].add(slot.day)
|
| 161 |
+
|
| 162 |
+
all_slots.extend(week_slots)
|
| 163 |
+
|
| 164 |
+
return all_slots
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
# ββ Convenience helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 168 |
+
|
| 169 |
+
def get_unfilled_slots(roster: list[ShiftSlot]) -> list[ShiftSlot]:
|
| 170 |
+
"""Return only the slots that have vacancies."""
|
| 171 |
+
return [s for s in roster if not s.is_filled]
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def week_number(slot: ShiftSlot, roster: list[ShiftSlot]) -> int:
|
| 175 |
+
"""1-based week number relative to the roster start."""
|
| 176 |
+
roster_start = roster[0].day
|
| 177 |
+
return (slot.day - roster_start).days // 7 + 1
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def nurse_shifts_in_week(nurse: Nurse, roster: list[ShiftSlot], week: int) -> int:
|
| 181 |
+
"""Count how many shifts a nurse already has in a given week."""
|
| 182 |
+
return sum(
|
| 183 |
+
1 for s in roster
|
| 184 |
+
if week_number(s, roster) == week and nurse in s.assigned
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def nurse_works_on_day(nurse: Nurse, roster: list[ShiftSlot], day: date) -> bool:
|
| 189 |
+
"""Check if a nurse is already assigned to any shift on a given day."""
|
| 190 |
+
return any(
|
| 191 |
+
s.day == day and nurse in s.assigned
|
| 192 |
+
for s in roster
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def eligible_nurses_for_slot(
|
| 197 |
+
slot: ShiftSlot,
|
| 198 |
+
nurses: list[Nurse],
|
| 199 |
+
roster: list[ShiftSlot],
|
| 200 |
+
) -> list[Nurse]:
|
| 201 |
+
"""Nurses who can fill a vacancy: not on that day, < 5 shifts that week."""
|
| 202 |
+
week = week_number(slot, roster)
|
| 203 |
+
return [
|
| 204 |
+
n for n in nurses
|
| 205 |
+
if n not in slot.assigned
|
| 206 |
+
and not nurse_works_on_day(n, roster, slot.day)
|
| 207 |
+
and nurse_shifts_in_week(n, roster, week) < MAX_SHIFTS_PER_WEEK
|
| 208 |
+
]
|
requirements.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio==5.23.0
|
| 2 |
+
pandas>=2.0
|