Shereen Lee commited on
Commit
e94fa19
·
1 Parent(s): e0cda33

fix loading time issues

Browse files
Files changed (6) hide show
  1. .gitignore +3 -0
  2. app.py +54 -35
  3. docs/architecture.md +4 -0
  4. docs/dev-blog.md +423 -0
  5. index.build.html +86 -70
  6. index.html +79 -66
.gitignore CHANGED
@@ -9,3 +9,6 @@ sozai_rooms.db
9
  **/.DS_Store
10
  *.HEIC
11
  *.heic
 
 
 
 
9
  **/.DS_Store
10
  *.HEIC
11
  *.heic
12
+ CLAUDE.md
13
+ __pycache__/
14
+ *.pyc
app.py CHANGED
@@ -56,6 +56,7 @@ os.environ.setdefault("HF_XET_HIGH_PERFORMANCE", "0")
56
  import asyncio
57
  import functools
58
  import hashlib
 
59
  import io
60
  import json
61
  import mimetypes
@@ -3121,13 +3122,27 @@ def _vendor_fetch(fname: str):
3121
  return None
3122
 
3123
 
 
 
 
3124
  @app.get("/vendor/{fname}")
3125
- def vendor_file(fname: str):
3126
- """Serve a vendored library (e.g. /vendor/maplibre-gl.js) from local cache."""
 
 
 
 
 
3127
  data = _vendor_fetch(fname)
3128
  if data is None:
3129
  raise HTTPException(status_code=404, detail="vendor file unavailable")
3130
  media = "text/javascript" if fname.endswith(".js") else ("text/css" if fname.endswith(".css") else "application/octet-stream")
 
 
 
 
 
 
3131
  return Response(content=data, media_type=media)
3132
 
3133
 
@@ -3138,36 +3153,13 @@ def _read_html(name: str) -> str:
3138
  return fh.read()
3139
 
3140
 
3141
- def _inline_maplibre(html: str) -> str:
3142
- """Replace the <!--MAPLIBRE_INLINE--> marker in the page with the cached
3143
- MapLibre CSS + JS inlined directly. This is the most robust delivery: the
3144
- browser executes the library inline with no extra request, sidestepping any
3145
- routing/MIME/proxy issues. If the library can't be cached (server offline),
3146
- the marker is left as-is and the page's CDN fallback loader takes over.
3147
- """
3148
- marker = "<!--MAPLIBRE_INLINE-->"
3149
- if marker not in html:
3150
- return html
3151
- js = _vendor_fetch("maplibre-gl.js")
3152
- css = _vendor_fetch("maplibre-gl.css")
3153
- if not js:
3154
- # leave the marker; the in-page CDN fallback will handle loading
3155
- return html
3156
- parts = []
3157
- if css:
3158
- css_text = css.decode("utf-8", "replace").replace("</style", "<\\/style")
3159
- parts.append("<style>\n" + css_text + "\n</style>")
3160
- js_text = js.decode("utf-8", "replace").replace("</script", "<\\/script")
3161
- parts.append("<script>\n" + js_text + "\n</script>")
3162
- return html.replace(marker, "\n".join(parts), 1)
3163
-
3164
-
3165
  _APP_HTML_CACHE: str | None = None
3166
 
3167
 
3168
  def _app_html() -> str:
3169
- """Assembled app HTML, built once and cached in memory (the file doesn't
3170
- change at runtime, so re-reading + re-inlining ~500 KB per request is waste).
 
3171
 
3172
  Prefers `index.build.html` — the precompiled output of build_frontend.py,
3173
  which ships plain JS instead of making the browser download @babel/standalone
@@ -3186,23 +3178,50 @@ def _app_html() -> str:
3186
  print("[frontend] no index.build.html — serving un-precompiled index.html "
3187
  "(slow first boot). Run `python build_frontend.py`.")
3188
  name = "index.html"
3189
- _APP_HTML_CACHE = _inline_maplibre(_read_html(name))
3190
  return _APP_HTML_CACHE
3191
 
3192
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3193
  @app.get("/", response_class=HTMLResponse)
3194
- async def landing():
3195
- return _read_html("landing.html")
3196
 
3197
 
3198
  @app.get("/app", response_class=HTMLResponse)
3199
- async def solo_app():
3200
- return _app_html()
3201
 
3202
 
3203
  @app.get("/room/{room_id}", response_class=HTMLResponse)
3204
- async def room_app(room_id: str):
3205
- return _app_html()
3206
 
3207
 
3208
  # --------------------------- Cleanup daemon -------------------------------- #
 
56
  import asyncio
57
  import functools
58
  import hashlib
59
+ import gzip
60
  import io
61
  import json
62
  import mimetypes
 
3122
  return None
3123
 
3124
 
3125
+ _VENDOR_GZIP: dict[str, bytes] = {}
3126
+
3127
+
3128
  @app.get("/vendor/{fname}")
3129
+ def vendor_file(fname: str, request: Request):
3130
+ """Serve a vendored library (e.g. /vendor/maplibre-gl.js) from local cache.
3131
+
3132
+ MapLibre (~800 KB) is lazy-loaded from here on demand rather than inlined
3133
+ into every page, so gzip it on the wire when the client supports it
3134
+ (~800 KB -> ~220 KB) and memoize the compressed bytes (vendor files are
3135
+ immutable, so compress each one only once)."""
3136
  data = _vendor_fetch(fname)
3137
  if data is None:
3138
  raise HTTPException(status_code=404, detail="vendor file unavailable")
3139
  media = "text/javascript" if fname.endswith(".js") else ("text/css" if fname.endswith(".css") else "application/octet-stream")
3140
+ if "gzip" in request.headers.get("accept-encoding", "").lower():
3141
+ gz = _VENDOR_GZIP.get(fname)
3142
+ if gz is None:
3143
+ gz = _VENDOR_GZIP[fname] = gzip.compress(data, 6)
3144
+ return Response(content=gz, media_type=media,
3145
+ headers={"Content-Encoding": "gzip", "Vary": "Accept-Encoding"})
3146
  return Response(content=data, media_type=media)
3147
 
3148
 
 
3153
  return fh.read()
3154
 
3155
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3156
  _APP_HTML_CACHE: str | None = None
3157
 
3158
 
3159
  def _app_html() -> str:
3160
+ """App HTML, read once and cached in memory (the file doesn't change at
3161
+ runtime, so re-reading ~500 KB per request is waste). MapLibre is no longer
3162
+ inlined here — the frontend lazy-loads it from /vendor on demand.
3163
 
3164
  Prefers `index.build.html` — the precompiled output of build_frontend.py,
3165
  which ships plain JS instead of making the browser download @babel/standalone
 
3178
  print("[frontend] no index.build.html — serving un-precompiled index.html "
3179
  "(slow first boot). Run `python build_frontend.py`.")
3180
  name = "index.html"
3181
+ _APP_HTML_CACHE = _read_html(name)
3182
  return _APP_HTML_CACHE
3183
 
