intersteller2887 commited on
Commit
03c4a10
·
verified ·
1 Parent(s): 28535b3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -74
app.py CHANGED
@@ -150,18 +150,26 @@ def show_sample_page_and_init(age, gender, education, education_other, user_data
150
  final_edu = education_other if education == "其他(请注明)" else education
151
  user_data.update({"age": age, "gender": gender, "education": final_edu})
152
  first_dim_title = DIMENSION_TITLES[0]
153
- return gr.update(visible=False), gr.update(visible=True), user_data, first_dim_title
 
 
 
 
 
154
 
155
  def update_sample_view(dimension_title):
156
  dim_data = next((d for d in DIMENSIONS_DATA if d["title"] == dimension_title), None)
157
  if dim_data:
158
- return (
159
- gr.update(value=dim_data["audio"]),
160
- gr.update(value=dim_data["desc"]),
161
- gr.update(choices=dim_data["sub_dims"], value=[], interactive=True),
162
- gr.update(value=dim_data["reference"])
163
- )
164
- return gr.update(), gr.update(), gr.update(), gr.update()
 
 
 
165
 
166
  def update_test_dimension_view(d_idx, selections):
167
  dimension = DIMENSIONS_DATA[d_idx]
@@ -204,10 +212,9 @@ def init_test_question(user_data, q_idx):
204
  gr.update(value=progress_q),
205
  dim_title_update,
206
  gr.update(value=question['audio']),
207
- gr.update(value=question['desc']),
208
  prev_btn_update,
209
  next_btn_update,
210
- gr.update(interactive=False),
211
  gr.update(interactive=False),
212
  ) + tuple(slider_updates)
213
 
@@ -223,15 +230,14 @@ def navigate_dimensions(direction, q_idx, d_idx, selections, *slider_values):
223
  return (
224
  gr.update(visible=False),
225
  gr.update(visible=True),
226
- q_idx, d_idx, selections,
227
  gr.update(),
228
- gr.update(value=""),
229
  gr.update(),
230
  gr.update(),
231
  gr.update(interactive=True),
232
- gr.update(interactive=True),
233
  gr.update(interactive=False),
234
- gr.update(value="下一维度", interactive=False),
 
235
  ) + (gr.update(),) * MAX_SUB_DIMS
236
 
237
  else:
@@ -246,8 +252,7 @@ def navigate_dimensions(direction, q_idx, d_idx, selections, *slider_values):
246
  dim_title_update,
247
  gr.update(),
248
  gr.update(),
249
- gr.update(interactive=False),
250
- gr.update(interactive=False),
251
  prev_btn_update,
252
  next_btn_update,
253
  ) + tuple(slider_updates)
@@ -277,38 +282,24 @@ def submit_question_and_advance(q_idx, d_idx, selections, final_choice, all_resu
277
  for sub_dim, score in dim_data.items():
278
  result_str += f" - *{sub_dim[:20]}...*: {score}/5\n"
279
 
280
- # This function now handles the upload to Hugging Face
281
  save_all_results_to_file(all_results, user_data)
282
 
283
  return (
284
  gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=True),
285
  q_idx, d_idx, {},
286
- gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(),
287
  gr.update(), gr.update(),
288
  ) + (gr.update(),) * MAX_SUB_DIMS + (all_results, result_str)
289
 
290
- # MODIFIED FUNCTION TO SAVE TO HUGGING FACE DATASET
291
  def save_all_results_to_file(all_results, user_data):
292
- """
293
- Packages results and uploads them as a single JSON file to a Hugging Face Dataset.
294
- """
295
- # IMPORTANT: Change this to your Hugging Face username and dataset repo name
296
- repo_id = "intersteller2887/Turing-test-dataset"
297
-
298
- # Create a unique filename for the submission
299
  username = user_data.get("age", "user")
300
  filename = f"submission_{username}_{pd.Timestamp.now().strftime('%Y%m%d_%H%M%S')}.json"
