fpessanha commited on
Commit
c2a9ce1
·
1 Parent(s): def4405

Feat: Update progress bar to contain current index

Browse files
Files changed (1) hide show
  1. app.py +38 -40
app.py CHANGED
@@ -62,20 +62,19 @@ css = """#myProgress {
62
 
63
 
64
  js_progress_bar = """
65
- function move(n_ann, total_ann) {
66
 
67
  var elem = document.getElementById("myBar");
68
  elem.style.width = n_ann/total_ann * 100 + "%";
69
- progressText.innerText = 'Completed: ' + n_ann + ' / ' + total_ann;
70
-
71
  const waveform = document.querySelector('#waveform div');
72
  const shadowRoot = waveform.shadowRoot;
73
  const canvases = shadowRoot.querySelector('.wrapper');
74
 
75
  console.log(canvases.offsetWidth)
76
 
77
- const leftOffsetPct = 0.3;
78
- const widthPct = 0.3;
79
 
80
 
81
  // Create a style element for the shadow DOM
@@ -214,7 +213,7 @@ global file_list
214
  global total_annotations
215
  # Initialize an empty DataFrame to store annotations
216
  annotations = pd.DataFrame(columns=['sample_id', 'sentence', 'emotion', 'confidence', 'comments'])
217
- current_index = {"index": 0} # Dictionary to allow modifying inside functions
218
  password_files = os.getenv("password_files")
219
 
220
  possible_ids = {'Tiger-001': 0, 'Panda-002': 0,
@@ -244,22 +243,22 @@ def get_storage(password):
244
  return files, f"{usage/(1024.0 ** 3):.3f}GB"
245
 
246
 
247
- def load_first_example(participant_id, ann_completed):
248
  """ Loads and first example and updates index"""
249
  global annotations
250
- global current_index
251
  path_ann = f'{persistent_storage}/{participant_id}_annotations.csv'
252
  print(path_ann)
253
  if os.path.exists(path_ann):
254
  annotations = pd.read_csv(path_ann)
255
 
256
- current_index['index'] = len(annotations)
257
  print('path was found')
258
  print(annotations)
259
  print(len(annotations))
260
  ann_completed = gr.Number(len(annotations) - 1, visible=False)
261
  print(len(annotations))
262
- return ann_completed, *load_example(current_index["index"])
263
 
264
  def load_example(index):
265
  """Loads the example in row #index from dataframe file_list.
@@ -274,15 +273,14 @@ def load_example(index):
274
  annotations.iloc[index].to_dict() if index < len(annotations) else {"sample_id": row["sample_id"], "emotion": 'Blank', "confidence": 0,
275
  "comments": ''}
276
  )
277
- print(previous_annotation)
278
- return (sentence, audio_path, previous_annotation['emotion'], previous_annotation['confidence'], current_index['index'], previous_annotation["comments"])
279
 
280
 
281
- def save_annotation(emotions, confidence, comments, participant_id, ann_completed):
282
  """Save the annotation for the current example."""
283
 
284
- idx = current_index["index"]
285
- row = file_list.iloc[idx]
286
  sample_id = row["sample_id"]
287
  sentence = row["sentence"]
288
 
@@ -297,43 +295,44 @@ def save_annotation(emotions, confidence, comments, participant_id, ann_complete
297
 
298
  return ann_completed
299
 
300
- def next_example(emotions, confidence, comments, participant_id, ann_completed):
301
  """Move to the next example."""
302
- global current_index
303
  if emotions == "Blank":
304
  gr.Warning("Please fill out the emotion section. 'Blank' is not a valid emotion.")
305
  else:
306
 
307
- ann_completed = save_annotation(emotions, confidence, comments, participant_id, ann_completed)
308
- if current_index["index"] < len(file_list) - 1:
309
- current_index["index"] += 1
310
- return load_example(current_index["index"])
311
 
312
- def previous_example(emotion, confidence, comments, participant_id, ann_completed):
313
  """Move to the previous example."""
314
- global current_index
315
  if emotion != "Blank":
316
- ann_completed = save_annotation(emotion, confidence, comments, participant_id, ann_completed)
317
- if current_index["index"] > 0:
318
- current_index["index"] -= 1
319
 
320
- return load_example(current_index["index"])
321
 
322
- def deactivate_participant_id(participant_id, lets_go, total, previous_button, next_button, sentence_text, audio_player, emotions, confidence, comments, ann_completed):
323
  global file_list
324
  global total_annotations
325
  if participant_id in possible_ids.keys():
326
  file_list = pd.read_csv(os.path.join(persistent_storage, 'files_to_annotate_2round', f'group_{possible_ids[participant_id]}.csv'))
327
 
328
- participant_id = gr.Textbox(label='What is your participant ID?', value = participant_id, interactive = False)
329
- lets_go = gr.Button("Participant selected!", interactive = False)
330
 
331
  total_annotations = len(file_list)
332
  total = gr.Number(total_annotations, visible=False)
333
 
334
 
335
- ann_completed, sentence, audio_player, emotions, confidence, current_index['index'], comments = load_first_example(participant_id, ann_completed)
336
 
 
 
337
  emotions = gr.Radio(["Blank", "Joy", "Sad", "Angry", "Neutral"], label="Predominant Emotion", value = emotions, visible = True)
338
  confidence = gr.Slider(label="How confident are you that the annotated emotion is present in the recording? (%)", minimum=0, maximum=100, step=10, visible = True, value = confidence)
339
  comments = gr.Textbox(label="Comments", visible =True, value = comments)
@@ -342,7 +341,7 @@ def deactivate_participant_id(participant_id, lets_go, total, previous_button, n
342
 
343
  else:
344
  gr.Warning("Please insert a valid participant ID")
345
- return participant_id, lets_go, total, previous_button, next_button, sentence_text, audio_player, emotions, confidence, comments, ann_completed
346
 
347
  # ===================
348
  # Gradio Interface
@@ -378,12 +377,13 @@ with (gr.Blocks(theme=gr.themes.Soft(), css = css) as demo):
378
  angry_audio = gr.Audio(value=f'{persistent_storage}/emotion_examples/angry_low.wav', label = "Anger (Low Intensity)")
379
  angry_int_audio = gr.Audio(value=f'{persistent_storage}/emotion_examples/angry_intense.wav', label = "Anger (High Intensity)")
380
 
381
- agreement = gr.Checkbox(value = False, label = "I agree", info = "I agree to have my annotations, comments, and questionnaire answers used for research purposes. I understand that any personal information will be anonymized.", interactive = True)
382
 
383
 
384
  with gr.Tab("Annotation Interface"):
385
  ann_completed = gr.Number(0, visible=False)
386
  total = gr.Number(0, visible=False)
 
387
  # Row with progress bar
388
 
389
  gr.HTML("""
@@ -422,20 +422,18 @@ with (gr.Blocks(theme=gr.themes.Soft(), css = css) as demo):
422
  # Go back
423
  previous_button.click(
424
  previous_example,
425
- inputs=[emotions, confidence, comments, participant_id, ann_completed],
426
- outputs=[sentence_text, audio_player, emotions, confidence, ann_completed, comments],
427
- )
428
 
429
  # Go to the next example
430
  next_button.click(
431
  next_example,
432
- inputs=[emotions, confidence, comments, participant_id, ann_completed],
433
- outputs=[sentence_text, audio_player, emotions, confidence, ann_completed, comments],
434
- ).then(None, [], [ann_completed, total], js = js_progress_bar)
435
 
436
  buttons = [previous_button, next_button]
437
  data = [sentence_text, audio_player, emotions, confidence, comments]
438
- lets_go.click(deactivate_participant_id, [participant_id, lets_go, total, *buttons, *data, ann_completed], [participant_id, lets_go, total, *buttons, *data, ann_completed]).then( None, [], [ann_completed, total], js = js_progress_bar)
439
 
440
 
441
  with gr.Tab("Access Files"):
 
62
 
63
 
64
  js_progress_bar = """
65
+ function move(current_index, n_ann, total_ann) {
66
 
67
  var elem = document.getElementById("myBar");
68
  elem.style.width = n_ann/total_ann * 100 + "%";
69
+ progressText.innerText = `${current_index} / ${total_ann} (Completed: ${n_ann})`;
 
70
  const waveform = document.querySelector('#waveform div');
71
  const shadowRoot = waveform.shadowRoot;
72
  const canvases = shadowRoot.querySelector('.wrapper');
73
 
74
  console.log(canvases.offsetWidth)
75
 
76
+ const leftOffsetPct = 0.5;
77
+ const widthPct = 0.5;
78
 
79
 
80
  // Create a style element for the shadow DOM
 
213
  global total_annotations
214
  # Initialize an empty DataFrame to store annotations
215
  annotations = pd.DataFrame(columns=['sample_id', 'sentence', 'emotion', 'confidence', 'comments'])
216
+
217
  password_files = os.getenv("password_files")
218
 
219
  possible_ids = {'Tiger-001': 0, 'Panda-002': 0,
 
243
  return files, f"{usage/(1024.0 ** 3):.3f}GB"
244
 
245
 
246
+ def load_first_example(participant_id, ann_completed, current_index):
247
  """ Loads and first example and updates index"""
248
  global annotations
249
+
250
  path_ann = f'{persistent_storage}/{participant_id}_annotations.csv'
251
  print(path_ann)
252
  if os.path.exists(path_ann):
253
  annotations = pd.read_csv(path_ann)
254
 
255
+ current_index = len(annotations)
256
  print('path was found')
257
  print(annotations)
258
  print(len(annotations))
259
  ann_completed = gr.Number(len(annotations) - 1, visible=False)
260
  print(len(annotations))
261
+ return *load_example(current_index), ann_completed, current_index
262
 
263
  def load_example(index):
264
  """Loads the example in row #index from dataframe file_list.
 
273
  annotations.iloc[index].to_dict() if index < len(annotations) else {"sample_id": row["sample_id"], "emotion": 'Blank', "confidence": 0,
274
  "comments": ''}
275
  )
276
+
277
+ return (sentence, audio_path, previous_annotation['emotion'], previous_annotation['confidence'], previous_annotation["comments"])
278
 
279
 
280
+ def save_annotation(emotions, confidence, comments, participant_id, ann_completed, current_index):
281
  """Save the annotation for the current example."""
282
 
283
+ row = file_list.iloc[current_index]
 
284
  sample_id = row["sample_id"]
285
  sentence = row["sentence"]
286
 
 
295
 
296
  return ann_completed
297
 
298
+ def next_example(emotions, confidence, comments, participant_id, ann_completed, current_index):
299
  """Move to the next example."""
300
+
301
  if emotions == "Blank":
302
  gr.Warning("Please fill out the emotion section. 'Blank' is not a valid emotion.")
303
  else:
304
 
305
+ ann_completed = save_annotation(emotions, confidence, comments, participant_id, ann_completed, current_index)
306
+ if current_index < len(file_list) - 1:
307
+ current_index += 1
308
+ return *load_example(current_index), ann_completed, current_index
309
 
310
+ def previous_example(emotion, confidence, comments, participant_id, ann_completed, current_index):
311
  """Move to the previous example."""
312
+
313
  if emotion != "Blank":
314
+ ann_completed = save_annotation(emotion, confidence, comments, participant_id, ann_completed, current_index)
315
+ if current_index > 0:
316
+ current_index -= 1
317
 
318
+ return *load_example(current_index), ann_completed, current_index
319
 
320
+ def deactivate_participant_id(participant_id, lets_go, total, previous_button, next_button, sentence_text, audio_player, emotions, confidence, comments, ann_completed, current_index):
321
  global file_list
322
  global total_annotations
323
  if participant_id in possible_ids.keys():
324
  file_list = pd.read_csv(os.path.join(persistent_storage, 'files_to_annotate_2round', f'group_{possible_ids[participant_id]}.csv'))
325
 
326
+
 
327
 
328
  total_annotations = len(file_list)
329
  total = gr.Number(total_annotations, visible=False)
330
 
331
 
332
+ sentence, audio_player, emotions, confidence, comments, ann_completed, current_index = load_first_example(participant_id, ann_completed, current_index)
333
 
334
+ participant_id = gr.Textbox(label='What is your participant ID?', value = participant_id, interactive = False)
335
+ lets_go = gr.Button("Participant selected!", interactive = False)
336
  emotions = gr.Radio(["Blank", "Joy", "Sad", "Angry", "Neutral"], label="Predominant Emotion", value = emotions, visible = True)
337
  confidence = gr.Slider(label="How confident are you that the annotated emotion is present in the recording? (%)", minimum=0, maximum=100, step=10, visible = True, value = confidence)
338
  comments = gr.Textbox(label="Comments", visible =True, value = comments)
 
341
 
342
  else:
343
  gr.Warning("Please insert a valid participant ID")
344
+ return participant_id, lets_go, total, previous_button, next_button, sentence_text, audio_player, emotions, confidence, comments, ann_completed, current_index
345
 
346
  # ===================
347
  # Gradio Interface
 
377
  angry_audio = gr.Audio(value=f'{persistent_storage}/emotion_examples/angry_low.wav', label = "Anger (Low Intensity)")
378
  angry_int_audio = gr.Audio(value=f'{persistent_storage}/emotion_examples/angry_intense.wav', label = "Anger (High Intensity)")
379
 
380
+ #agreement = gr.Checkbox(value = False, label = "I agree", info = "I agree to have my annotations, comments, and questionnaire answers used for research purposes. I understand that any personal information will be anonymized.", interactive = True)
381
 
382
 
383
  with gr.Tab("Annotation Interface"):
384
  ann_completed = gr.Number(0, visible=False)
385
  total = gr.Number(0, visible=False)
386
+ current_index = gr.Number(0, visible = False)
387
  # Row with progress bar
388
 
389
  gr.HTML("""
 
422
  # Go back
423
  previous_button.click(
424
  previous_example,
425
+ inputs=[emotions, confidence, comments, participant_id, ann_completed, current_index],
426
+ outputs=[sentence_text, audio_player, emotions, confidence, comments, ann_completed, current_index],).then(None, [], [current_index,ann_completed, total], js = js_progress_bar)
 
427
 
428
  # Go to the next example
429
  next_button.click(
430
  next_example,
431
+ inputs=[emotions, confidence, comments, participant_id, ann_completed, current_index],
432
+ outputs=[sentence_text, audio_player, emotions, confidence, comments, ann_completed, current_index ],).then(None, [], [current_index,ann_completed, total], js = js_progress_bar)
 
433
 
434
  buttons = [previous_button, next_button]
435
  data = [sentence_text, audio_player, emotions, confidence, comments]
436
+ lets_go.click(deactivate_participant_id, [participant_id, lets_go, total, *buttons, *data, ann_completed, current_index], [participant_id, lets_go, total, *buttons, *data, ann_completed, current_index]).then( None, [], [current_index, ann_completed, total], js = js_progress_bar)
437
 
438
 
439
  with gr.Tab("Access Files"):