Download app.py from Yaoyeeng/Nurse-Rostering-AI-Agent: direct link, hf CLI and curl.
- Browser
- Download file 21.5 kB
-
https://huggingface.co/spaces/Yaoyeeng/Nurse-Rostering-AI-Agent/resolve/main/app.py
- Command line
-
hf download hf://spaces/Yaoyeeng/Nurse-Rostering-AI-Agent/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Yaoyeeng/Nurse-Rostering-AI-Agent/resolve/main/app.py
21.5 kB
| """ | |
| 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 = """ | |
| <style> | |
| .r-wrap { font-family: 'Inter', -apple-system, sans-serif; } | |
| .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; } | |
| .r-stat { display: flex; align-items: center; gap: 6px; } | |
| .r-dot { width: 10px; height: 10px; border-radius: 50%; } | |
| .r-dot-green { background: #16a34a; } | |
| .r-dot-red { background: #dc2626; } | |
| .r-table { border-collapse: collapse; width: 100%; font-size: 13px; } | |
| .r-table th { background: #1e293b; color: #fff; padding: 10px 8px; text-align: center; border: 1px solid #cbd5e1; } | |
| .r-table td { padding: 8px 10px; border: 1px solid #cbd5e1; vertical-align: top; min-width: 150px; line-height: 1.6; } | |
| .r-filled { background: #f0fdf4; color: #14532d; } | |
| .r-unfilled { background: #fef2f2; color: #7f1d1d; } | |
| .r-week { background: #e2e8f0 !important; color: #0f172a; font-size: 14px; font-weight: 700; text-align: left; padding: 8px 14px; } | |
| .r-day { font-weight: 600; background: #f8fafc; color: #1e293b; text-align: center; white-space: nowrap; } | |
| .r-name { display: block; padding: 1px 0; font-size: 12.5px; } | |
| .r-gap { display: inline-block; background: #dc2626; color: #fff; padding: 2px 8px; border-radius: 4px; font-size: 11px; font-weight: 600; margin-top: 4px; } | |
| </style> | |
| <div class="r-wrap"> | |
| """ | |
| html += f""" | |
| <div class="r-stats"> | |
| <div class="r-stat"><b>π₯ ICU Roster</b> Β· 2-Week Schedule</div> | |
| <div class="r-stat"><span class="r-dot r-dot-green"></span> Filled: {filled_count}/{total_slots}</div> | |
| <div class="r-stat"><span class="r-dot r-dot-red"></span> Unfilled: {unfilled_count}</div> | |
| <div class="r-stat">π©ββοΈ {NUM_NURSES} nurses Β· {total_assignments} assignments</div> | |
| </div> | |
| """ | |
| html += '<table class="r-table"><tr><th>Date</th>' | |
| for sn, sh in SHIFTS: | |
| html += f"<th>{sn}<br><small>{sh}</small></th>" | |
| html += "</tr>" | |
| for i, dk in enumerate(all_days): | |
| if i == 0: | |
| html += '<tr><td colspan="4" class="r-week">π Week 1</td></tr>' | |
| elif i == 7: | |
| html += '<tr><td colspan="4" class="r-week">π Week 2</td></tr>' | |
| slots = days[dk] | |
| label = slots[0].day.strftime("%a %d %b") | |
| html += f'<tr><td class="r-day">{label}</td>' | |
| for slot in slots: | |
| cls = "r-unfilled" if slot.vacancies > 0 else "r-filled" | |
| cell = "" | |
| for n in slot.assigned: | |
| cell += f'<span class="r-name">π©ββοΈ {n.name.replace("Nurse ", "")}</span>' | |
| if slot.vacancies > 0: | |
| cell += f'<span class="r-gap">β οΈ NEED {slot.vacancies}</span>' | |
| html += f'<td class="{cls}">{cell}</td>' | |
| html += "</tr>" | |
| html += "</table></div>" | |
| 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 = """ | |
| <style> | |
| .ins { font-family: 'Inter', -apple-system, sans-serif; color: #1e293b; } | |
| .kpi-row { display: flex; gap: 16px; flex-wrap: wrap; margin-bottom: 24px; } | |
| .kpi { flex: 1; min-width: 160px; background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 12px; padding: 20px; text-align: center; } | |
| .kpi-val { font-size: 32px; font-weight: 800; margin-bottom: 4px; } | |
| .kpi-label { font-size: 13px; color: #64748b; } | |
| .bar-outer { width: 100%; height: 14px; background: #e2e8f0; border-radius: 7px; overflow: hidden; margin-top: 8px; } | |
| .bar-inner { height: 100%; border-radius: 7px; } | |
| .section { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 12px; padding: 20px; margin-bottom: 16px; } | |
| .section h3 { margin: 0 0 12px; font-size: 15px; color: #334155; } | |
| .gap-table { width: 100%; border-collapse: collapse; font-size: 13px; } | |
| .gap-table th { background: #f1f5f9; padding: 8px 12px; text-align: left; border-bottom: 2px solid #e2e8f0; color: #475569; } | |
| .gap-table td { padding: 8px 12px; border-bottom: 1px solid #f1f5f9; } | |
| .badge-red { background: #fee2e2; color: #991b1b; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: 600; } | |
| .badge-green { background: #dcfce7; color: #166534; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: 600; } | |
| </style> | |
| <div class="ins"> | |
| """ | |
| html += f""" | |
| <div class="kpi-row"> | |
| <div class="kpi"> | |
| <div class="kpi-val" style="color:{bar_col}">{fill_pct:.0f}%</div> | |
| <div class="kpi-label">Fill Rate</div> | |
| <div class="bar-outer"><div class="bar-inner" style="width:{fill_pct}%;background:{bar_col}"></div></div> | |
| </div> | |
| <div class="kpi"> | |
| <div class="kpi-val" style="color:#dc2626">{len(unfilled)}</div> | |
| <div class="kpi-label">Unfilled Shifts</div> | |
| </div> | |
| <div class="kpi"> | |
| <div class="kpi-val" style="color:#0ea5e9">{total}</div> | |
| <div class="kpi-label">Total Shifts (2 weeks)</div> | |
| </div> | |
| <div class="kpi"> | |
| <div class="kpi-val" style="color:#8b5cf6">{at_max}</div> | |
| <div class="kpi-label">Nurse-Weeks at Max (5/5)</div> | |
| </div> | |
| </div> | |
| """ | |
| # Gaps by shift type | |
| html += '<div class="section"><h3>π Gaps by Shift Type</h3><table class="gap-table"><tr><th>Shift</th><th>Unfilled Slots</th></tr>' | |
| for sn, _ in SHIFTS: | |
| cnt = gap_by_shift.get(sn, 0) | |
| badge = f'<span class="badge-red">{cnt}</span>' if cnt > 0 else '<span class="badge-green">0</span>' | |
| html += f"<tr><td>{sn}</td><td>{badge}</td></tr>" | |
| html += "</table></div>" | |
| # Gaps by week | |
| html += '<div class="section"><h3>π Gaps by Week</h3><table class="gap-table"><tr><th>Week</th><th>Unfilled Slots</th></tr>' | |
| for w in sorted(gap_by_week.keys()): | |
| cnt = gap_by_week[w] | |
| badge = f'<span class="badge-red">{cnt}</span>' if cnt > 0 else '<span class="badge-green">0</span>' | |
| html += f"<tr><td>Week {w}</td><td>{badge}</td></tr>" | |
| if not gap_by_week: | |
| html += '<tr><td colspan="2">β No gaps</td></tr>' | |
| html += "</table></div>" | |
| # Unfilled shift detail | |
| if unfilled: | |
| 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>' | |
| for i, s in enumerate(unfilled, 1): | |
| 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>' | |
| html += "</table></div>" | |
| else: | |
| html += '<div class="section"><h3>β All shifts are fully covered!</h3></div>' | |
| html += "</div>" | |
| 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 = """ | |
| <style> | |
| .na { font-family: 'Inter', -apple-system, sans-serif; color: #1e293b; } | |
| .na-count { font-size: 14px; color: #64748b; margin-bottom: 12px; } | |
| .na-table { width: 100%; border-collapse: collapse; font-size: 13px; } | |
| .na-table th { background: #f1f5f9; padding: 10px 12px; text-align: left; border-bottom: 2px solid #e2e8f0; color: #475569; font-weight: 600; } | |
| .na-table td { padding: 10px 12px; border-bottom: 1px solid #f1f5f9; vertical-align: top; } | |
| .na-table tr:hover { background: #f8fafc; } | |
| .cap-full { color: #dc2626; font-weight: 700; } | |
| .cap-has { color: #16a34a; font-weight: 700; } | |
| .day-chip { display: inline-block; background: #e0f2fe; color: #0c4a6e; padding: 1px 6px; border-radius: 4px; font-size: 11px; margin: 1px 2px; } | |
| .phone-txt { color: #64748b; font-size: 12px; } | |
| </style> | |
| <div class="na"> | |
| """ | |
| html += f'<div class="na-count">Showing {len(rows)} of {NUM_NURSES} nurses</div>' | |
| html += """ | |
| <table class="na-table"> | |
| <tr> | |
| <th>Nurse</th> | |
| <th>Phone</th> | |
| <th>Week 1 Shifts</th> | |
| <th>Week 1 Capacity</th> | |
| <th>Week 1 Days</th> | |
| <th>Week 2 Shifts</th> | |
| <th>Week 2 Capacity</th> | |
| <th>Week 2 Days</th> | |
| </tr> | |
| """ | |
| 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'<span class="day-chip">{d.strftime("%a %d")}</span>' for d in r["days_w1"]) or "β" | |
| days2_html = " ".join(f'<span class="day-chip">{d.strftime("%a %d")}</span>' for d in r["days_w2"]) or "β" | |
| html += f""" | |
| <tr> | |
| <td><b>π©ββοΈ {name_short}</b></td> | |
| <td><span class="phone-txt">{n.phone}</span></td> | |
| <td>{r['w1']}/5</td> | |
| <td class="{cap1_cls}">{r['cap1']} left</td> | |
| <td>{days1_html}</td> | |
| <td>{r['w2']}/5</td> | |
| <td class="{cap2_cls}">{r['cap2']} left</td> | |
| <td>{days2_html}</td> | |
| </tr>""" | |
| html += "</table></div>" | |
| 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) | |