Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,13 +5,20 @@ import re
|
|
| 5 |
import random
|
| 6 |
import librosa
|
| 7 |
import soundfile as sf
|
|
|
|
| 8 |
from transformers import pipeline
|
| 9 |
from datasets import load_dataset, Audio
|
| 10 |
from gradio_client import Client
|
| 11 |
from stats_data import get_indomain_breakdown, get_experimental_summary, SPEAKER_META
|
| 12 |
|
| 13 |
-
# 1.
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
whisper_asr = pipeline(
|
| 16 |
"automatic-speech-recognition",
|
| 17 |
model="openai/whisper-tiny",
|
|
@@ -23,81 +30,78 @@ whisper_asr = pipeline(
|
|
| 23 |
}
|
| 24 |
)
|
| 25 |
|
| 26 |
-
|
| 27 |
-
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 28 |
-
PRIVATE_BACKEND_URL = "st192011/Torgo-DSR-Private"
|
| 29 |
-
|
| 30 |
-
def normalize(text):
|
| 31 |
if not text: return ""
|
| 32 |
return re.sub(r'[^\w\s]', '', text).lower().strip()
|
| 33 |
|
|
|
|
|
|
|
| 34 |
def get_sample_logic(speaker_id):
|
| 35 |
-
"""
|
| 36 |
try:
|
| 37 |
-
if speaker_id == "F02
|
| 38 |
dataset = load_dataset("resproj007/uaspeech_female", split="train", streaming=True)
|
| 39 |
dataset = dataset.cast_column("audio", Audio(decode=False))
|
| 40 |
-
#
|
| 41 |
-
|
| 42 |
else:
|
| 43 |
dataset = load_dataset("abnerh/TORGO-database", split="train", streaming=True)
|
| 44 |
dataset = dataset.cast_column("audio", Audio(decode=False))
|
| 45 |
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
if not sid or sid == "NONE":
|
| 50 |
-
sid = os.path.basename(x['audio']['path']).split('_')[0].upper()
|
| 51 |
-
status = str(x.get('speech_status', '')).lower()
|
| 52 |
-
return sid == speaker_id and "control" not in status
|
| 53 |
-
|
| 54 |
-
speaker_ds = dataset.filter(is_target_dysarthric)
|
| 55 |
|
| 56 |
-
#
|
| 57 |
-
sample = next(iter(speaker_ds.shuffle(buffer_size=10)))
|
| 58 |
gt_text = sample.get('transcription') or sample.get('text') or sample.get('sentence') or "Unknown"
|
| 59 |
|
|
|
|
| 60 |
audio_bytes = sample['audio']['bytes']
|
| 61 |
-
audio_data,
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
-
temp_path
|
| 64 |
-
|
| 65 |
-
return temp_path, gt_text.lower().strip(), SPEAKER_META[speaker_id]
|
| 66 |
except Exception as e:
|
| 67 |
-
return None, f"
|
| 68 |
|
| 69 |
-
def
|
| 70 |
-
if not audio_path: return "
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
|
|
|
|
|
|
| 76 |
|
| 77 |
-
# Private Model Call
|
| 78 |
try:
|
| 79 |
client = Client(PRIVATE_BACKEND_URL, hf_token=HF_TOKEN)
|
| 80 |
-
#
|
| 81 |
-
prediction = client.predict(audio_path,
|
|
|
|
| 82 |
except Exception as e:
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
return w_raw, w_norm, prediction
|
| 86 |
|
| 87 |
-
# UI
|
| 88 |
with gr.Blocks(theme=gr.themes.Soft(), title="Torgo DSR Lab") as demo:
|
| 89 |
gr.Markdown("# βοΈ Torgo DSR Lab")
|
|
|
|
|
|
|
| 90 |
current_audio_path = gr.State("")
|
| 91 |
|
| 92 |
with gr.Tab("π¬ Laboratory"):
|
| 93 |
with gr.Row():
|
| 94 |
with gr.Column(scale=1):
|
| 95 |
-
gr.Markdown("### Step 1:
|
| 96 |
-
|
|
|
|
|
|
|
| 97 |
load_btn = gr.Button("Load Data")
|
| 98 |
-
|
| 99 |
gt_box = gr.Textbox(label="Ground Truth")
|
| 100 |
-
audio_input = gr.Audio(sources=["microphone", "upload"], type="filepath", label="Input Audio")
|
| 101 |
|
| 102 |
with gr.Column(scale=2):
|
| 103 |
gr.Markdown("### Step 2: ASR Baseline")
|
|
@@ -112,30 +116,30 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Torgo DSR Lab") as demo:
|
|
| 112 |
|
| 113 |
with gr.Tab("π Research Statistics"):
|
| 114 |
gr.Markdown("# π¬ Performance Evaluation")
|
|
|
|
| 115 |
with gr.Row():
|
| 116 |
with gr.Column():
|
| 117 |
gr.Markdown("""
|
| 118 |
### π Metric: Exact Match Accuracy
|
| 119 |
Accuracy is calculated as the percentage of samples where the **normalized prediction** (lowercase, no punctuation) exactly matches the **ground truth**.
|
| 120 |
""")
|
|
|
|
| 121 |
with gr.Column():
|
| 122 |
gr.Markdown("""
|
| 123 |
### π§ͺ Model Definitions
|
| 124 |
-
* **5K Pure Model:** Trained on
|
| 125 |
-
* **10K Triple-Mix Model:** Includes
|
| 126 |
""")
|
| 127 |
-
|
| 128 |
gr.Markdown("## 1. Torgo In-Domain Breakdown (By Speaker)")
|
| 129 |
gr.DataFrame(get_indomain_breakdown())
|
| 130 |
|
| 131 |
gr.Markdown("## 2. Experimental Summary")
|
| 132 |
gr.DataFrame(get_experimental_summary())
|
| 133 |
|
| 134 |
-
#
|
| 135 |
-
load_btn.click(get_sample_logic, inputs=
|
| 136 |
-
|
| 137 |
-
)
|
| 138 |
-
whisper_btn.click(run_whisper_step if 'run_whisper_step' in globals() else run_lab, inputs=current_audio_path, outputs=[w_raw, w_norm, final_out])
|
| 139 |
-
model_btn.click(run_lab, inputs=current_audio_path, outputs=[w_raw, w_norm, final_out])
|
| 140 |
|
| 141 |
demo.launch()
|
|
|
|
| 5 |
import random
|
| 6 |
import librosa
|
| 7 |
import soundfile as sf
|
| 8 |
+
import pandas as pd
|
| 9 |
from transformers import pipeline
|
| 10 |
from datasets import load_dataset, Audio
|
| 11 |
from gradio_client import Client
|
| 12 |
from stats_data import get_indomain_breakdown, get_experimental_summary, SPEAKER_META
|
| 13 |
|
| 14 |
+
# 1. Configuration & Indices
|
| 15 |
+
TORGO_INDICES = {'FC01': 0, 'FC02': 302, 'FC03': 2489, 'MC02': 4411, 'MC01': 5534, 'MC03': 7689, 'MC04': 9358, 'M05': 10978, 'M02': 11565, 'M04': 12337, 'M01': 13003, 'F01': 13746, 'M03': 13982, 'F04': 14792, 'F03': 15465}
|
| 16 |
+
|
| 17 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 18 |
+
PRIVATE_BACKEND_URL = "st192011/Torgo-DSR-Private"
|
| 19 |
+
|
| 20 |
+
# 2. Local Whisper Baseline
|
| 21 |
+
print("Loading Whisper Tiny...")
|
| 22 |
whisper_asr = pipeline(
|
| 23 |
"automatic-speech-recognition",
|
| 24 |
model="openai/whisper-tiny",
|
|
|
|
| 30 |
}
|
| 31 |
)
|
| 32 |
|
| 33 |
+
def normalize_text(text):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
if not text: return ""
|
| 35 |
return re.sub(r'[^\w\s]', '', text).lower().strip()
|
| 36 |
|
| 37 |
+
# --- Logic Functions ---
|
| 38 |
+
|
| 39 |
def get_sample_logic(speaker_id):
|
| 40 |
+
"""Bypasses internal decoders for both Torgo and UA to avoid environment errors."""
|
| 41 |
try:
|
| 42 |
+
if speaker_id == "F02":
|
| 43 |
dataset = load_dataset("resproj007/uaspeech_female", split="train", streaming=True)
|
| 44 |
dataset = dataset.cast_column("audio", Audio(decode=False))
|
| 45 |
+
# UA dataset is usually smaller; iterate to find variety or use F02 specifically
|
| 46 |
+
sample = next(iter(dataset.shuffle(buffer_size=50)))
|
| 47 |
else:
|
| 48 |
dataset = load_dataset("abnerh/TORGO-database", split="train", streaming=True)
|
| 49 |
dataset = dataset.cast_column("audio", Audio(decode=False))
|
| 50 |
|
| 51 |
+
start_idx = TORGO_INDICES.get(speaker_id, 0)
|
| 52 |
+
# Jump directly to speaker start + random offset within speaker range
|
| 53 |
+
sample = next(iter(dataset.skip(start_idx + random.randint(0, 15))))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
+
# Process Ground Truth
|
|
|
|
| 56 |
gt_text = sample.get('transcription') or sample.get('text') or sample.get('sentence') or "Unknown"
|
| 57 |
|
| 58 |
+
# Manual Decode via Librosa to ensure stability on CPU tier
|
| 59 |
audio_bytes = sample['audio']['bytes']
|
| 60 |
+
audio_data, sample_rate = librosa.load(io.BytesIO(audio_bytes), sr=16000)
|
| 61 |
+
|
| 62 |
+
temp_path = "current_sample.wav"
|
| 63 |
+
sf.write(temp_path, audio_data, sample_rate)
|
| 64 |
|
| 65 |
+
return temp_path, gt_text.lower().strip(), SPEAKER_META.get(speaker_id, {})
|
| 66 |
+
|
|
|
|
| 67 |
except Exception as e:
|
| 68 |
+
return None, f"Dataset Access Error: {e}", {}
|
| 69 |
|
| 70 |
+
def run_whisper_step(audio_path):
|
| 71 |
+
if not audio_path: return "No audio loaded", ""
|
| 72 |
+
result = whisper_asr(audio_path)
|
| 73 |
+
raw_w = result["text"]
|
| 74 |
+
norm_w = normalize_text(raw_w)
|
| 75 |
+
return raw_w, norm_w
|
| 76 |
+
|
| 77 |
+
def run_model_step(audio_path, norm_whisper):
|
| 78 |
+
if not audio_path or not norm_whisper: return "Load data and run Whisper first."
|
| 79 |
|
|
|
|
| 80 |
try:
|
| 81 |
client = Client(PRIVATE_BACKEND_URL, hf_token=HF_TOKEN)
|
| 82 |
+
# Calls private app for Gemma 3 5K Model prediction
|
| 83 |
+
prediction = client.predict(audio_path, norm_whisper, api_name="/predict_dsr")
|
| 84 |
+
return prediction
|
| 85 |
except Exception as e:
|
| 86 |
+
return f"Backend Offline. Research Details: {e}"
|
|
|
|
|
|
|
| 87 |
|
| 88 |
+
# --- UI Layout ---
|
| 89 |
with gr.Blocks(theme=gr.themes.Soft(), title="Torgo DSR Lab") as demo:
|
| 90 |
gr.Markdown("# βοΈ Torgo DSR Lab")
|
| 91 |
+
gr.Markdown("Reconstruction and Correction layer for severe dysarthric speech.")
|
| 92 |
+
|
| 93 |
current_audio_path = gr.State("")
|
| 94 |
|
| 95 |
with gr.Tab("π¬ Laboratory"):
|
| 96 |
with gr.Row():
|
| 97 |
with gr.Column(scale=1):
|
| 98 |
+
gr.Markdown("### Step 1: Select Speaker")
|
| 99 |
+
# Removed 'FC' control speakers from dropdown as requested
|
| 100 |
+
dysarthric_speakers = ["F01", "F03", "F04", "M01", "M02", "M03", "M04", "M05", "F02"]
|
| 101 |
+
speaker_input = gr.Dropdown(sorted(dysarthric_speakers), label="Speaker ID", value="F01")
|
| 102 |
load_btn = gr.Button("Load Data")
|
| 103 |
+
meta_display = gr.JSON(label="Speaker Meta")
|
| 104 |
gt_box = gr.Textbox(label="Ground Truth")
|
|
|
|
| 105 |
|
| 106 |
with gr.Column(scale=2):
|
| 107 |
gr.Markdown("### Step 2: ASR Baseline")
|
|
|
|
| 116 |
|
| 117 |
with gr.Tab("π Research Statistics"):
|
| 118 |
gr.Markdown("# π¬ Performance Evaluation")
|
| 119 |
+
|
| 120 |
with gr.Row():
|
| 121 |
with gr.Column():
|
| 122 |
gr.Markdown("""
|
| 123 |
### π Metric: Exact Match Accuracy
|
| 124 |
Accuracy is calculated as the percentage of samples where the **normalized prediction** (lowercase, no punctuation) exactly matches the **ground truth**.
|
| 125 |
""")
|
| 126 |
+
|
| 127 |
with gr.Column():
|
| 128 |
gr.Markdown("""
|
| 129 |
### π§ͺ Model Definitions
|
| 130 |
+
* **5K Pure Model:** Trained on real articulatory distortions. Optimized for phonetic fidelity.
|
| 131 |
+
* **10K Triple-Mix Model:** Includes anchors and synthetic data. Used to test **generalization (LOSO)** on unseen speakers.
|
| 132 |
""")
|
| 133 |
+
|
| 134 |
gr.Markdown("## 1. Torgo In-Domain Breakdown (By Speaker)")
|
| 135 |
gr.DataFrame(get_indomain_breakdown())
|
| 136 |
|
| 137 |
gr.Markdown("## 2. Experimental Summary")
|
| 138 |
gr.DataFrame(get_experimental_summary())
|
| 139 |
|
| 140 |
+
# Event Mapping
|
| 141 |
+
load_btn.click(get_sample_logic, inputs=speaker_input, outputs=[current_audio_path, gt_box, meta_display])
|
| 142 |
+
whisper_btn.click(run_whisper_step, inputs=current_audio_path, outputs=[w_raw, w_norm])
|
| 143 |
+
model_btn.click(run_model_step, inputs=[current_audio_path, w_norm], outputs=final_out)
|
|
|
|
|
|
|
| 144 |
|
| 145 |
demo.launch()
|