yvankob commited on
Commit
7fd7c54
·
1 Parent(s): 5c5156e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -94
app.py CHANGED
@@ -4,14 +4,10 @@ import gradio as gr
4
  import yt_dlp as youtube_dl
5
  from transformers import pipeline
6
  from transformers.pipelines.audio_utils import ffmpeg_read
7
- from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
8
- from flores200_codes import flores_codes
9
- from gradio.components import Audio, Dropdown, Radio, Textbox
10
 
11
  import tempfile
12
  import os
13
 
14
-
15
  MODEL_NAME = "openai/whisper-large-v2"
16
  BATCH_SIZE = 8
17
  FILE_LIMIT_MB = 1000
@@ -27,69 +23,12 @@ pipe = pipeline(
27
  )
28
 
29
 
30
- def load_models():
31
- # build model and tokenizer
32
- model_name_dict = {
33
- 'nllb-distilled-600M': 'facebook/nllb-200-distilled-600M',
34
- #'nllb-distilled-1.3B': 'facebook/nllb-200-distilled-1.3B',
35
- #'nllb-1.3B': 'facebook/nllb-200-1.3B',
36
- #'nllb-distilled-1.3B': 'facebook/nllb-200-distilled-1.3B',
37
- #'nllb-3.3B': 'facebook/nllb-200-3.3B',
38
- # 'nllb-distilled-600M': 'facebook/nllb-200-distilled-600M',
39
- }
40
-
41
- model_dict = {}
42
-
43
- for call_name, real_name in model_name_dict.items():
44
- print('\tLoading model: %s' % call_name)
45
- model = AutoModelForSeq2SeqLM.from_pretrained(real_name)
46
- tokenizer = AutoTokenizer.from_pretrained(real_name)
47
- model_dict[call_name+'_model'] = model
48
- model_dict[call_name+'_tokenizer'] = tokenizer
49
-
50
- return model_dict
51
-
52
- def translation(source, target, text):
53
- try:
54
- print("Début de la traduction")
55
- if len(model_dict) == 2:
56
- model_name = 'nllb-distilled-1.3B'
57
-
58
- start_time = time.time()
59
- source = flores_codes[source]
60
- target = flores_codes[target]
61
-
62
- model = model_dict[model_name + '_model']
63
- tokenizer = model_dict[model_name + '_tokenizer']
64
-
65
- translator = pipeline('translation', model=model, tokenizer=tokenizer, src_lang=source, tgt_lang=target)
66
- output = translator(text, max_length=400)
67
-
68
- end_time = time.time()
69
-
70
- output = output[0]['translation_text']
71
- result = {'inference_time': end_time - start_time,
72
- 'source': source,
73
- 'target': target,
74
- 'result': output}
75
- print("Fin de la transcription")
76
- except Exception as e:
77
- print(f"Erreur lors de la transcription : {e}")
78
- return result
79
-
80
-
81
- def transcribe(inputs, task, source, target):
82
  if inputs is None:
83
  raise gr.Error("No audio file submitted! Please upload or record an audio file before submitting your request.")
84
 
85
- try:
86
- print("Début de la transcription")
87
- text = pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)["text"]
88
- translated_text = translation(source, target, text)
89
- print("Fin de la transcription")
90
- except Exception as e:
91
- print(f"Erreur lors de la transcription : {e}")
92
- return text, translated_text
93
 
94
 
95
  def _return_yt_html_embed(yt_url):
@@ -102,29 +41,29 @@ def _return_yt_html_embed(yt_url):
102
 
103
  def download_yt_audio(yt_url, filename):
104
  info_loader = youtube_dl.YoutubeDL()
105
-
106
  try:
107
  info = info_loader.extract_info(yt_url, download=False)
108
  except youtube_dl.utils.DownloadError as err:
109
  raise gr.Error(str(err))
110
-
111
  file_length = info["duration_string"]
112
  file_h_m_s = file_length.split(":")
113
  file_h_m_s = [int(sub_length) for sub_length in file_h_m_s]
