Spaces:
Runtime error
Runtime error
Create utils.py
Browse files
utils.py
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from pytube import YouTube
|
3 |
+
import os
|
4 |
+
from pydub import AudioSegment
|
5 |
+
import ffmpeg
|
6 |
+
|
7 |
+
|
8 |
+
def convert_to_embed_url(youtube_url):
|
9 |
+
if "youtube.com/watch?v=" in youtube_url:
|
10 |
+
video_id = youtube_url.split("v=")[1].split("&")[0]
|
11 |
+
elif "youtu.be/" in youtube_url:
|
12 |
+
video_id = youtube_url.split("youtu.be/")[1].split("?")[0]
|
13 |
+
else:
|
14 |
+
return ""
|
15 |
+
embed_url = f"https://www.youtube.com/embed/{video_id}"
|
16 |
+
return f'<iframe width="100%" height="200" src="{embed_url}" style="border-radius:10px"></iframe>'
|
17 |
+
|
18 |
+
def download_audio_from_youtube(video_url):
|
19 |
+
try:
|
20 |
+
yt = YouTube(video_url)
|
21 |
+
audio_stream = yt.streams.filter(only_audio=True).first()
|
22 |
+
downloaded_file = audio_stream.download(".")
|
23 |
+
base, ext = os.path.splitext(downloaded_file)
|
24 |
+
mp3_file = base + '.mp3'
|
25 |
+
AudioSegment.from_file(downloaded_file).export(mp3_file, format='mp3')
|
26 |
+
os.remove(downloaded_file)
|
27 |
+
return base
|
28 |
+
except Exception as e:
|
29 |
+
gr.Error(f"An error occurred: {e}")
|
30 |
+
|
31 |
+
def convert_video_to_audio(input_file):
|
32 |
+
output_file = "audio.mp3"
|
33 |
+
try:
|
34 |
+
(
|
35 |
+
ffmpeg
|
36 |
+
.input(input_file)
|
37 |
+
.output(output_file)
|
38 |
+
.run()
|
39 |
+
)
|
40 |
+
return output_file
|
41 |
+
except ffmpeg.Error as e:
|
42 |
+
gr.Error(f"An error occurred: {e}")
|
43 |
+
|