youtube-dl / app.py
BertChristiaens's picture
add files
f57951a
raw
history blame
1.98 kB
"""This is the main module of the streamlit app that allows the user to download youtube videos as mp3 files."""
import streamlit as st
from yt_dlp import YoutubeDL
import os
from io import BytesIO
from datetime import datetime
URLS = ['https://www.youtube.com/watch?v=BaW_jenozKc']
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
'outtmpl': 'audio'
}
def download_video(url):
with YoutubeDL(ydl_opts) as ydl:
print(url)
error_code = ydl.download([url])
info = ydl.extract_info(url, download=False)
print(error_code)
return error_code, info
def main():
"""This method has a text input field, radio button and a button for downloading the video as mp3."""
st.title('Youtube to mp3')
st.write('Enter the url of the youtube video you want to download')
url = st.text_input('URL')
if st.button('Download video'):
with st.spinner('Downloading video'):
error_code, info = download_video(url)
print(info.keys())
st.session_state['latest_video'] = url
st.session_state['latest_title'] = info['fulltitle']
if error_code:
st.error('Error downloading video')
else:
st.success('Downloaded video')
if os.path.isfile('audio.mp3'):
video_url = st.session_state.get('latest_video', '/')
st.write(f"Last downloaded video is: {st.session_state.get('latest_title', '/')} with url {video_url}")
st.audio('audio.mp3')
buffer = BytesIO()
with open('audio.mp3', 'rb') as f:
buffer.write(f.read())
timestamp = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
st.download_button(label='Download mp3', data=buffer.getvalue(), file_name=f'audio_{timestamp}.mp3', mime='audio/mp3')
if __name__ == '__main__':
main()