3184
 
3185
+ # The app document is ~500 KB but gzips to ~130 KB. Nothing in this process adds
3186
+ # Content-Encoding (no GZipMiddleware — it would buffer/break the SSE collab
3187
+ # stream), so without this the whole document ships uncompressed on every load,
3188
+ # which dominates first paint. Pre-gzip the cached document once and serve it
3189
+ # compressed when the client advertises gzip; this touches ONLY these static
3190
+ # HTML routes and leaves /api/rooms/{id}/stream (SSE) untouched.
3191
+ _APP_HTML_GZIP: bytes | None = None
3192
+
3193
+
3194
+ def _serve_html(html: str, request: Request, gz: bytes | None = None) -> Response:
3195
+ if "gzip" in request.headers.get("accept-encoding", "").lower():
3196
+ body = gz if gz is not None else gzip.compress(html.encode("utf-8"), 6)
3197
+ return Response(
3198
+ content=body,
3199
+ media_type="text/html; charset=utf-8",
3200
+ headers={"Content-Encoding": "gzip", "Vary": "Accept-Encoding"},
3201
+ )
3202
+ return HTMLResponse(html)
3203
+
3204
+
3205
+ def _app_html_gzip() -> bytes:
3206
+ global _APP_HTML_GZIP
3207
+ if _APP_HTML_GZIP is None:
3208
+ _APP_HTML_GZIP = gzip.compress(_app_html().encode("utf-8"), 6)
3209
+ return _APP_HTML_GZIP
3210
+
3211
+
3212
  @app.get("/", response_class=HTMLResponse)
3213
+ async def landing(request: Request):
3214
+ return _serve_html(_read_html("landing.html"), request)
3215
 
3216
 
3217
  @app.get("/app", response_class=HTMLResponse)
3218
+ async def solo_app(request: Request):
3219
+ return _serve_html(_app_html(), request, _app_html_gzip())
3220
 
3221
 
3222
  @app.get("/room/{room_id}", response_class=HTMLResponse)
3223
+ async def room_app(room_id: str, request: Request):
3224
+ return _serve_html(_app_html(), request, _app_html_gzip())
3225
 
3226
 
3227
  # --------------------------- Cleanup daemon -------------------------------- #
docs/architecture.md CHANGED
@@ -1,5 +1,9 @@
1
  # Sozai — Architecture
2
 
 
 
 
 
3
  Sozai is a single-file React SPA (`index.html` / `landing.html`, compiled in the
4
  browser with Babel) backed by one FastAPI + Gradio process (`app.py`). The heavy
5
  models run on Hugging Face **ZeroGPU**, where CUDA may only be initialized inside
 
1
  # Sozai — Architecture
2
 
3
+ > Looking for the **end-to-end website walkthrough** (landing → rooms → add →
4
+ > darkroom → map, plus real-time collaboration)? See the companion
5
+ > [dev blog post](dev-blog.md). This doc is the deep dive on the img2img pipeline.
6
+
7
  Sozai is a single-file React SPA (`index.html` / `landing.html`, compiled in the
8
  browser with Babel) backed by one FastAPI + Gradio process (`app.py`). The heavy
9
  models run on Hugging Face **ZeroGPU**, where CUDA may only be initialized inside
