restore old app
Browse files
app.py
CHANGED
@@ -8,35 +8,44 @@ import firebase_admin
|
|
8 |
from firebase_admin import credentials, firestore, storage
|
9 |
from datetime import datetime, timedelta
|
10 |
import json
|
11 |
-
|
|
|
12 |
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
predicted_ids = torch.argmax(logits, dim=-1)
|
20 |
-
transcription = processor.batch_decode(predicted_ids)[0]
|
21 |
-
return transcription.replace("[UNK]", "")
|
22 |
-
except Exception as e:
|
23 |
-
return f"處理文件錯誤: {e}"
|
24 |
-
|
25 |
-
# Initialize Firebase
|
26 |
firebase_config = json.loads(os.environ.get('firebase_creds'))
|
27 |
cred = credentials.Certificate(firebase_config)
|
|
|
28 |
firebase_admin.initialize_app(cred, {
|
29 |
"storageBucket": "amis-asr-corrections-dem-8cf3d.firebasestorage.app"
|
30 |
})
|
31 |
db = firestore.client()
|
32 |
bucket = storage.bucket()
|
33 |
|
34 |
-
# Load ASR model and processor
|
35 |
MODEL_NAME = "eleferrand/XLSR_paiwan"
|
36 |
processor = Wav2Vec2Processor.from_pretrained(MODEL_NAME)
|
37 |
model = AutoModelForCTC.from_pretrained(MODEL_NAME)
|
38 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
def transcribe_both(audio_file):
|
|
|
40 |
transcription = transcribe(audio_file)
|
41 |
return transcription, transcription
|
42 |
|
@@ -44,103 +53,155 @@ def store_correction(original_transcription, corrected_transcription, audio_file
|
|
44 |
try:
|
45 |
audio_metadata = {}
|
46 |
audio_file_url = None
|
|
|
|
|
47 |
if audio_file and os.path.exists(audio_file):
|
48 |
audio, sr = librosa.load(audio_file, sr=44100)
|
49 |
duration = librosa.get_duration(y=audio, sr=sr)
|
50 |
file_size = os.path.getsize(audio_file)
|
51 |
audio_metadata = {'duration': duration, 'file_size': file_size}
|
|
|
|
|
52 |
unique_id = str(uuid.uuid4())
|
53 |
destination_path = f"audio/pai/{unique_id}.wav"
|
|
|
|
|
54 |
blob = bucket.blob(destination_path)
|
55 |
blob.upload_from_filename(audio_file)
|
|
|
|
|
56 |
audio_file_url = blob.generate_signed_url(expiration=timedelta(hours=1))
|
|
|
57 |
combined_data = {
|
58 |
-
'transcription_info': {
|
59 |
-
|
60 |
-
|
61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
}
|
|
|
63 |
db.collection('paiwan_transcriptions').add(combined_data)
|
64 |
-
return "校正保存成功!"
|
65 |
except Exception as e:
|
66 |
-
return f"保存失败: {e}"
|
67 |
|
68 |
def prepare_download(audio_file, original_transcription, corrected_transcription):
|
69 |
if audio_file is None:
|
70 |
return None
|
|
|
71 |
tmp_zip = tempfile.NamedTemporaryFile(delete=False, suffix=".zip")
|
72 |
tmp_zip.close()
|
73 |
with zipfile.ZipFile(tmp_zip.name, "w") as zf:
|
74 |
if os.path.exists(audio_file):
|
75 |
zf.write(audio_file, arcname="audio.wav")
|
|
|
76 |
orig_txt = "original_transcription.txt"
|
77 |
with open(orig_txt, "w", encoding="utf-8") as f:
|
78 |
f.write(original_transcription)
|
79 |
-
zf.write(orig_txt, arcname=
|
80 |
os.remove(orig_txt)
|
|
|
81 |
corr_txt = "corrected_transcription.txt"
|
82 |
with open(corr_txt, "w", encoding="utf-8") as f:
|
83 |
f.write(corrected_transcription)
|
84 |
-
zf.write(corr_txt, arcname=
|
85 |
os.remove(corr_txt)
|
86 |
return tmp_zip.name
|
87 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
88 |
# Interface
|
89 |
with gr.Blocks() as demo:
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
)
|
|
|
94 |
with gr.Row():
|
95 |
-
audio_input = gr.Audio(
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
step2 = gr.Markdown("步驟 2:審閱與編輯逐字稿 (Step 2: Review & Edit Transcription)")
|
100 |
with gr.Row():
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
label="更正逐字稿 (Corrected Transcription)", interactive=True, lines=5
|
106 |
-
)
|
107 |
-
# Automatically generate transcription on audio upload
|
108 |
-
audio_input.change(
|
109 |
-
transcribe_both,
|
110 |
-
inputs=audio_input,
|
111 |
-
outputs=[original_text, corrected_text],
|
112 |
-
queue=True
|
113 |
-
)
|
114 |
|
115 |
-
step3 = gr.Markdown("
|
116 |
with gr.Row():
|
117 |
-
age_input = gr.Slider(
|
118 |
-
|
119 |
-
)
|
120 |
-
native_speaker_input = gr.Checkbox(
|
121 |
-
label="母語排灣語使用者? (Native Paiwan Speaker?)", value=True
|
122 |
-
)
|
123 |
|
124 |
-
step4 = gr.Markdown("
|
125 |
with gr.Row():
|
126 |
-
save_button = gr.Button("
|
127 |
-
save_status = gr.Textbox(
|
128 |
-
|
129 |
-
)
|
130 |
-
|
131 |
with gr.Row():
|
132 |
-
download_button = gr.Button("
|
133 |
download_output = gr.File()
|
134 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
135 |
save_button.click(
|
136 |
-
store_correction,
|
137 |
-
inputs=[original_text, corrected_text, audio_input, age_input, native_speaker_input],
|
138 |
outputs=save_status
|
139 |
)
|
|
|
140 |
download_button.click(
|
141 |
-
prepare_download,
|
142 |
-
inputs=[audio_input, original_text, corrected_text],
|
143 |
outputs=download_output
|
144 |
)
|
145 |
|
146 |
-
demo.launch()
|
|
|
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 |
+
# 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, {
|
24 |
"storageBucket": "amis-asr-corrections-dem-8cf3d.firebasestorage.app"
|
25 |
})
|
26 |
db = firestore.client()
|
27 |
bucket = storage.bucket()
|
28 |
|
29 |
+
# Load the ASR model and processor
|
30 |
MODEL_NAME = "eleferrand/XLSR_paiwan"
|
31 |
processor = Wav2Vec2Processor.from_pretrained(MODEL_NAME)
|
32 |
model = AutoModelForCTC.from_pretrained(MODEL_NAME)
|
33 |
|
34 |
+
def transcribe(audio_file):
|
35 |
+
try:
|
36 |
+
audio, rate = librosa.load(audio_file, sr=16000)
|
37 |
+
input_values = processor(audio, sampling_rate=16000, return_tensors="pt").input_values
|
38 |
+
|
39 |
+
with torch.no_grad():
|
40 |
+
logits = model(input_values).logits
|
41 |
+
predicted_ids = torch.argmax(logits, dim=-1)
|
42 |
+
transcription = processor.batch_decode(predicted_ids)[0]
|
43 |
+
return transcription.replace("[UNK]", "")
|
44 |
+
except Exception as e:
|
45 |
+
return f"處理文件錯誤: {e}"
|
46 |
+
|
47 |
def transcribe_both(audio_file):
|
48 |
+
start_time = datetime.now()
|
49 |
transcription = transcribe(audio_file)
|
50 |
return transcription, transcription
|
51 |
|
|
|
53 |
try:
|
54 |
audio_metadata = {}
|
55 |
audio_file_url = None
|
56 |
+
|
57 |
+
# If an audio file is provided, upload it to Firebase Storage
|
58 |
if audio_file and os.path.exists(audio_file):
|
59 |
audio, sr = librosa.load(audio_file, sr=44100)
|
60 |
duration = librosa.get_duration(y=audio, sr=sr)
|
61 |
file_size = os.path.getsize(audio_file)
|
62 |
audio_metadata = {'duration': duration, 'file_size': file_size}
|
63 |
+
|
64 |
+
# Generate a unique identifier for the audio file
|
65 |
unique_id = str(uuid.uuid4())
|
66 |
destination_path = f"audio/pai/{unique_id}.wav"
|
67 |
+
|
68 |
+
# Create a blob and upload the file
|
69 |
blob = bucket.blob(destination_path)
|
70 |
blob.upload_from_filename(audio_file)
|
71 |
+
|
72 |
+
# Generate a signed download URL valid for 1 hour (adjust expiration as needed)
|
73 |
audio_file_url = blob.generate_signed_url(expiration=timedelta(hours=1))
|
74 |
+
|
75 |
combined_data = {
|
76 |
+
'transcription_info': {
|
77 |
+
'original_text': original_transcription,
|
78 |
+
'corrected_text': corrected_transcription,
|
79 |
+
'language': 'pai',
|
80 |
+
},
|
81 |
+
'audio_data': {
|
82 |
+
'audio_metadata': audio_metadata,
|
83 |
+
'audio_file_url': audio_file_url,
|
84 |
+
},
|
85 |
+
'user_info': {
|
86 |
+
'native_paiwan_speaker': native_speaker,
|
87 |
+
'age': age
|
88 |
+
},
|
89 |
+
'timestamp': datetime.now().isoformat(),
|
90 |
+
'model_name': MODEL_NAME
|
91 |
}
|
92 |
+
# Save data to a collection for that language
|
93 |
db.collection('paiwan_transcriptions').add(combined_data)
|
94 |
+
return "校正保存成功! (Correction saved successfully!)"
|
95 |
except Exception as e:
|
96 |
+
return f"保存失败: {e} (Error saving correction: {e})"
|
97 |
|
98 |
def prepare_download(audio_file, original_transcription, corrected_transcription):
|
99 |
if audio_file is None:
|
100 |
return None
|
101 |
+
|
102 |
tmp_zip = tempfile.NamedTemporaryFile(delete=False, suffix=".zip")
|
103 |
tmp_zip.close()
|
104 |
with zipfile.ZipFile(tmp_zip.name, "w") as zf:
|
105 |
if os.path.exists(audio_file):
|
106 |
zf.write(audio_file, arcname="audio.wav")
|
107 |
+
|
108 |
orig_txt = "original_transcription.txt"
|
109 |
with open(orig_txt, "w", encoding="utf-8") as f:
|
110 |
f.write(original_transcription)
|
111 |
+
zf.write(orig_txt, arcname="original_transcription.txt")
|
112 |
os.remove(orig_txt)
|
113 |
+
|
114 |
corr_txt = "corrected_transcription.txt"
|
115 |
with open(corr_txt, "w", encoding="utf-8") as f:
|
116 |
f.write(corrected_transcription)
|
117 |
+
zf.write(corr_txt, arcname="corrected_transcription.txt")
|
118 |
os.remove(corr_txt)
|
119 |
return tmp_zip.name
|
120 |
|
121 |
+
def toggle_language(switch):
|
122 |
+
"""Switch UI text between English and Traditional Chinese"""
|
123 |
+
if switch:
|
124 |
+
return (
|
125 |
+
"排灣語自動語音識別逐字稿與修正系統",
|
126 |
+
"步驟 1:音訊上傳與逐字稿",
|
127 |
+
"步驟 2:審閱與編輯逐字稿",
|
128 |
+
"步驟 3:使用者資訊",
|
129 |
+
"步驟 4:儲存與下載",
|
130 |
+
"音訊輸入", "語音辨識",
|
131 |
+
"原始逐字稿", "更正逐字稿",
|
132 |
+
"年齡", "母語排灣語使用者?",
|
133 |
+
"儲存更正", "儲存狀態",
|
134 |
+
"下載 ZIP 檔案"
|
135 |
+
)
|
136 |
+
else:
|
137 |
+
return (
|
138 |
+
"Paiwan ASR Transcription & Correction System",
|
139 |
+
"Step 1: Audio Upload & Transcription",
|
140 |
+
"Step 2: Review & Edit Transcription",
|
141 |
+
"Step 3: User Information",
|
142 |
+
"Step 4: Save & Download",
|
143 |
+
"Audio Input", "Transcribe Audio",
|
144 |
+
"Original Transcription", "Corrected Transcription",
|
145 |
+
"Age", "Native Paiwan Speaker?",
|
146 |
+
"Save Correction", "Save Status",
|
147 |
+
"Download ZIP File"
|
148 |
+
)
|
149 |
+
|
150 |
# Interface
|
151 |
with gr.Blocks() as demo:
|
152 |
+
lang_switch = gr.Checkbox(label="切換到繁體中文 (Switch to Traditional Chinese)")
|
153 |
+
|
154 |
+
title = gr.Markdown("Paiwan ASR Transcription & Correction System")
|
155 |
+
step1 = gr.Markdown("Step 1: Audio Upload & Transcription")
|
156 |
+
|
157 |
with gr.Row():
|
158 |
+
audio_input = gr.Audio(sources=["upload", "microphone"], type="filepath", label="Audio Input")
|
159 |
+
|
160 |
+
step2 = gr.Markdown("Step 2: Review & Edit Transcription")
|
|
|
|
|
161 |
with gr.Row():
|
162 |
+
transcribe_button = gr.Button("Transcribe Audio")
|
163 |
+
|
164 |
+
original_text = gr.Textbox(label="Original Transcription", interactive=False, lines=5)
|
165 |
+
corrected_text = gr.Textbox(label="Corrected Transcription", interactive=True, lines=5)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
166 |
|
167 |
+
step3 = gr.Markdown("Step 3: User Information")
|
168 |
with gr.Row():
|
169 |
+
age_input = gr.Slider(minimum=0, maximum=100, step=1, label="Age", value=25)
|
170 |
+
native_speaker_input = gr.Checkbox(label="Native Paiwan Speaker?", value=True)
|
|
|
|
|
|
|
|
|
171 |
|
172 |
+
step4 = gr.Markdown("Step 4: Save & Download")
|
173 |
with gr.Row():
|
174 |
+
save_button = gr.Button("Save Correction")
|
175 |
+
save_status = gr.Textbox(label="Save Status", interactive=False)
|
176 |
+
|
|
|
|
|
177 |
with gr.Row():
|
178 |
+
download_button = gr.Button("Download ZIP File")
|
179 |
download_output = gr.File()
|
180 |
|
181 |
+
lang_switch.change(
|
182 |
+
toggle_language,
|
183 |
+
inputs=lang_switch,
|
184 |
+
outputs=[title, step1, step2, step3, step4, audio_input, transcribe_button,
|
185 |
+
original_text, corrected_text, age_input, native_speaker_input,
|
186 |
+
save_button, save_status, download_button]
|
187 |
+
)
|
188 |
+
|
189 |
+
transcribe_button.click(
|
190 |
+
transcribe_both,
|
191 |
+
inputs=audio_input,
|
192 |
+
outputs=[original_text, corrected_text]
|
193 |
+
)
|
194 |
+
|
195 |
save_button.click(
|
196 |
+
store_correction,
|
197 |
+
inputs=[original_text, corrected_text, audio_input, age_input, native_speaker_input],
|
198 |
outputs=save_status
|
199 |
)
|
200 |
+
|
201 |
download_button.click(
|
202 |
+
prepare_download,
|
203 |
+
inputs=[audio_input, original_text, corrected_text],
|
204 |
outputs=download_output
|
205 |
)
|
206 |
|
207 |
+
demo.launch()
|