semakoc commited on
Commit
0e467b4
·
verified ·
1 Parent(s): 8d0fdab

added the paiwan model and db

Browse files
Files changed (1) hide show
  1. app.py +195 -23
app.py CHANGED
@@ -1,35 +1,207 @@
 
 
 
 
 
1
  import os
2
- import json
3
  import firebase_admin
4
- from firebase_admin import credentials, firestore
5
- import gradio as gr
6
-
7
- # Fetch Firebase credentials from Hugging Face Secrets (environment variable)
8
- firebase_creds = os.environ.get('firebase_creds')
9
-
10
- if not firebase_creds:
11
- raise ValueError("❌ ERROR: The environment variable 'firebase_creds' is NOT set. Please set it in Hugging Face Secrets.")
12
-
13
- # Convert the JSON string back into a dictionary
14
- firebase_config = json.loads(firebase_creds)
15
 
16
- # Initialize Firebase with credentials
 
 
 
 
 
 
17
  cred = credentials.Certificate(firebase_config)
18
- firebase_admin.initialize_app(cred)
 
 
 
19
  db = firestore.client()
 
20
 
21
- print("✅ Firebase initialized successfully!")
 
 
 
22
 
23
- # Gradio app setup
24
  def transcribe(audio_file):
25
- # Replace with actual transcription logic
26
- return "Transcription here"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
- # Define Gradio Interface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  with gr.Blocks() as demo:
30
- audio_input = gr.Audio(source="upload", type="filepath", label="Upload Audio")
31
- output = gr.Textbox(label="Transcription")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
- audio_input.change(transcribe, inputs=audio_input, outputs=output)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
- demo.launch()
 
1
+ import gradio as gr
2
+ import torch
3
+ import librosa
4
+ from transformers import Wav2Vec2Processor, AutoModelForCTC
5
+ import zipfile
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
+ # 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
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
+
52
+ def store_correction(original_transcription, corrected_transcription, audio_file, age, native_speaker):
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/paiwan/{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': "paiwan",
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': "eleferrand/XLSR_paiwan"
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
+ "Amis 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()