docs/dev-blog.md ADDED
@@ -0,0 +1,423 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Building Sozai: one process, one page, and a watercolour darkroom
2
+
3
+ > A developer's tour of how Sozai actually works — from the moment a visitor
4
+ > hits the landing page to a shared, real-time watercolour scrapbook.
5
+ >
6
+ > This is the **flow-oriented** companion to [`architecture.md`](architecture.md).
7
+ > Where that doc drills into the FLUX.2 img2img pipeline and the ZeroGPU pickle
8
+ > boundary, this one walks the **whole website** end to end.
9
+
10
+ ---
11
+
12
+ ## What Sozai is
13
+
14
+ Sozai (素材, *"material / source"*) is a collaborative photo-journaling app. You
15
+ drop in your photos, it captions and titles them for you by *looking* at them,
16
+ "develops" them into watercolour prints in a darkroom animation, and lets you pin
17
+ them onto a 2D or 3D map of where they happened — alone, or live with friends in
18
+ a shared room.
19
+
20
+ The whole thing is deliberately small in moving parts:
21
+
22
+ - **One frontend**, shipped as two hand-written HTML files (`landing.html` +
23
+ `index.html`) that compile React in the browser with Babel. No build step, no
24
+ bundler, no `node_modules`.
25
+ - **One backend**, a single `app.py` (~3k lines) running **FastAPI + Gradio** in
26
+ one CPU process.
27
+ - **Heavy models on demand**, run on Hugging Face **ZeroGPU**, where CUDA may
28
+ only be touched inside an ephemeral `@spaces.GPU` worker.
29
+
30
+ That's the entire system. Everything below is how those three pieces talk.
31
+
32
+ ---
33
+
34
+ ## The 10,000-foot view
35
+
36
+ ```mermaid
37
+ flowchart LR
38
+ subgraph Browser["Browser — single-file React SPA, no build step"]
39
+ SPA["landing.html · index.html<br/>screens · MapLibre 2D · Cesium 3D · Collab over SSE"]
40
+ end
41
+
42
+ subgraph Server["app.py — FastAPI + Gradio, one CPU process"]
43
+ HTTP["routes / /app /room/ID<br/>REST + Gradio API + SSE rooms"]
44
+ GW["lazy model gateways<br/>nsfw · autocaption · ASR · img2img"]
45
+ DB["SQLite — rooms · participants · room_state"]
46
+ PH["Phoenix tracing, in-process"]
47
+ end
48
+
49
+ subgraph GPU["ZeroGPU worker — @spaces.GPU, ephemeral"]
50
+ W["CUDA inits ONLY here<br/>MiniCPM-V · NeMo ASR · NSFW · FLUX.2-klein"]
51
+ end
52
+
53
+ Hub["HF Hub — weights cache"]
54
+ Ext["Browser-side: Stadia tiles · Cesium ion · OSM geocode"]
55
+
56
+ SPA -->|fetch / SSE / Gradio| HTTP
57
+ SPA -.->|tiles / geocode| Ext
58
+ HTTP --> GW
59
+ HTTP --> DB
60
+ GW -->|"@spaces.GPU"| W
61
+ GW --> PH
62
+ Server -->|download in MAIN process| Hub
63
+ W -->|read disk cache| Hub
64
+ ```
65
+
66
+ The single invariant worth burning into memory: **CUDA only ever initializes
67
+ inside a `@spaces.GPU` worker.** The main process stays CPU-only, which is why
68
+ model *downloads* happen in the main process (it owns the cache) while the worker
69
+ only *reads* them. The rest of the design falls out of that one rule.
70
+
71
+ ---
72
+
73
+ ## Part 1 — Two HTML files, three routes
74
+
75
+ There is no client-side router framework. The server hands out exactly three HTML
76
+ responses:
77
+
78
+ | Route | Serves | Purpose |
79
+ |-------|--------|---------|
80
+ | `GET /` | `landing.html` | the splash: make a room / join by code / go solo |
81
+ | `GET /app` | `index.html` | the app, **solo** (no room) |
82
+ | `GET /room/{room_id}` | `index.html` | the app, **in a room** (same file) |
83
+
84
+ `/app` and `/room/{id}` return the *identical* document. The app decides whether
85
+ it's collaborative purely by reading `location.pathname` at runtime:
86
+
87
+ ```js
88
+ function roomId() {
89
+ const m = location.pathname.match(/^\/room\/([^\/?#]+)/);
90
+ return m ? decodeURIComponent(m[1]) : null;
91
+ }
92
+ ```
93
+
94
+ If there's a room id in the URL, collaboration turns on. If not, every collab
95
+ call quietly no-ops. One codebase, two modes, zero branching at the route level.
96
+
97
+ One backend detail worth calling out: before `index.html` is served, the server
98
+ **inlines MapLibre GL** directly into the page (`_inline_maplibre`), replacing a
99
+ `<!--MAPLIBRE_INLINE-->` marker with the cached library source. This sidesteps
100
+ every CDN/MIME/proxy issue that can break a map on Hugging Face Spaces; if the
101
+ library can't be cached, the marker is left alone and an in-page CDN loader takes
102
+ over.
103
+
104
+ ---
105
+
106
+ ## Part 2 — The screen state machine
107
+
108
+ Once `index.html` boots, the entire app is a `<Root>` that renders one `<Page>`,
109
+ and `<Page>` is a tiny state machine keyed off a single string, `screen`:
110
+
111
+ ```mermaid
112
+ flowchart TD
113
+ start([Visitor]) --> L["Landing — landing.html<br/>GET /"]
114
+ L -->|make a room| MR["POST /api/rooms<br/>creates share code + room_id"]
115
+ L -->|join by code| JC["POST /api/join-by-code<br/>resolves code to room_id"]
116
+ L -->|continue without a room| SOLO["GET /app"]
117
+ MR --> ROOM["GET /room/ID"]
118
+ JC --> ROOM
119
+
120
+ SOLO --> BOOT["index.html SPA boots<br/>React + Babel in the browser"]
121
+ ROOM --> BOOT
122
+
123
+ BOOT --> CFG["GET /api/config<br/>feature flags + tokens"]
124
+ BOOT --> CONNECT{in a /room/ URL?}
125
+ CONNECT -->|yes| RT["Collab.connect — SSE<br/>RoomPersistence loads saved scrapbook"]
126
+ CONNECT -->|no| SOLOMODE["solo: collab no-ops, nothing persists"]
127
+
128
+ BOOT --> SCREENS
129
+
130
+ subgraph SCREENS["Root — single screen state machine"]
131
+ ADD["screen = add<br/>AddToAlbum + DetailsForm<br/>upload · EXIF · NSFW · auto caption/title/tags · mic"]
132
+ DARK["screen = darkroom<br/>DarkroomDeveloper<br/>baths animation then shake-to-reveal"]
133
+ MAP["screen = map<br/>MapOfMyTime — scrapbook · MapLibre 2D · Cesium 3D"]
134
+ PETS["screen = pets<br/>PetsScreen"]
135
+ TRACE["screen = trace<br/>TraceScreen — embedded Phoenix"]
136
+ end
137
+
138
+ ADD -->|all photos added| DARK
139
+ DARK -->|reveal all / skip| MAP
140
+ ADD -.-> PETS
141
+ ADD -.-> TRACE
142
+ PETS -.-> ADD
143
+ TRACE -.-> ADD
144
+ MAP -->|export| PDF["printable scrapbook<br/>browser print, no upload"]
145
+ ```
146
+
147
+ The mainline journey is **add → darkroom → map**. `pets` (a customizable desktop
148
+ companion) and `trace` (an embedded Phoenix LLM-trace viewer) are side branches
149
+ reachable from the top bar. The whole thing is driven by:
150
+
151
+ ```js
152
+ function Page({ screen, setScreen, ... }) {
153
+ if (screen === "add") return <AddToAlbum onAdded={() => setScreen("darkroom")} ... />;
154
+ if (screen === "darkroom") return <DarkroomDeveloper onDone={() => setScreen("map")} onSkip={() => setScreen("map")} ... />;
155
+ if (screen === "pets") return <PetsScreen onBack={() => setScreen("add")} />;
156
+ if (screen === "trace") return <TraceScreen onBack={() => setScreen("add")} />;
157
+ return <MapOfMyTime ... />; // "map"
158
+ }
159
+ ```
160
+
161
+ In a room, screen changes are **broadcast** — peers who have "Follow" enabled get
162
+ mirrored to the same screen (more on that in Part 6).
163
+
164
+ ### A note on the source of truth
165
+
166
+ Photos live in two stores, and the split is deliberate:
167
+
168
+ - **`stackPhotos`** (React state in `<Page>`) — the working list while you're in
169
+ the **add** flow. Each photo carries its own `title/caption/date/time/lat/lon`,
170
+ so the form fields can never desync from the photo list.
171
+ - **`window.SozaiPhotos`** — a small global pub/sub store that the **map** reads
172
+ from (pins, transforms, etc.).
173
+
174
+ Crucially, `SozaiPhotos` is **never** persisted to `localStorage`. Solo mode is
175
+ intentionally ephemeral (refresh = empty), and room photos live on the *server*
176
+ (`/api/rooms/{id}/state`), pulled in on join. Keeping a local copy would leak old
177
+ or deleted photos into a room you later joined — so the in-memory store plus the
178
+ server-side room state are the only two homes a photo ever has.
179
+
180
+ ---
181
+
182
+ ## Part 3 — Getting photos in (the `add` screen)
183
+
184
+ `AddToAlbum` + `DetailsForm` is where the AI earns its keep. When you add a
185
+ photo, several things happen, all backed by the same lazy-model pattern:
186
+
187
+ 1. **NSFW gate** — `POST /api/nsfw` runs `Falconsai/nsfw_image_detection`. If the
188
+ model or its deps are missing, the gate is **open** (score `0.0`) so a missing
189
+ optional dependency can never block an upload. Threshold is `0.80` by default.
190
+ 2. **Auto caption / title / tags** — each "✨ Auto" button calls the Gradio API
191
+ endpoint `autocaption(kind=...)`. One function serves all three: `kind`
192
+ selects the instruction, reply directive, generation length, and trace-span
193
+ name. The model (`MiniCPM-V`, a vision-language model) **looks at the pixels**
194
+ — the filename and alt text are only used as a fallback hint when no image can
195
+ be resolved.
196
+ 3. **Voice notes** — the mic button records audio and `POST /api/transcribe`
197
+ turns it into text via NVIDIA **NeMo** streaming ASR, so you can dictate a
198
+ caption instead of typing.
199
+
200
+ Every model call is wrapped in `traced(...)`, which opens a Phoenix span with the
201
+ model id, prompt, invocation params, and output — so the **trace** screen shows a
202
+ live timeline of every LLM call the app makes. On any failure, autocaption
203
+ returns a lightweight fallback derived from the alt text, so the button *always*
204
+ does something.
205
+
206
+ ---
207
+
208
+ ## Part 4 — The Darkroom (img2img watercolour develop)
209
+
210
+ When you've added your photos, **add → darkroom** drops you into `DarkroomDeveloper`,
211
+ which is the most theatrical part of the app. It has two phases:
212
+
213
+ - **`baths`** — a top-down view of developing trays; the prints "soak" while the
214
+ backend turns each photo into a watercolour.
215
+ - **`hang`** — the prints hang on a line, and you **shake each one** (drag it) to
216
+ reveal the developed watercolour, complete with water-ripple SVG filters and a
217
+ safelight flicker.
218
+
219
+ Under the hood, each print posts to `POST /api/img2img`, which runs
220
+ **FLUX.2-klein-4B** plus a watercolour-scene **LoRA** (trigger token `WTRCLR8`)
221
+ inside a `@spaces.GPU` worker. This is the flow the original
222
+ [`architecture.md`](architecture.md) covers in depth — including the **pickle
223
+ boundary** (send the *data*, never the *model*), the lazy ~24 GB background
224
+ download, the warm/cold cache layers, and why the first develop is slow but
225
+ repeats land in ~12 s. If you only read one section of that doc, read §2–3.
226
+
227
+ The frontend is forgiving here too: if the model is still downloading, the API
228
+ returns a 500 and the print simply keeps the original photo. The shake-to-reveal
229
+ just swaps the `<img>` once a developed version is available.
230
+
231
+ ---
232
+
233
+ ## Part 5 — The Map of My Time
234
+
235
+ **darkroom → map** lands on `MapOfMyTime`, which has three view variants the user
236
+ can switch between (and persists in `localStorage`):
237
+
238
+ | Variant | Component | Tech |
239
+ |---------|-----------|------|
240
+ | `scrapbook` | `DevelopScroll` | a scrolling, scrapbook-style layout |
241
+ | 2D map | `WatercolorMap` | **MapLibre GL** + Stadia watercolor raster tiles |
242
+ | 3D globe | `CesiumMap` | **Cesium ion** (only if a token is configured) |
243
+
244
+ Photos with EXIF GPS auto-pin; everything else sits in a draft **tray** you can
245
+ drag onto the map. Each pinned photo carries its own canvas transform (position,
246
+ rotation, scale), and the whole arrangement is part of the room state that gets
247
+ synced and saved. From here you can **export** the scrapbook — `exportScrapbook`
248
+ builds a clean, self-contained printable HTML document and opens the browser's
249
+ print dialog. No server round-trip, so it works offline and never uploads your
250
+ images.
251
+
252
+ Browser-side services (Stadia tiles, Cesium ion, OSM/Nominatim geocoding) are
253
+ called **directly from the browser** — they never round-trip through `app.py`.
254
+ `/api/config` hands the frontend the tokens (e.g. Cesium ion) it needs so they
255
+ can be rotated server-side in one place.
256
+
257
+ ---
258
+
259
+ ## Part 6 — Real-time collaboration
260
+
261
+ This is the part that makes "build memories *together*" literal. The transport is
262
+ deliberately humble: **Server-Sent Events inbound + plain POST outbound**, not
263
+ WebSockets. Why? Hugging Face Spaces' proxy drops custom WebSocket upgrades, so
264
+ the app uses the same SSE+POST channel Gradio itself uses on Spaces. EventSource
265
+ also auto-reconnects on its own, so there's no manual reconnect loop.
266
+
267
+ ```mermaid
268
+ sequenceDiagram
269
+ autonumber
270
+ participant A as Guest A — host
271
+ participant B as Guest B — joiner
272
+ participant S as app.py — Manager
273
+ participant DB as SQLite
274
+
275
+ A->>S: POST /api/rooms
276
+ S->>DB: insert room + share code
277
+ S-->>A: room_path /room/ID
278
+ A->>S: GET /api/rooms/ID/stream — SSE
279
+ S-->>A: init — you + participants
280
+
281
+ B->>S: POST /api/join-by-code
282
+ S-->>B: room_path /room/ID
283
+ B->>S: GET /api/rooms/ID/stream — SSE
284
+ S->>A: join_request — admit or decline
285
+ S-->>B: join_pending
286
+ A->>S: POST /send admit_join
287
+ S-->>B: init + presence_update
288
+ S->>A: presence_update
289
+
290
+ Note over A,B: live edits flow both ways
291
+ B->>S: POST /send object_updated · photo_pinned · cursor
292
+ S->>A: broadcast, excluding the sender
293
+ A->>S: POST /send screen_changed
294
+ S->>B: broadcast — followers mirror the view
295
+
296
+ Note over S,DB: durable layer, debounced
297
+ A->>S: PUT /api/rooms/ID/state
298
+ S->>DB: upsert room_state, versioned
299
+ B->>S: GET /api/rooms/ID/state on join
300
+ S-->>B: saved scrapbook
301
+ ```
302
+
303
+ A few design choices worth highlighting:
304
+
305
+ - **Host approval.** A joiner is *pending* until the host (the owner if connected,
306
+ else the earliest-connected participant, so approval never deadlocks) admits
307
+ them. Every SSE connection gets a queue up front — keyed by `session_id` — so a
308
+ pending joiner can still receive `join_pending` / `join_declined` before they're
309
+ a full participant.
310
+ - **Presence & "what are you touching."** Beyond cursors, the app emits throttled
311
+ `interaction` pings on button presses, field focus, and typing (captured
312
+ app-wide in the capture phase), so collaborators literally *see* labels float
313
+ near each other's cursors — "🔘 create room", "✏️ caption".
314
+ - **Follow vs. roam.** Screen and map-variant changes are broadcast; a per-user
315
+ "Following" toggle decides whether you mirror a peer's view or roam
316
+ independently. Accessibility prefs live in `localStorage` and are *never*
317
+ broadcast — everyone keeps their own a11y settings while everything else syncs.
318
+ - **No echo loop.** The shared store never re-broadcasts events it receives, so
319
+ applying a peer's `photo_moved` doesn't bounce back out.
320
+ - **Two layers of state.** Live edits flow over SSE for immediacy;
321
+ `RoomPersistence` is the *durable* layer — a debounced (1.2s), version-tracked
322
+ `PUT /api/rooms/{id}/state` that lets a returning user (or a late joiner) load
323
+ the scrapbook exactly as it was left. On a version conflict, the client adopts
324
+ the server's newer state.
325
+ - **Notifications without a server.** Chimes are synthesized in-browser with the
326
+ Web Audio API (themed note sequences), because the Python `chime` library would
327
+ only make sound on the machine running Python — useless when every participant
328
+ needs to hear it in their own browser.
329
+
330
+ ---
331
+
332
+ ## Part 7 — The AI plumbing
333
+
334
+ Four models, four endpoints, one pattern. Every model is loaded **lazily** and
335
+ **cached**, runs inference inside a `@spaces.GPU` worker, and degrades gracefully
336
+ if it's missing.
337
+
338
+ ```mermaid
339
+ flowchart LR
340
+ subgraph BROWSER["Browser"]
341
+ U1["upload a photo"]
342
+ U2["edit a field, hit Auto"]
343
+ U3["hold the mic"]
344
+ U4["enter the Darkroom"]
345
+ end
346
+
347
+ subgraph MAIN["app.py main process — CPU only"]
348
+ NSFW["/api/nsfw"]
349
+ CAP["autocaption — Gradio API"]
350
+ ASR["/api/transcribe"]
351
+ I2I["/api/img2img"]
352
+ TR["traced -> Phoenix span"]
353
+ DL["bg snapshot_download<br/>writes HF cache"]
354
+ end
355
+
356
+ subgraph GPU["ZeroGPU worker — @spaces.GPU, CUDA only here"]
357
+ GN["_nsfw_infer — Falconsai"]
358
+ GC["_caption_infer — MiniCPM-V"]
359
+ GA["_asr_run — NeMo"]
360
+ GI["_img2img_infer — FLUX.2-klein + LoRA"]
361
+ end
362
+
363
+ U1 --> NSFW --> GN
364
+ U2 --> CAP --> GC
365
+ U3 --> ASR --> GA
366
+ U4 --> I2I --> GI
367
+ CAP --> TR
368
+ ASR --> TR
369
+ I2I --> DL
370
+ GI -. reads cache .-> DL
371
+ ```
372
+
373
+ | Model | Job | Endpoint | Worker fn |
374
+ |-------|-----|----------|-----------|
375
+ | `Falconsai/nsfw_image_detection` | upload safety gate | `POST /api/nsfw` | `_nsfw_infer` |
376
+ | `MiniCPM-V` (GGUF, Q4_K_M) | caption / title / tags | `autocaption` (Gradio) | `_caption_infer` |
377
+ | NVIDIA NeMo streaming ASR | voice → text | `POST /api/transcribe` | `_asr_run` |
378
+ | `FLUX.2-klein-4B` + scene LoRA | photo → watercolour | `POST /api/img2img` | `_img2img_infer` |
379
+
380
+ `/api/config` reports which of these are available at runtime, so the UI can show
381
+ the active caption model, hide Cesium when there's no ion token, etc. **Phoenix**
382
+ runs in-process and is proxied at `/phoenix` (and embedded in the `trace` screen),
383
+ so every captioning/ASR call is observable without running a separate service.
384
+
385
+ ---
386
+
387
+ ## Part 8 — Lifecycle & housekeeping
388
+
389
+ Rooms are cheap and self-cleaning. State lives in SQLite (`rooms`,
390
+ `participants`, `room_state`) and a background daemon sweeps every 5 minutes:
391
+
392
+ 1. Rooms idle > **1 hour** are flagged inactive (can't be joined).
393
+ 2. Rooms idle past **1h10m** are deleted outright (keyed on `last_activity`, so
394
+ the DB tracks live usage, not creation time).
395
+ 3. A hard cap deletes anything older than **24 hours** regardless.
396
+ 4. Orphaned `participants` / `room_state` rows are cascaded away, and an hourly
397
+ `PRAGMA incremental_vacuum` returns freed pages to the OS so the heavy
398
+ `room_state` blobs don't bloat the file.
399
+
400
+ The cleanup is keyed on activity, not age, which is exactly what you want for
401
+ ephemeral collaborative rooms: an actively used room stays alive; an abandoned one
402
+ disappears within the grace window.
403
+
404
+ ---
405
+
406
+ ## The shape of it
407
+
408
+ If you remember four things about Sozai's architecture:
409
+
410
+ 1. **One page, one process, three routes.** `/` is the splash; `/app` and
411
+ `/room/{id}` are the *same* SPA in solo vs. collaborative mode.
412
+ 2. **The screen is a string.** `add → darkroom → map` is the whole user journey,
413
+ driven by one piece of state.
414
+ 3. **CUDA lives only in the worker.** Downloads happen in the CPU main process;
415
+ inference happens behind `@spaces.GPU`; only plain data crosses the boundary.
416
+ 4. **Live + durable are two layers.** SSE+POST for immediacy, a debounced
417
+ versioned `room_state` PUT for "load it back exactly as we left it."
418
+
419
+ Everything else — the watercolour develop, the floating interaction labels, the
420
+ synthesized chimes, the 3D globe — is detail hung on that frame.
421
+
422
+ *For the deep dive on the FLUX.2 img2img pipeline, the pickle boundary, and the
423
+ ZeroGPU cache lifetimes, see [`architecture.md`](architecture.md).*
index.build.html CHANGED
@@ -268,49 +268,54 @@
268
  watercolor map (real ArcGIS Watercolor.stylx palette on free OpenFreeMap
269
  tiles) plus OSM/CARTO basemaps. Geocoding via OpenStreetMap Nominatim.
270
 
271
- Loading strategy (most robust first):
272
- 1. The server (app.py) INLINES the cached MapLibre CSS+JS in place of the
273
- MAPLIBRE_INLINE marker below - no extra request, no MIME/route issues.
274
- 2. If the page is opened standalone (marker not replaced), a multi-CDN
275
- loader fetches MapLibre and sets window.maplibregl. -->
276
- <!--MAPLIBRE_INLINE-->
277
  <script>
278
- (function () {
279
- // If the server already inlined MapLibre, the global exists - skip CDNs.
280
- if (window.maplibregl) { console.log("[maplibre] using inlined build"); return; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
281
 
282
- // Otherwise (standalone file), pull CSS + JS from CDNs with fallbacks.
283
- var css = document.createElement("link");
284
- css.rel = "stylesheet";
285
- var cssSources = [
286
- "https://unpkg.com/maplibre-gl@4.7.1/dist/maplibre-gl.css",
287
- "https://cdn.jsdelivr.net/npm/maplibre-gl@4.7.1/dist/maplibre-gl.css",
288
- "https://cdnjs.cloudflare.com/ajax/libs/maplibre-gl/4.7.1/maplibre-gl.css"
289
- ];
290
- var ci = 0;
291
- css.href = cssSources[ci];
292
- css.onerror = function () { if (++ci < cssSources.length) css.href = cssSources[ci]; };
293
- document.head.appendChild(css);
294
-
295
- var jsSources = [
296
- "/vendor/maplibre-gl.js",
297
- "https://unpkg.com/maplibre-gl@4.7.1/dist/maplibre-gl.js",
298
- "https://cdn.jsdelivr.net/npm/maplibre-gl@4.7.1/dist/maplibre-gl.js",
299
- "https://cdnjs.cloudflare.com/ajax/libs/maplibre-gl/4.7.1/maplibre-gl.js"
300
- ];
301
- function loadJS(i) {
302
- if (i >= jsSources.length) { console.error("[maplibre] all sources failed to load"); return; }
303
- var s = document.createElement("script");
304
- s.src = jsSources[i];
305
- s.async = false;
306
- s.onload = function () {
307
- if (window.maplibregl) console.log("[maplibre] loaded from", jsSources[i]);
308
- else { console.warn("[maplibre] loaded but no global from", jsSources[i]); loadJS(i + 1); }
309
- };
310
- s.onerror = function () { console.warn("[maplibre] failed to load", jsSources[i]); loadJS(i + 1); };
311
- document.head.appendChild(s);
312
- }
313
- loadJS(0);
314
  })();
315
  </script>
316
 
@@ -1949,36 +1954,45 @@ function LocationPicker({ lat, lon, radius, locationName, onChange, onClose }) {
1949
  onChange(Object.assign({ lat: c.lat, lon: c.lon, locationName: nm, radius: radRef.current, pinned: true }, extra || {}));
1950
  }
1951
  useEffect(() => {
1952
- if (!window.maplibregl || !elRef.current) return;
1953
- const map = new window.maplibregl.Map({
1954
- container: elRef.current,
1955
- style: watercolorVectorStyle(),
1956
- center: [ptRef.current.lon, ptRef.current.lat],
1957
- zoom: lat != null ? 13 : 10,
1958
- attributionControl: false
1959
- });
1960
- mapRef.current = map;
1961
- map.on("load", () => {
1962
- map.resize();
1963
- map.addSource("loc-rad", { type: "geojson", data: circlePolygon(ptRef.current.lon, ptRef.current.lat, radRef.current) });
1964
- map.addLayer({ id: "loc-rad-fill", type: "fill", source: "loc-rad", paint: { "fill-color": "rgb(91,60,196)", "fill-opacity": 0.14 } });
1965
- map.addLayer({ id: "loc-rad-line", type: "line", source: "loc-rad", paint: { "line-color": "rgb(91,60,196)", "line-width": 1.4, "line-dasharray": [2, 2] } });
1966
- });
1967
- map.on("click", (e) => {
1968
- ptRef.current = { lon: e.lngLat.lng, lat: e.lngLat.lat };
1969
- markerRef.current && markerRef.current.setLngLat([e.lngLat.lng, e.lngLat.lat]);
1970
- paintCircle();
1971
- commit();
1972
- });
1973
- const marker = new window.maplibregl.Marker({ draggable: true, color: "#5b3cc4" }).setLngLat([ptRef.current.lon, ptRef.current.lat]).addTo(map);
1974
- markerRef.current = marker;
1975
- marker.on("drag", () => {
1976
- const ll = marker.getLngLat();
1977
- ptRef.current = { lon: ll.lng, lat: ll.lat };
1978
- paintCircle();
 
 
 
 
 
 
 
1979
  });
1980
- marker.on("dragend", () => commit());
1981
- return () => map.remove();
 
 
1982
  }, []);
1983
  async function search(e) {
1984
  e.preventDefault();
@@ -4212,6 +4226,8 @@ function WatercolorMap({ tileKey = "watercolor", cityName }) {
4212
  });
4213
  mapRef.current = map;
4214
  }
 
 
4215
  start();
4216
  const giveUp = setTimeout(() => {
4217
  if (!mapRef.current && !window.maplibregl) setLibMissing(true);
 
268
  watercolor map (real ArcGIS Watercolor.stylx palette on free OpenFreeMap
269
  tiles) plus OSM/CARTO basemaps. Geocoding via OpenStreetMap Nominatim.
270
 
271
+ LAZY-LOADED. MapLibre is ~800 KB; the visitor lands on the "add" screen
272
+ and may never open the map, so we do NOT inline or eagerly fetch it.
273
+ ensureMaplibre() loads it on demand (when a map mounts) from same-origin
274
+ /vendor first - which sidesteps the CDN/MIME/proxy issues that used to
275
+ motivate inlining - falling back to public CDNs, and memoizes the
276
+ in-flight promise so concurrent callers share one load. -->
277
  <script>
278
+ window.ensureMaplibre = (function () {
279
+ var promise = null;
280
+ return function () {
281
+ if (window.maplibregl) return Promise.resolve(window.maplibregl);
282
+ if (promise) return promise;
283
+ promise = new Promise(function (resolve, reject) {
284
+ var cssSources = [
285
+ "/vendor/maplibre-gl.css",
286
+ "https://unpkg.com/maplibre-gl@4.7.1/dist/maplibre-gl.css",
287
+ "https://cdn.jsdelivr.net/npm/maplibre-gl@4.7.1/dist/maplibre-gl.css",
288
+ "https://cdnjs.cloudflare.com/ajax/libs/maplibre-gl/4.7.1/maplibre-gl.css"
289
+ ];
290
+ var css = document.createElement("link");
291
+ css.rel = "stylesheet";
292
+ var ci = 0;
293
+ css.href = cssSources[ci];
294
+ css.onerror = function () { if (++ci < cssSources.length) css.href = cssSources[ci]; };
295
+ document.head.appendChild(css);
296
 
297
+ var jsSources = [
298
+ "/vendor/maplibre-gl.js",
299
+ "https://unpkg.com/maplibre-gl@4.7.1/dist/maplibre-gl.js",
300
+ "https://cdn.jsdelivr.net/npm/maplibre-gl@4.7.1/dist/maplibre-gl.js",
301
+ "https://cdnjs.cloudflare.com/ajax/libs/maplibre-gl/4.7.1/maplibre-gl.js"
302
+ ];
303
+ function loadJS(i) {
304
+ if (i >= jsSources.length) { console.error("[maplibre] all sources failed to load"); reject(new Error("maplibre unavailable")); return; }
305
+ var s = document.createElement("script");
306
+ s.src = jsSources[i];
307
+ s.async = true;
308
+ s.onload = function () {
309
+ if (window.maplibregl) { console.log("[maplibre] loaded from", jsSources[i]); resolve(window.maplibregl); }
310
+ else { console.warn("[maplibre] loaded but no global from", jsSources[i]); loadJS(i + 1); }
311
+ };
312
+ s.onerror = function () { console.warn("[maplibre] failed to load", jsSources[i]); loadJS(i + 1); };
313
+ document.head.appendChild(s);
314
+ }
315
+ loadJS(0);
316
+ });
317
+ return promise;
318
+ };
 
 
 
 
 
 
 
 
 
 
319
  })();
320
  </script>
321
 
 
1954
  onChange(Object.assign({ lat: c.lat, lon: c.lon, locationName: nm, radius: radRef.current, pinned: true }, extra || {}));
1955
  }
1956
  useEffect(() => {
1957
+ if (!elRef.current) return;
1958
+ let map = null, cancelled = false;
1959
+ const ready = window.ensureMaplibre ? window.ensureMaplibre() : Promise.resolve(window.maplibregl);
1960
+ ready.then(() => {
1961
+ if (cancelled || !elRef.current || !window.maplibregl) return;
1962
+ map = new window.maplibregl.Map({
1963
+ container: elRef.current,
1964
+ style: watercolorVectorStyle(),
1965
+ center: [ptRef.current.lon, ptRef.current.lat],
1966
+ zoom: lat != null ? 13 : 10,
1967
+ attributionControl: false
1968
+ });
1969
+ mapRef.current = map;
1970
+ map.on("load", () => {
1971
+ map.resize();
1972
+ map.addSource("loc-rad", { type: "geojson", data: circlePolygon(ptRef.current.lon, ptRef.current.lat, radRef.current) });
1973
+ map.addLayer({ id: "loc-rad-fill", type: "fill", source: "loc-rad", paint: { "fill-color": "rgb(91,60,196)", "fill-opacity": 0.14 } });
1974
+ map.addLayer({ id: "loc-rad-line", type: "line", source: "loc-rad", paint: { "line-color": "rgb(91,60,196)", "line-width": 1.4, "line-dasharray": [2, 2] } });
1975
+ });
1976
+ map.on("click", (e) => {
1977
+ ptRef.current = { lon: e.lngLat.lng, lat: e.lngLat.lat };
1978
+ markerRef.current && markerRef.current.setLngLat([e.lngLat.lng, e.lngLat.lat]);
1979
+ paintCircle();
1980
+ commit();
1981
+ });
1982
+ const marker = new window.maplibregl.Marker({ draggable: true, color: "#5b3cc4" }).setLngLat([ptRef.current.lon, ptRef.current.lat]).addTo(map);
1983
+ markerRef.current = marker;
1984
+ marker.on("drag", () => {
1985
+ const ll = marker.getLngLat();
1986
+ ptRef.current = { lon: ll.lng, lat: ll.lat };
1987
+ paintCircle();
1988
+ });
1989
+ marker.on("dragend", () => commit());
1990
+ }).catch(() => {
1991
  });
1992
+ return () => {
1993
+ cancelled = true;
1994
+ if (map) map.remove();
1995
+ };
1996
  }, []);
1997
  async function search(e) {
1998
  e.preventDefault();
 
4226
  });
4227
  mapRef.current = map;
4228
  }
