prateeksharmacoder commited on
Commit
1ac0f1d
·
1 Parent(s): 4a2cf36

fix: use gr.Blocks(head=, js=) for Leaflet map — Gradio 5 strips script tags from gr.HTML values

Browse files
Files changed (1) hide show
  1. app.py +136 -250
app.py CHANGED
@@ -120,264 +120,148 @@ def save_tensor_as_geotiff(tensor, attrs, out_path, super_resolved=False, sr_fac
120
  DEFAULT_LAT = 39.39785676571274
121
  DEFAULT_LON = -0.3798517619438821
122
 
123
- # LEAFLET_HEAD removed — Gradio 5 gr.HTML does not support 'head'.
124
- # Leaflet CSS/JS are inlined into MAP_HTML_VALUE below.
125
-
126
-
127
- # ============================================================
128
- # MAP JAVASCRIPT
129
- # ============================================================
130
-
131
- MAP_JS = """
132
- // ============================================================
133
- // TERRAVISION LEAFLET MAP
134
- // ============================================================
135
-
136
- const mapDiv = document.getElementById("terrativision-map");
137
-
138
- if (!mapDiv) {
139
-
140
- console.error("❌ TerraVision map container not found.");
141
-
142
- } else if (mapDiv._terraVisionMapInitialized) {
143
-
144
- console.log("ℹ️ TerraVision map already initialized.");
145
-
146
- } else {
147
-
148
- mapDiv._terraVisionMapInitialized = true;
149
-
150
- const defaultLat = __DEFAULT_LAT__;
151
- const defaultLon = __DEFAULT_LON__;
152
-
153
- // --------------------------------------------------------
154
- // CREATE MAP
155
- // --------------------------------------------------------
156
-
157
- const map = L.map(mapDiv).setView(
158
- [defaultLat, defaultLon],
159
- 10
160
- );
161
-
162
- // --------------------------------------------------------
163
- // STREET MAP
164
- // --------------------------------------------------------
165
-
166
- const osmLayer = L.tileLayer(
167
- "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
168
- {
169
- maxZoom: 19,
170
- attribution: "© OpenStreetMap contributors"
171
- }
172
- ).addTo(map);
173
-
174
- // --------------------------------------------------------
175
- // SATELLITE MAP
176
- // --------------------------------------------------------
177
-
178
- const satelliteLayer = L.tileLayer(
179
- "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}",
180
- {
181
- maxZoom: 19,
182
- attribution: "Tiles © Esri"
183
- }
184
- );
185
-
186
- // --------------------------------------------------------
187
- // LAYER CONTROL
188
- // --------------------------------------------------------
189
-
190
- L.control.layers(
191
- {
192
- "Street Map": osmLayer,
193
- "Satellite": satelliteLayer
194
- }
195
- ).addTo(map);
196
-
197
- // --------------------------------------------------------
198
- // MARKER
199
- // --------------------------------------------------------
200
-
201
- let marker = L.marker(
202
- [defaultLat, defaultLon]
203
- ).addTo(map);
204
-
205
- // --------------------------------------------------------
206
- // LOCATION DISPLAY
207
- // --------------------------------------------------------
208
-
209
- const locationDisplay =
210
- document.querySelector("#map-location-display");
211
-
212
- function updateLocationDisplay(lat, lon) {
213
-
214
- if (locationDisplay) {
215
-
216
- locationDisplay.innerHTML =
217
- "📍 <b>Selected:</b> " +
218
- lat.toFixed(8) +
219
- ", " +
220
- lon.toFixed(8);
221
- }
222
- }
223
-
224
- updateLocationDisplay(
225
- defaultLat,
226
- defaultLon
227
- );
228
-
229
- marker.bindPopup(
230
- "<b>Selected Location</b><br>" +
231
- defaultLat.toFixed(8) +
232
- ", " +
233
- defaultLon.toFixed(8)
234
- );
235
-
236
- // --------------------------------------------------------
237
- // MAP CLICK
238
- // --------------------------------------------------------
239
-
240
- map.on("click", function(e) {
241
-
242
- const lat = e.latlng.lat;
243
- const lon = e.latlng.lng;
244
 
245
- console.log(
246
- "📍 TerraVision selected:",
247
- lat,
248
- lon
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
249
  );
250
 
251
- // Move marker
252
- marker.setLatLng([lat, lon]);
253
-
254
- // Update popup
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
255
  marker.bindPopup(
256
  "<b>Selected Location</b><br>" +
257
- lat.toFixed(8) +
258
- ", " +
259
- lon.toFixed(8)
260
- ).openPopup();
261
-
262
- // Update visible selected text
263
- updateLocationDisplay(lat, lon);
264
-
265
- // --------------------------------------------------------
266
- // UPDATE GRADIO LATITUDE / LONGITUDE
267
- // --------------------------------------------------------
268
-
269
- function updateGradioNumber(elemId, value) {
270
-
271
- const container = document.getElementById(elemId);
272
-
273
- if (!container) {
274
- console.error(
275
- "❌ Gradio component not found:",
276
- elemId
277
- );
278
- return;
279
- }
280
-
281
- const input = container.querySelector("input");
282
-
283
- if (!input) {
284
- console.error(
285
- "❌ Input element not found:",
286
- elemId
287
  );
288
- return;
289
- }
290
-
291
- // Use the native HTML value setter.
292
- // This is important because Gradio uses a controlled input.
293
- const nativeSetter =
294
- Object.getOwnPropertyDescriptor(
295
- HTMLInputElement.prototype,
296
- "value"
297
- ).set;
298
-
299
- nativeSetter.call(
300
- input,
301
- String(value)
302
- );
303
-
304
- // Tell Gradio that the user changed the input
305
- input.dispatchEvent(
306
- new Event("input", {
307
- bubbles: true
308
- })
309
- );
310
-
311
- input.dispatchEvent(
312
- new Event("change", {
313
- bubbles: true
314
- })
315
- );
316
-
317
- console.log(
318
- "✅ Updated Gradio:",
319
- elemId,
320
- value
321
- );
322
- }
323
 
324
- updateGradioNumber(
325
- "latitude_input",
326
- lat
327
- );
328
-
329
- updateGradioNumber(
330
- "longitude_input",
331
- lon
332
- );
333
-
334
- });
335
-
336
- // --------------------------------------------------------
337
- // FIX MAP SIZE
338
- // --------------------------------------------------------
339
-
340
- setTimeout(function() {
341
-
342
- map.invalidateSize();
343
-
344
- }, 500);
345
-
346
- // Store map reference
347
- element._terraVisionMap = map;
348
-
349
- console.log(
350
- "✅ TerraVision Leaflet map initialized successfully."
351
- );
352
- }
 
 
 
 
 
 
 
 
 
 
 
 
353
  """
354
 
355
- # Insert Python values without using an f-string
356
- MAP_JS = MAP_JS.replace(
357
- "__DEFAULT_LAT__",
358
- str(DEFAULT_LAT)
359
- ).replace(
360
- "__DEFAULT_LON__",
361
- str(DEFAULT_LON)
362
- )
363
-
364
- # ============================================================
365
- # COMPLETE MAP HTML
366
- # Gradio 5 gr.HTML has no 'head' or 'js_on_load' parameters.
367
- # Inline Leaflet CSS, Leaflet JS, the map div, and the init
368
- # script all inside the value string.
369
- # ============================================================
370
- MAP_HTML_VALUE = f"""
371
- <link rel="stylesheet"
372
- href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
373
- <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
374
- <div id="terrativision-map"
375
- style="width:100%;height:400px;border-radius:14px;
376
- overflow:hidden;border:1px solid rgba(128,128,128,0.35);"></div>
377
- <script>
378
- {MAP_JS}
379
- </script>
380
- """
381
 
382
 
383
  # ============================================================
@@ -897,7 +781,9 @@ def run_app(latitude, longitude, start_date, end_date):
897
 
898
  with gr.Blocks(
899
  title="TerraVision — Sentinel-2 Super Resolution",
900
- css=custom_css
 
 
901
  ) as demo:
902
 
903
  # ========================================================
 
120
  DEFAULT_LAT = 39.39785676571274
121
  DEFAULT_LON = -0.3798517619438821
122
 
123
+ # --------------------------------------------------------
124
+ # Leaflet CDN — injected into <head> via gr.Blocks(head=).
125
+ # This is the correct Gradio 5 pattern for loading external
126
+ # JS/CSS libraries: gr.HTML strips <script> tags, but
127
+ # gr.Blocks(head=) injects them into the real page <head>.
128
+ # --------------------------------------------------------
129
+ LEAFLET_HEAD = """
130
+ <link rel="stylesheet"
131
+ href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
132
+ <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
133
+ """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
 
135
+ # --------------------------------------------------------
136
+ # Map container — just the div.
137
+ # Leaflet and the init script are handled separately.
138
+ # --------------------------------------------------------
139
+ MAP_HTML_VALUE = '<div id="terrativision-map"></div>'
140
+
141
+ # --------------------------------------------------------
142
+ # Map init JavaScript — passed to gr.Blocks(js=).
143
+ # Must be a function string. Uses retry loop because
144
+ # Gradio renders the DOM asynchronously.
145
+ # --------------------------------------------------------
146
+ MAP_JS = f"""
147
+ () => {{
148
+ function tryInitTerraVisionMap() {{
149
+
150
+ // Wait for Leaflet library to load
151
+ if (typeof L === "undefined") {{
152
+ setTimeout(tryInitTerraVisionMap, 300);
153
+ return;
154
+ }}
155
+
156
+ const mapDiv = document.getElementById("terrativision-map");
157
+
158
+ // Wait for the map container div to appear in the DOM
159
+ if (!mapDiv) {{
160
+ setTimeout(tryInitTerraVisionMap, 300);
161
+ return;
162
+ }}
163
+
164
+ // Prevent double-initialisation
165
+ if (mapDiv._terraVisionMapInitialized) return;
166
+ mapDiv._terraVisionMapInitialized = true;
167
+
168
+ const defaultLat = {DEFAULT_LAT};
169
+ const defaultLon = {DEFAULT_LON};
170
+
171
+ // ------------------------------------------------
172
+ // CREATE MAP
173
+ // ------------------------------------------------
174
+ const map = L.map(mapDiv).setView([defaultLat, defaultLon], 10);
175
+
176
+ // ------------------------------------------------
177
+ // STREET MAP
178
+ // ------------------------------------------------
179
+ const osmLayer = L.tileLayer(
180
+ "https://{{s}}.tile.openstreetmap.org/{{z}}/{{x}}/{{y}}.png",
181
+ {{ maxZoom: 19, attribution: "&copy; OpenStreetMap contributors" }}
182
+ ).addTo(map);
183
+
184
+ // ------------------------------------------------
185
+ // SATELLITE MAP
186
+ // ------------------------------------------------
187
+ const satelliteLayer = L.tileLayer(
188
+ "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{{z}}/{{y}}/{{x}}",
189
+ {{ maxZoom: 19, attribution: "Tiles &copy; Esri" }}
190
  );
191
 
192
+ // ------------------------------------------------
193
+ // LAYER CONTROL
194
+ // ------------------------------------------------
195
+ L.control.layers(
196
+ {{ "Street Map": osmLayer, "Satellite": satelliteLayer }}
197
+ ).addTo(map);
198
+
199
+ // ------------------------------------------------
200
+ // MARKER
201
+ // ------------------------------------------------
202
+ let marker = L.marker([defaultLat, defaultLon]).addTo(map);
203
+
204
+ // ------------------------------------------------
205
+ // LOCATION DISPLAY
206
+ // ------------------------------------------------
207
+ const locationDisplay = document.querySelector("#map-location-display");
208
+
209
+ function updateLocationDisplay(lat, lon) {{
210
+ if (locationDisplay) {{
211
+ locationDisplay.innerHTML =
212
+ "📍 <b>Selected:</b> " + lat.toFixed(8) + ", " + lon.toFixed(8);
213
+ }}
214
+ }}
215
+
216
+ updateLocationDisplay(defaultLat, defaultLon);
217
  marker.bindPopup(
218
  "<b>Selected Location</b><br>" +
219
+ defaultLat.toFixed(8) + ", " + defaultLon.toFixed(8)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
  );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221
 
222
+ // ------------------------------------------------
223
+ // MAP CLICK
224
+ // ------------------------------------------------
225
+ map.on("click", function(e) {{
226
+ const lat = e.latlng.lat;
227
+ const lon = e.latlng.lng;
228
+
229
+ marker.setLatLng([lat, lon]);
230
+ marker.bindPopup(
231
+ "<b>Selected Location</b><br>" + lat.toFixed(8) + ", " + lon.toFixed(8)
232
+ ).openPopup();
233
+
234
+ updateLocationDisplay(lat, lon);
235
+
236
+ // Update Gradio Number inputs
237
+ function updateGradioNumber(elemId, value) {{
238
+ const container = document.getElementById(elemId);
239
+ if (!container) return;
240
+ const input = container.querySelector("input");
241
+ if (!input) return;
242
+ const nativeSetter = Object.getOwnPropertyDescriptor(
243
+ HTMLInputElement.prototype, "value"
244
+ ).set;
245
+ nativeSetter.call(input, String(value));
246
+ input.dispatchEvent(new Event("input", {{ bubbles: true }}));
247
+ input.dispatchEvent(new Event("change", {{ bubbles: true }}));
248
+ }}
249
+
250
+ updateGradioNumber("latitude_input", lat);
251
+ updateGradioNumber("longitude_input", lon);
252
+ }});
253
+
254
+ // Fix map tile rendering after Gradio layout settles
255
+ setTimeout(function() {{ map.invalidateSize(); }}, 500);
256
+
257
+ console.log("✅ TerraVision Leaflet map initialized successfully.");
258
+ }}
259
+
260
+ // Delay first attempt to let Gradio finish rendering
261
+ setTimeout(tryInitTerraVisionMap, 800);
262
+ }}
263
  """
264
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
265
 
266
 
267
  # ============================================================
 
781
 
782
  with gr.Blocks(
783
  title="TerraVision — Sentinel-2 Super Resolution",
784
+ css=custom_css,
785
+ head=LEAFLET_HEAD, # Injects Leaflet CSS/JS into the page <head>
786
+ js=MAP_JS # Runs map init after Gradio finishes rendering
787
  ) as demo:
788
 
789
  # ========================================================