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

Feat: Add block of color

Browse files
Files changed (2) hide show
  1. app.py +72 -48
  2. requirements.txt +2 -1
app.py CHANGED
@@ -4,7 +4,8 @@ import os
4
  import gradio as gr
5
  from pathlib import Path
6
  from huggingface_hub import login
7
-
 
8
  css = """#myProgress {
9
  width: 100%;
10
  background-color: var(--block-border-color);
@@ -62,48 +63,51 @@ css = """#myProgress {
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
81
- const style = document.createElement('style');
82
- style.textContent = `
83
- .wrapper::after {
84
- content: '';
85
- position: absolute;
86
- top: 0;
87
- left: ${canvases.offsetWidth * leftOffsetPct}px;
88
- width: ${canvases.offsetWidth * widthPct}px;
89
- height: 100%;
90
- background-color: blue;
91
- z-index: 999;
92
- opacity: 0.5;
93
- }
94
-
95
- /* Ensure parent has positioning context */
96
- .wrapper {
97
- position: relative;
98
- }
99
- `;
100
-
101
- // Append the style to the shadow root
102
- shadowRoot.appendChild(style);
103
 
104
- console.log('Added pseudo-element to canvases');
 
 
 
 
 
 
105
 
 
106
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  }
108
  """
109
 
@@ -211,6 +215,7 @@ persistent_storage = Path('/data')
211
  # List of all audio files to annotate
212
  global file_list
213
  global total_annotations
 
214
  # Initialize an empty DataFrame to store annotations
215
  annotations = pd.DataFrame(columns=['sample_id', 'sentence', 'emotion', 'confidence', 'comments'])
216
 
@@ -223,6 +228,18 @@ possible_ids = {'Tiger-001': 0, 'Panda-002': 0,
223
  'Zebra-009': 4, 'Lion-010': 4,
224
  'Cheetah-011': 5, 'Bear-012': 5}
225
 
 
 
 
 
 
 
 
 
 
 
 
 
226
  def get_storage(password):
227
  #source: https://discuss.huggingface.co/t/accessing-data-folder-of-persistent-storage/46681/2
228
  if password == password_files:
@@ -273,8 +290,12 @@ def load_example(index):
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):
@@ -329,7 +350,7 @@ def deactivate_participant_id(participant_id, lets_go, total, previous_button, n
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)
@@ -341,7 +362,7 @@ def deactivate_participant_id(participant_id, lets_go, total, previous_button, n
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
@@ -384,6 +405,9 @@ with (gr.Blocks(theme=gr.themes.Soft(), css = css) as demo):
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("""
@@ -396,7 +420,7 @@ with (gr.Blocks(theme=gr.themes.Soft(), css = css) as demo):
396
 
397
  # Row with audio player
398
  with gr.Row():
399
- audio_player = gr.Audio(value= 'test.mp3', label="Audio", type="filepath", interactive=False, show_download_button = False, show_share_button = False)
400
 
401
  # Hidden row with corresponding sentence
402
  with gr.Row():
@@ -423,17 +447,17 @@ with (gr.Blocks(theme=gr.themes.Soft(), css = css) as demo):
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"):
 
4
  import gradio as gr
5
  from pathlib import Path
6
  from huggingface_hub import login
7
+ from mutagen.mp3 import MP3
8
+ from mutagen.wave import WAVE
9
  css = """#myProgress {
10
  width: 100%;
11
  background-color: var(--block-border-color);
 
63
 
64
 
65
  js_progress_bar = """
66
+ function move(start, end, total_duration, current_index, n_ann, total_ann) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
+ var elem = document.getElementById("myBar");
69
+ elem.style.width = n_ann/total_ann * 100 + "%";
70
+ progressText.innerText = `${current_index} / ${total_ann} (Completed: ${n_ann})`;
71
+
72
+ const waveform = document.querySelector('#audio_to_annotate #waveform div');
73
+ const shadowRoot = waveform.shadowRoot;
74
+ const canvases = shadowRoot.querySelector('.wrapper');
75
 
76
+ console.log(canvases.offsetWidth)
77
 
78
+ const leftOffsetPct = start / total_duration;
79
+ const widthPct = (end - start) / total_duration;
80
+
81
+ // Get CSS variable for background color
82
+ const blockColor = getComputedStyle(document.documentElement)
83
+ .getPropertyValue('--block-title-background-fill')
84
+ .trim() || 'red'; // Default to red if variable is not found
85
+
86
+ // Create a style element for the shadow DOM
87
+ const style = document.createElement('style');
88
+ style.textContent = `
89
+ .wrapper::after {
90
+ content: '';
91
+ position: absolute;
92
+ top: 0;
93
+ left: ${canvases.offsetWidth * leftOffsetPct}px;
94
+ width: ${canvases.offsetWidth * widthPct}px;
95
+ height: 100%;
96
+ background-color: blue;
97
+ z-index: 999;
98
+ opacity: 0.5;
99
+ }
100
+
101
+ /* Ensure parent has positioning context */
102
+ .wrapper {
103
+ position: relative;
104
+ }
105
+ `;
106
+
107
+ // Append the style to the shadow root
108
+ shadowRoot.appendChild(style);
109
+
110
+ console.log(start + ' ' + end + ' ' + total_duration);
111
  }
