yvankob commited on
Commit
634234c
1 Parent(s): adfb71c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +204 -0
app.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ 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
+ import numpy as np
8
+ from huggingface_hub import snapshot_download
9
+ from fairseq2.assets import InProcAssetMetadataProvider, asset_store
10
+ from seamless_communication.inference import Translator
11
+
12
+ import tempfile
13
+ import os
14
+
15
+
16
+ #from lang_list import (
17
+ #ASR_TARGET_LANGUAGE_NAMES,
18
+ #LANGUAGE_NAME_TO_CODE,
19
+ #S2ST_TARGET_LANGUAGE_NAMES,
20
+ #S2TT_TARGET_LANGUAGE_NAMES,
21
+ #T2ST_TARGET_LANGUAGE_NAMES,
22
+ #T2TT_TARGET_LANGUAGE_NAMES,
23
+ #TEXT_SOURCE_LANGUAGE_NAMES,
24
+ #)
25
+
26
+ CHECKPOINTS_PATH = pathlib.Path(os.getenv("CHECKPOINTS_PATH", "/home/user/app/models"))
27
+ if not CHECKPOINTS_PATH.exists():
28
+ snapshot_download(repo_id="facebook/seamless-m4t-v2-large", repo_type="model", local_dir=CHECKPOINTS_PATH)
29
+ asset_store.env_resolvers.clear()
30
+ asset_store.env_resolvers.append(lambda: "demo")
31
+ demo_metadata = [
32
+ {
33
+ "name": "seamlessM4T_v2_large@demo",
34
+ "checkpoint": f"file://{CHECKPOINTS_PATH}/seamlessM4T_v2_large.pt",
35
+ "char_tokenizer": f"file://{CHECKPOINTS_PATH}/spm_char_lang38_tc.model",
36
+ },
37
+ {
38
+ "name": "vocoder_v2@demo",
39
+ "checkpoint": f"file://{CHECKPOINTS_PATH}/vocoder_v2.pt",
40
+ },
41
+ ]
42
+ asset_store.metadata_providers.append(InProcAssetMetadataProvider(demo_metadata))
43
+
44
+
45
+ MODEL_NAME = "openai/whisper-large-v2"
46
+ BATCH_SIZE = 8
47
+ FILE_LIMIT_MB = 1000
48
+ YT_LENGTH_LIMIT_S = 3600 # limit to 1 hour YouTube files
49
+
50
+ DEFAULT_TARGET_LANGUAGE = "French"
51
+
52
+ device = 0 if torch.cuda.is_available() else "cpu"
53
+
54
+ pipe = pipeline(
55
+ task="automatic-speech-recognition",
56
+ model=MODEL_NAME,
57
+ chunk_length_s=30,
58
+ device=device,
59
+ )
60
+
61
+
62
+ def run_s2tt(input_audio: str, source_language: str, target_language: str) -> str:
63
+ preprocess_audio(input_audio)
64
+ source_language_code = LANGUAGE_NAME_TO_CODE[source_language]
65
+ target_language_code = LANGUAGE_NAME_TO_CODE[target_language]
66
+ out_texts, _ = translator.predict(
67
+ input=input_audio,
68
+ task_str="S2TT",
69
+ src_lang=source_language_code,
70
+ tgt_lang=target_language_code,
71
+ )
72
+ return str(out_texts[0])
73
+
74
+
75
+ def transcribe(inputs, task):
76
+ if inputs is None:
77
+ raise gr.Error("No audio file submitted! Please upload or record an audio file before submitting your request.")
78
+
79
+ text = pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)["text"]
80
+
81
+ # Traduire le texte transcrit en français
82
+ translated_text = run_s2tt(text, source_language, target_language)
83
+ return translated_text
84
+
85
+
86
+ def _return_yt_html_embed(yt_url):
87
+ video_id = yt_url.split("?v=")[-1]
88
+ HTML_str = (
89
+ f'<center> <iframe width="500" height="320" src="https://www.youtube.com/embed/{video_id}"> </iframe>'
90
+ " </center>"
91
+ )
92
+ return HTML_str
93
+
94
+ def download_yt_audio(yt_url, filename):
95
+ info_loader = youtube_dl.YoutubeDL()
96
+
97
+ try:
98
+ info = info_loader.extract_info(yt_url, download=False)
99
+ except youtube_dl.utils.DownloadError as err:
100
+ raise gr.Error(str(err))
101
+
102
+ file_length = info["duration_string"]
103
+ file_h_m_s = file_length.split(":")
104
+ file_h_m_s = [int(sub_length) for sub_length in file_h_m_s]
105
+
106
+ if len(file_h_m_s) == 1:
107
+ file_h_m_s.insert(0, 0)
108
+ if len(file_h_m_s) == 2:
109
+ file_h_m_s.insert(0, 0)
110
+ file_length_s = file_h_m_s[0] * 3600 + file_h_m_s[1] * 60 + file_h_m_s[2]
111
+
112
+ if file_length_s > YT_LENGTH_LIMIT_S:
113
+ yt_length_limit_hms = time.strftime("%HH:%MM:%SS", time.gmtime(YT_LENGTH_LIMIT_S))
114
+ file_length_hms = time.strftime("%HH:%MM:%SS", time.gmtime(file_length_s))
115
+ raise gr.Error(f"Maximum YouTube length is {yt_length_limit_hms}, got {file_length_hms} YouTube video.")
116
+
117
+ ydl_opts = {"outtmpl": filename, "format": "worstvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best"}
118
+
119
+ with youtube_dl.YoutubeDL(ydl_opts) as ydl:
120
+ try:
121
+ ydl.download([yt_url])
122
+ except youtube_dl.utils.ExtractorError as err:
123
+ raise gr.Error(str(err))
124
+
125
+
126
+ def yt_transcribe(yt_url, task, max_filesize=75.0):
127
+ html_embed_str = _return_yt_html_embed(yt_url)
128
+
129
+ with tempfile.TemporaryDirectory() as tmpdirname:
130
+ filepath = os.path.join(tmpdirname, "video.mp4")
131
+ download_yt_audio(yt_url, filepath)
132
+ with open(filepath, "rb") as f:
133
+ inputs = f.read()
134
+
135
+ inputs = ffmpeg_read(inputs, pipe.feature_extractor.sampling_rate)
136
+ inputs = {"array": inputs, "sampling_rate": pipe.feature_extractor.sampling_rate}
137
+
138
+ text = pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)["text"]
139
+
140
+ # Traduire le texte transcrit en français
141
+ translated_text = run_s2tt(text, source_language, target_language)
142
+ return html_embed_str, translated_text
143
+
144
+
145
+ demo = gr.Blocks()
146
+
147
+ mf_transcribe = gr.Interface(
148
+ fn=transcribe,
149
+ inputs=[
150
+ gr.inputs.Audio(source="microphone", type="filepath", optional=True),
151
+ gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
152
+ ],
153
+ outputs="text",
154
+ layout="horizontal",
155
+ theme="huggingface",
156
+ title="Whisper Large V2: Transcribe Audio",
157
+ description=(
158
+ "Transcribe long-form microphone or audio inputs with the click of a button! Demo uses the"
159
+ f" checkpoint [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and 🤗 Transformers to transcribe audio files"
160
+ " of arbitrary length."
161
+ ),
162
+ allow_flagging="never",
163
+ )
164
+
165
+ file_transcribe = gr.Interface(
166
+ fn=transcribe,
167
+ inputs=[
168
+ gr.inputs.Audio(source="upload", type="filepath", optional=True, label="Audio file"),
169
+ gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
170
+ ],
171
+ outputs="text",
172
+ layout="horizontal",
173
+ theme="huggingface",
174
+ title="Whisper Large V2: Transcribe Audio",
175
+ description=(
176
+ "Transcribe long-form microphone or audio inputs with the click of a button! Demo uses the"
177
+ f" checkpoint [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and 🤗 Transformers to transcribe audio files"
178
+ " of arbitrary length."
179
+ ),
180
+ allow_flagging="never",
181
+ )
182
+
183
+ yt_transcribe = gr.Interface(
184
+ fn=yt_transcribe,
185
+ inputs=[
186
+ gr.inputs.Textbox(lines=1, placeholder="Paste the URL to a YouTube video here", label="YouTube URL"),
187
+ gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe")
188
+ ],
189
+ outputs=["html", "text"],
190
+ layout="horizontal",
191
+ theme="huggingface",
192
+ title="Whisper Large V2: Transcribe YouTube",
193
+ description=(
194
+ "Transcribe long-form YouTube videos with the click of a button! Demo uses the checkpoint"
195
+ f" [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and 🤗 Transformers to transcribe video files of"
196
+ " arbitrary length."
197
+ ),
198
+ allow_flagging="never",
199
+ )
200
+
201
+ with demo:
202
+ gr.TabbedInterface([mf_transcribe, file_transcribe, yt_transcribe], ["Microphone", "Audio file", "YouTube"])
203
+
204
+ demo.launch(enable_queue=True)