Spaces:
Sleeping
Sleeping
File size: 21,429 Bytes
b7cfba6 0e332ee b7cfba6 3551c40 b7cfba6 694b9d1 b7cfba6 694b9d1 b7cfba6 694b9d1 b7cfba6 694b9d1 b7cfba6 3551c40 e39fce6 b7cfba6 98172ce b7cfba6 e39fce6 b7cfba6 694b9d1 b7cfba6 1991525 b7cfba6 1991525 b7cfba6 1991525 b7cfba6 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 |
import os
import csv
import json
import random
import base64
import mimetypes
from typing import Any
from pathlib import Path
from dotenv import load_dotenv
import requests
import gradio as gr
from openai import OpenAI
from country_list import countries_for_language
def load_scenarios() -> list[str]:
"""Load scenarios from a CSV file.
Returns:
list[str]: List of scenario descriptions.
"""
# load scenarios from CSV file
with open(Path(__file__).parent / "static" / "scenarios.csv", "r") as f:
reader = csv.reader(f)
_ = next(reader)
scenarios = [row[1] for row in reader if row]
return scenarios
def fetch_user_scenarios(username: str) -> list[int] | None:
"""Fetches the list of scenarios for a given user from the sheet.
Args:
username (str): Username.
Returns:
list[int] | None: List of scenario indices for the user, or None.
"""
try:
response = requests.get(os.getenv("PROGRESS_ENDPOINT_URL", ""), params={"user": username})
response.raise_for_status()
data = response.json()
if data.get("result") == "success":
return data.get("scenarios", [])
else:
print(f"Error fetching user data server: {data.get('error')}")
return None
except Exception as e:
print(f"Request failed: {e}")
return None
def load_user(request: gr.Request) -> tuple[str, list[int]]:
"""Load the user and their scenarios.
Args:
request (gr.Request): Gradio request object containing the username.
Returns:
tuple[str, list[int]]: Tuple containing the username and their scenarios.
"""
username = request.username
user_scenarios = fetch_user_scenarios(username)
return (username, user_scenarios)
def init_interface(
username: str, user_scenarios: list[int]
) -> tuple[dict[str, Any], str, dict[str, Any], str, int, str, str]:
"""Initialize the Gradio interface with the welcome message and scenario.
Args:
username (str): The username of the user.
user_scenarios (list[int]): List of scenario indices the user has completed.
Returns:
tuple: Gradio updates for the interface components.
- loader_ui: Update to hide the loading UI.
- status: Update to show the loader message.
- main_ui: Update to show the main UI.
- welcome_text: Welcome message for the user.
- scenario_idx: Randomly selected scenario index.
- scenario_text: The scenario text for the user to act out.
- progress_bar: Visual progress bar showing completed scenarios.
"""
welcome_msg = f"""## ๐ Welcome {username}!
[Logout](/logout)
### Please follow these steps to contribute to our dataset:
You will be presented with a series of scenarios. For each scenario, please:
1. **Formulate Your Query**: Read the scenario and imagine how you would ask Google Maps about it using voice input. <u>Be as creative as you like</u>! You can try different phrasings, expressions, or styles that feel natural.
2. **Record Your Query**: Once you're ready, hit โrecordโ and at the same time, speak your query to Google Maps. Once recording starts, the scenario will be hidden, so make sure your query is ready in your mind!
3. **Take a Screenshot**: After recording, capture the Google Maps results page that shows the system's response and upload it.
4. **Evaluate the Result**: Tell us whether Google Maps gave a satisfactory response. If not, please explain why.
5. **Provide a Transcript**: Post-edit and submit a written version of what you said in your query.
6. **Share Your Background**: Specify the variety of English that you identify with. Optionally, provide your Australian postcode for additional context.
For more details on the steps, please refer to the [annotation guidelines](https://docs.google.com/document/d/10YfIDRbE5uLEP-rvUPHgFSM5dg8GXxBLZ-i4Y1I_0hw/edit?usp=sharing).
"""
# load all scenarios and filter out those already completed by the user
all_scenarios = load_scenarios()
# handle case where user has completed all scenarios
if len(user_scenarios) >= len(all_scenarios):
complete_msg = (
f"๐ Congratulations {username}! You have completed all scenarios. Thank you for your contributions!"
)
return (
gr.update(visible=True),
complete_msg,
gr.update(visible=False),
None,
None,
None,
None,
)
# select random scenario that the user has not completed
scenario_idx = None
while scenario_idx is None or scenario_idx in user_scenarios:
scenario_idx = random.randint(0, len(all_scenarios) - 1)
scenario_text = all_scenarios[scenario_idx]
print(f"Selected scenario {scenario_idx}: {scenario_text}")
# give visual progress bar
def make_progress_bar(done: int, total: int) -> str:
percent = done / total * 100 if total > 0 else 0
return f"""
<div style="width: 100%; border: 1px solid white; border-radius: 8px; padding: 8px;">
<div style="text-align: center; margin-bottom: 4px; font-weight: bold;">
{int(percent)}% ({done}/{total} scenarios completed)
</div>
<div style="width: 100%; background-color: #eee; border-radius: 5px; overflow: hidden;">
<div style="width: {percent}%; background-color: #4CAF50; height: 20px;"></div>
</div>
</div>
"""
progress_bar = make_progress_bar(len(user_scenarios), len(all_scenarios))
return (
gr.update(visible=False),
None,
gr.update(visible=True),
welcome_msg,
scenario_idx,
scenario_text,
progress_bar,
)
def validate_inputs(
audio: str,
transcript: str,
country: str,
image: str,
expected: str,
satisfiable: str,
actual: str | None = None,
postcode: str | None = None,
) -> tuple[bool, str]:
"""Validate the inputs provided by the user.
Args:
audio (str): Path to the audio file.
transcript (str): Transcription of the audio.
country (str): Country of origin of the user.
image (str): Path to the image file.
expected (str): Expected output from Google Maps.
satisfiable (str): Whether the Google Maps results satisfied the query.
actual (str | None, optional): Actual output from Google Maps, if applicable. Defaults to None.
postcode (str | None, optional): Australian postcode, if provided. Defaults to None.
Returns:
tuple[bool, str]: A tuple containing a boolean indicating success or failure, and a message.
"""
errors = []
if not audio:
errors.append("audio")
if not transcript.strip():
errors.append("transcript")
if not country:
errors.append("country")
if not image:
errors.append("image")
if not expected.strip():
errors.append("expected output")
if not satisfiable:
errors.append("satisfiability")
if satisfiable == "No" and not actual.strip():
errors.append("actual output")
if postcode:
if not postcode.isdigit() or len(postcode) != 4:
errors.append("postcode (must be a 4-digit number)")
elif not (200 <= int(postcode) <= 7999):
errors.append("postcode (must be a valid Australian postcode between 200 and 7999)")
if errors:
return False, f"โ Submission failed. Missing: {', '.join(errors)}"
else:
return True, "โ
Submission successful! Thank you for your contribution."
def encode_file_as_json(path: str, name_override: str = None) -> dict | None:
"""Encode a file as a base64 JSON object.
Args:
path (str): Path to the file to encode.
name_override (str, optional): Filename to override, as temporary audio files default to `test.wav`. Defaults to None.
Returns:
dict | None: A dictionary containing the base64 encoded file, its MIME type, and its name, or None if the file does not exist.
"""
if path and os.path.exists(path):
with open(path, "rb") as f:
file_bytes = f.read()
base64_str = base64.b64encode(file_bytes).decode("utf-8")
mime_type, _ = mimetypes.guess_type(path)
return {
"base64": base64_str,
"type": mime_type or "application/octet-stream",
"name": name_override or os.path.basename(path),
}
return None
def upload_response(
username: str,
scenario_idx: int,
scenario_text: str,
audio_path: str,
transcript: str,
country: str,
image_path: str,
expected: str,
satisfiable: str,
actual: str | None = None,
postcode: str | None = None,
) -> dict:
"""Upload the user's response to the server.
Args:
username (str): Username of the user.
scenario_idx (int): Index of the scenario.
scenario_text (str): Text of the scenario.
audio_path (str): Path to the audio file.
transcript (str): Transcript of the audio.
country (str): Country of origin of the user.
image_path (str): Path to the image file.
expected (str): Expected output from Google Maps.
satisfiable (str): Whether the Google Maps results satisfied the query.
actual (str | None, optional): Actual output from Google Maps, if applicable. Defaults to None.
postcode (str | None, optional): Australian postcode, if provided. Defaults to None.
Returns:
dict: Response from the server indicating success or failure.
"""
image_obj = encode_file_as_json(image_path)
audio_obj = encode_file_as_json(audio_path, name_override=f"{username}_scenario_{scenario_idx}.wav")
payload = {
"username": username,
"scenario_idx": scenario_idx,
"scenario_text": scenario_text,
"audio_url": json.dumps(audio_obj),
"transcript": transcript,
"country": country,
"screenshot_url": json.dumps(image_obj),
"expected": expected,
"satisfiable": satisfiable,
"actual": actual,
"postcode": postcode,
}
try:
response = requests.post(os.getenv("UPLOAD_ENDPOINT_URL", ""), data=payload)
response.raise_for_status()
return response.json()
except requests.RequestException as e:
return {"result": "error", "error": str(e)}
def handle_submission(
username: str,
scenario_idx: int,
scenario_text: str,
audio_path: str,
transcript: str,
country: str,
image_path: str,
expected: str,
satisfiable: str,
user_scenarios: list[int],
actual: str | None = None,
postcode: str | None = None,
) -> list[int]:
"""Handle the submission of user data.
Args:
username (str): Username of the user.
scenario_idx (int): Index of the scenario.
scenario_text (str): Text of the scenario.
audio_path (str): Path to the audio file.
transcript (str): Transcript of the audio.
country (str): Country of origin of the user.
image_path (str): Path to the image file.
expected (str): Expected output from Google Maps.
satisfiable (str): Whether the Google Maps results satisfied the query.
user_scenarios (list[int]): List of scenario indices the user has completed.
actual (str | None, optional): Actual output from Google Maps, if applicable. Defaults to None.
postcode (str | None, optional): Australian postcode, if provided. Defaults to None.
Returns:
list[int]: Updated list of scenario indices the user has completed.
"""
valid, msg = validate_inputs(audio_path, transcript, country, image_path, expected, satisfiable, actual, postcode)
if not valid:
gr.Warning(msg)
return
response = upload_response(
username,
scenario_idx,
scenario_text,
audio_path,
transcript,
country,
image_path,
expected,
satisfiable,
actual,
postcode,
)
print(response)
if response.get("result") == "success":
user_scenarios.append(scenario_idx)
gr.Info(msg)
return user_scenarios
def transcribe_audio(audio_path: str) -> str | None:
"""Transcribe the audio file using OpenAI's Whisper model.
Args:
audio_path (str): Path to the audio file.
Returns:
str | None: Transcription of the audio, or None if an error occurs.
"""
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
if not audio_path or not os.path.exists(audio_path):
return None
audio_bytes = open(audio_path, "rb")
try:
response = client.audio.transcriptions.create(model="whisper-1", file=audio_bytes, language="en")
transcription = getattr(response, "text", "")
return transcription.strip()
except Exception as e:
print(f"Error during transcription: {e}")
return None
if __name__ == "__main__":
load_dotenv()
with gr.Blocks() as demo:
username = gr.State()
user_scenarios = gr.State([])
with gr.Row() as loader_ui:
status = gr.Image(
value=Path(__file__).parent / "static" / "loading.gif",
show_label=False,
interactive=False,
height=50,
show_download_button=False,
)
with gr.Column(visible=False) as main_ui:
gr.Markdown(f"# ๐บ๏ธ SemanticMap Annotation Dashboard")
welcome_text = gr.Markdown()
progress_display = gr.HTML()
with gr.Row():
scenario_idx_input = gr.Textbox(value=None, visible=False)
scenario_input = gr.Textbox(
label="Scenario",
value=None,
interactive=False,
info="Read this scenario. How would you describe it to Google Maps?",
max_lines=6,
)
with gr.Row(visible=False) as upload_ui:
upload_status = gr.Image(
value=Path(__file__).parent / "static" / "loading.gif",
show_label=False,
interactive=False,
height=50,
show_download_button=False,
)
with gr.Row() as form_ui:
with gr.Column():
audio_input = gr.Audio(type="filepath", label="Audio Upload (User Recording)")
transcript_input = gr.Textbox(
label="Transcript",
placeholder="Enter the transcript here...",
info="What did you say in the audio recording?",
)
country_select = gr.Dropdown(
label="Variety of English",
info="Which national variety of English do you identify with?",
choices=sorted([name for _, name in countries_for_language("en")]),
value=None,
interactive=True,
)
postcode_input = gr.Textbox(
label="Australian Postcode (Optional)",
placeholder="Enter your postcode (optional)",
info="If you want to provide your postcode, please enter it here. This is optional.",
)
# transcribe audio after upload
audio_input.input(fn=transcribe_audio, inputs=audio_input, outputs=transcript_input)
# hide scenario text when user starts recording
audio_input.start_recording(fn=lambda: gr.update(visible=False), outputs=scenario_input)
# show scenario text when user stops recording
audio_input.stop_recording(fn=lambda: gr.update(visible=True), outputs=scenario_input)
with gr.Column():
image_input = gr.Image(type="filepath", label="Image Upload (Google Maps Screenshot)", height=600)
expected_output = gr.Textbox(label="What did you expect Google Maps to return?")
satisfiable_radio = gr.Radio(
label="Did the Google Maps results satisfy your query?",
choices=["Yes", "No"],
)
actual_output = gr.Textbox(
label="What did Google Maps return instead?", visible=False, interactive=True
)
satisfiable_radio.change(
fn=lambda x: gr.update(visible=(x == "No")),
inputs=satisfiable_radio,
outputs=actual_output,
)
with gr.Row() as button_row:
skip_button = gr.Button("Skip Scenario", variant="secondary")
submit_button = gr.Button("Submit", variant="primary")
submit_button.click(
# on submit, show the upload status UI and hide the main UI and submit button
fn=lambda: (gr.update(visible=True), gr.update(visible=False), gr.update(visible=False)),
outputs=[upload_ui, form_ui, button_row],
).then(
# then handle the submission
fn=handle_submission,
inputs=[
username,
scenario_idx_input,
scenario_input,
audio_input,
transcript_input,
country_select,
image_input,
expected_output,
satisfiable_radio,
user_scenarios,
actual_output,
postcode_input,
],
outputs=[user_scenarios],
).then(
# then reload the user scenario data, fetching latest progress
init_interface,
inputs=[username, user_scenarios],
outputs=[
loader_ui,
status,
main_ui,
welcome_text,
scenario_idx_input,
scenario_input,
progress_display,
],
).then(
# then, clear form components except for the country select
fn=lambda: (
gr.update(value=None),
gr.update(value=None),
gr.update(value=None),
gr.update(value=None),
gr.update(value=None),
gr.update(value=None),
),
outputs=[audio_input, transcript_input, image_input, expected_output, satisfiable_radio, actual_output],
).then(
# then hide the upload UI and show the main UI and submit button again
fn=lambda: (gr.update(visible=False), gr.update(visible=True), gr.update(visible=True)),
outputs=[upload_ui, form_ui, button_row],
)
skip_button.click(
# on skip, show the upload status UI and hide the main UI and submit button
fn=lambda: (gr.update(visible=True), gr.update(visible=False), gr.update(visible=False)),
outputs=[upload_ui, form_ui, button_row],
).then(
# then reload the user scenario data, fetching latest progress
init_interface,
inputs=[username, user_scenarios],
outputs=[
loader_ui,
status,
main_ui,
welcome_text,
scenario_idx_input,
scenario_input,
progress_display,
],
).then(
# then, clear form components except for the country select
fn=lambda: (
gr.update(value=None),
gr.update(value=None),
gr.update(value=None),
gr.update(value=None),
gr.update(value=None),
gr.update(value=None),
),
outputs=[audio_input, transcript_input, image_input, expected_output, satisfiable_radio, actual_output],
).then(
# then hide the upload UI and show the main UI and submit button again
fn=lambda: (gr.update(visible=False), gr.update(visible=True), gr.update(visible=True)),
outputs=[upload_ui, form_ui, button_row],
)
demo.load(load_user, None, outputs=[username, user_scenarios]).then(
init_interface,
inputs=[username, user_scenarios],
outputs=[loader_ui, status, main_ui, welcome_text, scenario_idx_input, scenario_input, progress_display],
)
users = os.getenv("USERS", "").split(",")
passwords = os.getenv("PASSWORD", "").split(",")
demo.launch(auth=list(zip(users, passwords)), ssr_mode=False)
|