import gradio as gr import soundfile as sf import datetime import numpy as np import hashlib # Initialize a list to store file paths uploaded_files = [] # Function to save audio with label and speaker name def save_audio(audio, dropdown_label, custom_label, speaker_name): global uploaded_files # Determine the final label 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) # Get sample rate and audio data from Gradio sample_rate = audio[0] audio_data = np.array(audio[1]) # Check if the audio length exceeds 1 second max_length = 1 # in seconds if len(audio_data) / sample_rate > max_length: raise gr.Error("Recording is longer than 1 second 💥!", duration=5) # Generate speaker_id using a hash function to ensure consistency speaker_id = hashlib.sha256(speaker_name.encode()).hexdigest()[:8] # Generate file name filename = f"{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}_{speaker_id}_{label}.wav" # Save the audio file in wav format sf.write(filename, audio_data, sample_rate) # Add the new file path to the list of uploaded files uploaded_files.append(filename) # Return the list of all file paths for download return uploaded_files # Interface design using gr.Blocks def create_interface(): with gr.Blocks() as demo: labels = ["Label1", "Label2", "Label3", "Custom"] # Add a "Custom" option for custom label label_dropdown = gr.Dropdown(choices=labels, label="Select Label") custom_label = gr.Textbox(label="Enter Custom Label", visible=False) # Initially hidden # Function to show/hide custom label textbox based on dropdown selection 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(sources="microphone", type="numpy", label="Record Audio") submit_button = gr.Button("Submit") # Create a list to display all uploaded files 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 # Launch the interface if __name__ == "__main__": interface = create_interface() interface.launch()