Spaces:
Sleeping
Sleeping
Update app.py
Browse files5 unmodified lines67891011121314151617183 unmodified lines222324252627285 unmodified lines343536373839404142438 unmodified lines5253545556575810 unmodified lines697071727374757677787980818283848586878889909192939495969798991001011021035 unmodified linesimport gradio as grimport tempfileimport matplotlib.pyplot as pltfrom src.pronunciation_checker import PronunciationCheckerfrom src.audio_preprocessing import assess_pronunciation_qualityfrom datetime import datetime@spaces.GPUdef check_pronunciation(reference_audio, input_audio):timing_results = []# can be moved to src/utils3 unmodified lineslog_timing("Start")# Extract features from both audio fileslayer = 6ref_wav, sr = pronunciation_checker.preprocess_wav(reference_audio)log_timing("Reference Audio Preprocessing")5 unmodified linesraise ValueError("One or both of the waveforms are empty.")# Extract featuresref_features, ref_wav, sr = pronunciation_checker.extract_features(ref_wav, layer)log_timing("Reference Feature Extraction")input_features, comparison_wav, _ = pronunciation_checker.extract_features(comparison_wav, layer)log_timing("Input Feature Extraction")# Compute DTW8 unmodified linesraise ValueError("DTW computation failed.")PronunciationChecker.plot_waveform_with_overlay(ref_wav, sr, dist_matrix, path, "ref")log_timing("Visualization Generation")# Save the visualization to a temporary image file10 unmodified lines# Return the image file path for Gradio to displayreturn tmp_path, quality_score, needs_repeat, timing_analysis# Create Gradio interfacedemo = gr.Interface(fn=check_pronunciation,inputs=[gr.Audio(type="filepath",label="Reference Audio",format="wav",show_download_button=True,),gr.Audio(type="filepath",label="Input Audio",format="wav",show_download_button=True,),],outputs=[gr.Image(type="filepath", label="Pronunciation Comparison"),gr.Number(label="Quality Score"),gr.Textbox(label="Feedback"),gr.Textbox(label="Runtime Analysis")],title="Pronunciation Checker",description="Pronunciation Checker")if __name__ == "__main__":pronunciation_checker = PronunciationChecker("microsoft/wavlm-large")demo.launch(share=True, height=700)5 unmodified lines67891011121314151617181920213 unmodified lines2526272829305 unmodified lines363738394041424344458 unmodified lines5455565758596010 unmodified lines71727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382395 unmodified linesimport gradio as grimport tempfileimport matplotlib.pyplot as pltimport osfrom src.pronunciation_checker import PronunciationCheckerfrom src.audio_preprocessing import assess_pronunciation_qualityfrom datetime import datetimefrom pathlib import Path@spaces.GPUdef check_pronunciation(reference_audio, input_audio, threshold, wavlm_layer):wavlm_layer = int(wavlm_layer)timing_results = []# can be moved to src/utils3 unmodified lineslog_timing("Start")# Extract features from both audio filesref_wav, sr = pronunciation_checker.preprocess_wav(reference_audio)log_timing("Reference Audio Preprocessing")5 unmodified linesraise ValueError("One or both of the waveforms are empty.")# Extract featuresref_features, ref_wav, sr = pronunciation_checker.extract_features(ref_wav, wavlm_layer)log_timing("Reference Feature Extraction")input_features, comparison_wav, _ = pronunciation_checker.extract_features(comparison_wav, wavlm_layer)log_timing("Input Feature Extraction")# Compute DTW8 unmodified linesraise ValueError("DTW computation failed.")PronunciationChecker.plot_waveform_with_overlay(ref_wav, sr, dist_matrix, path, "ref", threshold)log_timing("Visualization Generation")# Save the visualization to a temporary image file10 unmodified lines# Return the image file path for Gradio to displayreturn tmp_path, quality_score, needs_repeat, timing_analysis@spaces.GPUdef run_tests(threshold=0.4, wavlm_layer=24):# Create a directory for storing plots if it doesn't existplots_dir = Path("temp_plots")plots_dir.mkdir(exist_ok=True)benchmark_dir = Path("benchmark")test_cases = []# Clear any old plot filesfor old_plot in plots_dir.glob("*.png"):old_plot.unlink()for test_word_dir in benchmark_dir.iterdir():if test_word_dir.is_dir():word = test_word_dir.nameref_file = test_word_dir / "ref.wav"if not ref_file.exists():test_cases.append({"heading": f"Error: Missing reference file for '{word}'","plot": None,"text": f"Reference file not found for test word '{word}'."})continuefor input_file in test_word_dir.glob("input_*.wav"):if not input_file.exists():test_cases.append({"heading": f"Error: Missing input files for '{word}'","plot": None,"text": f"No input files found for test word '{word}'."})continuetry:# Generate a unique filename for this test's plotplot_filename = f"{word}_{input_file.stem}_{datetime.now().strftime('%H%M%S')}.png"plot_path = plots_dir / plot_filename# Run the pronunciation checkertmp_path, quality_score, needs_repeat, timing_analysis = check_pronunciation(ref_file, input_file, threshold, wavlm_layer)# Move the plot to our persistent directoryif os.path.exists(tmp_path):os.rename(tmp_path, plot_path)test_cases.append({"heading": f"Word: {word}, Input: {input_file.name}","plot": str(plot_path),"text": f"Quality Score: {quality_score:.2f}\n"f"Needs Repeat: {needs_repeat}"})except Exception as e:test_cases.append({"heading": f"Error for '{word}' with '{input_file.name}'","plot": None,"text": str(e)})return test_casesdef display_test_results(threshold, wavlm_layer):test_cases = run_tests(threshold, wavlm_layer)components = []for case in test_cases:components.append(gr.Markdown(f"### {case['heading']}"))if case["plot"]:components.append(gr.Image(case["plot"], type="filepath", label="Plot"))components.append(gr.Textbox(case["text"], label="Details", interactive=False, lines=8))return componentswith gr.Blocks() as demo:with gr.Tabs():with gr.Tab("Pronunciation Checker"):gr.Interface(fn=check_pronunciation,inputs=[gr.Audio(type="filepath",label="Reference Audio",format="wav",show_download_button=True,),gr.Audio(type="filepath",label="Input Audio",format="wav",show_download_button=True,),gr.Slider(minimum=0.0, maximum=1.0, value=0.4, label="Decision Threshold"),gr.Slider(minimum=0, maximum=24, value=24, step=1, label="WavLM Layer"),],outputs=[gr.Image(type="filepath", label="Pronunciation Comparison"),gr.Number(label="Quality Score"),gr.Textbox(label="Feedback"),gr.Textbox(label="Runtime Analysis")],live=False,title="Pronunciation Checker",description="Pronunciation Checker")with gr.Tab("Run Tests"):with gr.Column():gr.Markdown("## Run Automated Tests")with gr.Row():threshold_slider = gr.Slider(minimum=0.0, maximum=1.0, value=0.4, label="Decision Threshold")wavlm_layer_slider = gr.Slider(minimum=0, maximum=24, value=24, step=1, label="WavLM Layer")run_tests_button = gr.Button("Run Tests", variant="primary", interactive=True)# Create static containers for resultswith gr.Column(visible=False) as results_container:# Pre-create components for up to 10 test casestest_case_components = []for i in range(10): # Adjust number based on your needswith gr.Column(visible=False) as case_container:heading = gr.Markdown()details = gr.Markdown()image = gr.Image(width=800)separator = gr.Markdown("---")test_case_components.append({"container": case_container,"heading": heading,"details": details,"image": image,"separator": separator})def format_test_results(threshold, wavlm_layer):test_cases = run_tests(threshold, wavlm_layer)updates = {results_container: gr.update(visible=True)}# Update pre-created components with new resultsfor i, components in enumerate(test_case_components):if i < len(test_cases) and test_cases[i]['plot']:case = test_cases[i]updates[components["container"]] = gr.update(visible=True)updates[components["heading"]] = f"### {case['heading']}"updates[components["details"]] = case['text']updates[components["image"]] = case['plot']else:updates[components["container"]] = gr.update(visible=False)return updates# Update results when button is clickedrun_tests_button.click(fn=format_test_results,inputs=[threshold_slider, wavlm_layer_slider],outputs=[results_container] + [comp for components in test_case_componentsfor comp in [components["container"],components["heading"],components["details"],components["image"]]])if __name__ == "__main__":pronunciation_checker = PronunciationChecker("microsoft/wavlm-large")demo.launch()
app.py+169-33