Spaces:
Runtime error
Runtime error
File size: 1,984 Bytes
f57951a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
"""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() |