fruk19 commited on
Commit
af53b0c
·
verified ·
1 Parent(s): 818b1e2

Create app.py

Browse files

first asr commit

Files changed (1) hide show
  1. app.py +211 -0
app.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch # นำเข้า PyTorch สำหรับการใช้งาน GPU
2
+
3
+ import gradio as gr # นำเข้า Gradio สำหรับสร้าง UI
4
+ import yt_dlp as youtube_dl # นำเข้า yt-dlp สำหรับการดาวน์โหลดวิดีโอจาก YouTube
5
+ from transformers import pipeline # นำเข้า pipeline จาก transformers สำหรับ ASR
6
+ from transformers.pipelines.audio_utils import ffmpeg_read # นำเข้า ffmpeg_read สำหรับการอ่านไฟล์เสียง
7
+
8
+ import tempfile # นำเข้า tempfile สำหรับการสร้างไฟล์ชั่วคราว
9
+ import os # นำเข้า os สำหรับการจัดการไฟล์และไดเรกทอรี
10
+
11
+ # ตั้งค่าค่าคงที่ต่าง ๆ
12
+ MODEL_NAME = "openai/whisper-large-v2" # ชื่อของโมเดลที่ใช้
13
+ BATCH_SIZE = 8 # ขนาดของ batch ที่ใช้ในการประมวลผล
14
+ FILE_LIMIT_MB = 1000 # ขนาดไฟล์สูงสุด (MB)
15
+ YT_LENGTH_LIMIT_S = 3600 # จำกัดความยาวไฟล์ YouTube สูงสุดที่ 1 ชั่วโมง
16
+
17
+ # ตรวจสอบว่ามี GPU หรือไม่ ถ้ามีให้ใช้ GPU (device=0) ถ้าไม่มีให้ใช้ CPU
18
+ device = 0 if torch.cuda.is_available() else "cpu"
19
+
20
+ # สร้าง pipeline สำหรับ automatic speech recognition (ASR)
21
+ pipe = pipeline(
22
+ task="automatic-speech-recognition", # งานที่ทำคือการรู้จำเสียงอัตโนมัติ
23
+ model=MODEL_NAME, # โมเดลที่ใช้
24
+ chunk_length_s=30, # ความยาวของ chunk ในหน่วยวินาที
25
+ device=device, # อุปกรณ์ที่ใช้ (GPU หรือ CPU)
26
+ )
27
+
28
+ def transcribe(inputs):
29
+ """
30
+ Transcribe the given audio input to text using the Whisper model.
31
+
32
+ Args:
33
+ inputs (str): Path to the audio file.
34
+
35
+ Returns:
36
+ str: Transcribed text.
37
+
38
+ Raises:
39
+ gr.Error: If no audio file is submitted.
40
+ """
41
+ if inputs is None:
42
+ # ถ้าไม่มีไฟล์เสียงถูกส่งเข้ามา ให้แสดงข้อผิดพลาด
43
+ raise gr.Error("No audio file submitted! Please upload or record an audio file before submitting your request.")
44
+
45
+ # ถอดความเสียงเป็นข้อความ
46
+ text = pipe(inputs, batch_size=BATCH_SIZE, return_timestamps=True)["text"]
47
+ return text # ส่งคืนข้อความที่ถอดความแล้ว
48
+
49
+ def _return_yt_html_embed(yt_url):
50
+ """
51
+ Return an HTML string to embed a YouTube video.
52
+
53
+ Args:
54
+ yt_url (str): YouTube video URL.
55
+
56
+ Returns:
57
+ str: HTML string for embedding the YouTube video.
58
+ """
59
+ # ดึง video_id จาก URL
60
+ video_id = yt_url.split("?v=")[-1]
61
+ # สร้าง HTML สำหรับฝังวิดีโอ YouTube
62
+ HTML_str = (
63
+ f'<center> <iframe width="500" height="320" src="https://www.youtube.com/embed/{video_id}"> </iframe>'
64
+ " </center>"
65
+ )
66
+ return HTML_str # ส่งคืน HTML string
67
+
68
+ def download_yt_audio(yt_url, filename):
69
+ """
70
+ Download audio from a YouTube video and save it to a file.
71
+
72
+ Args:
73
+ yt_url (str): YouTube video URL.
74
+ filename (str): Path to save the downloaded file.
75
+
76
+ Raises:
77
+ gr.Error: If there is a problem with downloading the YouTube video.
78
+ """
79
+ # สร้างตัวโหลดข้อมูลจาก YouTube
80
+ info_loader = youtube_dl.YoutubeDL()
81
+
82
+ try:
83
+ # ดึงข้อมูลของวิดีโอจาก YouTube โดยไม่ดาวน์โหลด
84
+ info = info_loader.extract_info(yt_url, download=False)
85
+ except youtube_dl.utils.DownloadError as err:
86
+ # ถ้ามีข้อผิดพลาดในการดึงข้อมูล ให้แสดงข้อผิดพลาด
87
+ raise gr.Error(str(err))
88
+
89
+ # ตรวจสอบความยาวของไฟล์
90
+ file_length = info["duration_string"] # ความยาวของไฟล์ในรูปแบบ HH:MM:SS
91
+ file_h_m_s = file_length.split(":") # แยกเวลาเป็นชั่วโมง นาที และวินาที
92
+ file_h_m_s = [int(sub_length) for sub_length in file_h_m_s] # แปลงค่าเวลาเป็นจำนวนเต็ม
93
+
94
+ if len(file_h_m_s) == 1:
95
+ file_h_m_s.insert(0, 0) # ถ้ามีแค่ค่าเดียว ให้เพิ่มชั่วโมงเป็น 0
96
+ if len(file_h_m_s) == 2:
97
+ file_h_m_s.insert(0, 0) # ถ้ามีสองค่า ให้เพิ่มชั่วโมงเป็น 0
98
+ # คำนวณความยาวของไฟล์ในหน่วยวินาที
99
+ file_length_s = file_h_m_s[0] * 3600 + file_h_m_s[1] * 60 + file_h_m_s[2]
100
+
101
+ if file_length_s > YT_LENGTH_LIMIT_S:
102
+ # ถ้าความยาวไฟล์เกินขีดจำกัด ให้แสดงข้อผิดพลาด
103
+ yt_length_limit_hms = time.strftime("%HH:%MM:%SS", time.gmtime(YT_LENGTH_LIMIT_S))
104
+ file_length_hms = time.strftime("%HH:%MM:%SS", time.gmtime(file_length_s))
105
+ raise gr.Error(f"Maximum YouTube length is {yt_length_limit_hms}, got {file_length_hms} YouTube video.")
106
+
107
+ # ตั้งค่าตัวเลือกสำหรับ yt-dlp
108
+ ydl_opts = {"outtmpl": filename, "format": "worstvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best"}
109
+
110
+ with youtube_dl.YoutubeDL(ydl_opts) as ydl:
111
+ try:
112
+ # ดาวน์โหลดวิดีโอจาก YouTube
113
+ ydl.download([yt_url])
114
+ except youtube_dl.utils.ExtractorError as err:
115
+ # ถ้ามีข้อผิดพลาดในการดาวน์โหลด ให้แสดงข้อผิดพลาด
116
+ raise gr.Error(str(err))
117
+
118
+ def yt_transcribe(yt_url):
119
+ """
120
+ Transcribe the audio from a YouTube video to text using the Whisper model.
121
+
122
+ Args:
123
+ yt_url (str): YouTube video URL.
124
+
125
+ Returns:
126
+ tuple: HTML string for embedding the YouTube video, transcribed text.
127
+ """
128
+ # สร้าง HTML สำหรับฝังวิดีโอ YouTube
129
+ html_embed_str = _return_yt_html_embed(yt_url)
130
+
131
+ with tempfile.TemporaryDirectory() as tmpdirname:
132
+ # สร้างไดเรกทอรีชั่วคราว
133
+ filepath = os.path.join(tmpdirname, "video.mp4")
134
+ # ดาวน์โหลดไฟล์เสียงจาก YouTube
135
+ download_yt_audio(yt_url, filepath)
136
+ with open(filepath, "rb") as f:
137
+ # อ่านข้อมูลจากไฟล์
138
+ inputs = f.read()
139
+
140
+ # อ่านข้อมูลเสียงจากไฟล์วิดีโอ
141
+ inputs = ffmpeg_read(inputs, pipe.feature_extractor.sampling_rate)
142
+ inputs = {"array": inputs, "sampling_rate": pipe.feature_extractor.sampling_rate}
143
+
144
+ # ถอดความเสียงเป็นข้อความ
145
+ text = pipe(inputs, batch_size=BATCH_SIZE, return_timestamps=True)["text"]
146
+
147
+ return html_embed_str, text # ส่งคืน HTML string และข้อความที่ถอดความแล้ว
148
+
149
+ # สร้าง UI สำหรับแอปพลิเคชันด้วย Gradio
150
+ demo = gr.Blocks()
151
+
152
+ # อินเตอร์เฟสสำหรับถอดความจากไมโครโฟน
153
+ mf_transcribe = gr.Interface(
154
+ fn=transcribe, # ฟังก์ชันที่ใช้ในการถอดความ
155
+ inputs=[
156
+ gr.inputs.Audio(source="microphone", type="filepath", optional=True), # อินพุตเป็นเสียงจากไมโครโฟน
157
+ ],
158
+ outputs="text", # ผลลัพธ์เป็นข้อความ
159
+ layout="horizontal", # เลย์เอาต์แบบแนวนอน
160
+ theme="huggingface", # ธีมของ Gradio
161
+ title="Whisper Large V2: Transcribe Audio", # ชื่อของแอปพลิเคชัน
162
+ description=(
163
+ "Transcribe long-form microphone or audio inputs with the click of a button! Demo uses the"
164
+ f" checkpoint [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and 🤗 Transformers to transcribe audio files"
165
+ " of arbitrary length."
166
+ ), # คำอธิบายของแอปพลิเคชัน
167
+ allow_flagging="never", # ไม่อนุญาตให้ flag ผลลัพธ์
168
+ )
169
+
170
+ # อินเตอร์เฟสสำหรับถอดความจากไฟล์เสียงที่อัปโหลด
171
+ file_transcribe = gr.Interface(
172
+ fn=transcribe, # ฟังก์ชันที่ใช้ในการถอดความ
173
+ inputs=[
174
+ gr.inputs.Audio(source="upload", type="filepath", optional=True, label="Audio file"), # อินพุตเป็นไฟล์เสียงที่อัปโหลด
175
+ ],
176
+ outputs="text", # ผลลัพธ์เป็นข้อความ
177
+ layout="horizontal", # เลย์เอาต์แบบแนวนอน
178
+ theme="huggingface", # ธีมของ Gradio
179
+ title="Whisper Large V2: Transcribe Audio", # ชื่อของแอปพลิเคชัน
180
+ description=(
181
+ "Transcribe long-form microphone or audio inputs with the click of a button! Demo uses the"
182
+ f" checkpoint [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and 🤗 Transformers to transcribe audio files"
183
+ " of arbitrary length."
184
+ ), # คำอธิบายของแอปพลิเคชัน
185
+ allow_flagging="never", # ไม่อนุญาตให้ flag ผลลัพธ์
186
+ )
187
+
188
+ # อินเตอร์เฟสสำหรับถอดความจากวิดีโอ YouTube
189
+ yt_transcribe = gr.Interface(
190
+ fn=yt_transcribe, # ฟังก์ชันที่ใช้ในการถอดความ
191
+ inputs=[
192
+ gr.inputs.Textbox(lines=1, placeholder="Paste the URL to a YouTube video here", label="YouTube URL"), # อินพุตเป็น URL ของ YouTube
193
+ ],
194
+ outputs=["html", "text"], # ผลลัพธ์เป็น HTML สำหรับฝังวิดีโอและข้อความที่ถอดความแล้ว
195
+ layout="horizontal", # เลย์เอาต์แบบแนวนอน
196
+ theme="huggingface", # ธีมของ Gradio
197
+ title="Whisper Large V2: Transcribe YouTube", # ชื่อของแอปพลิเคชัน
198
+ description=(
199
+ "Transcribe long-form YouTube videos with the click of a button! Demo uses the checkpoint"
200
+ f" [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and 🤗 Transformers to transcribe video files of"
201
+ " arbitrary length."
202
+ ), # คำอธิบายของแอปพลิเคชัน
203
+ allow_flagging="never", # ไม่อนุญาตให้ flag ผลลัพธ์
204
+ )
205
+
206
+ # รวม UI ของทุกส่วนเข้าด้วยกันใน Tabbed Interface
207
+ with demo:
208
+ gr.TabbedInterface([mf_transcribe, file_transcribe, yt_transcribe], ["Microphone", "Audio file", "YouTube"])
209
+
210
+ # เริ่มต้น Gradio demo
211
+ demo.launch(enable_queue=True)