RisingZhang commited on
Commit
7b81ab7
·
1 Parent(s): a6c4f3b

Update app files and dataset, exclude mp3 files from git

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +0 -1
  2. .gitignore +0 -4
  3. README.md +0 -29
  4. app.py +0 -1050
  5. appPre.py +0 -618
  6. data/audios/1006260212valenciamaralbufeira.mp3 +0 -3
  7. data/audios/14SavannaGrainBins20141022.mp3 +0 -3
  8. data/audios/1706watersystem.mp3 +0 -3
  9. data/audios/18042900522.mp3 +0 -3
  10. data/audios/2014clermontferrandfountain2.mp3 +0 -3
  11. data/audios/43troyescathedrale03089h00.mp3 +0 -3
  12. data/audios/AMOSMKE201510200201.mp3 +0 -3
  13. data/audios/AMOSMKE201511172138.mp3 +0 -3
  14. data/audios/Ambiant2extractmono.mp3 +0 -3
  15. data/audios/BAB2.mp3 +0 -3
  16. data/audios/BaltiMarktPrnikVaniljebellstram.mp3 +0 -3
  17. data/audios/Birdsinthehedgesofthefarmerspath29012010.mp3 +0 -3
  18. data/audios/CityCountryMeStettinschritteschnee.mp3 +0 -3
  19. data/audios/CityCountryMemariaamuferremisesommercampinstituteforintermediatestudies290709001.mp3 +0 -3
  20. data/audios/CityCountryMesanderstrdreharbeiten.mp3 +0 -3
  21. data/audios/DuesseldorfTanzhausNRWGangProbestudios.mp3 +0 -3
  22. data/audios/FrancoisEmmanuelFodereButrintNationalParkButhroteInsectsandflaginwind.mp3 +0 -3
  23. data/audios/GPSwalktrack04.mp3 +0 -3
  24. data/audios/GoldenGateBridgeSF1.mp3 +0 -3
  25. data/audios/LLN104.mp3 +0 -3
  26. data/audios/NewBarnTeaMeditationPt31110am0110172.mp3 +0 -3
  27. data/audios/NikkoTempelZuweg02.mp3 +0 -3
  28. data/audios/OijSchiffeamRhein01.mp3 +0 -3
  29. data/audios/OiseauxAbeilleVentRuisseau2303181205.mp3 +0 -3
  30. data/audios/Placesound1.mp3 +0 -3
  31. data/audios/RegioZugfahrtTuerMRosenh.mp3 +0 -3
  32. data/audios/SkatingSoundsPier25HudsonPark.mp3 +0 -3
  33. data/audios/SoundMap2012020171.mp3 +0 -3
  34. data/audios/SoundMap201207031314.mp3 +0 -3
  35. data/audios/SoundMap201210151.mp3 +0 -3
  36. data/audios/SoundMap201211043.mp3 +0 -3
  37. data/audios/Soundmap2012022542.mp3 +0 -3
  38. data/audios/TRAIN58.mp3 +0 -3
  39. data/audios/UCSBFencingPractice.mp3 +0 -3
  40. data/audios/UnderCongressBats.mp3 +0 -3
  41. data/audios/WindwaveUNOcity.mp3 +0 -3
  42. data/audios/WolfsburgSpielsalon.mp3 +0 -3
  43. data/audios/athenLeofPosidonosWaves160406.mp3 +0 -3
  44. data/audios/avignonbellG.mp3 +0 -3
  45. data/audios/boarderdeadmemorialmarchBerlinJune2015.mp3 +0 -3
  46. data/audios/brama.mp3 +0 -3
  47. data/audios/buerknerBackyardRain310511.mp3 +0 -3
  48. data/audios/langskomendesneltreinstationdeVink.mp3 +0 -3
  49. data/audios/luxembourgHotelParcVentilation050714.mp3 +0 -3
  50. data/audios/namakanjeKos16maj20131149.mp3 +0 -3
.gitattributes DELETED
@@ -1 +0,0 @@
1
- *.mp3 filter=lfs diff=lfs merge=lfs -text
 
 
.gitignore DELETED
@@ -1,4 +0,0 @@
1
- venv/
2
- __pycache__/
3
- game_app2.py
4
- game_app3.py
 
 
 
 
 