112
  """
113
 
 
215
  # List of all audio files to annotate
216
  global file_list
217
  global total_annotations
218
+
219
  # Initialize an empty DataFrame to store annotations
220
  annotations = pd.DataFrame(columns=['sample_id', 'sentence', 'emotion', 'confidence', 'comments'])
221
 
 
228
  'Zebra-009': 4, 'Lion-010': 4,
229
  'Cheetah-011': 5, 'Bear-012': 5}
230
 
231
+
232
+
233
+ def get_audio_duration(file_path):
234
+ if file_path.lower().endswith('.mp3'):
235
+ audio = MP3(file_path)
236
+ elif file_path.lower().endswith(('.wav', '.wave')):
237
+ audio = WAVE(file_path)
238
+ else:
239
+ raise ValueError("Unsupported file format")
240
+
241
+ return audio.info.length # Duration in seconds
242
+
243
  def get_storage(password):
244
  #source: https://discuss.huggingface.co/t/accessing-data-folder-of-persistent-storage/46681/2
245
  if password == password_files:
 
290
  annotations.iloc[index].to_dict() if index < len(annotations) else {"sample_id": row["sample_id"], "emotion": 'Blank', "confidence": 0,
291
  "comments": ''}
292
  )
293
+
294
+ start = row['start']
295
+ end = row['end']
296
+ duration = get_audio_duration(audio_path)
297
+ print(f'{start} {end} {duration}')
298
+ return (sentence, audio_path, previous_annotation['emotion'], previous_annotation['confidence'], previous_annotation["comments"], start, end, duration)
299
 
300
 
301
  def save_annotation(emotions, confidence, comments, participant_id, ann_completed, current_index):
 
350
  total = gr.Number(total_annotations, visible=False)
351
 
352
 
353
+ sentence, audio_player, emotions, confidence, comments, start, end, duration, ann_completed, current_index = load_first_example(participant_id, ann_completed, current_index)
354
 
355
  participant_id = gr.Textbox(label='What is your participant ID?', value = participant_id, interactive = False)
356
  lets_go = gr.Button("Participant selected!", interactive = False)
 
362
 
363
  else:
364
  gr.Warning("Please insert a valid participant ID")
365
+ return participant_id, lets_go, total, previous_button, next_button, sentence_text, audio_player, emotions, confidence, comments, start, end, duration, ann_completed, current_index
366
 
367
  # ===================
368
  # Gradio Interface
 
405
  ann_completed = gr.Number(0, visible=False)
406
  total = gr.Number(0, visible=False)
407
  current_index = gr.Number(0, visible = False)
408
+ start = gr.Number(0, visible = False)
409
+ end = gr.Number(0, visible = False)
410
+ duration = gr.Number(0, visible = False)
411
  # Row with progress bar
412
 
413
  gr.HTML("""
 
420
 
421
  # Row with audio player
422
  with gr.Row():
423
+ audio_player = gr.Audio(value= 'test.mp3', label="Audio", type="filepath", interactive=False, show_download_button = False, show_share_button = False, elem_id = "audio_to_annotate")
424
 
425
  # Hidden row with corresponding sentence
426
  with gr.Row():
 
447
  previous_button.click(
448
  previous_example,
449
  inputs=[emotions, confidence, comments, participant_id, ann_completed, current_index],
450
+ outputs=[sentence_text, audio_player, emotions, confidence, comments, start, end, duration, ann_completed, current_index],).then(None, [], [start, end, duration, current_index,ann_completed, total], js = js_progress_bar)
451
 
452
  # Go to the next example
453
  next_button.click(
454
  next_example,
455
  inputs=[emotions, confidence, comments, participant_id, ann_completed, current_index],
456
+ outputs=[sentence_text, audio_player, emotions, confidence, comments, start, end, duration, ann_completed, current_index],).then(None, [], [start, end, duration, current_index,ann_completed, total], js = js_progress_bar)
457
 
458
  buttons = [previous_button, next_button]
459
  data = [sentence_text, audio_player, emotions, confidence, comments]
460
+ lets_go.click(deactivate_participant_id, [participant_id, lets_go, total, *buttons, *data, ann_completed, current_index], [participant_id, lets_go, total, *buttons, *data, start, end, duration, ann_completed, current_index]).then( None, [], [start, end, duration, current_index, ann_completed, total], js = js_progress_bar)
461
 
462
 
463
  with gr.Tab("Access Files"):
requirements.txt CHANGED
@@ -1 +1,2 @@
1
- openpyxl
 
 
1
+ openpyxl
2
+ mutagen