114
-
115
  if len(file_h_m_s) == 1:
116
  file_h_m_s.insert(0, 0)
117
  if len(file_h_m_s) == 2:
118
  file_h_m_s.insert(0, 0)
119
  file_length_s = file_h_m_s[0] * 3600 + file_h_m_s[1] * 60 + file_h_m_s[2]
120
-
121
  if file_length_s > YT_LENGTH_LIMIT_S:
122
  yt_length_limit_hms = time.strftime("%HH:%MM:%SS", time.gmtime(YT_LENGTH_LIMIT_S))
123
  file_length_hms = time.strftime("%HH:%MM:%SS", time.gmtime(file_length_s))
124
  raise gr.Error(f"Maximum YouTube length is {yt_length_limit_hms}, got {file_length_hms} YouTube video.")
125
-
126
  ydl_opts = {"outtmpl": filename, "format": "worstvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best"}
127
-
128
  with youtube_dl.YoutubeDL(ydl_opts) as ydl:
129
  try:
130
  ydl.download([yt_url])
@@ -145,28 +84,19 @@ def yt_transcribe(yt_url, task, max_filesize=75.0):
145
  inputs = {"array": inputs, "sampling_rate": pipe.feature_extractor.sampling_rate}
146
 
147
  text = pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)["text"]
148
- translated_text = translation(source, target, text)
149
-
150
- return html_embed_str, text, translated_text
151
 
152
-
153
- global model_dict
154
- model_dict = load_models()
155
 
156
 
157
  demo = gr.Blocks()
158
 