README.md DELETED
@@ -1,29 +0,0 @@
1
- ---
2
- title: Audio Geo-Localization Game
3
- emoji: 🎵🌍
4
- colorFrom: blue
5
- colorTo: green
6
- sdk: gradio
7
- sdk_version: "5.49.1"
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- # Audio Geo-Localization Game
13
-
14
- An interactive game where players listen to audio clips and guess their geographic location on a world map.
15
-
16
- ## How to Play
17
-
18
- 1. Listen to the audio clip
19
- 2. Click on the interactive map to set your guess coordinates
20
- 3. Submit your answer
21
- 4. View the correct answer and your error distance
22
-
23
- ## Features
24
-
25
- - Interactive world map with zoom and pan
26
- - Audio playback for location clues
27
- - Real-time coordinate input
28
- - Previous round answer display with OpenStreetMap links
29
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app.py DELETED
@@ -1,1050 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import csv
4
- import datetime as dt
5
- import math
6
- import random
7
- from dataclasses import dataclass
8
- from pathlib import Path
9
- from typing import Dict, List, Optional, Tuple
10
-
11
- import numpy as np
12
-
13
- if not hasattr(np, "bool"): # pandas<2 compatibility on numpy>=2
14
- np.bool = bool # type: ignore[attr-defined]
15
-
16
- EXAMPLE_PROMPT = "## Input-Output Example. When you submit an answer, the following lines will display the last input and the corresponding correct answer."
17
- LAST_PROMPT = "## The input and the correct output of the last question."
18
- import pandas as pd
19
- from PIL import Image, ImageDraw
20
- import plotly.graph_objects as go
21
- def _create_plotly_map(marker_lat: Optional[float] = None, marker_lon: Optional[float] = None):
22
- """Create a Plotly map figure (OpenStreetMap) with optional visible marker.
23
- Also adds a dense transparent grid of points so plotly_click 能在任意位置触发。
24
- """
25
- # Dense transparent grid points to capture clicks anywhere on the map
26
- grid_lats: List[float] = []
27
- grid_lons: List[float] = []
28
- # 1° 网格,尽量保证任意点击都能命中到一个数据点
29
- for lat in range(-90, 91, 1):
30
- for lon in range(-180, 181, 1):
31
- grid_lats.append(float(lat))
32
- grid_lons.append(float(lon))
33
-
34
- fig = go.Figure()
35
- fig.add_trace(
36
- go.Scattermap(
37
- lat=grid_lats,
38
- lon=grid_lons,
39
- mode="markers",
40
- marker=go.scattermap.Marker(size=40, color="#000"),
41
- opacity=0.01, # 透明但可点中
42
- hoverinfo="skip",
43
- name="grid",
44
- )
45
- )
46
-
47
- if marker_lat is not None and marker_lon is not None:
48
- fig.add_trace(
49
- go.Scattermap(
50
- lat=[marker_lat],
51
- lon=[marker_lon],
52
- mode="markers",
53
- marker=go.scattermap.Marker(size=16, color="red"),
54
- hoverinfo="text",
55
- text=["Your guess"],
56
- name="marker",
57
- )
58
- )
59
-
60
- fig.update_layout(
61
- map=dict(style="open-street-map", center=dict(lat=20, lon=0), zoom=2),
62
- margin=dict(l=0, r=0, t=0, b=0),
63
- height=600,
64
- clickmode="event+select", # 明确开启点击事件
65
- dragmode="pan",
66
- )
67
- return fig
68
- import gradio as gr
69
-
70
-
71
-
72
- BASE_DIR = Path(__file__).resolve().parent
73
- DATASET_PATH = BASE_DIR / "data" / "dataset.csv"
74
- AUDIO_BASE_DIR = BASE_DIR / "data" / "audios"
75
- LOG_PATH = BASE_DIR / "player_runs.csv"
76
- RECENT_COLUMNS = ["timestamp", "player_id", "question_id", "distance_km"]
77
-
78
-
79
- @dataclass
80
- class Sample:
81
- question_id: str
82
- audio_path: Path
83
- longitude: float
84
- latitude: float
85
- city: str
86
- country: str
87
- continent: str
88
- description: str
89
- title: str
90
-
91
-
92
- def _load_samples() -> List[Sample]:
93
- if not DATASET_PATH.exists():
94
- raise FileNotFoundError(f"Dataset not found at {DATASET_PATH}")
95
-
96
- df = pd.read_csv(DATASET_PATH)
97
- start_idx = int(len(df) * 0.9)
98
- test_df = df.iloc[start_idx:].reset_index(drop=True)
99
-
100
- samples: List[Sample] = []
101
- missing_audio = 0
102
- missing_coords = 0
103
-
104
- for row in test_df.itertuples():
105
- audio_path = AUDIO_BASE_DIR / getattr(row, "mp3name")
106
- longitude = getattr(row, "longitude")
107
- latitude = getattr(row, "latitude")
108
-
109
- if math.isnan(longitude) or math.isnan(latitude):
110
- missing_coords += 1
111
- continue
112
-
113
- if not audio_path.exists():
114
- missing_audio += 1
115
- continue
116
-
117
- samples.append(
118
- Sample(
119
- question_id=str(getattr(row, "key")),
120
- audio_path=audio_path,
121
- longitude=float(longitude),
122
- latitude=float(latitude),
123
- city=str(getattr(row, "city", "") or ""),
124
- country=str(getattr(row, "country", "") or ""),
125
- continent=str(getattr(row, "continent", "") or ""),
126
- description=str(getattr(row, "description", "") or ""),
127
- title=str(getattr(row, "title", "") or ""),
128
- )
129
- )
130
-
131
- if not samples:
132
- raise RuntimeError("No playable samples were found in the test split.")
133
-
134
- if missing_audio:
135
- print(f"[game_app] Skipped {missing_audio} samples because audio files are missing.")
136
- if missing_coords:
137
- print(f"[game_app] Skipped {missing_coords} samples because coordinates are missing.")
138
-
139
- return samples
140
-
141
-
142
- def _get_example_sample() -> Optional[Sample]:
143
- """Get the example sample (aporee_45102_51242) for the first round."""
144
- if not DATASET_PATH.exists():
145
- return None
146
-
147
- df = pd.read_csv(DATASET_PATH)
148
- example_row = df[df["key"] == "aporee_45102_51242"]
149
-
150
- if example_row.empty:
151
- return None
152
-
153
- row = example_row.iloc[0]
154
- audio_path = AUDIO_BASE_DIR / row["mp3name"]
155
-
156
- if not audio_path.exists():
157
- return None
158
-
159
- return Sample(
160
- question_id=str(row["key"]),
161
- audio_path=audio_path,
162
- longitude=float(row["longitude"]),
163
- latitude=float(row["latitude"]),
164
- city=str(row.get("city", "") or ""),
165
- country=str(row.get("country", "") or ""),
166
- continent=str(row.get("continent", "") or ""),
167
- description=str(row.get("description", "") or ""),
168
- title=str(row.get("title", "") or ""),
169
- )
170
-
171
-
172
- SAMPLES: List[Sample] = _load_samples()
173
-
174
-
175
- def _random_queue() -> List[int]:
176
- queue = list(range(len(SAMPLES)))
177
- random.shuffle(queue)
178
- return queue
179
-
180
-
181
-
182
- def _latlon_to_text(lat: float, lon: float) -> str:
183
- return f"Selected latitude {lat:.3f}°, longitude {lon:.3f}°"
184
-
185
-
186
- def _haversine(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
187
- r = 6371.0
188
- phi1, phi2 = math.radians(lat1), math.radians(lat2)
189
- d_phi = math.radians(lat2 - lat1)
190
- d_lambda = math.radians(lon2 - lon1)
191
-
192
- a = math.sin(d_phi / 2.0) ** 2 + math.cos(phi1) * math.cos(phi2) * math.sin(d_lambda / 2.0) ** 2
193
- c = 2.0 * math.atan2(math.sqrt(a), math.sqrt(1.0 - a))
194
- return r * c
195
-
196
-
197
- def _base_map_array() -> np.ndarray:
198
- return np.array(BASE_MAP_IMAGE)
199
-
200
-
201
-
202
-
203
- def _on_coords_change(lon_text: str, lat_text: str) -> None:
204
- """Log coordinate changes to backend terminal for debugging."""
205
- try:
206
- lon = float(lon_text) if lon_text else None
207
- lat = float(lat_text) if lat_text else None
208
- print(f"[PLOT CLICK] lon={lon} lat={lat}")
209
- except Exception as e:
210
- print(f"[PLOT CLICK] parse error: {e} | lon_text={lon_text} lat_text={lat_text}")
211
-
212
-
213
- def _prepare_clip_info(sample: Sample, round_idx: int) -> str:
214
- intro_lines = [
215
- f"## Question ID: {sample.question_id}. Now it's your turn to play."
216
- ]
217
- return "\n\n".join(intro_lines)
218
-
219
-
220
- def _append_log(entry: Dict[str, object]) -> None:
221
- write_header = not LOG_PATH.exists()
222
- with LOG_PATH.open("a", newline="", encoding="utf-8") as f:
223
- writer = csv.DictWriter(f, fieldnames=list(entry.keys()))
224
- if write_header:
225
- writer.writeheader()
226
- writer.writerow(entry)
227
-
228
-
229
- def _load_recent_runs(limit: int = 5) -> List[Dict[str, object]]:
230
- if not LOG_PATH.exists():
231
- return []
232
-
233
- rows = []
234
- with LOG_PATH.open("r", encoding="utf-8") as f:
235
- reader = csv.DictReader(f)
236
- for row in reader:
237
- rows.append(row)
238
- return rows[-limit:]
239
-
240
-
241
- def _format_recent_rows(rows: List[Dict[str, object]]) -> List[List[object]]:
242
- formatted: List[List[object]] = []
243
- for row in rows:
244
- timestamp_str = row.get("timestamp", "")
245
- if timestamp_str:
246
- try:
247
- # Parse ISO format timestamp and format as readable string
248
- dt_obj = dt.datetime.fromisoformat(str(timestamp_str).replace('Z', '+00:00'))
249
- formatted_timestamp = dt_obj.strftime("%Y-%m-%d %H:%M:%S")
250
- except (ValueError, AttributeError):
251
- formatted_timestamp = str(timestamp_str)
252
- else:
253
- formatted_timestamp = ""
254
-
255
- formatted_row = [formatted_timestamp]
256
- formatted_row.extend([row.get(col, "") for col in RECENT_COLUMNS[1:]])
257
- formatted.append(formatted_row)
258
- return formatted
259
-
260
-
261
- def _format_previous_answer(sample: Optional[Sample], is_example: bool = False, distance_km: Optional[float] = None, guess_lat: Optional[float] = None, guess_lon: Optional[float] = None) -> str:
262
- """Format the previous answer display with location info and OpenStreetMap link."""
263
- if sample is None:
264
- return ""
265
-
266
- lat = sample.latitude
267
- lon = sample.longitude
268
- city = sample.city or "Unknown city"
269
- country = sample.country or "Unknown country"
270
- continent = sample.continent or "Unknown continent"
271
-
272
- # Create OpenStreetMap link
273
- osm_link = f"https://www.openstreetmap.org/?mlat={lat}&mlon={lon}&zoom=15"
274
-
275
- lines = [
276
- f"**Location:** {city}, {country}, {continent}",
277
- f"**Coordinates:** {lat:.6f}°, {lon:.6f}°",
278
- ]
279
-
280
- # Add player's prediction for non-example cases
281
- if not is_example and guess_lat is not None and guess_lon is not None:
282
- lines.append(f"**Your Prediction:** {guess_lat:.6f}°, {guess_lon:.6f}°")
283
-
284
- # Add error distance for non-example cases
285
- if not is_example and distance_km is not None:
286
- lines.append(f"**Error distance:** {distance_km:.1f} km")
287
-
288
- lines.append(f"**OpenStreetMap:** [View on map]({osm_link})")
289
-
290
- # Add example explanation if it's the example sample
291
- if is_example and sample.question_id == "aporee_45102_51242":
292
- lines.append("")
293
- lines.append("**Explanation:** I can clearly identify the rolling of polyurethane wheels on concrete, the sharp 'pop' of a skateboard's tail hitting the ground to initiate a trick. This firmly places the recording at a skatepark. The background ambiance is that of a bustling city, characterized by the constant, though somewhat distant, hum of traffic. Furthermore, there are several instances of spoken English. The speakers have a clear North American English accent. The combination points to a major city in the United States with a prominent skate culture. New York City is one of the most iconic locations for street skateboarding globally.")
294
-
295
- return "\n\n".join(lines)
296
-
297
-
298
- def initialize_round() -> Tuple[Dict[str, object], Dict[str, Optional[float]], str, str, str, str, List[List[object]], str, str, str, str, str]:
299
- queue = _random_queue()
300
- current_index = queue.pop()
301
-
302
- state = {
303
- "queue": queue,
304
- "current_index": current_index,
305
- "round": 1,
306
- "previous_sample": None, # No previous sample for first round
307
- "is_example": True, # First round shows example
308
- }
309
-
310
- current_sample = SAMPLES[current_index]
311
- audio_value = str(current_sample.audio_path)
312
- clip_md = _prepare_clip_info(current_sample, state["round"])
313
- prompt_text = "Click once on the map to pick your guess. The marker will update to your last selection."
314
- guess_state = {"lat": None, "lon": None, "pixel": None}
315
- recent_runs = _format_recent_rows(_load_recent_runs())
316
-
317
- # For first round, show example sample
318
- example_sample = _get_example_sample()
319
- previous_audio = str(example_sample.audio_path) if example_sample else None
320
- previous_answer = _format_previous_answer(example_sample, is_example=True) if example_sample else ""
321
- previous_title = EXAMPLE_PROMPT if example_sample else ""
322
-
323
- return state, guess_state, audio_value, clip_md, _create_plotly_map(), prompt_text, recent_runs, "", "", previous_audio or "", previous_answer, previous_title
324
-
325
-
326
- def _next_sample(state: Dict[str, object]) -> Sample:
327
- queue: List[int] = state["queue"]
328
- if not queue:
329
- queue.extend(_random_queue())
330
-
331
- next_index = queue.pop()
332
- state["current_index"] = next_index
333
- state["round"] = state.get("round", 1) + 1
334
- return SAMPLES[next_index]
335
-
336
-
337
- def _ensure_guess_state(state: Optional[Dict[str, Optional[float]]]) -> Dict[str, Optional[float]]:
338
- if not isinstance(state, dict):
339
- return {"lat": None, "lon": None, "pixel": None}
340
- return {
341
- "lat": state.get("lat"),
342
- "lon": state.get("lon"),
343
- "pixel": state.get("pixel"),
344
- }
345
-
346
-
347
-
348
- def submit_guess(
349
- player_id: str,
350
- game_state: Optional[Dict[str, object]],
351
- guess_state: Optional[Dict[str, Optional[float]]],
352
- longitude: str,
353
- latitude: str,
354
- ) -> Tuple[
355
- Dict[str, object],
356
- Dict[str, Optional[float]],
357
- str,
358
- str,
359
- str,
360
- str,
361
- List[List[object]],
362
- str,
363
- str,
364
- str,
365
- str,
366
- str,
367
- ]:
368
- if game_state is None:
369
- # Re-initialize if state is lost
370
- return initialize_round()
371
-
372
- guess_state = _ensure_guess_state(guess_state)
373
- player_id = (player_id or "").strip()
374
- if not player_id:
375
- message = "Please enter your player ID before submitting."
376
- current_sample = SAMPLES[game_state["current_index"]]
377
- clip_md = _prepare_clip_info(current_sample, game_state.get("round", 1))
378
- prompt_text = message
379
- previous_sample = game_state.get("previous_sample")
380
- previous_audio = str(previous_sample.audio_path) if previous_sample else ""
381
- previous_distance = game_state.get("previous_distance_km")
382
- previous_guess_lat = game_state.get("previous_guess_lat")
383
- previous_guess_lon = game_state.get("previous_guess_lon")
384
- previous_answer = _format_previous_answer(previous_sample, distance_km=previous_distance, guess_lat=previous_guess_lat, guess_lon=previous_guess_lon) if previous_sample else ""
385
- is_example = game_state.get("is_example", False)
386
- previous_title = EXAMPLE_PROMPT if is_example else ""
387
- return (
388
- game_state,
389
- guess_state,
390
- str(current_sample.audio_path),
391
- clip_md,
392
- _create_plotly_map(),
393
- prompt_text,
394
- _format_recent_rows(_load_recent_runs()),
395
- longitude,
396
- latitude,
397
- previous_audio,
398
- previous_answer,
399
- previous_title,
400
- )
401
-
402
- # Parse longitude and latitude from text inputs
403
- try:
404
- longitude = longitude.strip() if longitude else ""
405
- latitude = latitude.strip() if latitude else ""
406
-
407
- if not longitude or not latitude:
408
- message = "Please enter both longitude and latitude, or click on the map to select a location."
409
- current_sample = SAMPLES[game_state["current_index"]]
410
- clip_md = _prepare_clip_info(current_sample, game_state.get("round", 1))
411
- prompt_text = message
412
- previous_sample = game_state.get("previous_sample")
413
- previous_audio = str(previous_sample.audio_path) if previous_sample else ""
414
- previous_distance = game_state.get("previous_distance_km")
415
- previous_answer = _format_previous_answer(previous_sample, distance_km=previous_distance) if previous_sample else ""
416
- is_example = game_state.get("is_example", False)
417
- previous_title = EXAMPLE_PROMPT if is_example else ""
418
- return (
419
- game_state,
420
- guess_state,
421
- str(current_sample.audio_path),
422
- clip_md,
423
- gr.update(),
424
- prompt_text,
425
- _format_recent_rows(_load_recent_runs()),
426
- longitude,
427
- latitude,
428
- previous_audio,
429
- previous_answer,
430
- previous_title,
431
- )
432
-
433
- guess_lon = float(longitude)
434
- guess_lat = float(latitude)
435
-
436
- # Validate ranges
437
- if not (-180 <= guess_lon <= 180):
438
- message = "Longitude must be between -180 and 180."
439
- current_sample = SAMPLES[game_state["current_index"]]
440
- clip_md = _prepare_clip_info(current_sample, game_state.get("round", 1))
441
- prompt_text = message
442
- previous_sample = game_state.get("previous_sample")
443
- previous_audio = str(previous_sample.audio_path) if previous_sample else ""
444
- previous_distance = game_state.get("previous_distance_km")
445
- previous_answer = _format_previous_answer(previous_sample, distance_km=previous_distance) if previous_sample else ""
446
- is_example = game_state.get("is_example", False)
447
- previous_title = EXAMPLE_PROMPT if is_example else ""
448
- return (
449
- game_state,
450
- guess_state,
451
- str(current_sample.audio_path),
452
- clip_md,
453
- gr.update(),
454
- prompt_text,
455
- _format_recent_rows(_load_recent_runs()),
456
- longitude,
457
- latitude,
458
- previous_audio,
459
- previous_answer,
460
- previous_title,
461
- )
462
-
463
- if not (-90 <= guess_lat <= 90):
464
- message = "Latitude must be between -90 and 90."
465
- current_sample = SAMPLES[game_state["current_index"]]
466
- clip_md = _prepare_clip_info(current_sample, game_state.get("round", 1))
467
- prompt_text = message
468
- previous_sample = game_state.get("previous_sample")
469
- previous_audio = str(previous_sample.audio_path) if previous_sample else ""
470
- previous_distance = game_state.get("previous_distance_km")
471
- previous_guess_lat = game_state.get("previous_guess_lat")
472
- previous_guess_lon = game_state.get("previous_guess_lon")
473
- previous_answer = _format_previous_answer(previous_sample, distance_km=previous_distance, guess_lat=previous_guess_lat, guess_lon=previous_guess_lon) if previous_sample else ""
474
- is_example = game_state.get("is_example", False)
475
- previous_title = EXAMPLE_PROMPT if is_example else LAST_PROMPT
476
- return (
477
- game_state,
478
- guess_state,
479
- str(current_sample.audio_path),
480
- clip_md,
481
- gr.update(),
482
- prompt_text,
483
- _format_recent_rows(_load_recent_runs()),
484
- longitude,
485
- latitude,
486
- previous_audio,
487
- previous_answer,
488
- previous_title,
489
- )
490
- except ValueError:
491
- message = "Invalid coordinates. Please enter valid numbers."
492
- current_sample = SAMPLES[game_state["current_index"]]
493
- clip_md = _prepare_clip_info(current_sample, game_state.get("round", 1))
494
- prompt_text = message
495
- previous_sample = game_state.get("previous_sample")
496
- previous_audio = str(previous_sample.audio_path) if previous_sample else ""
497
- previous_distance = game_state.get("previous_distance_km")
498
- previous_guess_lat = game_state.get("previous_guess_lat")
499
- previous_guess_lon = game_state.get("previous_guess_lon")
500
- previous_answer = _format_previous_answer(previous_sample, distance_km=previous_distance, guess_lat=previous_guess_lat, guess_lon=previous_guess_lon) if previous_sample else ""
501
- is_example = game_state.get("is_example", False)
502
- previous_title = EXAMPLE_PROMPT if is_example else LAST_PROMPT
503
- return (
504
- game_state,
505
- guess_state,
506
- str(current_sample.audio_path),
507
- clip_md,
508
- _create_plotly_map(),
509
- prompt_text,
510
- _format_recent_rows(_load_recent_runs()),
511
- longitude,
512
- latitude,
513
- previous_audio,
514
- previous_answer,
515
- previous_title,
516
- )
517
-
518
- current_sample = SAMPLES[game_state["current_index"]]
519
- true_lat = current_sample.latitude
520
- true_lon = current_sample.longitude
521
-
522
- distance_km = _haversine(true_lat, true_lon, guess_lat, guess_lon)
523
- reveal_lines = [
524
- f"Real location: {current_sample.city or 'Unknown city'}, {current_sample.country or 'Unknown country'} ({true_lat:.3f}°, {true_lon:.3f}°)",
525
- f"Your guess: ({guess_lat:.3f}°, {guess_lon:.3f}°)",
526
- f"Error distance: {distance_km:.1f} km",
527
- ]
528
-
529
- log_entry = {
530
- "timestamp": dt.datetime.utcnow().isoformat(),
531
- "player_id": player_id,
532
- "question_id": current_sample.question_id,
533
- "audio_path": str(current_sample.audio_path),
534
- "guess_latitude": guess_lat,
535
- "guess_longitude": guess_lon,
536
- "true_latitude": true_lat,
537
- "true_longitude": true_lon,
538
- "distance_km": round(distance_km, 3),
539
- "city": current_sample.city,
540
- "country": current_sample.country,
541
- "continent": current_sample.continent,
542
- "title": current_sample.title,
543
- "description": current_sample.description,
544
- }
545
- _append_log(log_entry)
546
-
547
- # Save current sample and distance as previous for next round
548
- game_state["previous_sample"] = current_sample
549
- game_state["previous_distance_km"] = distance_km
550
- game_state["previous_guess_lat"] = guess_lat
551
- game_state["previous_guess_lon"] = guess_lon
552
- game_state["is_example"] = False # After first round, it's no longer example
553
-
554
- next_sample = _next_sample(game_state)
555
- audio_value = str(next_sample.audio_path)
556
- clip_md = _prepare_clip_info(next_sample, game_state["round"])
557
-
558
- new_guess_state = {"lat": None, "lon": None, "pixel": None}
559
- prompt_text = "Click once on the map to pick your guess. The marker will update to your last selection."
560
- recent_runs = _format_recent_rows(_load_recent_runs())
561
-
562
- # Format previous answer (current sample becomes previous for next round)
563
- previous_audio = str(current_sample.audio_path)
564
- previous_distance = game_state.get("previous_distance_km")
565
- previous_guess_lat = game_state.get("previous_guess_lat")
566
- previous_guess_lon = game_state.get("previous_guess_lon")
567
- previous_answer = _format_previous_answer(current_sample, is_example=False, distance_km=previous_distance, guess_lat=previous_guess_lat, guess_lon=previous_guess_lon)
568
- previous_title = LAST_PROMPT
569
-
570
- return (
571
- game_state,
572
- new_guess_state,
573
- audio_value,
574
- clip_md,
575
- gr.update(),
576
- prompt_text,
577
- recent_runs,
578
- "", # Reset longitude input
579
- "", # Reset latitude input
580
- previous_audio,
581
- previous_answer,
582
- previous_title,
583
- )
584
-
585
-
586
- custom_css = """
587
- h1 {
588
- font-size: 2.5rem !important;
589
- font-weight: 700 !important;
590
- margin-bottom: 1rem !important;
591
- text-align: center !important;
592
- }
593
- .intro-text {
594
- font-size: 1.1rem !important;
595
- line-height: 1.6 !important;
596
- margin-bottom: 1.5rem !important;
597
- color: #555 !important;
598
- text-align: center !important;
599
- }
600
- /* Apply size restrictions to regular (non-fullscreen) image */
601
- .gradio-image:not([class*="fullscreen"]) {
602
- max-width: 100% !important;
603
- max-height: none !important;
604
- height: auto !important;
605
- margin: 0 auto !important;
606
- display: block !important;
607
- }
608
- .gradio-image:not([class*="fullscreen"]) > div {
609
- max-width: 100% !important;
610
- max-height: none !important;
611
- height: auto !important;
612
- margin: 0 auto !important;
613
- display: block !important;
614
- }
615
- .gradio-image:not([class*="fullscreen"]) iframe,
616
- .gradio-image:not([class*="fullscreen"]) div[id^="map-"] {
617
- max-width: 100% !important;
618
- max-height: none !important;
619
- height: 800px !important;
620
- min-height: 800px !important;
621
- width: 100% !important;
622
- margin: 0 auto !important;
623
- display: block !important;
624
- }
625
- .gradio-image:not([class*="fullscreen"]) img {
626
- max-width: 100% !important;
627
- max-height: 600px !important;
628
- width: auto !important;
629
- height: auto !important;
630
- object-fit: contain !important;
631
- margin: 0 auto !important;
632
- }
633
- /* Ensure map plot has consistent height */
634
- .gradio-plot {
635
- min-height: 500px !important;
636
- height: 500px !important;
637
- }
638
- /* Make sure the map column aligns properly */
639
- .gradio-row > .gradio-column:first-child {
640
- display: flex !important;
641
- flex-direction: column !important;
642
- }
643
- .gradio-row > .gradio-column:first-child > * {
644
- flex-shrink: 0 !important;
645
- }
646
- /* Allow fullscreen modal to override size restrictions - higher specificity */
647
- /* Target common Gradio fullscreen containers */
648
- div[class*="modal"] .gradio-image,
649
- div[class*="modal"] .gradio-image > div,
650
- div[class*="modal"] .gradio-image img,
651
- div[class*="fullscreen"] .gradio-image,
652
- div[class*="fullscreen"] .gradio-image > div,
653
- div[class*="fullscreen"] .gradio-image img,
654
- div[id*="lightbox"] .gradio-image,
655
- div[id*="lightbox"] .gradio-image img,
656
- .gradio-image[class*="fullscreen"],
657
- .gradio-image[class*="fullscreen"] > div,
658
- .gradio-image[class*="fullscreen"] img {
659
- max-width: none !important;
660
- max-height: none !important;
661
- width: 100% !important;
662
- height: 100% !important;
663
- }
664
- .selection-text {
665
- font-size: 1.15rem !important;
666
- text-align: left !important;
667
- color: #666 !important;
668
- margin: 0.5rem 0 !important;
669
- }
670
- .selection-text * {
671
- font-size: 1.15rem !important;
672
- }
673
- .feedback-box {
674
- font-size: 1.15rem !important;
675
- line-height: 1.6 !important;
676
- }
677
- .feedback-box p,
678
- .feedback-box div,
679
- .feedback-box span {
680
- font-size: 1.15rem !important;
681
- line-height: 1.6 !important;
682
- }
683
- .clip-info {
684
- font-size: 1.1rem !important;
685
- }
686
- .clip-info p,
687
- .clip-info div,
688
- .clip-info span {
689
- font-size: 1.1rem !important;
690
- }
691
- .clip-info label {
692
- font-size: 1.1rem !important;
693
- font-weight: 600 !important;
694
- }
695
- label {
696
- font-size: 1rem !important;
697
- font-weight: 500 !important;
698
- }
699
- .form-text input {
700
- font-size: 0.95rem !important;
701
- }
702
- /* Table label styling - only target the label, not table content */
703
- .gradio-dataframe label,
704
- [data-testid="dataframe"] label,
705
- label[for*="recent"],
706
- .form-group label {
707
- font-size: 1.15rem !important;
708
- font-weight: 600 !important;
709
- }
710
- """
711
-
712
- with gr.Blocks(title="Audio Geo-Localization Game", theme=gr.themes.Soft(), css=custom_css) as demo:
713
- gr.Markdown("# Audio Geo-Localization Game")
714
- gr.HTML('<p class="intro-text">Welcome to the Audio Geo-Localization Game. Listen to an ambient audio clip, then guess where it was recorded by clicking on the world map. Submit to see the true location and how close you came.</p>')
715
-
716
- game_state = gr.State()
717
- guess_state = gr.State()
718
-
719
-
720
- # New row for previous question audio and answer with title
721
- previous_title_display = gr.Markdown(value="", elem_classes=["clip-info"])
722
- with gr.Row():
723
- with gr.Column(scale=1):
724
- previous_audio_player = gr.Audio(
725
- label="Previous audio clip",
726
- autoplay=False,
727
- interactive=False,
728
- streaming=False,
729
- visible=True
730
- )
731
- with gr.Column(scale=1):
732
- previous_answer_display = gr.Markdown(
733
- label="Previous answer",
734
- value="",
735
- elem_classes=["clip-info"]
736
- )
737
-
738
- # Add separator/divider between previous and current round
739
- gr.Markdown("---")
740
-
741
-
742
-
743
- clip_info = gr.Markdown(label="Clip details", elem_classes=["clip-info"])
744
-
745
-
746
- with gr.Row():
747
- with gr.Column(scale=2):
748
- map_component = gr.Plot(
749
- value=_create_plotly_map(),
750
- label="World map (click to set your guess)",
751
- elem_classes=["gradio-image"]
752
- )
753
-
754
- with gr.Column(scale=1):
755
- player_id = gr.Textbox(label="Player ID", placeholder="Enter an identifier so scores can be tracked", elem_classes=["form-text"])
756
-
757
- audio_player = gr.Audio(label="Mystery audio clip", autoplay=False, interactive=False, streaming=False)
758
-
759
- selection_text = gr.Markdown("Click once on the map to pick your guess. The marker will update to your last selection.", elem_classes=["selection-text"])
760
-
761
- with gr.Row():
762
- longitude_input = gr.Textbox(
763
- label="Longitude",
764
- placeholder="Enter longitude or click map",
765
- elem_classes=["form-text"],
766
- elem_id="lon_input"
767
- )
768
- latitude_input = gr.Textbox(
769
- label="Latitude",
770
- placeholder="Enter latitude or click map",
771
- elem_classes=["form-text"],
772
- elem_id="lat_input"
773
- )
774
-
775
- submit_button = gr.Button("Submit Guess", variant="primary")
776
- recent_table = gr.Dataframe(
777
- headers=[
778
- "timestamp",
779
- "player_id",
780
- "question_id",
781
- "distance_km",
782
- ],
783
- datatype=["str", "str", "str", "number"],
784
- value=[],
785
- interactive=False,
786
- label="Recent submissions (latest last)",
787
- wrap=True,
788
- )
789
-
790
- demo.load(
791
- initialize_round,
792
- inputs=None,
793
- outputs=[game_state, guess_state, audio_player, clip_info, map_component, selection_text, recent_table, longitude_input, latitude_input, previous_audio_player, previous_answer_display, previous_title_display]
794
- )
795
-
796
- # 后端监听文本框变化,在终端打印坐标(便于你观察点击数据是否到达后端)
797
- longitude_input.change(_on_coords_change, inputs=[longitude_input, latitude_input], outputs=[])
798
- latitude_input.change(_on_coords_change, inputs=[longitude_input, latitude_input], outputs=[])
799
-
800
- # Attach plotly_click to update the lon/lat textboxes (no Python roundtrip)
801
- plotly_click_js = r"""
802
- () => {
803
- console.log('[PLOTLY SETUP] Starting plotly click handler setup...');
804
-
805
- const updateInputs = (lat, lon) => {
806
- console.log('[PLOTLY CLICK] Received coordinates:', {lat, lon});
807
-
808
- // Method 1: Try Gradio component API
809
- if (window.gradio_app) {
810
- try {
811
- const components = window.gradio_app.__components || {};
812
- Object.keys(components).forEach(key => {
813
- const comp = components[key];
814
- if (comp && comp.props && comp.props.elem_id) {
815
- if (comp.props.elem_id === 'lon_input' && comp.component) {
816
- comp.component.value = Number(lon).toFixed(6);
817
- comp.component.dispatch('change');
818
- console.log('[PLOTLY CLICK] Updated longitude via Gradio API');
819
- }
820
- if (comp.props.elem_id === 'lat_input' && comp.component) {
821
- comp.component.value = Number(lat).toFixed(6);
822
- comp.component.dispatch('change');
823
- console.log('[PLOTLY CLICK] Updated latitude via Gradio API');
824
- }
825
- }
826
- });
827
- } catch (e) {
828
- console.log('[PLOTLY CLICK] Gradio API method failed:', e);
829
- }
830
- }
831
-
832
- // Method 2: Find by label text, then find input nearby
833
- const allLabels = Array.from(document.querySelectorAll('label'));
834
- allLabels.forEach(label => {
835
- const labelText = label.textContent.toLowerCase();
836
- if (labelText.includes('longitude')) {
837
- const container = label.closest('div, form, .gr-box');
838
- if (container) {
839
- const input = container.querySelector('input, textarea');
840
- if (input) {
841
- input.value = Number(lon).toFixed(6);
842
- input.dispatchEvent(new Event('input', { bubbles: true }));
843
- input.dispatchEvent(new Event('change', { bubbles: true }));
844
- console.log('[PLOTLY CLICK] Updated longitude via label:', input.value);
845
- }
846
- }
847
- }
848
- if (labelText.includes('latitude')) {
849
- const container = label.closest('div, form, .gr-box');
850
- if (container) {
851
- const input = container.querySelector('input, textarea');
852
- if (input) {
853
- input.value = Number(lat).toFixed(6);
854
- input.dispatchEvent(new Event('input', { bubbles: true }));
855
- input.dispatchEvent(new Event('change', { bubbles: true }));
856
- console.log('[PLOTLY CLICK] Updated latitude via label:', input.value);
857
- }
858
- }
859
- }
860
- });
861
-
862
- // Method 3: Try finding by placeholder in all possible elements
863
- const allElements = document.querySelectorAll('input, textarea, [contenteditable="true"]');
864
- allElements.forEach(el => {
865
- const ph = (el.placeholder || el.getAttribute('placeholder') || '').toLowerCase();
866
- if (ph.includes('longitude') && !ph.includes('latitude')) {
867
- if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') {
868
- el.value = Number(lon).toFixed(6);
869
- el.dispatchEvent(new Event('input', { bubbles: true }));
870
- el.dispatchEvent(new Event('change', { bubbles: true }));
871
- console.log('[PLOTLY CLICK] Updated longitude via placeholder:', el.value);
872
- }
873
- }
874
- if (ph.includes('latitude') && !ph.includes('longitude')) {
875
- if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') {
876
- el.value = Number(lat).toFixed(6);
877
- el.dispatchEvent(new Event('input', { bubbles: true }));
878
- el.dispatchEvent(new Event('change', { bubbles: true }));
879
- console.log('[PLOTLY CLICK] Updated latitude via placeholder:', el.value);
880
- }
881
- }
882
- });
883
-
884
- console.log('[PLOTLY CLICK] Update attempts completed');
885
- };
886
-
887
- const wirePlotly = () => {
888
- const plots = document.querySelectorAll('.js-plotly-plot');
889
- console.log('[PLOTLY SETUP] Found', plots.length, 'plotly plots');
890
-
891
- plots.forEach((plotDiv, idx) => {
892
- if (plotDiv.dataset._wired === '1') {
893
- console.log('[PLOTLY SETUP] Plot', idx, 'already wired');
894
- return;
895
- }
896
-
897
- console.log('[PLOTLY SETUP] Wiring plot', idx);
898
- plotDiv.dataset._wired = '1';
899
-
900
- // Listen for plotly_click DOM event (Plotly fires this as a custom event)
901
- plotDiv.addEventListener('plotly_click', (e) => {
902
- console.log('[PLOTLY CLICK] Event received:', e);
903
- console.log('[PLOTLY CLICK] e.points:', e.points);
904
-
905
- // Plotly click event data is directly on the event object
906
- let points = e.points;
907
- if (!points && e.detail) {
908
- points = e.detail.points;
909
- }
910
-
911
- if (points && points.length > 0) {
912
- const pt = points[0];
913
- console.log('[PLOTLY CLICK] Point data:', pt);
914
- const lat = pt.lat;
915
- const lon = pt.lon;
916
- console.log('[PLOTLY CLICK] Extracted lat:', lat, 'lon:', lon);
917
- if (lat !== undefined && lon !== undefined && !isNaN(lat) && !isNaN(lon)) {
918
- updateInputs(lat, lon);
919
- } else {
920
- console.error('[PLOTLY CLICK] Invalid coordinates:', {lat, lon, point: pt});
921
- }
922
- } else {
923
- console.error('[PLOTLY CLICK] No points found in event');
924
- }
925
- });
926
-
927
- // Fallback: Listen for raw click events and calculate coordinates from map config
928
- plotDiv.addEventListener('click', (e) => {
929
- console.log('[PLOTLY CLICK] Raw click event:', e);
930
-
931
- try {
932
- if (!plotDiv._fullLayout || !plotDiv._fullLayout.map) {
933
- console.error('[PLOTLY CLICK] map layout not available');
934
- return;
935
- }
936
-
937
- const mapConfig = plotDiv._fullLayout.map;
938
- const center = mapConfig.center || {lat: 0, lon: 0};
939
- const zoom = mapConfig.zoom || 2;
940
-
941
- console.log('[PLOTLY CLICK] Map config:', {center, zoom});
942
-
943
- // Get click position relative to plot div
944
- const rect = plotDiv.getBoundingClientRect();
945
- const width = rect.width;
946
- const height = rect.height;
947
- const x = e.clientX - rect.left;
948
- const y = e.clientY - rect.top;
949
-
950
- console.log('[PLOTLY CLICK] Click position:', {x, y, width, height});
951
-
952
- // Convert pixel coordinates to lat/lon using Web Mercator projection
953
- // Simplified calculation based on map center and zoom
954
- const normalizedX = (x / width) - 0.5; // -0.5 to 0.5
955
- const normalizedY = 0.5 - (y / height); // 0.5 to -0.5 (flipped Y)
956
-
957
- // Calculate pixel-to-degree conversion at current zoom
958
- // At zoom level z, one tile = 256 pixels, world = 2^z tiles wide
959
- const tilesAtZoom = Math.pow(2, zoom);
960
- const pixelsPerTile = 256;
961
- const worldWidthPixels = tilesAtZoom * pixelsPerTile;
962
- const worldWidthDegrees = 360;
963
- const degreesPerPixel = worldWidthDegrees / worldWidthPixels;
964
-
965
- // Longitude: linear mapping
966
- const lon = center.lon + (normalizedX * width * degreesPerPixel);
967
-
968
- // Latitude: Web Mercator inverse
969
- // Mercator Y at center: y_center = ln(tan(π/4 + center_lat/2))
970
- // Click Y offset in pixels: dy = normalizedY * height
971
- // Convert to Mercator units and then to latitude
972
- const mercatorYCenter = Math.log(Math.tan(Math.PI / 4 + (center.lat * Math.PI / 180) / 2));
973
- const dyMercator = normalizedY * height * degreesPerPixel / (180 / Math.PI);
974
- const mercatorYClick = mercatorYCenter + dyMercator;
975
- const latRad = 2 * Math.atan(Math.exp(mercatorYClick)) - Math.PI / 2;
976
- const lat = latRad * 180 / Math.PI;
977
-
978
- console.log('[PLOTLY CLICK] Calculated coordinates - lat:', lat, 'lon:', lon);
979
-
980
- if (!isNaN(lat) && !isNaN(lon) && lat >= -90 && lat <= 90 && lon >= -180 && lon <= 180) {
981
- updateInputs(lat, lon);
982
- } else {
983
- console.error('[PLOTLY CLICK] Invalid calculated coordinates:', {lat, lon});
984
- }
985
- } catch (err) {
986
- console.error('[PLOTLY CLICK] Error in click handler:', err);
987
- console.error('[PLOTLY CLICK] Error stack:', err.stack);
988
- }
989
- });
990
-
991
- });
992
- };
993
-
994
- // Initial wire with retry logic
995
- let retryCount = 0;
996
- const maxRetries = 10;
997
- const tryWire = () => {
998
- const plots = document.querySelectorAll('.js-plotly-plot');
999
- if (plots.length === 0 && retryCount < maxRetries) {
1000
- retryCount++;
1001
- console.log('[PLOTLY SETUP] No plots found, retry', retryCount, '/', maxRetries);
1002
- setTimeout(tryWire, 500);
1003
- return;
1004
- }
1005
- wirePlotly();
1006
- console.log('[PLOTLY SETUP] Initial wire complete, found', plots.length, 'plots');
1007
- };
1008
-
1009
- // Wait for Plotly library to load
1010
- if (window.Plotly) {
1011
- console.log('[PLOTLY SETUP] Plotly library found immediately');
1012
- setTimeout(tryWire, 1500);
1013
- } else {
1014
- console.warn('[PLOTLY SETUP] Plotly library not found, waiting...');
1015
- let plotlyWaitCount = 0;
1016
- const waitForPlotly = () => {
1017
- if (window.Plotly) {
1018
- console.log('[PLOTLY SETUP] Plotly library loaded after', plotlyWaitCount * 200, 'ms');
1019
- setTimeout(tryWire, 1000);
1020
- } else if (plotlyWaitCount < 20) {
1021
- plotlyWaitCount++;
1022
- setTimeout(waitForPlotly, 200);
1023
- } else {
1024
- console.error('[PLOTLY SETUP] Plotly library not found after 4 seconds, proceeding anyway');
1025
- setTimeout(tryWire, 1000);
1026
- }
1027
- };
1028
- waitForPlotly();
1029
- }
1030
-
1031
- // Watch for new plots
1032
- const obs = new MutationObserver(() => {
1033
- setTimeout(wirePlotly, 500);
1034
- });
1035
- obs.observe(document.body, { childList: true, subtree: true });
1036
- }
1037
- """
1038
-
1039
- demo.load(None, js=plotly_click_js)
1040
-
1041
- submit_button.click(
1042
- submit_guess,
1043
- inputs=[player_id, game_state, guess_state, longitude_input, latitude_input],
1044
- outputs=[game_state, guess_state, audio_player, clip_info, map_component, selection_text, recent_table, longitude_input, latitude_input, previous_audio_player, previous_answer_display, previous_title_display],
1045
- )
1046
-
1047
-
1048
- if __name__ == "__main__":
1049
- # Allow Gradio to serve audio files that live outside the CWD by whitelisting the project dir
1050
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
appPre.py DELETED
@@ -1,618 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import csv
4
- import datetime as dt
5
- import math
6
- import random
7
- from dataclasses import dataclass
8
- from pathlib import Path
9
- from typing import Dict, List, Optional, Tuple
10
-
11
- import numpy as np
12
-
13
- if not hasattr(np, "bool"): # pandas<2 compatibility on numpy>=2
14
- np.bool = bool # type: ignore[attr-defined]
15
-
16
- import pandas as pd
17
- from PIL import Image, ImageDraw
18
-
19
- import gradio as gr
20
-
21
-
22
- BASE_DIR = Path(__file__).resolve().parent
23
- DATASET_PATH = BASE_DIR / "data" / "dataset.csv"
24
- AUDIO_BASE_DIR = BASE_DIR / "data" / "audios"
25
- ASSETS_DIR = BASE_DIR / "assets"
26
- MAP_IMAGE_PATH = ASSETS_DIR / "world_map.png"
27
- LOG_PATH = BASE_DIR / "player_runs.csv"
28
- RECENT_COLUMNS = ["timestamp", "player_id", "question_id", "distance_km"]
29
-
30
-
31
- @dataclass
32
- class Sample:
33
- question_id: str
34
- audio_path: Path
35
- longitude: float
36
- latitude: float
37
- city: str
38
- country: str
39
- continent: str
40
- description: str
41
- title: str
42
-
43
-
44
- def _load_samples() -> List[Sample]:
45
- if not DATASET_PATH.exists():
46
- raise FileNotFoundError(f"Dataset not found at {DATASET_PATH}")
47
-
48
- df = pd.read_csv(DATASET_PATH)
49
- start_idx = int(len(df) * 0.9)
50
- test_df = df.iloc[start_idx:].reset_index(drop=True)
51
-
52
- samples: List[Sample] = []
53
- missing_audio = 0
54
- missing_coords = 0
55
-
56
- for row in test_df.itertuples():
57
- audio_path = AUDIO_BASE_DIR / getattr(row, "mp3name")
58
- longitude = getattr(row, "longitude")
59
- latitude = getattr(row, "latitude")
60
-
61
- if math.isnan(longitude) or math.isnan(latitude):
62
- missing_coords += 1
63
- continue
64
-
65
- if not audio_path.exists():
66
- missing_audio += 1
67
- continue
68
-
69
- samples.append(
70
- Sample(
71
- question_id=str(getattr(row, "key")),
72
- audio_path=audio_path,
73
- longitude=float(longitude),
74
- latitude=float(latitude),
75
- city=str(getattr(row, "city", "") or ""),
76
- country=str(getattr(row, "country", "") or ""),
77
- continent=str(getattr(row, "continent", "") or ""),
78
- description=str(getattr(row, "description", "") or ""),
79
- title=str(getattr(row, "title", "") or ""),
80
- )
81
- )
82
-
83
- if not samples:
84
- raise RuntimeError("No playable samples were found in the test split.")
85
-
86
- if missing_audio:
87
- print(f"[game_app] Skipped {missing_audio} samples because audio files are missing.")
88
- if missing_coords:
89
- print(f"[game_app] Skipped {missing_coords} samples because coordinates are missing.")
90
-
91
- return samples
92
-
93
-
94
- SAMPLES: List[Sample] = _load_samples()
95
- BASE_MAP_IMAGE = Image.open(MAP_IMAGE_PATH).convert("RGB")
96
- MAP_WIDTH, MAP_HEIGHT = BASE_MAP_IMAGE.size
97
-
98
-
99
- def _random_queue() -> List[int]:
100
- queue = list(range(len(SAMPLES)))
101
- random.shuffle(queue)
102
- return queue
103
-
104
-
105
- def _pixel_to_latlon(x: int, y: int) -> Tuple[float, float]:
106
- lon = (x / (MAP_WIDTH - 1)) * 360.0 - 180.0
107
- lat = 90.0 - (y / (MAP_HEIGHT - 1)) * 180.0
108
- return round(lat, 6), round(lon, 6)
109
-
110
-
111
- def _latlon_to_text(lat: float, lon: float) -> str:
112
- return f"Selected latitude {lat:.3f}°, longitude {lon:.3f}°"
113
-
114
-
115
- def _haversine(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
116
- r = 6371.0
117
- phi1, phi2 = math.radians(lat1), math.radians(lat2)
118
- d_phi = math.radians(lat2 - lat1)
119
- d_lambda = math.radians(lon2 - lon1)
120
-
121
- a = math.sin(d_phi / 2.0) ** 2 + math.cos(phi1) * math.cos(phi2) * math.sin(d_lambda / 2.0) ** 2
122
- c = 2.0 * math.atan2(math.sqrt(a), math.sqrt(1.0 - a))
123
- return r * c
124
-
125
-
126
- def _map_with_marker(x: int, y: int) -> np.ndarray:
127
- marker_radius = max(6, MAP_WIDTH // 150)
128
- img = BASE_MAP_IMAGE.copy()
129
- draw = ImageDraw.Draw(img)
130
- draw.ellipse(
131
- (
132
- x - marker_radius,
133
- y - marker_radius,
134
- x + marker_radius,
135
- y + marker_radius,
136
- ),
137
- fill=(225, 64, 64),
138
- outline=(0, 0, 0),
139
- width=2,
140
- )
141
- return np.array(img)
142
-
143
-
144
- def _base_map_array() -> np.ndarray:
145
- return np.array(BASE_MAP_IMAGE)
146
-
147
-
148
- def _prepare_clip_info(sample: Sample, round_idx: int) -> str:
149
- intro_lines = [
150
- f"**Round:** {round_idx}"
151
- ]
152
- return "\n\n".join(intro_lines)
153
-
154
-
155
- def _append_log(entry: Dict[str, object]) -> None:
156
- write_header = not LOG_PATH.exists()
157
- with LOG_PATH.open("a", newline="", encoding="utf-8") as f:
158
- writer = csv.DictWriter(f, fieldnames=list(entry.keys()))
159
- if write_header:
160
- writer.writeheader()
161
- writer.writerow(entry)
162
-
163
-
164
- def _load_recent_runs(limit: int = 5) -> List[Dict[str, object]]:
165
- if not LOG_PATH.exists():
166
- return []
167
-
168
- rows = []
169
- with LOG_PATH.open("r", encoding="utf-8") as f:
170
- reader = csv.DictReader(f)
171
- for row in reader:
172
- rows.append(row)
173
- return rows[-limit:]
174
-
175
-
176
- def _format_recent_rows(rows: List[Dict[str, object]]) -> List[List[object]]:
177
- formatted: List[List[object]] = []
178
- for row in rows:
179
- timestamp_str = row.get("timestamp", "")
180
- if timestamp_str:
181
- try:
182
- # Parse ISO format timestamp and format as readable string
183
- dt_obj = dt.datetime.fromisoformat(str(timestamp_str).replace('Z', '+00:00'))
184
- formatted_timestamp = dt_obj.strftime("%Y-%m-%d %H:%M:%S")
185
- except (ValueError, AttributeError):
186
- formatted_timestamp = str(timestamp_str)
187
- else:
188
- formatted_timestamp = ""
189
-
190
- formatted_row = [formatted_timestamp]
191
- formatted_row.extend([row.get(col, "") for col in RECENT_COLUMNS[1:]])
192
- formatted.append(formatted_row)
193
- return formatted
194
-
195
-
196
- def initialize_round() -> Tuple[Dict[str, object], Dict[str, Optional[float]], str, str, np.ndarray, str, List[List[object]], str, str]:
197
- queue = _random_queue()
198
- current_index = queue.pop()
199
-
200
- state = {
201
- "queue": queue,
202
- "current_index": current_index,
203
- "round": 1,
204
- }
205
-
206
- current_sample = SAMPLES[current_index]
207
- audio_value = str(current_sample.audio_path)
208
- clip_md = _prepare_clip_info(current_sample, state["round"])
209
- prompt_text = "Click once on the map to pick your guess. The marker will update to your last selection."
210
- guess_state = {"lat": None, "lon": None, "pixel": None}
211
- recent_runs = _format_recent_rows(_load_recent_runs())
212
-
213
- return state, guess_state, audio_value, clip_md, _base_map_array(), prompt_text, recent_runs, "", ""
214
-
215
-
216
- def _next_sample(state: Dict[str, object]) -> Sample:
217
- queue: List[int] = state["queue"]
218
- if not queue:
219
- queue.extend(_random_queue())
220
-
221
- next_index = queue.pop()
222
- state["current_index"] = next_index
223
- state["round"] = state.get("round", 1) + 1
224
- return SAMPLES[next_index]
225
-
226
-
227
- def _ensure_guess_state(state: Optional[Dict[str, Optional[float]]]) -> Dict[str, Optional[float]]:
228
- if not isinstance(state, dict):
229
- return {"lat": None, "lon": None, "pixel": None}
230
- return {
231
- "lat": state.get("lat"),
232
- "lon": state.get("lon"),
233
- "pixel": state.get("pixel"),
234
- }
235
-
236
-
237
- def handle_map_click(
238
- evt: gr.SelectData,
239
- current_guess_state: Optional[Dict[str, Optional[float]]],
240
- ) -> Tuple[np.ndarray, str, Dict[str, Optional[float]], str, str]:
241
- guess_state = _ensure_guess_state(current_guess_state)
242
- if evt is None:
243
- return _base_map_array(), "Unable to read selection. Please try again.", guess_state, "", ""
244
-
245
- index = getattr(evt, "index", None)
246
- value = getattr(evt, "value", None)
247
-
248
- x = y = None
249
- if isinstance(index, (tuple, list)) and len(index) >= 2:
250
- x, y = index[0], index[1]
251
- elif isinstance(index, dict):
252
- x = index.get("x")
253
- y = index.get("y")
254
-
255
- if (x is None or y is None) and isinstance(value, dict):
256
- x = value.get("x", x)
257
- y = value.get("y", y)
258
- elif (x is None or y is None) and isinstance(value, (tuple, list)) and len(value) >= 2:
259
- if x is None:
260
- x = value[0]
261
- if y is None:
262
- y = value[1]
263
-
264
- if x is None or y is None:
265
- return _base_map_array(), "Unable to read selection. Please try again.", guess_state, "", ""
266
-
267
- x = int(x)
268
- y = int(y)
269
-
270
- lat, lon = _pixel_to_latlon(x, y)
271
- guess_state = {"lat": lat, "lon": lon, "pixel": (x, y)}
272
- image_with_marker = _map_with_marker(x, y)
273
- return image_with_marker, _latlon_to_text(lat, lon), guess_state, f"{lon:.6f}", f"{lat:.6f}"
274
-
275
-
276
- def submit_guess(
277
- player_id: str,
278
- game_state: Dict[str, object],
279
- guess_state: Optional[Dict[str, Optional[float]]],
280
- longitude: str,
281
- latitude: str,
282
- ) -> Tuple[
283
- Dict[str, object],
284
- Dict[str, Optional[float]],
285
- str,
286
- str,
287
- np.ndarray,
288
- str,
289
- List[List[object]],
290
- str,
291
- str,
292
- ]:
293
- guess_state = _ensure_guess_state(guess_state)
294
- player_id = (player_id or "").strip()
295
- if not player_id:
296
- message = "Please enter your player ID before submitting."
297
- current_sample = SAMPLES[game_state["current_index"]]
298
- clip_md = _prepare_clip_info(current_sample, game_state.get("round", 1))
299
- prompt_text = message
300
- return (
301
- game_state,
302
- guess_state,
303
- str(current_sample.audio_path),
304
- clip_md,
305
- _base_map_array(),
306
- prompt_text,
307
- _format_recent_rows(_load_recent_runs()),
308
- longitude,
309
- latitude,
310
- )
311
-
312
- # Parse longitude and latitude from text inputs
313
- try:
314
- longitude = longitude.strip() if longitude else ""
315
- latitude = latitude.strip() if latitude else ""
316
-
317
- if not longitude or not latitude:
318
- message = "Please enter both longitude and latitude, or click on the map to select a location."
319
- current_sample = SAMPLES[game_state["current_index"]]
320
- clip_md = _prepare_clip_info(current_sample, game_state.get("round", 1))
321
- prompt_text = message
322
- return (
323
- game_state,
324
- guess_state,
325
- str(current_sample.audio_path),
326
- clip_md,
327
- _base_map_array(),
328
- prompt_text,
329
- _format_recent_rows(_load_recent_runs()),
330
- longitude,
331
- latitude,
332
- )
333
-
334
- guess_lon = float(longitude)
335
- guess_lat = float(latitude)
336
-
337
- # Validate ranges
338
- if not (-180 <= guess_lon <= 180):
339
- message = "Longitude must be between -180 and 180."
340
- current_sample = SAMPLES[game_state["current_index"]]
341
- clip_md = _prepare_clip_info(current_sample, game_state.get("round", 1))
342
- prompt_text = message
343
- return (
344
- game_state,
345
- guess_state,
346
- str(current_sample.audio_path),
347
- clip_md,
348
- _base_map_array(),
349
- prompt_text,
350
- _format_recent_rows(_load_recent_runs()),
351
- longitude,
352
- latitude,
353
- )
354
-
355
- if not (-90 <= guess_lat <= 90):
356
- message = "Latitude must be between -90 and 90."
357
- current_sample = SAMPLES[game_state["current_index"]]
358
- clip_md = _prepare_clip_info(current_sample, game_state.get("round", 1))
359
- prompt_text = message
360
- return (
361
- game_state,
362
- guess_state,
363
- str(current_sample.audio_path),
364
- clip_md,
365
- _base_map_array(),
366
- prompt_text,
367
- _format_recent_rows(_load_recent_runs()),
368
- longitude,
369
- latitude,
370
- )
371
- except ValueError:
372
- message = "Invalid coordinates. Please enter valid numbers."
373
- current_sample = SAMPLES[game_state["current_index"]]
374
- clip_md = _prepare_clip_info(current_sample, game_state.get("round", 1))
375
- prompt_text = message
376
- return (
377
- game_state,
378
- guess_state,
379
- str(current_sample.audio_path),
380
- clip_md,
381
- _base_map_array(),
382
- prompt_text,
383
- _format_recent_rows(_load_recent_runs()),
384
- longitude,
385
- latitude,
386
- )
387
-
388
- current_sample = SAMPLES[game_state["current_index"]]
389
- true_lat = current_sample.latitude
390
- true_lon = current_sample.longitude
391
-
392
- distance_km = _haversine(true_lat, true_lon, guess_lat, guess_lon)
393
- reveal_lines = [
394
- f"Real location: {current_sample.city or 'Unknown city'}, {current_sample.country or 'Unknown country'} ({true_lat:.3f}°, {true_lon:.3f}°)",
395
- f"Your guess: ({guess_lat:.3f}°, {guess_lon:.3f}°)",
396
- f"Error distance: {distance_km:.1f} km",
397
- ]
398
-
399
- log_entry = {
400
- "timestamp": dt.datetime.utcnow().isoformat(),
401
- "player_id": player_id,
402
- "question_id": current_sample.question_id,
403
- "audio_path": str(current_sample.audio_path),
404
- "guess_latitude": guess_lat,
405
- "guess_longitude": guess_lon,
406
- "true_latitude": true_lat,
407
- "true_longitude": true_lon,
408
- "distance_km": round(distance_km, 3),
409
- "city": current_sample.city,
410
- "country": current_sample.country,
411
- "continent": current_sample.continent,
412
- "title": current_sample.title,
413
- "description": current_sample.description,
414
- }
415
- _append_log(log_entry)
416
-
417
- next_sample = _next_sample(game_state)
418
- audio_value = str(next_sample.audio_path)
419
- clip_md = _prepare_clip_info(next_sample, game_state["round"])
420
-
421
- new_guess_state = {"lat": None, "lon": None, "pixel": None}
422
- prompt_text = "Click once on the map to pick your guess. The marker will update to your last selection."
423
- recent_runs = _format_recent_rows(_load_recent_runs())
424
-
425
- return (
426
- game_state,
427
- new_guess_state,
428
- audio_value,
429
- clip_md,
430
- _base_map_array(),
431
- prompt_text,
432
- recent_runs,
433
- "", # Reset longitude input
434
- "", # Reset latitude input
435
- )
436
-
437
-
438
- custom_css = """
439
- h1 {
440
- font-size: 2.5rem !important;
441
- font-weight: 700 !important;
442
- margin-bottom: 1rem !important;
443
- text-align: center !important;
444
- }
445
- .intro-text {
446
- font-size: 1.1rem !important;
447
- line-height: 1.6 !important;
448
- margin-bottom: 1.5rem !important;
449
- color: #555 !important;
450
- text-align: center !important;
451
- }
452
- /* Apply size restrictions to regular (non-fullscreen) image */
453
- .gradio-image:not([class*="fullscreen"]) {
454
- max-width: 100% !important;
455
- max-height: 600px !important;
456
- margin: 0 auto !important;
457
- display: flex !important;
458
- justify-content: center !important;
459
- }
460
- .gradio-image:not([class*="fullscreen"]) > div {
461
- max-width: 100% !important;
462
- max-height: 600px !important;
463
- margin: 0 auto !important;
464
- display: flex !important;
465
- justify-content: center !important;
466
- }
467
- .gradio-image:not([class*="fullscreen"]) img {
468
- max-width: 100% !important;
469
- max-height: 600px !important;
470
- width: auto !important;
471
- height: auto !important;
472
- object-fit: contain !important;
473
- margin: 0 auto !important;
474
- }
475
- /* Allow fullscreen modal to override size restrictions - higher specificity */
476
- /* Target common Gradio fullscreen containers */
477
- div[class*="modal"] .gradio-image,
478
- div[class*="modal"] .gradio-image > div,
479
- div[class*="modal"] .gradio-image img,
480
- div[class*="fullscreen"] .gradio-image,
481
- div[class*="fullscreen"] .gradio-image > div,
482
- div[class*="fullscreen"] .gradio-image img,
483
- div[id*="lightbox"] .gradio-image,
484
- div[id*="lightbox"] .gradio-image img,
485
- .gradio-image[class*="fullscreen"],
486
- .gradio-image[class*="fullscreen"] > div,
487
- .gradio-image[class*="fullscreen"] img {
488
- max-width: none !important;
489
- max-height: none !important;
490
- width: 100% !important;
491
- height: 100% !important;
492
- }
493
- .selection-text {
494
- font-size: 1.15rem !important;
495
- text-align: left !important;
496
- color: #666 !important;
497
- margin: 0.5rem 0 !important;
498
- }
499
- .selection-text * {
500
- font-size: 1.15rem !important;
501
- }
502
- .feedback-box {
503
- font-size: 1.15rem !important;
504
- line-height: 1.6 !important;
505
- }
506
- .feedback-box p,
507
- .feedback-box div,
508
- .feedback-box span {
509
- font-size: 1.15rem !important;
510
- line-height: 1.6 !important;
511
- }
512
- .clip-info {
513
- font-size: 1.1rem !important;
514
- }
515
- .clip-info p,
516
- .clip-info div,
517
- .clip-info span {
518
- font-size: 1.1rem !important;
519
- }
520
- .clip-info label {
521
- font-size: 1.1rem !important;
522
- font-weight: 600 !important;
523
- }
524
- label {
525
- font-size: 1rem !important;
526
- font-weight: 500 !important;
527
- }
528
- .form-text input {
529
- font-size: 0.95rem !important;
530
- }
531
- /* Table label styling - only target the label, not table content */
532
- .gradio-dataframe label,
533
- [data-testid="dataframe"] label,
534
- label[for*="recent"],
535
- .form-group label {
536
- font-size: 1.15rem !important;
537
- font-weight: 600 !important;
538
- }
539
- """
540
-
541
- with gr.Blocks(title="Audio Geo-Localization Game", theme=gr.themes.Soft(), css=custom_css) as demo:
542
- gr.Markdown("# Audio Geo-Localization Game")
543
- gr.HTML('<p class="intro-text">Welcome to the Audio Geo-Localization Game. Listen to an ambient audio clip, then guess where it was recorded by clicking on the world map. Submit to see the true location and how close you came.</p>')
544
-
545
- game_state = gr.State()
546
- guess_state = gr.State()
547
-
548
-
549
- clip_info = gr.Markdown(label="Clip details", elem_classes=["clip-info"])
550
-
551
-
552
- with gr.Row():
553
- with gr.Column(scale=2):
554
- map_component = gr.Image(
555
- value=_base_map_array(),
556
- label="World map (click to set your guess)",
557
- interactive=True,
558
- type="numpy",
559
- image_mode="RGB",
560
- elem_classes=["gradio-image"],
561
- )
562
-
563
- with gr.Column(scale=1):
564
- player_id = gr.Textbox(label="Player ID", placeholder="Enter an identifier so scores can be tracked", elem_classes=["form-text"])
565
-
566
- audio_player = gr.Audio(label="Mystery audio clip", autoplay=False, interactive=False, streaming=False)
567
-
568
- selection_text = gr.Markdown("Click once on the map to pick your guess. The marker will update to your last selection.", elem_classes=["selection-text"])
569
-
570
- with gr.Row():
571
- longitude_input = gr.Textbox(
572
- label="Longitude",
573
- placeholder="Enter longitude (-180 to 180) or click map",
574
- elem_classes=["form-text"]
575
- )
576
- latitude_input = gr.Textbox(
577
- label="Latitude",
578
- placeholder="Enter latitude (-90 to 90) or click map",
579
- elem_classes=["form-text"]
580
- )
581
-
582
- submit_button = gr.Button("Submit Guess", variant="primary")
583
- recent_table = gr.Dataframe(
584
- headers=[
585
- "timestamp",
586
- "player_id",
587
- "question_id",
588
- "distance_km",
589
- ],
590
- datatype=["str", "str", "str", "number"],
591
- value=[],
592
- interactive=False,
593
- label="Recent submissions (latest last)",
594
- wrap=True,
595
- )
596
-
597
- demo.load(
598
- initialize_round,
599
- inputs=None,
600
- outputs=[game_state, guess_state, audio_player, clip_info, map_component, selection_text, recent_table, longitude_input, latitude_input],
601
- )
602
-
603
- map_component.select(
604
- handle_map_click,
605
- inputs=[guess_state],
606
- outputs=[map_component, selection_text, guess_state, longitude_input, latitude_input],
607
- preprocess=False,
608
- )
609
-
610
- submit_button.click(
611
- submit_guess,
612
- inputs=[player_id, game_state, guess_state, longitude_input, latitude_input],
613
- outputs=[game_state, guess_state, audio_player, clip_info, map_component, selection_text, recent_table, longitude_input, latitude_input],
614
- )
615
-
616
-
617
- if __name__ == "__main__":
618
- demo.launch(server_name="0.0.0.0", server_port=3828)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
data/audios/1006260212valenciamaralbufeira.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:a69e7afff1665fc66a6fa04964c95e7b34c4b05ea9a6152aa76d829bb0fd25e2
3
- size 3423360
 
 
 
 
data/audios/14SavannaGrainBins20141022.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:73cbe5881faec0f36b543a1a5ea2205cba2bc5ea1dd42e58cab3fe22abc150c2
3
- size 1439744
 
 
 
 
data/audios/1706watersystem.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:66f822d059033a483c4f932bf8114fe52198b158acb90bac8b5d049eeff0ca3c
3
- size 3445408
 
 
 
 
data/audios/18042900522.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:664e39a86ea77756cc1171376f6a66c4087b3fc81e2cbc25a15d282cdb35f5b5
3
- size 3160450
 
 
 
 
data/audios/2014clermontferrandfountain2.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:2619d18d59b4df3cf10ee1abb806ae240b30317867c93ad12d72e08a39d7d9ba
3
- size 1792512
 
 
 
 
data/audios/43troyescathedrale03089h00.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:267b1ccdf1f5f6bb7a0daba7b7352437736fcf5a260c6885a108b1eb8a82f14e
3
- size 3877661
 
 
 
 
data/audios/AMOSMKE201510200201.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:515e5d2b04d3cff1841a0896ded5d815b42c431f67bbc1e6afa105a84e4282e0
3
- size 2034176
 
 
 
 
data/audios/AMOSMKE201511172138.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:0a9c84dfc3755044e32ed5a4fdcceacae1c03c747592e3a80d8501a5ad4fa2af
3
- size 2015744
 
 
 
 
data/audios/Ambiant2extractmono.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:eb6b7b7fde13deb2b2c2b1bde6af1f76b71777b5820e1e35c8962afd1e0543b7
3
- size 3050112
 
 
 
 
data/audios/BAB2.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:3f8303930496c906830a126e1a5e0817a75d4e9f1fd2cb42d719a1f68d73032b
3
- size 1533909
 
 
 
 
data/audios/BaltiMarktPrnikVaniljebellstram.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:5624c625e29aeb4958eeeaea6afe8d70ec36255471a2caba8db10e859f026ce7
3
- size 1857436
 
 
 
 
data/audios/Birdsinthehedgesofthefarmerspath29012010.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:34a22f43ee2ee47f685bdc9347bcd3a3c9e21a335e3815bf70eb31bda1fbb20e
3
- size 2042567
 
 
 
 
data/audios/CityCountryMeStettinschritteschnee.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:b640a40abe334a685d0a23528c3c6f09553097c1fff8d8685284605dfe0e3446
3
- size 1375631
 
 
 
 
data/audios/CityCountryMemariaamuferremisesommercampinstituteforintermediatestudies290709001.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:de61337c24a158577c9ceb5515095035f5887368dde9233eaf3621428f592abc
3
- size 2242688
 
 
 
 
data/audios/CityCountryMesanderstrdreharbeiten.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:da1325835c98ed8b64eb64fd97436090044752c6bd47903209b752fa573cbdf0
3
- size 898322
 
 
 
 
data/audios/DuesseldorfTanzhausNRWGangProbestudios.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:72173182969163d03fa90cd738e8a832c72a293d63570bcdf762d2606aef87e0
3
- size 4553563
 
 
 
 
data/audios/FrancoisEmmanuelFodereButrintNationalParkButhroteInsectsandflaginwind.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:8dac642d545ab8bc8e99e7ebb4d47df95c69bdad0251897770c92f12df241892
3
- size 7005040
 
 
 
 
data/audios/GPSwalktrack04.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:6635b21900211e82a091300925ff084c47c48d0fcdc7bbd86994a038ca828c0e
3
- size 1003624
 
 
 
 
data/audios/GoldenGateBridgeSF1.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:4a23ddc827e8e431223a51f27297b6a12920e030978921558349551215677333
3
- size 1661211
 
 
 
 
data/audios/LLN104.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:030c5acbf3258486103d6b0f5bb8cf21f2ff20638fd404bdf95987463ee8a40a
3
- size 3237137
 
 
 
 
data/audios/NewBarnTeaMeditationPt31110am0110172.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:8f392bcf7b392394c85a0ad9ded3478cd065ac1468a9ae06896048f677f5f9e2
3
- size 6626316
 
 
 
 
data/audios/NikkoTempelZuweg02.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:031bcbca899d22433d0f58bfa2480587c2f2c4abc78bd484412c2841d04ce931
3
- size 1903429
 
 
 
 
data/audios/OijSchiffeamRhein01.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:b2a4f2c1b8c392699a990ddf8d1246ee399fb51f49010a280177d03ee784b14a
3
- size 5526301
 
 
 
 
data/audios/OiseauxAbeilleVentRuisseau2303181205.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:2977f974a4de97587bea365808683c8227df36ba7fc3120d897c96fbe8fc8a30
3
- size 4077912
 
 
 
 
data/audios/Placesound1.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:939db2682c8fd9a918f4e0110c5e9eae61c6ce4515d5de51fa27f2946855ae00
3
- size 2225062
 
 
 
 
data/audios/RegioZugfahrtTuerMRosenh.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:06a75c2bf0da2b46c142aff657674b0f43f310b06f9add87ab944b76341b8fc5
3
- size 3529956
 
 
 
 
data/audios/SkatingSoundsPier25HudsonPark.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:ab1cc7f06d367c1ed7a2bc30fc9cc84b51698cc1facb6f2677f5c6a899e1cbaa
3
- size 7028027
 
 
 
 
data/audios/SoundMap2012020171.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:9be59466147343d52b15c27b2e6c9f51b5070ef2ee80f04107b82572bfbf0492
3
- size 3966144
 
 
 
 
data/audios/SoundMap201207031314.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:dc4c124ca81b7fc8876475d3889eb2463fd34da4545c168afbf6c6bf48bf3112
3
- size 5766144
 
 
 
 
data/audios/SoundMap201210151.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:520458ae698980711e7050902cbb4d5929f06951a17f5ff428eb668764a19844
3
- size 1210368
 
 
 
 
data/audios/SoundMap201211043.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:31801cb962db53edf1c2fc3c51240c2880ac0b6b2b847f9abac11d0c5f8a98d6
3
- size 5126784
 
 
 
 
data/audios/Soundmap2012022542.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:5c48f35e75d7863c5a232ae4cb4b301d25ff5f5216b017fccd6538004ae9c3e1
3
- size 4479744
 
 
 
 
data/audios/TRAIN58.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:a98ee0de7c138f4e6a048934209e96534f2df40379dec297cc8cd6640faa9bcf
3
- size 2614464
 
 
 
 
data/audios/UCSBFencingPractice.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:071e8547654f719a1770d52c3aaf4f7a8d6b4d8f454ef4e0f75477656624c6c0
3
- size 2219343
 
 
 
 
data/audios/UnderCongressBats.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:9cab7e1351f0d508631b87d649d153ccfbcb6a061ead7b633da7ffd2a9833cac
3
- size 2658816
 
 
 
 
data/audios/WindwaveUNOcity.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:7239c31cc45ed5543b48db9041451bd9eef4371555e6d7d99d2e525a5717bff0
3
- size 2693955
 
 
 
 
data/audios/WolfsburgSpielsalon.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:6c30387f261f1b36c708e3058a967263c859ac07b8fd2ce0c75033a6aa0ed7d7
3
- size 3406683
 
 
 
 
data/audios/athenLeofPosidonosWaves160406.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:60d5e26101bf341afb518e883c657a831dad6f083cd71644a7d4a11842675d4d
3
- size 4808664
 
 
 
 
data/audios/avignonbellG.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:b1151ec48ca237efbff75b9e596efd5532ca5e388226272228f5df8353074829
3
- size 4943069
 
 
 
 
data/audios/boarderdeadmemorialmarchBerlinJune2015.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:688863d7942436ee740af3bc8fde56265949257be3c62d927f349f6625dc336f
3
- size 5620905
 
 
 
 
data/audios/brama.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:a391bb67dec558efc39481059e81c0b063648d68ebd81582a82cce76ab1e666e
3
- size 2165072
 
 
 
 
data/audios/buerknerBackyardRain310511.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:84ca16131b90d27236a2f19709c6f7e47c800cebae048f7e8d1b9ee325ab26ed
3
- size 6004105
 
 
 
 
data/audios/langskomendesneltreinstationdeVink.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:c6f787b77c754be788aceb1dbad23899ce8f4abf26fbe5e8864ec3d894bf6735
3
- size 2969947
 
 
 
 
data/audios/luxembourgHotelParcVentilation050714.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:03be1ca82e07848c36ebc1a3c0dca91bb93a7ecb46971711270dd6757d8a327c
3
- size 6408402
 
 
 
 
data/audios/namakanjeKos16maj20131149.mp3 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:9da5681fdf00a54e7df19360420e1e7f2394713d12e0f32b4749762208b99b89
3
- size 1498427