abidlabs's picture
abidlabs HF staff
Create utils.py
651b30f verified
raw
history blame
1.35 kB
import gradio as gr
from pytube import YouTube
import os
from pydub import AudioSegment
import ffmpeg
def convert_to_embed_url(youtube_url):
if "youtube.com/watch?v=" in youtube_url:
video_id = youtube_url.split("v=")[1].split("&")[0]
elif "youtu.be/" in youtube_url:
video_id = youtube_url.split("youtu.be/")[1].split("?")[0]
else:
return ""
embed_url = f"https://www.youtube.com/embed/{video_id}"
return f'<iframe width="100%" height="200" src="{embed_url}" style="border-radius:10px"></iframe>'
def download_audio_from_youtube(video_url):
try:
yt = YouTube(video_url)
audio_stream = yt.streams.filter(only_audio=True).first()
downloaded_file = audio_stream.download(".")
base, ext = os.path.splitext(downloaded_file)
mp3_file = base + '.mp3'
AudioSegment.from_file(downloaded_file).export(mp3_file, format='mp3')
os.remove(downloaded_file)
return base
except Exception as e:
gr.Error(f"An error occurred: {e}")
def convert_video_to_audio(input_file):
output_file = "audio.mp3"
try:
(
ffmpeg
.input(input_file)
.output(output_file)
.run()
)
return output_file
except ffmpeg.Error as e:
gr.Error(f"An error occurred: {e}")