Update app.py
Browse files
app.py
CHANGED
@@ -1,266 +1,126 @@
|
|
1 |
import gradio as gr
|
2 |
-
import torch
|
3 |
-
import librosa
|
4 |
from transformers import Wav2Vec2Processor, AutoModelForCTC
|
5 |
-
import
|
6 |
-
import os
|
7 |
import firebase_admin
|
8 |
from firebase_admin import credentials, firestore, storage
|
9 |
-
from datetime import datetime, timedelta
|
10 |
-
import json
|
11 |
-
import tempfile
|
12 |
-
import uuid
|
13 |
|
14 |
-
#
|
15 |
-
|
16 |
-
os.chdir(os.path.dirname(os.path.abspath(__file__)))
|
17 |
-
cred = credentials.Certificate("serviceAccountKey.json")
|
18 |
-
'''
|
19 |
-
# Deployed Initialization
|
20 |
-
firebase_config = json.loads(os.environ.get('firebase_creds'))
|
21 |
cred = credentials.Certificate(firebase_config)
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
})
|
26 |
db = firestore.client()
|
27 |
bucket = storage.bucket()
|
28 |
|
29 |
-
#
|
30 |
MODEL_NAME = "eleferrand/XLSR_paiwan"
|
31 |
processor = Wav2Vec2Processor.from_pretrained(MODEL_NAME)
|
32 |
model = AutoModelForCTC.from_pretrained(MODEL_NAME)
|
33 |
|
34 |
-
|
35 |
-
|
36 |
-
# Core ASR helper functions
|
37 |
-
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
38 |
-
|
39 |
-
def transcribe(audio_file: str):
|
40 |
-
"""Run ASR on the uploaded audio file and return the raw transcription."""
|
41 |
try:
|
42 |
-
audio, _ = librosa.load(
|
43 |
-
|
44 |
with torch.no_grad():
|
45 |
-
logits = model(
|
46 |
-
|
47 |
-
|
48 |
-
return
|
49 |
except Exception as e:
|
50 |
return f"่็ๆไปถ้ฏ่ชค: {e}"
|
51 |
|
|
|
|
|
|
|
52 |
|
53 |
-
def
|
54 |
-
"""Wrapper that provides UIโfriendly status messages."""
|
55 |
-
if audio_file is None:
|
56 |
-
return "", "", gr.update(value="่ซๅ
ไธๅณ้ณ่จ (Please upload audio first)", visible=True)
|
57 |
-
|
58 |
-
# Show processing message first
|
59 |
-
processing_msg = gr.update(value="่็ไธญ๏ผ่ซ็จๅโฆ (Processing, please waitโฆ)", visible=True)
|
60 |
-
transcription = transcribe(audio_file)
|
61 |
-
done_msg = gr.update(value="ๅฎๆ๏ผ(Done!)", visible=True)
|
62 |
-
return transcription, transcription, done_msg
|
63 |
-
|
64 |
-
|
65 |
-
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
66 |
-
# Firebase helpers
|
67 |
-
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
68 |
-
|
69 |
-
def store_correction(original_transcription, corrected_transcription, audio_file, age, native_speaker):
|
70 |
-
"""Upload audio (if provided) + transcription pair to Firestore/Storage."""
|
71 |
try:
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
"
|
78 |
-
"file_size": os.path.getsize(audio_file),
|
79 |
}
|
80 |
-
uid =
|
81 |
-
|
82 |
-
blob
|
83 |
-
blob.
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
"
|
94 |
-
"
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
"age": age,
|
99 |
-
},
|
100 |
-
"timestamp": datetime.now().isoformat(),
|
101 |
-
"model_name": MODEL_NAME,
|
102 |
-
})
|
103 |
return "ๆ กๆญฃไฟๅญๆๅ! (Correction saved successfully!)"
|
104 |
except Exception as e:
|
105 |
-
return f"
|
106 |
|
107 |
-
|
108 |
-
|
109 |
-
"""Bundle audio + TXT files into a ZIP for download."""
|
110 |
-
if audio_file is None:
|
111 |
return None
|
112 |
-
|
113 |
-
tmp_zip
|
114 |
-
with zipfile.ZipFile(tmp_zip, "w") as
|
115 |
-
if os.path.exists(
|
116 |
-
|
117 |
-
for name,
|
118 |
-
|
119 |
-
("corrected_transcription.txt", corrected_transcription),
|
120 |
-
]:
|
121 |
with open(name, "w", encoding="utf-8") as f:
|
122 |
-
f.write(
|
123 |
-
|
124 |
os.remove(name)
|
125 |
-
return tmp_zip
|
126 |
-
|
127 |
-
|
128 |
-
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
129 |
-
# Dynamic label switching โ uses gr.update() so values arenโt overwritten
|
130 |
-
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
131 |
-
|
132 |
-
def toggle_language(switch: bool):
|
133 |
-
"""Return a tuple of updates for each UI component when the language toggle flips."""
|
134 |
-
|
135 |
-
if switch: # Traditional Chinese UI
|
136 |
-
return (
|
137 |
-
"ๆ็ฃ่ช่ชๅ่ช้ณ่ญๅฅ้ๅญ็จฟ่ไฟฎๆญฃ็ณป็ตฑ", # Title (Markdown)
|
138 |
-
"ๆญฅ้ฉ 1๏ผ้ณ่จไธๅณ่้ๅญ็จฟ", # Step 1 (Markdown)
|
139 |
-
"ๆญฅ้ฉ 2๏ผๅฏฉ้ฑ่็ทจ่ผฏ้ๅญ็จฟ", # Step 2 (Markdown)
|
140 |
-
"ๆญฅ้ฉ 3๏ผไฝฟ็จ่
่ณ่จ", # Step 3 (Markdown)
|
141 |
-
"ๆญฅ้ฉ 4๏ผๅฒๅญ่ไธ่ผ", # Step 4 (Markdown)
|
142 |
-
gr.update(label="้ณ่จ่ผธๅ
ฅ"), # Audio component label
|
143 |
-
gr.update(value="็ข็้ๅญ็จฟ"), # Transcribe button text
|
144 |
-
gr.update(label="ๅๅง้ๅญ็จฟ"), # Original transcription textbox label
|
145 |
-
gr.update(label="ๆดๆญฃ้ๅญ็จฟ"), # Corrected transcription textbox label
|
146 |
-
gr.update(label="ๅนด้ฝก"), # Age slider label
|
147 |
-
gr.update(label="ๆฏ่ชๆ็ฃ่ชไฝฟ็จ่
?"), # Native speaker checkbox label
|
148 |
-
gr.update(value="ๅฒๅญ"), # Save button text
|
149 |
-
gr.update(label="ๅฒๅญ็ๆ
"), # Saveโstatus textbox label
|
150 |
-
gr.update(value="ไธ่ผ ZIP ๆชๆก"), # Download button text
|
151 |
-
gr.update(value="่็ไธญ๏ผ่ซ็จๅโฆ") # Status message default
|
152 |
-
)
|
153 |
-
|
154 |
-
# English UI
|
155 |
-
return (
|
156 |
-
"Paiwan ASR Transcription & Correction System",
|
157 |
-
"Step 1: Audio Upload & Transcription",
|
158 |
-
"Step 2: Review & Edit Transcription",
|
159 |
-
"Step 3: User Information",
|
160 |
-
"Step 4: Save & Download",
|
161 |
-
gr.update(label="Audio Input"),
|
162 |
-
gr.update(value="Generate Transcript"),
|
163 |
-
gr.update(label="Original Transcription"),
|
164 |
-
gr.update(label="Corrected Transcription"),
|
165 |
-
gr.update(label="Age"),
|
166 |
-
gr.update(label="Native Paiwan Speaker?"),
|
167 |
-
gr.update(value="Save"),
|
168 |
-
gr.update(label="Save Status"),
|
169 |
-
gr.update(value="Download ZIP File"),
|
170 |
-
gr.update(value="Processing, please waitโฆ"),
|
171 |
-
)
|
172 |
-
|
173 |
-
|
174 |
-
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
175 |
-
# Gradio UI
|
176 |
-
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
177 |
|
|
|
178 |
with gr.Blocks() as demo:
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
184 |
with gr.Row():
|
185 |
-
|
|
|
186 |
|
187 |
-
|
188 |
-
|
189 |
-
step2 = gr.Markdown()
|
190 |
with gr.Row():
|
191 |
-
|
192 |
-
|
193 |
-
original_text = gr.Textbox(interactive=False, lines=5)
|
194 |
-
corrected_text = gr.Textbox(interactive=True, lines=5)
|
195 |
-
|
196 |
-
step3 = gr.Markdown()
|
197 |
-
with gr.Row():
|
198 |
-
age_input = gr.Slider(minimum=0, maximum=100, step=1, value=25)
|
199 |
-
native_speaker_input = gr.Checkbox(value=True)
|
200 |
-
|
201 |
-
step4 = gr.Markdown()
|
202 |
with gr.Row():
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
(title.value, step1.value, step2.value, step3.value, step4.value,
|
213 |
-
audio_input, transcribe_button, original_text, corrected_text,
|
214 |
-
age_input, native_speaker_input, save_button, save_status,
|
215 |
-
download_button, status_message_init) = init_vals
|
216 |
-
|
217 |
-
audio_input.label = "Audio Input"
|
218 |
-
transcribe_button.value = "Generate Transcript"
|
219 |
-
original_text.label = "Original Transcription"
|
220 |
-
corrected_text.label = "Corrected Transcription"
|
221 |
-
age_input.label = "Age"
|
222 |
-
native_speaker_input.label = "Native Paiwan Speaker?"
|
223 |
-
save_button.value = "Save"
|
224 |
-
save_status.label = "Save Status"
|
225 |
-
download_button.value = "Download ZIP File"
|
226 |
-
status_message.value = status_message_init.value
|
227 |
-
|
228 |
-
# Language switch โ wonโt overwrite component values anymore
|
229 |
-
lang_switch.change(
|
230 |
-
toggle_language,
|
231 |
-
inputs=lang_switch,
|
232 |
-
outputs=[title, step1, step2, step3, step4,
|
233 |
-
audio_input, transcribe_button, original_text, corrected_text,
|
234 |
-
age_input, native_speaker_input, save_button, save_status,
|
235 |
-
download_button, status_message]
|
236 |
-
)
|
237 |
-
|
238 |
-
# Auto transcription on upload
|
239 |
-
audio_input.change(
|
240 |
-
transcribe_with_status,
|
241 |
-
inputs=audio_input,
|
242 |
-
outputs=[original_text, corrected_text, status_message]
|
243 |
-
)
|
244 |
-
|
245 |
-
# Manual transcription button
|
246 |
-
transcribe_button.click(
|
247 |
-
transcribe_with_status,
|
248 |
-
inputs=audio_input,
|
249 |
-
outputs=[original_text, corrected_text, status_message]
|
250 |
-
)
|
251 |
-
|
252 |
-
# Save to Firebase
|
253 |
-
save_button.click(
|
254 |
-
store_correction,
|
255 |
-
inputs=[original_text, corrected_text, audio_input, age_input, native_speaker_input],
|
256 |
-
outputs=save_status,
|
257 |
-
)
|
258 |
-
|
259 |
-
# Download ZIP
|
260 |
-
download_button.click(
|
261 |
-
prepare_download,
|
262 |
-
inputs=[audio_input, original_text, corrected_text],
|
263 |
-
outputs=download_output,
|
264 |
-
)
|
265 |
|
266 |
demo.launch()
|
|
|
1 |
import gradio as gr
|
2 |
+
import torch, librosa, zipfile, os, json, tempfile, uuid
|
|
|
3 |
from transformers import Wav2Vec2Processor, AutoModelForCTC
|
4 |
+
from datetime import datetime, timedelta
|
|
|
5 |
import firebase_admin
|
6 |
from firebase_admin import credentials, firestore, storage
|
|
|
|
|
|
|
|
|
7 |
|
8 |
+
# ---------- Firebase init ----------
|
9 |
+
firebase_config = json.loads(os.environ.get("firebase_creds"))
|
|
|
|
|
|
|
|
|
|
|
10 |
cred = credentials.Certificate(firebase_config)
|
11 |
+
firebase_admin.initialize_app(
|
12 |
+
cred, {"storageBucket": "amis-asr-corrections-dem-8cf3d.firebasestorage.app"}
|
13 |
+
)
|
|
|
14 |
db = firestore.client()
|
15 |
bucket = storage.bucket()
|
16 |
|
17 |
+
# ---------- ASR model ----------
|
18 |
MODEL_NAME = "eleferrand/XLSR_paiwan"
|
19 |
processor = Wav2Vec2Processor.from_pretrained(MODEL_NAME)
|
20 |
model = AutoModelForCTC.from_pretrained(MODEL_NAME)
|
21 |
|
22 |
+
# ---------- Core helpers ----------
|
23 |
+
def transcribe(path):
|
|
|
|
|
|
|
|
|
|
|
24 |
try:
|
25 |
+
audio, _ = librosa.load(path, sr=16_000)
|
26 |
+
inputs = processor(audio, sampling_rate=16_000, return_tensors="pt").input_values
|
27 |
with torch.no_grad():
|
28 |
+
logits = model(inputs).logits
|
29 |
+
ids = torch.argmax(logits, dim=-1)
|
30 |
+
text = processor.batch_decode(ids)[0]
|
31 |
+
return text.replace("[UNK]", "")
|
32 |
except Exception as e:
|
33 |
return f"่็ๆไปถ้ฏ่ชค: {e}"
|
34 |
|
35 |
+
def transcribe_both(path):
|
36 |
+
txt = transcribe(path)
|
37 |
+
return txt, txt # original & editable copies
|
38 |
|
39 |
+
def store_correction(orig, corr, audio, age, native):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
40 |
try:
|
41 |
+
audio_meta, audio_url = {}, None
|
42 |
+
if audio and os.path.exists(audio):
|
43 |
+
a, sr = librosa.load(audio, sr=44_100)
|
44 |
+
audio_meta = {
|
45 |
+
"duration": librosa.get_duration(y=a, sr=sr),
|
46 |
+
"file_size": os.path.getsize(audio),
|
|
|
47 |
}
|
48 |
+
uid = f"{uuid.uuid4()}.wav"
|
49 |
+
blob = bucket.blob(f"audio/pai/{uid}")
|
50 |
+
blob.upload_from_filename(audio)
|
51 |
+
audio_url = blob.generate_signed_url(expiration=timedelta(hours=1))
|
52 |
+
|
53 |
+
db.collection("paiwan_transcriptions").add(
|
54 |
+
{
|
55 |
+
"transcription_info": {
|
56 |
+
"original_text": orig,
|
57 |
+
"corrected_text": corr,
|
58 |
+
"language": "pai",
|
59 |
+
},
|
60 |
+
"audio_data": {"audio_metadata": audio_meta, "audio_file_url": audio_url},
|
61 |
+
"user_info": {"native_paiwan_speaker": native, "age": age},
|
62 |
+
"timestamp": datetime.now().isoformat(),
|
63 |
+
"model_name": MODEL_NAME,
|
64 |
+
}
|
65 |
+
)
|
|
|
|
|
|
|
|
|
|
|
66 |
return "ๆ กๆญฃไฟๅญๆๅ! (Correction saved successfully!)"
|
67 |
except Exception as e:
|
68 |
+
return f"ไฟๅญๅคฑๆ: {e} (Error saving correction: {e})"
|
69 |
|
70 |
+
def prepare_download(audio, orig, corr):
|
71 |
+
if not audio:
|
|
|
|
|
72 |
return None
|
73 |
+
tmp_zip = tempfile.NamedTemporaryFile(delete=False, suffix=".zip")
|
74 |
+
tmp_zip.close()
|
75 |
+
with zipfile.ZipFile(tmp_zip.name, "w") as z:
|
76 |
+
if os.path.exists(audio):
|
77 |
+
z.write(audio, arcname="audio.wav")
|
78 |
+
for name, txt in [("original_transcription.txt", orig),
|
79 |
+
("corrected_transcription.txt", corr)]:
|
|
|
|
|
80 |
with open(name, "w", encoding="utf-8") as f:
|
81 |
+
f.write(txt)
|
82 |
+
z.write(name, arcname=name)
|
83 |
os.remove(name)
|
84 |
+
return tmp_zip.name
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
85 |
|
86 |
+
# ---------- Interface ----------
|
87 |
with gr.Blocks() as demo:
|
88 |
+
gr.Markdown("# ๆ็ฃ่ช่ชๅ่ช้ณ่ญๅฅ้ๅญ็จฟ่ไฟฎๆญฃ็ณป็ตฑ (Paiwan ASR Transcription & Correction System)")
|
89 |
+
|
90 |
+
# Step 1
|
91 |
+
gr.Markdown("### ๆญฅ้ฉ 1๏ผ้ณ่จไธๅณ (Audio Upload)")
|
92 |
+
gr.Markdown("ไธๅณๅพ่ซ่ณๆญฅ้ฉ 2 ๆใ็ข็้ๅญ็จฟใ๏ผ็ณป็ตฑ่็ๆ่ซ่ๅฟ็ญๅพ
โฆ")
|
93 |
+
audio_input = gr.Audio(["upload", "microphone"], type="filepath",
|
94 |
+
label="้ณ่จ่ผธๅ
ฅ (Audio Input)")
|
95 |
+
|
96 |
+
# Step 2
|
97 |
+
gr.Markdown("### ๆญฅ้ฉ 2๏ผ็ข็่็ทจ่ผฏ้ๅญ็จฟ (Generate & Edit Transcript)")
|
98 |
+
trans_btn = gr.Button("็ข็้ๅญ็จฟ (Generate Transcript)")
|
99 |
+
original = gr.Textbox(label="ๅๅง้ๅญ็จฟ (Original Transcription)",
|
100 |
+
interactive=False, lines=6)
|
101 |
+
corrected = gr.Textbox(label="ๆดๆญฃ้ๅญ็จฟ (Corrected Transcription)",
|
102 |
+
interactive=True, lines=6)
|
103 |
+
|
104 |
+
# Step 3
|
105 |
+
gr.Markdown("### ๆญฅ้ฉ 3๏ผไฝฟ็จ่
่ณ่จ (User Information)")
|
106 |
with gr.Row():
|
107 |
+
age = gr.Slider(0, 100, step=1, value=25, label="ๅนด้ฝก (Age)")
|
108 |
+
native = gr.Checkbox(value=True, label="ๆฏ่ชๆ็ฃ่ชไฝฟ็จ่
๏ผ(Native Paiwan Speaker?)")
|
109 |
|
110 |
+
# Step 4
|
111 |
+
gr.Markdown("### ๆญฅ้ฉ 4๏ผๅฒๅญ่ไธ่ผ (Save & Download)")
|
|
|
112 |
with gr.Row():
|
113 |
+
save_btn = gr.Button("ๅฒๅญ (Save)")
|
114 |
+
save_msg = gr.Textbox(label="ๅฒๅญ็ๆ
(Save Status)", interactive=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
115 |
with gr.Row():
|
116 |
+
dl_btn = gr.Button("ไธ่ผ ZIP ๆชๆก (Download ZIP File)")
|
117 |
+
dl_out = gr.File()
|
118 |
+
|
119 |
+
# --- wiring ---
|
120 |
+
trans_btn.click(transcribe_both, audio_input, [original, corrected])
|
121 |
+
save_btn.click(store_correction,
|
122 |
+
[original, corrected, audio_input, age, native],
|
123 |
+
save_msg)
|
124 |
+
dl_btn.click(prepare_download, [audio_input, original, corrected], dl_out)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
125 |
|
126 |
demo.launch()
|