yvankob commited on
Commit
29d0597
·
1 Parent(s): 7fd7c54

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -135
app.py CHANGED
@@ -1,151 +1,99 @@
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
-
8
  import tempfile
 
 
9
  import os
10
-
11
- MODEL_NAME = "openai/whisper-large-v2"
12
- BATCH_SIZE = 8
13
- FILE_LIMIT_MB = 1000
14
- YT_LENGTH_LIMIT_S = 3600 # limit to 1 hour YouTube files
15
-
16
- device = 0 if torch.cuda.is_available() else "cpu"
17
-
18
- pipe = pipeline(
19
- task="automatic-speech-recognition",
20
- model=MODEL_NAME,
21
- chunk_length_s=30,
22
- device=device,
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):
35
- video_id = yt_url.split("?v=")[-1]
36
- HTML_str = (
37
- f'<center> <iframe width="500" height="320" src="https://www.youtube.com/embed/{video_id}"> </iframe>'
38
- " </center>"
39
- )
40
- return HTML_str
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])
70
- except youtube_dl.utils.ExtractorError as err:
71
- raise gr.Error(str(err))
72
 
73
-
74
- def yt_transcribe(yt_url, task, max_filesize=75.0):
75
- html_embed_str = _return_yt_html_embed(yt_url)
76
-
77
- with tempfile.TemporaryDirectory() as tmpdirname:
78
- filepath = os.path.join(tmpdirname, "video.mp4")
79
- download_yt_audio(yt_url, filepath)
80
- with open(filepath, "rb") as f:
81
- inputs = f.read()
82
-
83
- inputs = ffmpeg_read(inputs, pipe.feature_extractor.sampling_rate)
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",
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"
106
- " of arbitrary length."
107
- ),
108
- allow_flagging="never",
109
  )
110
 
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",
121
- description=(
122
- "Transcribe long-form microphone or audio inputs with the click of a button! Demo uses the"
123
- f" checkpoint [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and 🤗 Transformers to transcribe audio files"
124
- " of arbitrary length."
125
- ),
126
- allow_flagging="never",
127
- )
128
-
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",
139
- description=(
140
- "Transcribe long-form YouTube videos with the click of a button! Demo uses the checkpoint"
141
- f" [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and 🤗 Transformers to transcribe video files of"
142
- " arbitrary length."
143
- ),
144
- allow_flagging="never",
145
- )
146
-
147
- with demo:
148
- gr.TabbedInterface([mf_transcribe, file_transcribe, yt_transcribe], ["Microphone", "Audio file", "YouTube"])
149
-
150
- demo.launch(enable_queue=True)
151
 
 
1
  import torch
 
2
  import gradio as gr
3
+ from faster_whisper import WhisperModel
4
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
5
+ from pydub import AudioSegment
6
  import yt_dlp as youtube_dl
 
 
 
7
  import tempfile
8
+ from transformers.pipelines.audio_utils import ffmpeg_read
9
+ from gradio.components import Audio, Dropdown, Radio, Textbox
10
  import os
11
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
 
14
+ # Paramètres
15
+ FILE_LIMIT_MB = 1000
16
+ YT_LENGTH_LIMIT_S = 3600 # Limite de 1 heure pour les vidéos YouTube
17
+
18
+ # Charger les codes de langue
19
+ from flores200_codes import flores_codes
20
+ lang_codes = list(flores_codes.keys())
21
+
22
+ # Fonction pour déterminer le device
23
+ def set_device():
24
+ return torch.device("cuda" if torch.cuda.is_available() else "cpu")
25
+
26
+ device = set_device()
27
+
28
+ # Charger les modèles une seule fois
29
+ model_dict = {}
30
+ def load_models():
31
+ global model_dict
32
+ if not model_dict:
33
+ model_name_dict = {
34
+ #'nllb-distilled-1.3B': 'facebook/nllb-200-distilled-1.3B',
35
+ 'nllb-distilled-600M': 'facebook/nllb-200-distilled-600M',
36
+ #'nllb-1.3B': 'facebook/nllb-200-1.3B',
37
+ #'nllb-distilled-1.3B': 'facebook/nllb-200-distilled-1.3B',
38
+ #'nllb-3.3B': 'facebook/nllb-200-3.3B',
39
+ # 'nllb-distilled-600M': 'facebook/nllb-200-distilled-600M',
40
+ }
41
+ for call_name, real_name in model_name_dict.items():
42
+ model = AutoModelForSeq2SeqLM.from_pretrained(real_name)
43
+ tokenizer = AutoTokenizer.from_pretrained(real_name)
44
+ model_dict[call_name+'_model'] = model
45
+ model_dict[call_name+'_tokenizer'] = tokenizer
46
+
47
+ load_models()
48
+
49
+ # Fonction pour la transcription
50
+ def transcribe_audio(audio_file):
51
+ model_size = "large-v2"
52
+ model = WhisperModel(model_size)
53
+ # model = WhisperModel(model_size, device=device, compute_type="int8")
54
+ segments, _ = model.transcribe(audio_file, beam_size=1)
55
+ transcriptions = [("[%.2fs -> %.2fs]" % (seg.start, seg.end), seg.text) for seg in segments]
56
+ return transcriptions
57
+
58
+ # Fonction pour la traduction
59
+ def traduction(text, source_lang, target_lang):
60
+ model_name = "nllb-distilled-600M"
61
+ model = model_dict[model_name + "_model"]
62
+ tokenizer = model_dict[model_name + "_tokenizer"]
63
+ translator = pipeline("translation", model=model, tokenizer=tokenizer)
64
+ return translator(text, src_lang=flores_codes[source_lang], tgt_lang=flores_codes[target_lang])[0]["translation_text"]
65
+
66
+ # Fonction principale
67
+ def full_transcription_and_translation(audio_file, source_lang, target_lang):
68
+ transcriptions = transcribe_audio(audio_file)
69
+ translations = [(timestamp, traduction(text, source_lang, target_lang)) for timestamp, text in transcriptions]
70
+ return transcriptions, translations
71
+
72
+ # Téléchargement audio YouTube
73
  def download_yt_audio(yt_url, filename):
74
+ with youtube_dl.YoutubeDL({'format': 'bestaudio'}) as ydl:
75
+ ydl.download([yt_url])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
+ # Interface Gradio
78
+ def gradio_interface(audio_file, source_lang, target_lang):
79
+ transcriptions, translations = full_transcription_and_translation(audio_file, source_lang, target_lang)
80
+ transcribed_text = '\n'.join([f"{timestamp}: {text}" for timestamp, text in transcriptions])
81
+ translated_text = '\n'.join([f"{timestamp}: {text}" for timestamp, text in translations])
82
+ return transcribed_text, translated_text
83
 
 
 
 
 
 
84
 
85
+ iface = gr.Interface(
86
+ fn=gradio_interface,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  inputs=[
88
+ gr.Audio(type="filepath"),
89
+ gr.Dropdown(lang_codes, value='French', label='Source Language'),
90
+ gr.Dropdown(lang_codes, value='English', label='Target Language'),
91
  ],
92
+ outputs=[
93
+ gr.Textbox(label="Transcribed Text"),
94
+ gr.Textbox(label="Translated Text")
95
+ ]
 
 
 
 
 
 
96
  )
97
 
98
+ iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99