Marathon23 commited on
Commit
52007c6
·
verified ·
1 Parent(s): 2106f78

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -83
app.py CHANGED
@@ -1,19 +1,13 @@
1
- import spaces
2
  import torch
3
-
4
  import gradio as gr
5
- import yt_dlp as youtube_dl
6
  from transformers import pipeline
7
- from transformers.pipelines.audio_utils import ffmpeg_read
8
-
9
  import tempfile
10
- import os
11
 
 
12
  MODEL_NAME = "openai/whisper-large-v3-turbo"
13
  BATCH_SIZE = 8
14
- FILE_LIMIT_MB = 1000
15
- YT_LENGTH_LIMIT_S = 3600 # limit to 1 hour YouTube files
16
-
17
  device = 0 if torch.cuda.is_available() else "cpu"
18
 
19
  pipe = pipeline(
@@ -23,83 +17,42 @@ pipe = pipeline(
23
  device=device,
24
  )
25
 
 
26
 
27
- @spaces.GPU
28
  def transcribe(inputs, task):
29
  if inputs is None:
30
  raise gr.Error("No audio file submitted! Please upload or record an audio file before submitting your request.")
31
-
32
  text = pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)["text"]
33
- return text
34
-
35
 
36
- def _return_yt_html_embed(yt_url):
37
- video_id = yt_url.split("?v=")[-1]
38
- HTML_str = (
39
- f'<center> <iframe width="500" height="320" src="https://www.youtube.com/embed/{video_id}"> </iframe>'
40
- " </center>"
41
- )
42
- return HTML_str
43
-
44
- def download_yt_audio(yt_url, filename):
45
- info_loader = youtube_dl.YoutubeDL()
46
 
47
  try:
48
- info = info_loader.extract_info(yt_url, download=False)
49
- except youtube_dl.utils.DownloadError as err:
50
- raise gr.Error(str(err))
51
-
52
- file_length = info["duration_string"]
53
- file_h_m_s = file_length.split(":")
54
- file_h_m_s = [int(sub_length) for sub_length in file_h_m_s]
55
-
56
- if len(file_h_m_s) == 1:
57
- file_h_m_s.insert(0, 0)
58
- if len(file_h_m_s) == 2:
59
- file_h_m_s.insert(0, 0)
60
- file_length_s = file_h_m_s[0] * 3600 + file_h_m_s[1] * 60 + file_h_m_s[2]
61
-
62
- if file_length_s > YT_LENGTH_LIMIT_S:
63
- yt_length_limit_hms = time.strftime("%HH:%MM:%SS", time.gmtime(YT_LENGTH_LIMIT_S))
64
- file_length_hms = time.strftime("%HH:%MM:%SS", time.gmtime(file_length_s))
65
- raise gr.Error(f"Maximum YouTube length is {yt_length_limit_hms}, got {file_length_hms} YouTube video.")
66
-
67
- ydl_opts = {"outtmpl": filename, "format": "worstvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best"}
68
-
69
- with youtube_dl.YoutubeDL(ydl_opts) as ydl:
70
- try:
71
- ydl.download([yt_url])
72
- except youtube_dl.utils.ExtractorError as err:
73
- raise gr.Error(str(err))
74
-
75
- @spaces.GPU
76
- def yt_transcribe(yt_url, task, max_filesize=75.0):
77
- html_embed_str = _return_yt_html_embed(yt_url)
78
-
79
- with tempfile.TemporaryDirectory() as tmpdirname:
80
- filepath = os.path.join(tmpdirname, "video.mp4")
81
- download_yt_audio(yt_url, filepath)
82
- with open(filepath, "rb") as f:
83
- inputs = f.read()
84
-
85
- inputs = ffmpeg_read(inputs, pipe.feature_extractor.sampling_rate)
86
- inputs = {"array": inputs, "sampling_rate": pipe.feature_extractor.sampling_rate}
87
-
88
- text = pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)["text"]
89
-
90
- return html_embed_str, text
91
-
92
-
93
- demo = gr.Blocks(theme=gr.themes.Ocean())
94
 
