st192011 commited on
Commit
b3a0889
Β·
verified Β·
1 Parent(s): 08dd52c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -54
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. Setup Local Whisper (Forced to English, High Repetition Penalty)
14
- print("Initializing ASR Baseline...")
 
 
 
 
 
 
15
  whisper_asr = pipeline(
16
  "automatic-speech-recognition",
17
  model="openai/whisper-tiny",
@@ -23,81 +30,78 @@ whisper_asr = pipeline(
23
  }
24
  )
25
 
26
- # 2. Private Backend Config
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
- """Optimized data loader: Skips normal control speakers to find targets faster."""
36
  try:
37
- if speaker_id == "F02 (UA)":
38
  dataset = load_dataset("resproj007/uaspeech_female", split="train", streaming=True)
39
  dataset = dataset.cast_column("audio", Audio(decode=False))
40
- # F02 is the primary dysarthric speaker in this split
41
- speaker_ds = dataset.filter(lambda x: x["speaker_id"] == "F02")
42
  else:
43
  dataset = load_dataset("abnerh/TORGO-database", split="train", streaming=True)
44
  dataset = dataset.cast_column("audio", Audio(decode=False))
45
 
46
- # Skip logic: ignore samples with 'control' status to speed up stream
47
- def is_target_dysarthric(x):
48
- sid = str(x.get('speaker_id', '')).upper()
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
- # Get sample and decode
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, sr = librosa.load(io.BytesIO(audio_bytes), sr=16000)
 
 
 
62
 
63
- temp_path = "sample.wav"
64
- sf.write(temp_path, audio_data, sr)
65
- return temp_path, gt_text.lower().strip(), SPEAKER_META[speaker_id]
66
  except Exception as e:
67
- return None, f"Loading error: {e}", {}
68
 
69
- def run_lab(audio_path):
70
- if not audio_path: return "", "", "Error: No Audio"
71
-
72
- # Baseline
73
- w_res = whisper_asr(audio_path)
74
- w_raw = w_res["text"]
75
- w_norm = normalize(w_raw)
 
 
76
 
77
- # Private Model Call
78
  try:
79
  client = Client(PRIVATE_BACKEND_URL, hf_token=HF_TOKEN)
80
- # Assuming private backend returns the 5K prediction string
81
- prediction = client.predict(audio_path, w_norm, api_name="/predict_dsr")
 
82
  except Exception as e:
83
- prediction = f"Backend offline or Error: {e}"
84
-
85
- return w_raw, w_norm, prediction
86
 
87
- # UI Construction
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: Data Selection")
96
- spk_input = gr.Dropdown(sorted(list(SPEAKER_META.keys())), label="Speaker ID", value="F01")
 
 
97
  load_btn = gr.Button("Load Data")
98
- meta_json = gr.JSON(label="Speaker Metadata")
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 5,000 real Torgo samples. Optimized for articulatory fidelity.
125
- * **10K Triple-Mix Model:** Includes phonetic anchors and synthetic data. Utilized to test **generalization (LOSO)** on unseen speakers.
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
- # Connection logic
135
- load_btn.click(get_sample_logic, inputs=spk_input, outputs=[current_audio_path, gt_box, meta_json]).then(
136
- lambda x: x, inputs=current_audio_path, outputs=audio_input
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()