-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
233 lines (194 loc) · 7.39 KB
/
Copy pathmain.py
File metadata and controls
233 lines (194 loc) · 7.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
"""
main.py — ExitFlow FastAPI application.
Serves landing page, attendee view, organizer dashboard, and JSON APIs.
"""
import asyncio
import os
from contextlib import asynccontextmanager
from dotenv import load_dotenv
load_dotenv()
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel
import simulator
import gemini_client
# ---------------------------------------------------------------------------
# App lifespan: seed data, start background tick, run initial Gemini strategy
# ---------------------------------------------------------------------------
@asynccontextmanager
async def lifespan(app: FastAPI):
# Seed with default wave assignments first so the app is immediately usable
simulator.seed()
# Try to get a Gemini-generated dispersal strategy
venue_snapshot = {
"venue_name": simulator.VENUE_NAME,
"event_name": simulator.EVENT_NAME,
"gates": {
gid: {
"name": g["name"],
"capacity": g["capacity"],
"direction": g["direction"],
"transit": g["transit"],
}
for gid, g in simulator.GATES.items()
},
"transit_nodes": {
tid: {
"name": t["name"],
"capacity": t["capacity"],
"walk_min": t["walk_min"],
}
for tid, t in simulator.TRANSIT_NODES.items()
},
"sections": simulator.SECTIONS,
"total_attendees": 15000,
}
strategy = await gemini_client.generate_dispersal_strategy(venue_snapshot)
simulator.dispersal_strategy_text = strategy.get("rationale", "")
# Re-seed with Gemini-suggested wave assignments
wave_override = strategy.get("wave_assignments", {})
simulator.seed(strategy_override={
gid: {"wave": w} for gid, w in wave_override.items()
})
simulator.dispersal_strategy_text = strategy.get("rationale", "")
# Start background simulation tick
task = asyncio.create_task(_simulation_loop())
yield
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
async def _simulation_loop() -> None:
while True:
await asyncio.sleep(5)
simulator.tick()
# Enrich any new alerts with Gemini suggestions (non-blocking)
for alert in simulator.active_alerts:
if alert.get("suggestion") is None:
try:
alert["suggestion"] = await gemini_client.generate_intervention(alert)
except Exception:
alert["suggestion"] = gemini_client._fallback_intervention(alert)
# ---------------------------------------------------------------------------
# FastAPI app
# ---------------------------------------------------------------------------
app = FastAPI(title="ExitFlow", lifespan=lifespan)
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
# ---------------------------------------------------------------------------
# Page routes
# ---------------------------------------------------------------------------
@app.get("/", response_class=HTMLResponse)
async def landing(request: Request):
demo_ticket = simulator.get_demo_ticket()
return templates.TemplateResponse(
"index.html",
{
"request": request,
"event_name": simulator.EVENT_NAME,
"venue_name": simulator.VENUE_NAME,
"demo_ticket": demo_ticket,
"strategy_text": simulator.dispersal_strategy_text,
},
)
@app.get("/attendee/{ticket_id}", response_class=HTMLResponse)
async def attendee_view(request: Request, ticket_id: str):
ctx = simulator.get_attendee_context(ticket_id)
if not ctx:
raise HTTPException(status_code=404, detail=f"Ticket {ticket_id} not found")
gate_id = ctx["gate_id"]
gate = simulator.GATES[gate_id]
transit_id = gate["transit"] # "metro" | "bus" | "taxi"
transit = simulator.TRANSIT_NODES[transit_id]
# Build timeline steps
wave_offset = round(ctx["depart_offset_min"])
gate_arrive = wave_offset + 3 # ~3 min walk
transit_arrive = gate_arrive + 5 # ~5 min at gate
board_time = transit_arrive + transit["walk_min"]
timeline = [
{
"icon": "🪑",
"label": "Leave your seat",
"detail": f"Section {ctx['section']}, Row {ctx['seat_row']}",
"offset_min": wave_offset,
"state": "depart",
},
{
"icon": "🚶",
"label": f"Walk to {gate['name']}",
"detail": f"Head {gate['direction']} — follow green ExitFlow signs",
"offset_min": gate_arrive,
"state": "walk",
},
{
"icon": "🚪",
"label": "Exit through gate",
"detail": "Have your ticket ready for scanning",
"offset_min": transit_arrive,
"state": "gate",
},
{
"icon": transit["icon"],
"label": f"Board at {transit['name']}",
"detail": f"{transit['walk_min']} min walk from gate",
"offset_min": board_time,
"state": "transit",
},
]
return templates.TemplateResponse(
"attendee.html",
{
"request": request,
"ctx": ctx,
"gate": gate,
"transit": transit,
"transit_id": transit_id,
"timeline": timeline,
"ticket_id": ticket_id,
"event_name": simulator.EVENT_NAME,
"venue_name": simulator.VENUE_NAME,
},
)
@app.get("/dashboard", response_class=HTMLResponse)
async def dashboard(request: Request):
return templates.TemplateResponse(
"dashboard.html",
{
"request": request,
"event_name": simulator.EVENT_NAME,
"venue_name": simulator.VENUE_NAME,
"venue_center": simulator.VENUE_CENTER,
"gates": [{"gate_id": gid, **g} for gid, g in simulator.GATES.items()],
"transit_nodes": [{"transit_id": tid, **t} for tid, t in simulator.TRANSIT_NODES.items()],
"strategy_text": simulator.dispersal_strategy_text,
},
)
# ---------------------------------------------------------------------------
# API routes
# ---------------------------------------------------------------------------
class ChatRequest(BaseModel):
ticket_id: str
message: str
@app.post("/api/chat")
async def chat(req: ChatRequest):
ctx = simulator.get_attendee_context(req.ticket_id)
if not ctx:
raise HTTPException(status_code=404, detail="Ticket not found")
reply = await gemini_client.chat_with_attendee(req.message, ctx)
return {"reply": reply}
@app.get("/api/crowd_state")
async def crowd_state():
return JSONResponse(simulator.get_crowd_state_snapshot())
@app.get("/api/alerts")
async def alerts():
# Ensure all alerts have suggestions before returning
for alert in simulator.active_alerts:
if alert.get("suggestion") is None:
alert["suggestion"] = gemini_client._fallback_intervention(alert)
return JSONResponse({"alerts": simulator.active_alerts})
@app.get("/api/strategy")
async def strategy():
return {"strategy": simulator.dispersal_strategy_text}