Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import re, unidecode
|
3 |
+
from unidecode import unidecode
|
4 |
+
import yt_dlp
|
5 |
+
import os
|
6 |
+
import pydub
|
7 |
+
import numpy as np
|
8 |
+
|
9 |
+
# no space, punctuation, accent in lower string
|
10 |
+
def cleanString(string):
|
11 |
+
cleanString = unidecode(string)
|
12 |
+
cleanString = re.sub('\W+','_', cleanString)
|
13 |
+
return cleanString.lower()
|
14 |
+
|
15 |
+
def read_audio(f, normalized=False):
|
16 |
+
"""MP3 to numpy array"""
|
17 |
+
a = pydub.AudioSegment.from_mp3(f)
|
18 |
+
y = np.array(a.get_array_of_samples())
|
19 |
+
if a.channels == 2:
|
20 |
+
y = y.reshape((-1, 2))
|
21 |
+
if normalized:
|
22 |
+
return a.frame_rate, np.float32(y) / 2**15
|
23 |
+
else:
|
24 |
+
return a.frame_rate, y
|
25 |
+
|
26 |
+
def download_audio(url):
|
27 |
+
path_to_folder_audio_mp3 = "./audio/"
|
28 |
+
ydl_opts = {
|
29 |
+
'format': 'm4a/bestaudio/best',
|
30 |
+
'outtmpl': f'{path_to_folder_audio_mp3}%(title)s',
|
31 |
+
'postprocessors': [{
|
32 |
+
'key': 'FFmpegExtractAudio',
|
33 |
+
'preferredcodec': 'mp3',
|
34 |
+
}]
|
35 |
+
}
|
36 |
+
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
37 |
+
info_dict = ydl.extract_info(url, download=True)
|
38 |
+
video_title = info_dict['title']
|
39 |
+
|
40 |
+
# Rename the audio file
|
41 |
+
local_link = video_title + ".mp3"
|
42 |
+
new_local_link = cleanString(video_title) + ".mp3"
|
43 |
+
for filename in os.listdir(path_to_folder_audio_mp3):
|
44 |
+
if cleanString(local_link) == cleanString(filename):
|
45 |
+
os.rename(os.path.join(path_to_folder_audio_mp3, filename),os.path.join(path_to_folder_audio_mp3, new_local_link))
|
46 |
+
|
47 |
+
file_path = path_to_folder_audio_mp3 + new_local_link
|
48 |
+
|
49 |
+
return file_path, read_audio(file_path)
|
50 |
+
|
51 |
+
# Gradio interface
|
52 |
+
iface = gr.Interface(fn=download_audio,
|
53 |
+
inputs=gr.Textbox(label="YouTube Video URL"),
|
54 |
+
outputs=[
|
55 |
+
gr.File(label="Output Audio File"),
|
56 |
+
gr.Audio(label="Play Audio", show_download_button=False, format="mp3"),
|
57 |
+
],
|
58 |
+
allow_flagging="never"
|
59 |
+
)
|
60 |
+
iface.launch(debug=True)
|