4229
+ if (window.ensureMaplibre) window.ensureMaplibre().catch(() => {
4230
+ });
4231
  start();
4232
  const giveUp = setTimeout(() => {
4233
  if (!mapRef.current && !window.maplibregl) setLibMissing(true);
index.html CHANGED
@@ -372,49 +372,54 @@
372
  watercolor map (real ArcGIS Watercolor.stylx palette on free OpenFreeMap
373
  tiles) plus OSM/CARTO basemaps. Geocoding via OpenStreetMap Nominatim.
374
 
375
- Loading strategy (most robust first):
376
- 1. The server (app.py) INLINES the cached MapLibre CSS+JS in place of the
377
- MAPLIBRE_INLINE marker below - no extra request, no MIME/route issues.
378
- 2. If the page is opened standalone (marker not replaced), a multi-CDN
379
- loader fetches MapLibre and sets window.maplibregl. -->
380
- <!--MAPLIBRE_INLINE-->
381
  <script>
382
- (function () {
383
- // If the server already inlined MapLibre, the global exists - skip CDNs.
384
- if (window.maplibregl) { console.log("[maplibre] using inlined build"); return; }
385
-
386
- // Otherwise (standalone file), pull CSS + JS from CDNs with fallbacks.
387
- var css = document.createElement("link");
388
- css.rel = "stylesheet";
389
- var cssSources = [
390
- "https://unpkg.com/maplibre-gl@4.7.1/dist/maplibre-gl.css",
391
- "https://cdn.jsdelivr.net/npm/maplibre-gl@4.7.1/dist/maplibre-gl.css",
392
- "https://cdnjs.cloudflare.com/ajax/libs/maplibre-gl/4.7.1/maplibre-gl.css"
393
- ];
394
- var ci = 0;
395
- css.href = cssSources[ci];
396
- css.onerror = function () { if (++ci < cssSources.length) css.href = cssSources[ci]; };
397
- document.head.appendChild(css);
398
-
399
- var jsSources = [
400
- "/vendor/maplibre-gl.js",
401
- "https://unpkg.com/maplibre-gl@4.7.1/dist/maplibre-gl.js",
402
- "https://cdn.jsdelivr.net/npm/maplibre-gl@4.7.1/dist/maplibre-gl.js",
403
- "https://cdnjs.cloudflare.com/ajax/libs/maplibre-gl/4.7.1/maplibre-gl.js"
404
- ];
405
- function loadJS(i) {
406
- if (i >= jsSources.length) { console.error("[maplibre] all sources failed to load"); return; }
407
- var s = document.createElement("script");
408
- s.src = jsSources[i];
409
- s.async = false;
410
- s.onload = function () {
411
- if (window.maplibregl) console.log("[maplibre] loaded from", jsSources[i]);
412
- else { console.warn("[maplibre] loaded but no global from", jsSources[i]); loadJS(i + 1); }
413
- };
414
- s.onerror = function () { console.warn("[maplibre] failed to load", jsSources[i]); loadJS(i + 1); };
415
- document.head.appendChild(s);
416
- }
417
- loadJS(0);
 
 
 
 
 
418
  })();
419
  </script>
420
 
@@ -2020,30 +2025,35 @@
2020
  onChange(Object.assign({ lat: c.lat, lon: c.lon, locationName: nm, radius: radRef.current, pinned: true }, extra || {}));
2021
  }
2022
  useEffect(() => {
2023
- if (!window.maplibregl || !elRef.current) return;
2024
- const map = new window.maplibregl.Map({
2025
- container: elRef.current, style: watercolorVectorStyle(),
2026
- center: [ptRef.current.lon, ptRef.current.lat], zoom: lat != null ? 13 : 10,
2027
- attributionControl: false,
2028
- });
2029
- mapRef.current = map;
2030
- map.on("load", () => {
2031
- map.resize();
2032
- map.addSource("loc-rad", { type: "geojson", data: circlePolygon(ptRef.current.lon, ptRef.current.lat, radRef.current) });
2033
- map.addLayer({ id: "loc-rad-fill", type: "fill", source: "loc-rad", paint: { "fill-color": "rgb(91,60,196)", "fill-opacity": 0.14 } });
2034
- map.addLayer({ id: "loc-rad-line", type: "line", source: "loc-rad", paint: { "line-color": "rgb(91,60,196)", "line-width": 1.4, "line-dasharray": [2, 2] } });
2035
- });
2036
- map.on("click", (e) => {
2037
- ptRef.current = { lon: e.lngLat.lng, lat: e.lngLat.lat };
2038
- markerRef.current && markerRef.current.setLngLat([e.lngLat.lng, e.lngLat.lat]);
2039
- paintCircle(); commit();
2040
- });
2041
- const marker = new window.maplibregl.Marker({ draggable: true, color: "#5b3cc4" })
2042
- .setLngLat([ptRef.current.lon, ptRef.current.lat]).addTo(map);
2043
- markerRef.current = marker;
2044
- marker.on("drag", () => { const ll = marker.getLngLat(); ptRef.current = { lon: ll.lng, lat: ll.lat }; paintCircle(); });
2045
- marker.on("dragend", () => commit());
2046
- return () => map.remove();
 
 
 
 
 
2047
  }, []); // eslint-disable-line
2048
  async function search(e) {
2049
  e.preventDefault();
@@ -4473,6 +4483,9 @@
4473
  mapRef.current = map;
4474
  }
4475
 
 
 
 
4476
  start();
4477
  // last resort: if MapLibre never loads at all, show the offline notice
4478
  const giveUp = setTimeout(() => { if (!mapRef.current && !window.maplibregl) setLibMissing(true); }, 9000);
 
372
  watercolor map (real ArcGIS Watercolor.stylx palette on free OpenFreeMap
373
  tiles) plus OSM/CARTO basemaps. Geocoding via OpenStreetMap Nominatim.
374
 
375
+ LAZY-LOADED. MapLibre is ~800 KB; the visitor lands on the "add" screen
376
+ and may never open the map, so we do NOT inline or eagerly fetch it.
377
+ ensureMaplibre() loads it on demand (when a map mounts) from same-origin
378
+ /vendor first - which sidesteps the CDN/MIME/proxy issues that used to
379
+ motivate inlining - falling back to public CDNs, and memoizes the
380
+ in-flight promise so concurrent callers share one load. -->
381
  <script>
382
+ window.ensureMaplibre = (function () {
383
+ var promise = null;
384
+ return function () {
385
+ if (window.maplibregl) return Promise.resolve(window.maplibregl);
386
+ if (promise) return promise;
387
+ promise = new Promise(function (resolve, reject) {
388
+ var cssSources = [
389
+ "/vendor/maplibre-gl.css",
390
+ "https://unpkg.com/maplibre-gl@4.7.1/dist/maplibre-gl.css",
391
+ "https://cdn.jsdelivr.net/npm/maplibre-gl@4.7.1/dist/maplibre-gl.css",
392
+ "https://cdnjs.cloudflare.com/ajax/libs/maplibre-gl/4.7.1/maplibre-gl.css"
393
+ ];
394
+ var css = document.createElement("link");
395
+ css.rel = "stylesheet";
396
+ var ci = 0;
397
+ css.href = cssSources[ci];
398
+ css.onerror = function () { if (++ci < cssSources.length) css.href = cssSources[ci]; };
399
+ document.head.appendChild(css);
400
+
401
+ var jsSources = [
402
+ "/vendor/maplibre-gl.js",
403
+ "https://unpkg.com/maplibre-gl@4.7.1/dist/maplibre-gl.js",
404
+ "https://cdn.jsdelivr.net/npm/maplibre-gl@4.7.1/dist/maplibre-gl.js",
405
+ "https://cdnjs.cloudflare.com/ajax/libs/maplibre-gl/4.7.1/maplibre-gl.js"
406
+ ];
407
+ function loadJS(i) {
408
+ if (i >= jsSources.length) { console.error("[maplibre] all sources failed to load"); reject(new Error("maplibre unavailable")); return; }
409
+ var s = document.createElement("script");
410
+ s.src = jsSources[i];
411
+ s.async = true;
412
+ s.onload = function () {
413
+ if (window.maplibregl) { console.log("[maplibre] loaded from", jsSources[i]); resolve(window.maplibregl); }
414
+ else { console.warn("[maplibre] loaded but no global from", jsSources[i]); loadJS(i + 1); }
415
+ };
416
+ s.onerror = function () { console.warn("[maplibre] failed to load", jsSources[i]); loadJS(i + 1); };
417
+ document.head.appendChild(s);
418
+ }
419
+ loadJS(0);
420
+ });
421
+ return promise;
422
+ };
423
  })();
424
  </script>
425
 
 
2025
  onChange(Object.assign({ lat: c.lat, lon: c.lon, locationName: nm, radius: radRef.current, pinned: true }, extra || {}));
2026
  }
