tbdavid2019 commited on
Commit
0d08e41
·
1 Parent(s): 0c0daff
Files changed (2) hide show
  1. app.py +20 -12
  2. requirements.txt +2 -2
app.py CHANGED
@@ -2,8 +2,9 @@ import gradio as gr
2
  import whisper
3
  import os
4
  import requests
5
- from pytube import YouTube
6
  from pydub import AudioSegment
 
 
7
 
8
  # 載入模型,預設為 small
9
  MODEL_OPTIONS = ["tiny", "base", "small", "medium", "large", "large-v2", "large-v3"]
@@ -13,18 +14,25 @@ DEFAULT_PROMPT = "請轉錄以下內容為繁體中文"
13
  # 處理 YouTube URL 並下載音訊
14
  def download_audio_from_youtube(youtube_url):
15
  try:
16
- yt = YouTube(youtube_url)
17
- video_stream = yt.streams.filter(only_audio=True, file_extension="mp4").first()
18
- if not video_stream:
19
- return None, "無法找到適合的音訊流"
20
- output_path = video_stream.download(filename="temp_audio.mp4")
 
 
 
 
 
 
 
 
21
 
22
- # 使用 pydub 轉換為 WAV 格式
23
- audio = AudioSegment.from_file(output_path)
24
- wav_output_path = "temp_audio.wav"
25
- audio.export(wav_output_path, format="wav")
26
- os.remove(output_path) # 刪除原始 MP4 文件
27
- return wav_output_path, None
28
  except Exception as e:
29
  return None, f"下載音訊失敗: {str(e)}"
30
 
 
2
  import whisper
3
  import os
4
  import requests
 
5
  from pydub import AudioSegment
6
+ import os
7
+ from yt_dlp import YoutubeDL
8
 
9
  # 載入模型,預設為 small
10
  MODEL_OPTIONS = ["tiny", "base", "small", "medium", "large", "large-v2", "large-v3"]
 
14
  # 處理 YouTube URL 並下載音訊
15
  def download_audio_from_youtube(youtube_url):
16
  try:
17
+ # 使用 yt-dlp 下載音訊
18
+ ydl_opts = {
19
+ 'format': 'bestaudio/best',
20
+ 'outtmpl': 'temp_audio.%(ext)s',
21
+ 'quiet': True,
22
+ 'postprocessors': [{
23
+ 'key': 'FFmpegExtractAudio',
24
+ 'preferredcodec': 'wav',
25
+ 'preferredquality': '192',
26
+ }],
27
+ }
28
+ with YoutubeDL(ydl_opts) as ydl:
29
+ ydl.download([youtube_url])
30
 
31
+ # 查找轉換後的音訊檔案
32
+ for file in os.listdir():
33
+ if file.endswith(".wav"):
34
+ return file, None
35
+ return None, "音訊下載失敗"
 
36
  except Exception as e:
37
  return None, f"下載音訊失敗: {str(e)}"
38
 
requirements.txt CHANGED
@@ -1,7 +1,7 @@
1
  gradio
2
  openai-whisper
3
  openai
4
- pytube
5
  imageio[ffmpeg]
6
  ffmpeg
7
- pydub
 
 
1
  gradio
2
  openai-whisper
3
  openai
 
4
  imageio[ffmpeg]
5
  ffmpeg
6
+ pydub
7
+ yt-dlp