Update app.py
Browse files
app.py
CHANGED
@@ -11,13 +11,13 @@ import json
|
|
11 |
import tempfile
|
12 |
import uuid
|
13 |
|
14 |
-
# LOCAL INITIALIZATION - ONLY USE ON YOUR OWN DEVICE
|
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(
|
21 |
cred = credentials.Certificate(firebase_config)
|
22 |
|
23 |
firebase_admin.initialize_app(cred, {
|
@@ -31,201 +31,220 @@ MODEL_NAME = "eleferrand/XLSR_paiwan"
|
|
31 |
processor = Wav2Vec2Processor.from_pretrained(MODEL_NAME)
|
32 |
model = AutoModelForCTC.from_pretrained(MODEL_NAME)
|
33 |
|
34 |
-
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
35 |
-
# Helper functions
|
36 |
-
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
37 |
|
38 |
-
def transcribe(audio_file
|
39 |
-
"""Run ASR on *audio_file* and return the raw transcription."""
|
40 |
try:
|
41 |
-
audio,
|
42 |
-
input_values = processor(audio, sampling_rate=
|
|
|
43 |
with torch.no_grad():
|
44 |
logits = model(input_values).logits
|
45 |
predicted_ids = torch.argmax(logits, dim=-1)
|
46 |
transcription = processor.batch_decode(predicted_ids)[0]
|
47 |
return transcription.replace("[UNK]", "")
|
48 |
except Exception as e:
|
49 |
-
return f"
|
50 |
-
|
51 |
|
52 |
-
def transcribe_both_and_clear(audio_file: str):
|
53 |
-
"""Transcribe and populate both textboxes, then hide the status message."""
|
54 |
-
text = transcribe(audio_file)
|
55 |
-
return text, text, gr.update(visible=False, value="")
|
56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
|
58 |
-
def show_processing(_):
|
59 |
-
"""Display a temporary โprocessingโ notice while ASR runs."""
|
60 |
-
return gr.update(visible=True, value="โณ ่ฝ่ญฏไธญ๏ผ่ซ็จๅโฆ / Transcribingโฆ please waitโฆ")
|
61 |
|
62 |
-
|
63 |
-
def store_correction(original: str, corrected: str, audio_file: str, age: int, native: bool):
|
64 |
-
"""Save user correction + optional audio to Firebase."""
|
65 |
try:
|
66 |
-
|
|
|
|
|
|
|
67 |
if audio_file and os.path.exists(audio_file):
|
68 |
-
audio, sr = librosa.load(audio_file, sr=
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
|
|
|
|
|
|
76 |
blob.upload_from_filename(audio_file)
|
77 |
-
audio_url = blob.generate_signed_url(expiration=timedelta(hours=1))
|
78 |
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
|
|
|
|
|
|
84 |
},
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
89 |
}
|
90 |
-
|
91 |
-
|
|
|
92 |
except Exception as e:
|
93 |
-
return f"
|
94 |
|
95 |
|
96 |
-
def prepare_download(audio_file
|
97 |
-
|
98 |
-
if not audio_file:
|
99 |
return None
|
100 |
|
101 |
-
|
102 |
-
|
103 |
-
with zipfile.ZipFile(
|
104 |
if os.path.exists(audio_file):
|
105 |
zf.write(audio_file, arcname="audio.wav")
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
("", {"value": ""}),
|
154 |
-
)
|
155 |
-
|
156 |
-
|
157 |
-
def toggle_language(switch: bool):
|
158 |
-
"""Return gr.update objects in correct order for all UI components."""
|
159 |
-
labels = zh_TW_labels if switch else en_labels
|
160 |
-
updates = []
|
161 |
-
for comp_text, kwargs in labels:
|
162 |
-
# Markdown components expect value update; others use kwargs
|
163 |
-
if comp_text is not None and "value" not in kwargs:
|
164 |
-
kwargs["value"] = comp_text
|
165 |
-
updates.append(gr.update(**kwargs))
|
166 |
-
return tuple(updates)
|
167 |
-
|
168 |
-
|
169 |
-
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
170 |
# Interface
|
171 |
-
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
172 |
with gr.Blocks() as demo:
|
173 |
lang_switch = gr.Checkbox(label="ๅๆๅฐ็น้ซไธญๆ (Switch to Traditional Chinese)")
|
174 |
|
175 |
-
# Component stubs (order matters!)
|
176 |
title = gr.Markdown()
|
177 |
step1 = gr.Markdown()
|
178 |
-
step2 = gr.Markdown()
|
179 |
-
step3 = gr.Markdown()
|
180 |
-
step4 = gr.Markdown()
|
181 |
|
182 |
-
|
183 |
-
|
184 |
-
corrected_text = gr.Textbox(interactive=True, lines=5)
|
185 |
|
186 |
-
|
187 |
-
native_speaker_input = gr.Checkbox(value=True)
|
188 |
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
status_msg = gr.Markdown(visible=False)
|
193 |
|
194 |
-
|
195 |
-
|
196 |
-
audio_input, original_text, corrected_text,
|
197 |
-
age_input, native_speaker_input,
|
198 |
-
save_button, save_status, download_button,
|
199 |
-
status_msg,
|
200 |
-
]
|
201 |
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
|
207 |
-
|
208 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
209 |
|
210 |
-
#
|
211 |
-
audio_input.change(show_processing, inputs=audio_input, outputs=status_msg)
|
212 |
audio_input.change(
|
213 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
214 |
inputs=audio_input,
|
215 |
-
outputs=[original_text, corrected_text,
|
216 |
)
|
217 |
|
218 |
-
# Save & download actions
|
219 |
save_button.click(
|
220 |
store_correction,
|
221 |
inputs=[original_text, corrected_text, audio_input, age_input, native_speaker_input],
|
222 |
-
outputs=save_status
|
223 |
)
|
224 |
|
225 |
download_button.click(
|
226 |
prepare_download,
|
227 |
inputs=[audio_input, original_text, corrected_text],
|
228 |
-
outputs=download_output
|
229 |
)
|
230 |
|
231 |
demo.launch()
|
|
|
11 |
import tempfile
|
12 |
import uuid
|
13 |
|
14 |
+
# LOCAL INITIALIZATION - ONLY USE ON YOUR OWN DEVICE
|
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 |
firebase_admin.initialize_app(cred, {
|
|
|
31 |
processor = Wav2Vec2Processor.from_pretrained(MODEL_NAME)
|
32 |
model = AutoModelForCTC.from_pretrained(MODEL_NAME)
|
33 |
|
|
|
|
|
|
|
34 |
|
35 |
+
def transcribe(audio_file):
|
|
|
36 |
try:
|
37 |
+
audio, rate = librosa.load(audio_file, sr=16000)
|
38 |
+
input_values = processor(audio, sampling_rate=16000, return_tensors="pt").input_values
|
39 |
+
|
40 |
with torch.no_grad():
|
41 |
logits = model(input_values).logits
|
42 |
predicted_ids = torch.argmax(logits, dim=-1)
|
43 |
transcription = processor.batch_decode(predicted_ids)[0]
|
44 |
return transcription.replace("[UNK]", "")
|
45 |
except Exception as e:
|
46 |
+
return f"่็ๆไปถ้ฏ่ชค: {e}"
|
|
|
47 |
|
|
|
|
|
|
|
|
|
48 |
|
49 |
+
def transcribe_with_status(audio_file):
|
50 |
+
if audio_file is None:
|
51 |
+
return "", "", "่ซๅ
ไธๅณ้ณ่จ (Please upload audio first)"
|
52 |
+
status = "่็ไธญ๏ผ่ซ็จๅโฆ (Processing, please waitโฆ)"
|
53 |
+
transcription = transcribe(audio_file)
|
54 |
+
return transcription, transcription, "ๅฎๆ๏ผ(Done!)"
|
55 |
|
|
|
|
|
|
|
56 |
|
57 |
+
def store_correction(original_transcription, corrected_transcription, audio_file, age, native_speaker):
|
|
|
|
|
58 |
try:
|
59 |
+
audio_metadata = {}
|
60 |
+
audio_file_url = None
|
61 |
+
|
62 |
+
# If an audio file is provided, upload it to Firebase Storage
|
63 |
if audio_file and os.path.exists(audio_file):
|
64 |
+
audio, sr = librosa.load(audio_file, sr=44100)
|
65 |
+
duration = librosa.get_duration(y=audio, sr=sr)
|
66 |
+
file_size = os.path.getsize(audio_file)
|
67 |
+
audio_metadata = {'duration': duration, 'file_size': file_size}
|
68 |
+
|
69 |
+
# Generate a unique identifier for the audio file
|
70 |
+
unique_id = str(uuid.uuid4())
|
71 |
+
destination_path = f"audio/pai/{unique_id}.wav"
|
72 |
+
|
73 |
+
# Create a blob and upload the file
|
74 |
+
blob = bucket.blob(destination_path)
|
75 |
blob.upload_from_filename(audio_file)
|
|
|
76 |
|
77 |
+
# Generate a signed download URL valid for 1 hour (adjust expiration as needed)
|
78 |
+
audio_file_url = blob.generate_signed_url(expiration=timedelta(hours=1))
|
79 |
+
|
80 |
+
combined_data = {
|
81 |
+
'transcription_info': {
|
82 |
+
'original_text': original_transcription,
|
83 |
+
'corrected_text': corrected_transcription,
|
84 |
+
'language': 'pai',
|
85 |
},
|
86 |
+
'audio_data': {
|
87 |
+
'audio_metadata': audio_metadata,
|
88 |
+
'audio_file_url': audio_file_url,
|
89 |
+
},
|
90 |
+
'user_info': {
|
91 |
+
'native_paiwan_speaker': native_speaker,
|
92 |
+
'age': age
|
93 |
+
},
|
94 |
+
'timestamp': datetime.now().isoformat(),
|
95 |
+
'model_name': MODEL_NAME
|
96 |
}
|
97 |
+
# Save data to a collection for that language
|
98 |
+
db.collection('paiwan_transcriptions').add(combined_data)
|
99 |
+
return "ๆ กๆญฃไฟๅญๆๅ! (Correction saved successfully!)"
|
100 |
except Exception as e:
|
101 |
+
return f"ไฟๅญๅคฑ่ดฅ: {e} (Error saving correction: {e})"
|
102 |
|
103 |
|
104 |
+
def prepare_download(audio_file, original_transcription, corrected_transcription):
|
105 |
+
if audio_file is None:
|
|
|
106 |
return None
|
107 |
|
108 |
+
tmp_zip = tempfile.NamedTemporaryFile(delete=False, suffix=".zip")
|
109 |
+
tmp_zip.close()
|
110 |
+
with zipfile.ZipFile(tmp_zip.name, "w") as zf:
|
111 |
if os.path.exists(audio_file):
|
112 |
zf.write(audio_file, arcname="audio.wav")
|
113 |
+
|
114 |
+
orig_txt = "original_transcription.txt"
|
115 |
+
with open(orig_txt, "w", encoding="utf-8") as f:
|
116 |
+
f.write(original_transcription)
|
117 |
+
zf.write(orig_txt, arcname="original_transcription.txt")
|
118 |
+
os.remove(orig_txt)
|
119 |
+
|
120 |
+
corr_txt = "corrected_transcription.txt"
|
121 |
+
with open(corr_txt, "w", encoding="utf-8") as f:
|
122 |
+
f.write(corrected_transcription)
|
123 |
+
zf.write(corr_txt, arcname="corrected_transcription.txt")
|
124 |
+
os.remove(corr_txt)
|
125 |
+
return tmp_zip.name
|
126 |
+
|
127 |
+
|
128 |
+
def toggle_language(switch):
|
129 |
+
"""Switch UI text between English and Traditional Chinese"""
|
130 |
+
if switch:
|
131 |
+
return (
|
132 |
+
"ๆ็ฃ่ช่ชๅ่ช้ณ่ญๅฅ้ๅญ็จฟ่ไฟฎๆญฃ็ณป็ตฑ", # Title
|
133 |
+
"ๆญฅ้ฉ 1๏ผ้ณ่จไธๅณ่้ๅญ็จฟ", # Step 1
|
134 |
+
"ๆญฅ้ฉ 2๏ผๅฏฉ้ฑ่็ทจ่ผฏ้ๅญ็จฟ", # Step 2
|
135 |
+
"ๆญฅ้ฉ 3๏ผไฝฟ็จ่
่ณ่จ", # Step 3
|
136 |
+
"ๆญฅ้ฉ 4๏ผๅฒๅญ่ไธ่ผ", # Step 4
|
137 |
+
"้ณ่จ่ผธๅ
ฅ", "็ข็้ๅญ็จฟ", # Audio label, Transcribe button
|
138 |
+
"ๅๅง้ๅญ็จฟ", "ๆดๆญฃ้ๅญ็จฟ", # Textboxes
|
139 |
+
"ๅนด้ฝก", "ๆฏ่ชๆ็ฃ่ชไฝฟ็จ่
?", # Age, Native speaker?
|
140 |
+
"ๅฒๅญ", "ๅฒๅญ็ๆ
", # Save button, Save status
|
141 |
+
"ไธ่ผ ZIP ๆชๆก", # Download button
|
142 |
+
"่็ไธญ๏ผ่ซ็จๅโฆ" # Status message default (Chinese)
|
143 |
+
)
|
144 |
+
else:
|
145 |
+
return (
|
146 |
+
"Paiwan ASR Transcription & Correction System",
|
147 |
+
"Step 1: Audio Upload & Transcription",
|
148 |
+
"Step 2: Review & Edit Transcription",
|
149 |
+
"Step 3: User Information",
|
150 |
+
"Step 4: Save & Download",
|
151 |
+
"Audio Input", "Generate Transcript",
|
152 |
+
"Original Transcription", "Corrected Transcription",
|
153 |
+
"Age", "Native Paiwan Speaker?",
|
154 |
+
"Save", "Save Status",
|
155 |
+
"Download ZIP File",
|
156 |
+
"Processing, please waitโฆ"
|
157 |
+
)
|
158 |
+
|
159 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
160 |
# Interface
|
|
|
161 |
with gr.Blocks() as demo:
|
162 |
lang_switch = gr.Checkbox(label="ๅๆๅฐ็น้ซไธญๆ (Switch to Traditional Chinese)")
|
163 |
|
|
|
164 |
title = gr.Markdown()
|
165 |
step1 = gr.Markdown()
|
|
|
|
|
|
|
166 |
|
167 |
+
with gr.Row():
|
168 |
+
audio_input = gr.Audio(sources=["upload", "microphone"], type="filepath")
|
|
|
169 |
|
170 |
+
status_message = gr.Markdown(visible=False)
|
|
|
171 |
|
172 |
+
step2 = gr.Markdown()
|
173 |
+
with gr.Row():
|
174 |
+
transcribe_button = gr.Button()
|
|
|
175 |
|
176 |
+
original_text = gr.Textbox(interactive=False, lines=5)
|
177 |
+
corrected_text = gr.Textbox(interactive=True, lines=5)
|
|
|
|
|
|
|
|
|
|
|
178 |
|
179 |
+
step3 = gr.Markdown()
|
180 |
+
with gr.Row():
|
181 |
+
age_input = gr.Slider(minimum=0, maximum=100, step=1, value=25)
|
182 |
+
native_speaker_input = gr.Checkbox(value=True)
|
183 |
|
184 |
+
step4 = gr.Markdown()
|
185 |
+
with gr.Row():
|
186 |
+
save_button = gr.Button()
|
187 |
+
save_status = gr.Textbox(interactive=False)
|
188 |
+
|
189 |
+
with gr.Row():
|
190 |
+
download_button = gr.Button()
|
191 |
+
download_output = gr.File()
|
192 |
+
|
193 |
+
# Initialize UI texts according to default language (English)
|
194 |
+
(title_text, step1_text, step2_text, step3_text, step4_text,
|
195 |
+
audio_label, transcribe_label, orig_label, corr_label,
|
196 |
+
age_label, native_label, save_label, save_status_label,
|
197 |
+
download_label, default_status) = toggle_language(False)
|
198 |
+
|
199 |
+
title.value = title_text
|
200 |
+
step1.value = step1_text
|
201 |
+
step2.value = step2_text
|
202 |
+
step3.value = step3_text
|
203 |
+
step4.value = step4_text
|
204 |
+
audio_input.label = audio_label
|
205 |
+
transcribe_button.value = transcribe_label
|
206 |
+
original_text.label = orig_label
|
207 |
+
corrected_text.label = corr_label
|
208 |
+
age_input.label = age_label
|
209 |
+
native_speaker_input.label = native_label
|
210 |
+
save_button.value = save_label
|
211 |
+
save_status.label = save_status_label
|
212 |
+
download_button.value = download_label
|
213 |
+
status_message.value = default_status
|
214 |
+
|
215 |
+
# Language switcher
|
216 |
+
lang_switch.change(
|
217 |
+
toggle_language,
|
218 |
+
inputs=lang_switch,
|
219 |
+
outputs=[title, step1, step2, step3, step4, audio_input, transcribe_button,
|
220 |
+
original_text, corrected_text, age_input, native_speaker_input,
|
221 |
+
save_button, save_status, download_button, status_message]
|
222 |
+
)
|
223 |
|
224 |
+
# Automatic transcription on audio upload
|
|
|
225 |
audio_input.change(
|
226 |
+
transcribe_with_status,
|
227 |
+
inputs=audio_input,
|
228 |
+
outputs=[original_text, corrected_text, status_message]
|
229 |
+
)
|
230 |
+
|
231 |
+
# Manual transcription button (optional)
|
232 |
+
transcribe_button.click(
|
233 |
+
transcribe_with_status,
|
234 |
inputs=audio_input,
|
235 |
+
outputs=[original_text, corrected_text, status_message]
|
236 |
)
|
237 |
|
|
|
238 |
save_button.click(
|
239 |
store_correction,
|
240 |
inputs=[original_text, corrected_text, audio_input, age_input, native_speaker_input],
|
241 |
+
outputs=save_status
|
242 |
)
|
243 |
|
244 |
download_button.click(
|
245 |
prepare_download,
|
246 |
inputs=[audio_input, original_text, corrected_text],
|
247 |
+
outputs=download_output
|
248 |
)
|
249 |
|
250 |
demo.launch()
|