Hyeonsieun commited on
Commit
53a0ee6
·
verified ·
1 Parent(s): bea9333

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +182 -0
app.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ import gradio as gr
4
+
5
+ from transformers import pipeline, T5ForConditionalGeneration, T5Tokenizer
6
+
7
+ import os
8
+
9
+ import whisper
10
+
11
+ import matplotlib as plt
12
+
13
+ whisper_model = whisper.load_model('large-v2') # Whisper 모델을 불러오기
14
+
15
+
16
+ path = "Hyeonsieun/NTtoGT_1epoch"
17
+ tokenizer = T5Tokenizer.from_pretrained(path)
18
+ model = T5ForConditionalGeneration.from_pretrained(path)
19
+
20
+ BATCH_SIZE = 8
21
+ FILE_LIMIT_MB = 1000
22
+ YT_LENGTH_LIMIT_S = 3600 # limit to 1 hour YouTube files
23
+
24
+ def do_correction(text, model, tokenizer):
25
+ input_text = f"translate the text pronouncing the formula to a LaTeX equation: {text}"
26
+ inputs = tokenizer.encode(
27
+ input_text,
28
+ return_tensors='pt',
29
+ max_length=325,
30
+ padding='max_length',
31
+ truncation=True
32
+ )
33
+
34
+ # Get correct sentence ids.
35
+ corrected_ids = model.generate(
36
+ inputs,
37
+ max_length=325,
38
+ num_beams=5, # `num_beams=1` indicated temperature sampling.
39
+ early_stopping=True
40
+ )
41
+
42
+ # Decode.
43
+ corrected_sentence = tokenizer.decode(
44
+ corrected_ids[0],
45
+ skip_special_tokens=False
46
+ )
47
+ return corrected_sentence
48
+
49
+
50
+ pipe = pipeline(
51
+ task="automatic-speech-recognition",
52
+ model=MODEL_NAME,
53
+ chunk_length_s=30,
54
+ device=device,
55
+ )
56
+
57
+
58
+ def transcribe(inputs, task):
59
+ if inputs is None:
60
+ raise gr.Error("No audio file submitted! Please upload or record an audio file before submitting your request.")
61
+
62
+ text = pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)["text"]
63
+ return text
64
+
65
+
66
+ def _return_yt_html_embed(yt_url):
67
+ video_id = yt_url.split("?v=")[-1]
68
+ HTML_str = (
69
+ f'<center> <iframe width="500" height="320" src="https://www.youtube.com/embed/{video_id}"> </iframe>'
70
+ " </center>"
71
+ )
72
+ return HTML_str
73
+
74
+ def download_yt_audio(yt_url, filename):
75
+ info_loader = youtube_dl.YoutubeDL()
76
+
77
+ try:
78
+ info = info_loader.extract_info(yt_url, download=False)
79
+ except youtube_dl.utils.DownloadError as err:
80
+ raise gr.Error(str(err))
81
+
82
+ file_length = info["duration_string"]
83
+ file_h_m_s = file_length.split(":")
84
+ file_h_m_s = [int(sub_length) for sub_length in file_h_m_s]
85
+
86
+ if len(file_h_m_s) == 1:
87
+ file_h_m_s.insert(0, 0)
88
+ if len(file_h_m_s) == 2:
89
+ file_h_m_s.insert(0, 0)
90
+ file_length_s = file_h_m_s[0] * 3600 + file_h_m_s[1] * 60 + file_h_m_s[2]
91
+
92
+ if file_length_s > YT_LENGTH_LIMIT_S:
93
+ yt_length_limit_hms = time.strftime("%HH:%MM:%SS", time.gmtime(YT_LENGTH_LIMIT_S))
94
+ file_length_hms = time.strftime("%HH:%MM:%SS", time.gmtime(file_length_s))
95
+ raise gr.Error(f"Maximum YouTube length is {yt_length_limit_hms}, got {file_length_hms} YouTube video.")
96
+
97
+ ydl_opts = {"outtmpl": filename, "format": "worstvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best"}
98
+
99
+ with youtube_dl.YoutubeDL(ydl_opts) as ydl:
100
+ try:
101
+ ydl.download([yt_url])
102
+ except youtube_dl.utils.ExtractorError as err:
103
+ raise gr.Error(str(err))
104
+
105
+
106
+ def yt_transcribe(yt_url, task, max_filesize=75.0):
107
+ html_embed_str = _return_yt_html_embed(yt_url)
108
+
109
+ with tempfile.TemporaryDirectory() as tmpdirname:
110
+ filepath = os.path.join(tmpdirname, "video.mp4")
111
+ download_yt_audio(yt_url, filepath)
112
+ with open(filepath, "rb") as f:
113
+ inputs = f.read()
114
+
115
+ inputs = ffmpeg_read(inputs, pipe.feature_extractor.sampling_rate)
116
+ inputs = {"array": inputs, "sampling_rate": pipe.feature_extractor.sampling_rate}
117
+
118
+ text = pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)["text"]
119
+
120
+ return html_embed_str, text
121
+
122
+
123
+ demo = gr.Blocks()
124
+
125
+ mf_transcribe = gr.Interface(
126
+ fn=transcribe,
127
+ inputs=[
128
+ gr.inputs.Audio(source="microphone", type="filepath", optional=True),
129
+ gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
130
+ ],
131
+ outputs="text",
132
+ layout="horizontal",
133
+ theme="huggingface",
134
+ title="Whisper Large V3: Transcribe Audio",
135
+ description=(
136
+ "Transcribe long-form microphone or audio inputs with the click of a button! Demo uses the OpenAI Whisper"
137
+ f" checkpoint [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and 🤗 Transformers to transcribe audio files"
138
+ " of arbitrary length."
139
+ ),
140
+ allow_flagging="never",
141
+ )
142
+
143
+ file_transcribe = gr.Interface(
144
+ fn=transcribe,
145
+ inputs=[
146
+ gr.inputs.Audio(source="upload", type="filepath", optional=True, label="Audio file"),
147
+ gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
148
+ ],
149
+ outputs="text",
150
+ layout="horizontal",
151
+ theme="huggingface",
152
+ title="Whisper Large V3: Transcribe Audio",
153
+ description=(
154
+ "Transcribe long-form microphone or audio inputs with the click of a button! Demo uses the OpenAI Whisper"
155
+ f" checkpoint [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and 🤗 Transformers to transcribe audio files"
156
+ " of arbitrary length."
157
+ ),
158
+ allow_flagging="never",
159
+ )
160
+
161
+ yt_transcribe = gr.Interface(
162
+ fn=yt_transcribe,
163
+ inputs=[
164
+ gr.inputs.Textbox(lines=1, placeholder="Paste the URL to a YouTube video here", label="YouTube URL"),
165
+ gr.inputs.Radio(["transcribe", "translate"], label="Task", default="transcribe")
166
+ ],
167
+ outputs=["html", "text"],
168
+ layout="horizontal",
169
+ theme="huggingface",
170
+ title="Whisper Large V3: Transcribe YouTube",
171
+ description=(
172
+ "Transcribe long-form YouTube videos with the click of a button! Demo uses the OpenAI Whisper checkpoint"
173
+ f" [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and 🤗 Transformers to transcribe video files of"
174
+ " arbitrary length."
175
+ ),
176
+ allow_flagging="never",
177
+ )
178
+
179
+ with demo:
180
+ gr.TabbedInterface([mf_transcribe, file_transcribe, yt_transcribe], ["Microphone", "Audio file", "YouTube"])
181
+
182
+ demo.launch(enable_queue=True)