301
-
302
- # Package all data into a single dictionary
303
  final_data_package = {
304
  "user_info": user_data,
305
  "results": all_results
306
  }
307
-
308
- # Convert the dictionary to a JSON string in memory
309
  json_string = json.dumps(final_data_package, ensure_ascii=False, indent=4)
310
-
311
- # Get the Hugging Face token from the environment secrets
312
  hf_token = os.getenv("HF_TOKEN")
313
 
314
  if not hf_token:
@@ -316,13 +307,10 @@ def save_all_results_to_file(all_results, user_data):
316
  return
317
 
318
  try:
319
- # Instantiate the HfApi client
320
  api = HfApi()
321
-
322
- # Upload the JSON string as a file to the specified dataset repository
323
  api.upload_file(
324
  path_or_fileobj=bytes(json_string, "utf-8"),
325
- path_in_repo=f"submissions/{filename}", # We recommend saving to a subfolder
326
  repo_id=repo_id,
327
  repo_type="dataset",
328
  token=hf_token,
@@ -333,30 +321,32 @@ def save_all_results_to_file(all_results, user_data):
333
  except Exception as e:
334
  print(f"Error uploading to Hugging Face Hub: {e}")
335
 
336
-
337
- def toggle_reference_view(current):
338
- if current == "参考": return gr.update(visible=False), gr.update(visible=True), gr.update(value="返回")
339
- else: return gr.update(visible=True), gr.update(visible=False), gr.update(value="参考")
340
-
341
  def back_to_welcome():
342
  return (
343
- gr.update(visible=True), {}, 0, 0, {}, [],
344
- gr.update(visible=False), gr.update(visible=False), gr.update(visible=False),
345
- gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
 
 
 
 
 
 
 
 
 
346
  )
347
 
348
  # ==============================================================================
349
  # Gradio 界面定义 (Gradio UI Definition)
350
  # ==============================================================================
351
  with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {max-width: 960px !important}") as demo:
352
- # --- 状态变量 (State Variables) ---
353
  user_data_state = gr.State({})
354
  current_question_index = gr.State(0)
355
  current_test_dimension_index = gr.State(0)
356
  current_question_selections = gr.State({})
357
  test_results = gr.State([])
358
 
359
- # --- 页面 (Pages) ---
360
  welcome_page = gr.Column(visible=True)
361
  info_page = gr.Column(visible=False)
362
  sample_page = gr.Column(visible=False)
@@ -383,28 +373,22 @@ with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {max-width: 960px
383
  submit_info_btn = gr.Button("提交并开始学习样例", variant="primary", interactive=False)
384
 
385
  with sample_page:
386
- gr.Markdown("## 样例分析\n请选择一个维度进行学习。所有维度共用同一个样例音频。")
387
  sample_dimension_selector = gr.Radio(DIMENSION_TITLES, label="选择学习维度", value=DIMENSION_TITLES[0])
388
  with gr.Row():
389
  with gr.Column(scale=1):
390
  sample_audio = gr.Audio(label="样例音频", value=DIMENSIONS_DATA[0]["audio"])
391
- sample_desc = gr.Textbox(label="文本描述", interactive=False, value=DIMENSIONS_DATA[0]["desc"])
392
  with gr.Column(scale=2):
393
- with gr.Column(visible=True) as interactive_view:
394
- interactive_checkbox_group = gr.CheckboxGroup(label="维度特征", choices=DIMENSIONS_DATA[0]["sub_dims"], interactive=True)
395
- with gr.Column(visible=False) as reference_view:
396
- gr.Markdown("### 参考答案解析")
397
- reference_text = gr.Markdown(value=DIMENSIONS_DATA[0]["reference"])
398
- reference_btn = gr.Button("参考")
399
  go_to_pretest_btn = gr.Button("我明白了,开始测试", variant="primary")
400
 
401
  with pretest_page:
402
  gr.Markdown("## 测试说明\n"
403
- "- 对于每一道题,你都需要对全部 **5 个维度** 进行评估。\n"
404
- "- 在每个维度下,请为出现的每个特征 **从0到5打分**。\n"
405
-
406
- "- 完成5个维度的打分后,你将需要做出“人类”或“机器人”的 **最终判断**。\n"
407
- "- 你可以使用“上一维度”和“下一维度”按钮在5个维度间自由切换和修改分数。")
408
  go_to_test_btn = gr.Button("开始测试", variant="primary")
409
 
410
  with test_page:
@@ -412,11 +396,8 @@ with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {max-width: 960px
412
  question_progress_text = gr.Markdown()
413
  test_dimension_title = gr.Markdown()
414
  test_audio = gr.Audio(label="测试音频")
415
- test_desc = gr.Textbox(label="文本描述", interactive=False)
416
  gr.Markdown("--- \n ### 请为以下特征打分 (0-5分)")
417
-
418
  test_sliders = [gr.Slider(minimum=0, maximum=5, step=1, label=f"Sub-dim {i+1}", visible=False, interactive=True) for i in range(MAX_SUB_DIMS)]
419
-
420
  with gr.Row():
421
  prev_dim_btn = gr.Button("上一维度")
422
  next_dim_btn = gr.Button("下一维度", variant="primary")
@@ -424,7 +405,7 @@ with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {max-width: 960px
424
  with final_judgment_page:
425
  gr.Markdown("## 最终判断")
426
  gr.Markdown("您已完成对所有维度的评分。请根据您的综合印象,做出最终判断。")
427
- final_human_robot_radio = gr.Radio(["👤 人类", "🤖 机器人"], label="请判断回应者类型 (必填)", interactive=False)
428
  submit_final_answer_btn = gr.Button("提交本题答案", variant="primary", interactive=False)
429
 
430
  with result_page:
@@ -435,10 +416,12 @@ with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {max-width: 960px
435
  # ==============================================================================
436
  # 事件绑定 (Event Binding) & IO 列表定义
437
  # ==============================================================================
 
 
438
  test_init_outputs = [
439
  pretest_page, test_page, final_judgment_page, result_page,
440
  current_question_index, current_test_dimension_index, current_question_selections,
441
- question_progress_text, test_dimension_title, test_audio, test_desc,
442
  prev_dim_btn, next_dim_btn,
443
  final_human_robot_radio, submit_final_answer_btn,
444
  ] + test_sliders
@@ -447,7 +430,7 @@ with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {max-width: 960px
447
  nav_outputs = [
448
  test_page, final_judgment_page,
449
  current_question_index, current_test_dimension_index, current_question_selections,
450
- question_progress_text, test_dimension_title, test_audio, test_desc,
451
  final_human_robot_radio, submit_final_answer_btn,
452
  prev_dim_btn, next_dim_btn,
453
  ] + test_sliders
@@ -461,11 +444,17 @@ with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {max-width: 960px
461
 
462
  education_input.change(fn=toggle_education_other, inputs=education_input, outputs=education_other_input)
463
 
464
- submit_info_btn.click(fn=show_sample_page_and_init, inputs=[age_input, gender_input, education_input, education_other_input, user_data_state], outputs=[info_page, sample_page, user_data_state, sample_dimension_selector])
465
-
466
- sample_dimension_selector.change(fn=update_sample_view, inputs=sample_dimension_selector, outputs=[sample_audio, sample_desc, interactive_checkbox_group, reference_text])
 
 
467
 
468
- reference_btn.click(fn=toggle_reference_view, inputs=reference_btn, outputs=[interactive_view, reference_view, reference_btn])
 
 
 
 
469
 
470
  go_to_pretest_btn.click(lambda: (gr.update(visible=False), gr.update(visible=True)), outputs=[sample_page, pretest_page])
471
 
@@ -485,6 +474,12 @@ with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {max-width: 960px
485
  inputs=nav_inputs, outputs=nav_outputs
486
  )
487
 
 
 
 
 
 
 
488
  submit_final_answer_btn.click(
489
  fn=submit_question_and_advance,
490
  inputs=[current_question_index, current_test_dimension_index, current_question_selections, final_human_robot_radio, test_results, user_data_state],
@@ -497,13 +492,10 @@ with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {max-width: 960px
497
  # 程序入口 (Entry Point)
498
  # ==============================================================================
499
  if __name__ == "__main__":
500
- """if not os.path.exists("audio"):
501
- os.makedirs("audio")"""
502
- # A quick check to see if we're in a deployed Space, to avoid local errors.
503
  if "SPACE_ID" in os.environ:
504
  print("Running in a Hugging Face Space, checking for audio files...")
505
- # In a real deployment, you'd ensure the audio files are in the repo.
506
- # This is just a placeholder check.
507
  all_files = [q["audio"] for q in QUESTION_SET] + [d["audio"] for d in DIMENSIONS_DATA]
508
  for audio_file in set(all_files):
509
  if not os.path.exists(audio_file):
 
150
  final_edu = education_other if education == "其他(请注明)" else education
151
  user_data.update({"age": age, "gender": gender, "education": final_edu})
152
  first_dim_title = DIMENSION_TITLES[0]
153
+
154
+ initial_updates = update_sample_view(first_dim_title)
155
+
156
+ return [
157
+ gr.update(visible=False), gr.update(visible=True), user_data, first_dim_title
158
+ ] + initial_updates
159
 
160
  def update_sample_view(dimension_title):
161
  dim_data = next((d for d in DIMENSIONS_DATA if d["title"] == dimension_title), None)
162
  if dim_data:
163
+ audio_update = gr.update(value=dim_data["audio"])
164
+ slider_updates = []
165
+ for i in range(MAX_SUB_DIMS):
166
+ if i < len(dim_data['sub_dims']):
167
+ slider_updates.append(gr.update(visible=True, label=dim_data['sub_dims'][i], value=0))
168
+ else:
169
+ slider_updates.append(gr.update(visible=False, value=0))
170
+ return [audio_update] + slider_updates
171
+
172
+ return [gr.update()] + [gr.update()] * MAX_SUB_DIMS
173
 
174
  def update_test_dimension_view(d_idx, selections):
175
  dimension = DIMENSIONS_DATA[d_idx]
 
212
  gr.update(value=progress_q),
213
  dim_title_update,
214
  gr.update(value=question['audio']),
 
215
  prev_btn_update,
216
  next_btn_update,
217
+ gr.update(value=None), # BUG FIX: Changed from "" to None to correctly clear the radio button
218
  gr.update(interactive=False),
219
  ) + tuple(slider_updates)
220
 
 
230
  return (
231
  gr.update(visible=False),
232
  gr.update(visible=True),
233
+ q_idx, new_d_idx, selections,
234
  gr.update(),
 
235
  gr.update(),
236
  gr.update(),
237
  gr.update(interactive=True),
 
238
  gr.update(interactive=False),
239
+ gr.update(interactive=False),
240
+ gr.update(interactive=False),
241
  ) + (gr.update(),) * MAX_SUB_DIMS
242
 
243
  else:
 
252
  dim_title_update,
253
  gr.update(),
254
  gr.update(),
255
+ gr.update(),
 
256
  prev_btn_update,
257
  next_btn_update,
258
  ) + tuple(slider_updates)
 
282
  for sub_dim, score in dim_data.items():
283
  result_str += f" - *{sub_dim[:20]}...*: {score}/5\n"
284
 
 
285
  save_all_results_to_file(all_results, user_data)
286
 
287
  return (
288
  gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=True),
289
  q_idx, d_idx, {},
290
+ gr.update(), gr.update(), gr.update(), gr.update(), gr.update(),
291
  gr.update(), gr.update(),
292
  ) + (gr.update(),) * MAX_SUB_DIMS + (all_results, result_str)
293
 
 
294
  def save_all_results_to_file(all_results, user_data):
295
+ repo_id = "Hu6ery/Turing-Test-Submissions"
 
 
 
 
 
 
296
  username = user_data.get("age", "user")
297
  filename = f"submission_{username}_{pd.Timestamp.now().strftime('%Y%m%d_%H%M%S')}.json"
 
 
298
  final_data_package = {
299
  "user_info": user_data,
300
  "results": all_results
301
  }
 
 
302
  json_string = json.dumps(final_data_package, ensure_ascii=False, indent=4)
 
 
303
  hf_token = os.getenv("HF_TOKEN")
304
 
305
  if not hf_token:
 
307
  return
308
 
309
  try:
 
310
  api = HfApi()
 
 
311
  api.upload_file(
312
  path_or_fileobj=bytes(json_string, "utf-8"),
313
+ path_in_repo=f"data/{filename}",
314
  repo_id=repo_id,
315
  repo_type="dataset",
316
  token=hf_token,
 
321
  except Exception as e:
322
  print(f"Error uploading to Hugging Face Hub: {e}")
323
 
 
 
 
 
 
324
  def back_to_welcome():
325
  return (
326
+ gr.update(visible=True), # welcome_page
327
+ gr.update(visible=False), # info_page
328
+ gr.update(visible=False), # sample_page
329
+ gr.update(visible=False), # pretest_page
330
+ gr.update(visible=False), # test_page
331
+ gr.update(visible=False), # final_judgment_page
332
+ gr.update(visible=False), # result_page
333
+ {}, # user_data_state
334
+ 0, # current_question_index
335
+ 0, # current_test_dimension_index
336
+ {}, # current_question_selections
337
+ [] # test_results
338
  )
339
 
340
  # ==============================================================================
341
  # Gradio 界面定义 (Gradio UI Definition)
342
  # ==============================================================================
343
  with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {max-width: 960px !important}") as demo:
 
344
  user_data_state = gr.State({})
345
  current_question_index = gr.State(0)
346
  current_test_dimension_index = gr.State(0)
347
  current_question_selections = gr.State({})
348
  test_results = gr.State([])
349
 
 
350
  welcome_page = gr.Column(visible=True)
351
  info_page = gr.Column(visible=False)
352
  sample_page = gr.Column(visible=False)
 
373
  submit_info_btn = gr.Button("提交并开始学习样例", variant="primary", interactive=False)
374
 
375
  with sample_page:
376
+ gr.Markdown("## 样例分析\n请选择一个维度进行学习和打分练习。所有维度共用同一个样例音频。")
377
  sample_dimension_selector = gr.Radio(DIMENSION_TITLES, label="选择学习维度", value=DIMENSION_TITLES[0])
378
  with gr.Row():
379
  with gr.Column(scale=1):
380
  sample_audio = gr.Audio(label="样例音频", value=DIMENSIONS_DATA[0]["audio"])
 
381
  with gr.Column(scale=2):
382
+ gr.Markdown("#### 请为以下特征打分 (0-5分)")
383
+ sample_sliders = [gr.Slider(minimum=0, maximum=5, step=1, label=f"Sub-dim {i+1}", visible=False, interactive=True) for i in range(MAX_SUB_DIMS)]
 
 
 
 
384
  go_to_pretest_btn = gr.Button("我明白了,开始测试", variant="primary")
385
 
386
  with pretest_page:
387
  gr.Markdown("## 测试说明\n"
388
+ "- 对于每一道题,你都需要对全部 **5 个维度** 进行评估。\n"
389
+ "- 在每个维度下,请为出现的每个特征 **从0到5打分**。\n"
390
+ "- 完成5个维度的打分后��你将需要做出“人类”或“机器人”的 **最终判断**。\n"
391
+ "- 你可以使用“上一维度”和“下一维度”按钮在5个维度间自由切换和修改分数。")
 
392
  go_to_test_btn = gr.Button("开始测试", variant="primary")
393
 
394
  with test_page:
 
396
  question_progress_text = gr.Markdown()
397
  test_dimension_title = gr.Markdown()
398
  test_audio = gr.Audio(label="测试音频")
 
399
  gr.Markdown("--- \n ### 请为以下特征打分 (0-5分)")
 
400
  test_sliders = [gr.Slider(minimum=0, maximum=5, step=1, label=f"Sub-dim {i+1}", visible=False, interactive=True) for i in range(MAX_SUB_DIMS)]
 
401
  with gr.Row():
402
  prev_dim_btn = gr.Button("上一维度")
403
  next_dim_btn = gr.Button("下一维度", variant="primary")
 
405
  with final_judgment_page:
406
  gr.Markdown("## 最终判断")
407
  gr.Markdown("您已完成对所有维度的评分。请根据您的综合印象,做出最终判断。")
408
+ final_human_robot_radio = gr.Radio(["👤 人类", "🤖 机器人"], label="请判断回应者类型 (必填)")
409
  submit_final_answer_btn = gr.Button("提交本题答案", variant="primary", interactive=False)
410
 
411
  with result_page:
 
416
  # ==============================================================================
417
  # 事件绑定 (Event Binding) & IO 列表定义
418
  # ==============================================================================
419
+ sample_init_outputs = [info_page, sample_page, user_data_state, sample_dimension_selector, sample_audio] + sample_sliders
420
+
421
  test_init_outputs = [
422
  pretest_page, test_page, final_judgment_page, result_page,
423
  current_question_index, current_test_dimension_index, current_question_selections,
424
+ question_progress_text, test_dimension_title, test_audio,
425
  prev_dim_btn, next_dim_btn,
426
  final_human_robot_radio, submit_final_answer_btn,
427
  ] + test_sliders
 
430
  nav_outputs = [
431
  test_page, final_judgment_page,
432
  current_question_index, current_test_dimension_index, current_question_selections,
433
+ question_progress_text, test_dimension_title, test_audio,
434
  final_human_robot_radio, submit_final_answer_btn,
435
  prev_dim_btn, next_dim_btn,
436
  ] + test_sliders
 
444
 
445
  education_input.change(fn=toggle_education_other, inputs=education_input, outputs=education_other_input)
446
 
447
+ submit_info_btn.click(
448
+ fn=show_sample_page_and_init,
449
+ inputs=[age_input, gender_input, education_input, education_other_input, user_data_state],
450
+ outputs=sample_init_outputs
451
+ )
452
 
453
+ sample_dimension_selector.change(
454
+ fn=update_sample_view,
455
+ inputs=sample_dimension_selector,
456
+ outputs=[sample_audio] + sample_sliders
457
+ )
458
 
459
  go_to_pretest_btn.click(lambda: (gr.update(visible=False), gr.update(visible=True)), outputs=[sample_page, pretest_page])
460
 
 
474
  inputs=nav_inputs, outputs=nav_outputs
475
  )
476
 
477
+ final_human_robot_radio.change(
478
+ fn=lambda choice: gr.update(interactive=bool(choice)),
479
+ inputs=final_human_robot_radio,
480
+ outputs=submit_final_answer_btn
481
+ )
482
+
483
  submit_final_answer_btn.click(
484
  fn=submit_question_and_advance,
485
  inputs=[current_question_index, current_test_dimension_index, current_question_selections, final_human_robot_radio, test_results, user_data_state],
 
492
  # 程序入口 (Entry Point)
493
  # ==============================================================================
494
  if __name__ == "__main__":
495
+ if not os.path.exists("audio"):
496
+ os.makedirs("audio")
 
497
  if "SPACE_ID" in os.environ:
498
  print("Running in a Hugging Face Space, checking for audio files...")
 
 
499
  all_files = [q["audio"] for q in QUESTION_SET] + [d["audio"] for d in DIMENSIONS_DATA]
500
  for audio_file in set(all_files):
501
  if not os.path.exists(audio_file):