95
  mf_transcribe = gr.Interface(
96
  fn=transcribe,
97
  inputs=[
98
- gr.Audio(sources="microphone", type="filepath"),
99
  gr.Radio(["transcribe", "translate"], label="Task", value="transcribe"),
100
  ],
101
  outputs="text",
102
- title="清華大學多模態課程&廖老師嫡傳弟子-第二組 「語音轉文字」model",
103
  description=(
104
  "Transcribe long-form microphone or audio inputs with the click of a button! Demo uses the"
105
  f" checkpoint [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and 🤗 Transformers to transcribe audio files"
@@ -111,7 +64,7 @@ mf_transcribe = gr.Interface(
111
  file_transcribe = gr.Interface(
112
  fn=transcribe,
113
  inputs=[
114
- gr.Audio(sources="upload", type="filepath", label="Audio file"),
115
  gr.Radio(["transcribe", "translate"], label="Task", value="transcribe"),
116
  ],
117
  outputs="text",
@@ -124,23 +77,47 @@ file_transcribe = gr.Interface(
124
  allow_flagging="never",
125
  )
126
 
127
- yt_transcribe = gr.Interface(
128
- fn=yt_transcribe,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
  inputs=[
130
- gr.Textbox(lines=1, placeholder="Paste the URL to a YouTube video here", label="YouTube URL"),
131
- gr.Radio(["transcribe", "translate"], label="Task", value="transcribe")
 
132
  ],
133
- outputs=["html", "text"],
134
- title="Whisper Large V3: Transcribe YouTube",
135
  description=(
136
- "Transcribe long-form YouTube videos with the click of a button! Demo uses the checkpoint"
137
- f" [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and 🤗 Transformers to transcribe video files of"
138
- " arbitrary length."
139
  ),
140
  allow_flagging="never",
141
  )
142
 
 
143
  with demo:
144
- gr.TabbedInterface([mf_transcribe, file_transcribe, yt_transcribe], ["Microphone", "Audio file", "YouTube"])
145
 
146
- demo.queue().launch(ssr_mode=False)
 
 
1
  import torch
 
2
  import gradio as gr
 
3
  from transformers import pipeline
4
+ import openai # Import OpenAI for GPT-4 API integration
5
+ import os # 確保導入 os
6
  import tempfile
 
7
 
8
+ # 使用 Whisper Large 模型進行語音轉錄
9
  MODEL_NAME = "openai/whisper-large-v3-turbo"
10
  BATCH_SIZE = 8
 
 
 
11
  device = 0 if torch.cuda.is_available() else "cpu"
12
 
13
  pipe = pipeline(
 
17
  device=device,
18
  )
19
 
20
+ openai_api_key = os.getenv('OPENAI_API_KEY') # Load OpenAI API key
21
 
22
+ # 語音轉文字的功能
23
  def transcribe(inputs, task):
24
  if inputs is None:
25
  raise gr.Error("No audio file submitted! Please upload or record an audio file before submitting your request.")
26
+
27
  text = pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)["text"]
28
+ return text
 
29
 
30
+ # 增加翻譯功能,呼叫 GPT-4 API
31
+ def translate_text(text, target_language):
32
+ prompt = f"Translate the following text to {target_language}:\n\n{text}"
 
 
 
 
 
 
 
33
 
34
  try:
35
+ response = openai.ChatCompletion.create(
36
+ model="gpt-4o", # 使用 GPT-4o 模型
37
+ messages=[{"role": "user", "content": prompt}],
38
+ max_tokens=500
39
+ )
40
+ translation = response.choices[0].message["content"]
41
+ return translation
42
+ except Exception as e:
43
+ return f"翻譯時出錯: {str(e)}"
44
+
45
+ # Gradio 介面
46
+ demo = gr.Blocks()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
  mf_transcribe = gr.Interface(
49
  fn=transcribe,
50
  inputs=[
51
+ gr.Audio(source="microphone", type="filepath"),
52
  gr.Radio(["transcribe", "translate"], label="Task", value="transcribe"),
53
  ],
54
  outputs="text",
55
+ title="Whisper Large V3 Turbo: Transcribe Audio",
56
  description=(
57
  "Transcribe long-form microphone or audio inputs with the click of a button! Demo uses the"
58
  f" checkpoint [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and 🤗 Transformers to transcribe audio files"
 
64
  file_transcribe = gr.Interface(
65
  fn=transcribe,
66
  inputs=[
67
+ gr.Audio(source="upload", type="filepath", label="Audio file"),
68
  gr.Radio(["transcribe", "translate"], label="Task", value="transcribe"),
69
  ],
70
  outputs="text",
 
77
  allow_flagging="never",
78
  )
79
 
80
+ # 增加翻譯���能,讓使用者選擇要翻譯的語言
81
+ def transcribe_and_translate(inputs, task, target_language):
82
+ text = transcribe(inputs, task)
83
+ if target_language != "None":
84
+ translated_text = translate_text(text, target_language)
85
+ return text, translated_text
86
+ return text, None
87
+
88
+ # 介面結合了轉錄和翻譯功能
89
+ mf_transcribe_and_translate = gr.Interface(
90
+ fn=transcribe_and_translate,
91
+ inputs=[
92
+ gr.Audio(source="microphone", type="filepath"),
93
+ gr.Radio(["transcribe", "translate"], label="Task", value="transcribe"),
94
+ gr.Dropdown(choices=["French", "German", "Spanish", "Chinese", "None"], label="Translate to Language", value="None")
95
+ ],
96
+ outputs=["text", "text"], # 兩個輸出,一個是原文,一個是翻譯後的文字
97
+ title="Whisper Large V3 Turbo: Transcribe and Translate",
98
+ description=(
99
+ "Transcribe audio from microphone inputs and optionally translate it to a selected language using OpenAI GPT-4."
100
+ ),
101
+ allow_flagging="never",
102
+ )
103
+
104
+ file_transcribe_and_translate = gr.Interface(
105
+ fn=transcribe_and_translate,
106
  inputs=[
107
+ gr.Audio(source="upload", type="filepath", label="Audio file"),
108
+ gr.Radio(["transcribe", "translate"], label="Task", value="transcribe"),
109
+ gr.Dropdown(choices=["French", "German", "Spanish", "Chinese", "None"], label="Translate to Language", value="None")
110
  ],
111
+ outputs=["text", "text"], # 兩個輸出,一個是原文,一個是翻譯後的文字
112
+ title="Whisper Large V3: Transcribe and Translate",
113
  description=(
114
+ "Transcribe audio from uploaded files and optionally translate it to a selected language using OpenAI GPT-4."
 
 
115
  ),
116
  allow_flagging="never",
117
  )
118
 
119
+ # 結合 Gradio 介面
120
  with demo:
121
+ gr.TabbedInterface([mf_transcribe_and_translate, file_transcribe_and_translate], ["Microphone Transcription", "File Transcription"])
122
 
123
+ demo.queue().launch()