"""
app.py — Nurse Rostering AI Agent Demo (Gradio)
4-Tab Dashboard:
Tab 1 → AI Chat (agent fills gaps)
Tab 2 → Roster View (white background, readable)
Tab 3 → Insights (macro gap analysis)
Tab 4 → Nurse Availability (search & filter)
Deploy: gradio deploy
Local: python app.py
"""
from __future__ import annotations
import gradio as gr
import pandas as pd
from collections import defaultdict
from mock_data import (
MAX_SHIFTS_PER_WEEK,
NUM_NURSES,
NURSES_PER_SHIFT,
SHIFTS,
generate_nurses,
generate_roster,
get_unfilled_slots,
week_number,
nurse_shifts_in_week,
nurse_works_on_day,
eligible_nurses_for_slot,
ShiftSlot,
Nurse,
)
from agent import run_agent
# ── Global state ──────────────────────────────────────────────────────────────
nurses: list[Nurse] = []
roster: list[ShiftSlot] = []
def init_state():
global nurses, roster
nurses = generate_nurses()
roster = generate_roster(nurses)
init_state()
# ═══════════════════════════════════════════════════════════════════════════════
# TAB 2 — ROSTER VIEW (white background, high contrast)
# ═══════════════════════════════════════════════════════════════════════════════
def roster_to_html(roster: list[ShiftSlot]) -> str:
days: dict[str, list[ShiftSlot]] = {}
for slot in roster:
days.setdefault(slot.day.isoformat(), []).append(slot)
all_days = sorted(days.keys())
total_slots = len(roster)
unfilled_count = len(get_unfilled_slots(roster))
filled_count = total_slots - unfilled_count
total_assignments = sum(len(s.assigned) for s in roster)
html = """
"""
html += f"""
🏥 ICU Roster · 2-Week Schedule
Filled: {filled_count}/{total_slots}
Unfilled: {unfilled_count}
👩⚕️ {NUM_NURSES} nurses · {total_assignments} assignments
"""
html += '
| Date | '
for sn, sh in SHIFTS:
html += f"{sn} {sh} | "
html += "
"
for i, dk in enumerate(all_days):
if i == 0:
html += '| 📅 Week 1 |
'
elif i == 7:
html += '| 📅 Week 2 |
'
slots = days[dk]
label = slots[0].day.strftime("%a %d %b")
html += f'| {label} | '
for slot in slots:
cls = "r-unfilled" if slot.vacancies > 0 else "r-filled"
cell = ""
for n in slot.assigned:
cell += f'👩⚕️ {n.name.replace("Nurse ", "")}'
if slot.vacancies > 0:
cell += f'⚠️ NEED {slot.vacancies}'
html += f'{cell} | '
html += "
"
html += "
"
return html
# ═══════════════════════════════════════════════════════════════════════════════
# TAB 3 — INSIGHTS
# ═══════════════════════════════════════════════════════════════════════════════
def build_insights_html(roster: list[ShiftSlot]) -> str:
unfilled = get_unfilled_slots(roster)
total = len(roster)
filled = total - len(unfilled)
fill_pct = filled / total * 100 if total else 0
# Gaps by shift type
gap_by_shift: dict[str, int] = defaultdict(int)
for s in unfilled:
gap_by_shift[s.shift_name] += s.vacancies
# Gaps by week
gap_by_week: dict[int, int] = defaultdict(int)
for s in unfilled:
w = week_number(s, roster)
gap_by_week[w] += s.vacancies
# Nurse utilisation
nurse_load: dict[int, dict[int, int]] = defaultdict(lambda: defaultdict(int))
for s in roster:
w = week_number(s, roster)
for n in s.assigned:
nurse_load[n.id][w] += 1
at_max = sum(1 for nw in nurse_load.values() for c in nw.values() if c >= MAX_SHIFTS_PER_WEEK)
bar_col = "#16a34a" if fill_pct >= 95 else "#f59e0b" if fill_pct >= 85 else "#dc2626"
html = """
"""
html += f"""
{fill_pct:.0f}%
Fill Rate
{len(unfilled)}
Unfilled Shifts
{total}
Total Shifts (2 weeks)
{at_max}
Nurse-Weeks at Max (5/5)
"""
# Gaps by shift type
html += '
📊 Gaps by Shift Type
| Shift | Unfilled Slots |
'
for sn, _ in SHIFTS:
cnt = gap_by_shift.get(sn, 0)
badge = f'{cnt}' if cnt > 0 else '0'
html += f"| {sn} | {badge} |
"
html += "
"
# Gaps by week
html += '
📅 Gaps by Week
| Week | Unfilled Slots |
'
for w in sorted(gap_by_week.keys()):
cnt = gap_by_week[w]
badge = f'{cnt}' if cnt > 0 else '0'
html += f"| Week {w} | {badge} |
"
if not gap_by_week:
html += '| ✅ No gaps |
'
html += "
"
# Unfilled shift detail
if unfilled:
html += '
🔴 Unfilled Shift Details
| # | Date | Day | Shift | Vacancies |
'
for i, s in enumerate(unfilled, 1):
html += f'| {i} | {s.day.strftime("%d %b %Y")} | {s.day.strftime("%A")} | {s.shift_name} ({s.shift_hours}) | {s.vacancies} |
'
html += "
"
else:
html += '
✅ All shifts are fully covered!
'
html += "
"
return html
# ═══════════════════════════════════════════════════════════════════════════════
# TAB 4 — NURSE AVAILABILITY (search / filter)
# ═══════════════════════════════════════════════════════════════════════════════
def build_nurse_table(name_filter: str, week_filter: str, availability_filter: str) -> str:
"""Build an HTML table of nurses with their weekly loads and availability."""
week_num = None
if week_filter and week_filter != "All":
week_num = int(week_filter.replace("Week ", ""))
only_available = availability_filter == "Has Capacity"
rows = []
for n in nurses:
if name_filter and name_filter.lower() not in n.name.lower():
continue
w1 = nurse_shifts_in_week(n, roster, 1)
w2 = nurse_shifts_in_week(n, roster, 2)
cap1 = MAX_SHIFTS_PER_WEEK - w1
cap2 = MAX_SHIFTS_PER_WEEK - w2
days_w1 = sorted(set(
s.day for s in roster
if week_number(s, roster) == 1 and n in s.assigned
))
days_w2 = sorted(set(
s.day for s in roster
if week_number(s, roster) == 2 and n in s.assigned
))
if week_num == 1 and only_available and cap1 <= 0:
continue
if week_num == 2 and only_available and cap2 <= 0:
continue
if week_num is None and only_available and cap1 <= 0 and cap2 <= 0:
continue
rows.append({
"nurse": n,
"w1": w1, "w2": w2,
"cap1": cap1, "cap2": cap2,
"days_w1": days_w1, "days_w2": days_w2,
})
html = """
"""
html += f'
Showing {len(rows)} of {NUM_NURSES} nurses
'
html += """
| Nurse |
Phone |
Week 1 Shifts |
Week 1 Capacity |
Week 1 Days |
Week 2 Shifts |
Week 2 Capacity |
Week 2 Days |
"""
for r in rows:
n = r["nurse"]
name_short = n.name.replace("Nurse ", "")
cap1_cls = "cap-full" if r["cap1"] <= 0 else "cap-has"
cap2_cls = "cap-full" if r["cap2"] <= 0 else "cap-has"
days1_html = " ".join(f'{d.strftime("%a %d")}' for d in r["days_w1"]) or "—"
days2_html = " ".join(f'{d.strftime("%a %d")}' for d in r["days_w2"]) or "—"
html += f"""
| 👩⚕️ {name_short} |
{n.phone} |
{r['w1']}/5 |
{r['cap1']} left |
{days1_html} |
{r['w2']}/5 |
{r['cap2']} left |
{days2_html} |
"""
html += "
"
return html
# ═══════════════════════════════════════════════════════════════════════════════
# TAB 1 — AI CHAT
# ═══════════════════════════════════════════════════════════════════════════════
def handle_chat(user_message: str, history: list[dict]) -> tuple:
"""Process user message → agent steps → update roster + all tabs."""
global roster
full_response = ""
for step in run_agent(roster, nurses, user_message):
full_response += f"### {step.phase}\n\n{step.message}\n\n---\n\n"
history.append({"role": "user", "content": user_message})
history.append({"role": "assistant", "content": full_response})
return (
history,
"", # clear textbox
roster_to_html(roster), # tab 2
build_insights_html(roster), # tab 3
build_nurse_table("", "All", "All"), # tab 4
)
def reset_demo():
global nurses, roster
init_state()
return (
[], # chat
roster_to_html(roster),
build_insights_html(roster),
build_nurse_table("", "All", "All"),
)
# ═══════════════════════════════════════════════════════════════════════════════
# GRADIO APP
# ═══════════════════════════════════════════════════════════════════════════════
def create_app() -> gr.Blocks:
with gr.Blocks(title="🏥 Nurse Rostering AI Agent") as app:
gr.Markdown(
"""
# 🏥 Nurse Rostering AI Agent — ICU Department
**AI-Powered Workforce Scheduling Demo** · 20 Nurses · 3 Shifts / Day · 2-Week Roster
"""
)
with gr.Tabs():
# ── Tab 1: AI Chat ────────────────────────────────────────────
with gr.Tab("🤖 AI Manager"):
gr.Markdown(
"> 💡 Type **\"Fill the unfilled shifts\"** to watch the AI agent "
"analyze gaps, find available nurses, send outreach, and update the roster."
)
chatbot = gr.Chatbot(
type="messages",
value=[{
"role": "assistant",
"content": (
"👋 Hi! I'm your AI Roster Manager for the **ICU department**.\n\n"
"I can see there are **unfilled shifts** in the 2-week roster. "
"How can I help?\n\n"
"**Try asking:**\n"
'- *"Fill the unfilled shifts"*\n'
'- *"Show me the gaps for this week"*\n'
'- *"Find nurses for the night shift"*'
),
}],
height=520,
)
with gr.Row():
msg_input = gr.Textbox(
placeholder="e.g. Fill the unfilled shifts for this week…",
show_label=False,
scale=5,
container=False,
)
send_btn = gr.Button("Send", variant="primary", scale=1)
reset_btn = gr.Button("🔄 Reset Demo", variant="secondary", size="sm")
# ── Tab 2: Roster View ────────────────────────────────────────
with gr.Tab("📋 Roster View"):
roster_display = gr.HTML(value=roster_to_html(roster))
# ── Tab 3: Insights ───────────────────────────────────────────
with gr.Tab("📊 Insights"):
insights_display = gr.HTML(value=build_insights_html(roster))
# ── Tab 4: Nurse Availability ─────────────────────────────────
with gr.Tab("👩⚕️ Nurse Availability"):
with gr.Row():
name_search = gr.Textbox(
label="🔍 Search by name",
placeholder="e.g. Priya, Mei Ling…",
scale=3,
)
week_dd = gr.Dropdown(
label="Week",
choices=["All", "Week 1", "Week 2"],
value="All",
scale=1,
)
avail_dd = gr.Dropdown(
label="Availability",
choices=["All", "Has Capacity"],
value="All",
scale=1,
)
filter_btn = gr.Button("Apply Filter", variant="primary", scale=1)
nurse_display = gr.HTML(value=build_nurse_table("", "All", "All"))
# ── Event wiring ──────────────────────────────────────────────────
chat_outputs = [chatbot, msg_input, roster_display, insights_display, nurse_display]
send_btn.click(
fn=handle_chat,
inputs=[msg_input, chatbot],
outputs=chat_outputs,
)
msg_input.submit(
fn=handle_chat,
inputs=[msg_input, chatbot],
outputs=chat_outputs,
)
reset_btn.click(
fn=reset_demo,
outputs=[chatbot, roster_display, insights_display, nurse_display],
)
filter_btn.click(
fn=build_nurse_table,
inputs=[name_search, week_dd, avail_dd],
outputs=nurse_display,
)
name_search.submit(
fn=build_nurse_table,
inputs=[name_search, week_dd, avail_dd],
outputs=nurse_display,
)
return app
# ── Entry point ───────────────────────────────────────────────────────────────
if __name__ == "__main__":
app = create_app()
app.launch(show_error=True)