Spaces:
Sleeping
Sleeping
import gradio as gr | |
from transformers import pipeline | |
import os | |
# Load the model | |
pipe = pipeline("audio-classification", model="dima806/english_accents_classification") | |
def classify_accent(audio): | |
try: | |
result = pipe(audio) | |
if not result: | |
return "<p style='color: red; font-weight: bold;'>⚠️ No prediction returned. Please try a different audio file.</p>" | |
table = """ | |
<table style='width: 100%; border-collapse: collapse; font-family: Arial, sans-serif; margin-top: 1em;'> | |
<thead> | |
<tr style='border-bottom: 2px solid #4CAF50; background-color: #f2f2f2;'> | |
<th style='text-align:left; padding: 8px; font-size: 1.1em; color: #333;'>Accent</th> | |
<th style='text-align:left; padding: 8px; font-size: 1.1em; color: #333;'>Confidence</th> | |
</tr> | |
</thead> | |
<tbody> | |
""" | |
for i, r in enumerate(result): | |
label = r['label'].capitalize() | |
score = f"{r['score'] * 100:.2f}%" | |
if i == 0: | |
row = f""" | |
<tr style='background-color:#d4edda; font-weight: bold; color: #155724;'> | |
<td style='padding: 8px; border-bottom: 1px solid #c3e6cb;'>{label}</td> | |
<td style='padding: 8px; border-bottom: 1px solid #c3e6cb;'>{score}</td> | |
</tr> | |
""" | |
else: | |
row = f""" | |
<tr style='color: #333;'> | |
<td style='padding: 8px; border-bottom: 1px solid #ddd;'>{label}</td> | |
<td style='padding: 8px; border-bottom: 1px solid #ddd;'>{score}</td> | |
</tr> | |
""" | |
table += row | |
table += "</tbody></table>" | |
top_result = result[0] | |
return f""" | |
<h3 style='color: #2E7D32; font-family: Arial, sans-serif;'> | |
🎤 Predicted Accent: <span style='font-weight:bold'>{top_result['label'].capitalize()}</span> | |
</h3> | |
{table} | |
""" | |
except Exception as e: | |
return f"<p style='color: red; font-weight: bold;'>⚠️ Error: {str(e)}<br>Please upload a valid English audio file (e.g., .wav, .mp3).</p>" | |
# Determine if it's safe to enable the submit button | |
def enable_submit(audio_path): | |
if audio_path is None: | |
return gr.update(interactive=False) | |
# If file name contains "microphone", assume it’s from mic input and delay submission | |
if "microphone" in os.path.basename(audio_path).lower(): | |
return gr.update(interactive=True) # Enable only when recording finishes | |
return gr.update(interactive=True) # File upload: enable immediately | |
# Build UI | |
with gr.Blocks(theme="default") as demo: | |
gr.Markdown("## 🌍 English Accent Classifier\nRecord or upload English audio to detect accent.") | |
audio_input = gr.Audio(type="filepath", label="🎙 Record or Upload English Audio") | |
submit_button = gr.Button("Submit", interactive=False) | |
result_output = gr.HTML() | |
# Reactively enable submit only after audio is uploaded or recording stops | |
audio_input.change(enable_submit, inputs=audio_input, outputs=submit_button) | |
submit_button.click(classify_accent, inputs=audio_input, outputs=result_output) | |
demo.launch(share=True) | |