159
- lang_codes = list(flores_codes.keys())
160
-
161
  mf_transcribe = gr.Interface(
162
  fn=transcribe,
163
  inputs=[
164
- Audio(source="microphone", type="filepath"),
165
- Radio(["transcribe", "translate"], label="Task"),
166
- Dropdown(lang_codes, default='English', label='Source'),
167
- Dropdown(lang_codes, default='French', label='Target'),
168
  ],
169
- outputs=[Textbox(label="Transcribed Text"), Textbox(label="Translated Text")],
170
  layout="horizontal",
171
  theme="huggingface",
172
  title="Whisper Large V2: Transcribe Audio",
@@ -181,12 +111,10 @@ mf_transcribe = gr.Interface(
181
  file_transcribe = gr.Interface(
182
  fn=transcribe,
183
  inputs=[
184
- Audio(source="upload", type="filepath", label="Audio file"),
185
- Radio(["transcribe", "translate"], label="Task"),
186
- Dropdown(lang_codes, default='English', label='Source'),
187
- Dropdown(lang_codes, default='French', label='Target'),
188
  ],
189
- outputs=[Textbox(label="Transcribed Text"), Textbox(label="Translated Text")],
190
  layout="horizontal",
191
  theme="huggingface",
192
  title="Whisper Large V2: Transcribe Audio",
@@ -201,12 +129,10 @@ file_transcribe = gr.Interface(
201
  yt_transcribe = gr.Interface(
202
  fn=yt_transcribe,
203
  inputs=[
204
- Textbox(lines=1, placeholder="Paste the URL to a YouTube video here", label="YouTube URL"),
205
- Radio(["transcribe", "translate"], label="Task"),
206
- Dropdown(lang_codes, default='English', label='Source'),
207
- Dropdown(lang_codes, default='French', label='Target'),
208
  ],
209
- outputs=[Textbox(label="html"), Textbox(label="Transcribed Text"), Textbox(label="Translated Text")],
210
  layout="horizontal",
211
  theme="huggingface",
212
  title="Whisper Large V2: Transcribe YouTube",
@@ -221,5 +147,5 @@ yt_transcribe = gr.Interface(
221
  with demo:
222
  gr.TabbedInterface([mf_transcribe, file_transcribe, yt_transcribe], ["Microphone", "Audio file", "YouTube"])
223
 
224
- demo.launch().queue()
225
 
 
4
  import yt_dlp as youtube_dl
5
  from transformers import pipeline
6
  from transformers.pipelines.audio_utils import ffmpeg_read
 
 
 
7
 
8
  import tempfile
9
  import os
10
 
 
11
  MODEL_NAME = "openai/whisper-large-v2"
12
  BATCH_SIZE = 8
13
  FILE_LIMIT_MB = 1000
 
23
  )
24
 
25
 
26
+ def transcribe(inputs, task):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  if inputs is None:
28
  raise gr.Error("No audio file submitted! Please upload or record an audio file before submitting your request.")
29
 
30
+ text = pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)["text"]
31
+ return text
 
 
 
 
 
 
32
 
33
 
34
  def _return_yt_html_embed(yt_url):
 
41
 
42
  def download_yt_audio(yt_url, filename):
43
  info_loader = youtube_dl.YoutubeDL()
44
+
45
  try:
46
  info = info_loader.extract_info(yt_url, download=False)
47
  except youtube_dl.utils.DownloadError as err:
48
  raise gr.Error(str(err))
49
+
50
  file_length = info["duration_string"]
51
  file_h_m_s = file_length.split(":")
52
  file_h_m_s = [int(sub_length) for sub_length in file_h_m_s]
53
+
54
  if len(file_h_m_s) == 1:
55
  file_h_m_s.insert(0, 0)
56
  if len(file_h_m_s) == 2:
57
  file_h_m_s.insert(0, 0)
58
  file_length_s = file_h_m_s[0] * 3600 + file_h_m_s[1] * 60 + file_h_m_s[2]
59
+
60
  if file_length_s > YT_LENGTH_LIMIT_S:
61
  yt_length_limit_hms = time.strftime("%HH:%MM:%SS", time.gmtime(YT_LENGTH_LIMIT_S))
62
  file_length_hms = time.strftime("%HH:%MM:%SS", time.gmtime(file_length_s))
63
  raise gr.Error(f"Maximum YouTube length is {yt_length_limit_hms}, got {file_length_hms} YouTube video.")
64
+
65
  ydl_opts = {"outtmpl": filename, "format": "worstvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best"}
66
+
67
  with youtube_dl.YoutubeDL(ydl_opts) as ydl:
68
  try:
69
  ydl.download([yt_url])
 
84
  inputs = {"array": inputs, "sampling_rate": pipe.feature_extractor.sampling_rate}
85
 
86
  text = pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)["text"]
 
 
 
87
 
88
+ return html_embed_str, text
 
 
89
 
90
 
91
  demo = gr.Blocks()
92
 
 
 
93
  mf_transcribe = gr.Interface(
94
  fn=transcribe,
95
  inputs=[
96
+ gr.inputs.Audio(source="microphone", type="filepath", optional=True),
97
+ gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
 
 
98
  ],
99
+ outputs="text",
100
  layout="horizontal",
101
  theme="huggingface",
102
  title="Whisper Large V2: Transcribe Audio",
 
111
  file_transcribe = gr.Interface(
112
  fn=transcribe,
113
  inputs=[
114
+ gr.inputs.Audio(source="upload", type="filepath", optional=True, label="Audio file"),
115
+ gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
 
 
116
  ],
117
+ outputs="text",
118
  layout="horizontal",
119
  theme="huggingface",
120
  title="Whisper Large V2: Transcribe Audio",
 
129
  yt_transcribe = gr.Interface(
130
  fn=yt_transcribe,
131
  inputs=[
132
+ gr.inputs.Textbox(lines=1, placeholder="Paste the URL to a YouTube video here", label="YouTube URL"),
133
+ gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe")
 
 
134
  ],
135
+ outputs=["html", "text"],
136
  layout="horizontal",
137
  theme="huggingface",
138
  title="Whisper Large V2: Transcribe YouTube",
 
147
  with demo:
148
  gr.TabbedInterface([mf_transcribe, file_transcribe, yt_transcribe], ["Microphone", "Audio file", "YouTube"])
149
 
150
+ demo.launch(enable_queue=True)
151