2027
  useEffect(() => {
2028
+ if (!elRef.current) return;
2029
+ let map = null, cancelled = false;
2030
+ const ready = window.ensureMaplibre ? window.ensureMaplibre() : Promise.resolve(window.maplibregl);
2031
+ ready.then(() => {
2032
+ if (cancelled || !elRef.current || !window.maplibregl) return;
2033
+ map = new window.maplibregl.Map({
2034
+ container: elRef.current, style: watercolorVectorStyle(),
2035
+ center: [ptRef.current.lon, ptRef.current.lat], zoom: lat != null ? 13 : 10,
2036
+ attributionControl: false,
2037
+ });
2038
+ mapRef.current = map;
2039
+ map.on("load", () => {
2040
+ map.resize();
2041
+ map.addSource("loc-rad", { type: "geojson", data: circlePolygon(ptRef.current.lon, ptRef.current.lat, radRef.current) });
2042
+ map.addLayer({ id: "loc-rad-fill", type: "fill", source: "loc-rad", paint: { "fill-color": "rgb(91,60,196)", "fill-opacity": 0.14 } });
2043
+ map.addLayer({ id: "loc-rad-line", type: "line", source: "loc-rad", paint: { "line-color": "rgb(91,60,196)", "line-width": 1.4, "line-dasharray": [2, 2] } });
2044
+ });
2045
+ map.on("click", (e) => {
2046
+ ptRef.current = { lon: e.lngLat.lng, lat: e.lngLat.lat };
2047
+ markerRef.current && markerRef.current.setLngLat([e.lngLat.lng, e.lngLat.lat]);
2048
+ paintCircle(); commit();
2049
+ });
2050
+ const marker = new window.maplibregl.Marker({ draggable: true, color: "#5b3cc4" })
2051
+ .setLngLat([ptRef.current.lon, ptRef.current.lat]).addTo(map);
2052
+ markerRef.current = marker;
2053
+ marker.on("drag", () => { const ll = marker.getLngLat(); ptRef.current = { lon: ll.lng, lat: ll.lat }; paintCircle(); });
2054
+ marker.on("dragend", () => commit());
2055
+ }).catch(() => {});
2056
+ return () => { cancelled = true; if (map) map.remove(); };
2057
  }, []); // eslint-disable-line
2058
  async function search(e) {
2059
  e.preventDefault();
 
4483
  mapRef.current = map;
4484
  }
4485
 
4486
+ // Kick off the lazy MapLibre load; start()'s retry loop picks up the
4487
+ // global once it's ready (or giveUp below surfaces a failure).
4488
+ if (window.ensureMaplibre) window.ensureMaplibre().catch(() => {});
4489
  start();
4490
  // last resort: if MapLibre never loads at all, show the offline notice
4491
  const giveUp = setTimeout(() => { if (!mapRef.current && !window.maplibregl) setLibMissing(true); }, 9000);