| import gradio as gr |
| import soundfile as sf |
| import datetime |
| import numpy as np |
| import hashlib |
|
|
| |
| uploaded_files = [] |
|
|
| |
| def save_audio(audio, dropdown_label, custom_label, speaker_name): |
| global uploaded_files |
| |
| |
| label = custom_label if dropdown_label == "Custom" else dropdown_label |
|
|
| if not label: |
| raise gr.Error("Label cannot be empty 💥!", duration=5) |
| if not speaker_name: |
| raise gr.Error("User name cannot be empty 💥!", duration=5) |
|
|
| |
| sample_rate = audio[0] |
| audio_data = np.array(audio[1]) |
|
|
| |
| max_length = 1 |
| if len(audio_data) / sample_rate > max_length: |
| raise gr.Error("Recording is longer than 1 second 💥!", duration=5) |
|
|
| |
| speaker_id = hashlib.sha256(speaker_name.encode()).hexdigest()[:8] |
|
|
| |
| filename = f"{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}_{speaker_id}_{label}.wav" |
|
|
| |
| sf.write(filename, audio_data, sample_rate) |
|
|
| |
| uploaded_files.append(filename) |
|
|
| |
| return uploaded_files |
|
|
| |
| def create_interface(): |
| with gr.Blocks() as demo: |
| labels = ["Label1", "Label2", "Label3", "Custom"] |
| label_dropdown = gr.Dropdown(choices=labels, label="Select Label") |
| custom_label = gr.Textbox(label="Enter Custom Label", visible=False) |
|
|
| |
| def toggle_custom_label(selected_label): |
| return gr.update(visible=True) if selected_label == "Custom" else gr.update(visible=False) |
|
|
| label_dropdown.change(toggle_custom_label, inputs=label_dropdown, outputs=custom_label) |
|
|
| speaker_name = gr.Textbox(label="Enter User Name") |
| audio = gr.Audio(source="microphone", type="numpy", label="Record Audio") |
|
|
| submit_button = gr.Button("Submit") |
|
|
| |
| file_list = gr.Files(label="Download your recordings") |
|
|
| submit_button.click( |
| fn=save_audio, |
| inputs=[audio, label_dropdown, custom_label, speaker_name], |
| outputs=file_list, |
| ) |
|
|
| return demo |
|
|
| |
| if __name__ == "__main__": |
| interface = create_interface() |
| interface.launch() |
|
|