Spaces:
Runtime error
Runtime error
| """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 clean_files(): | |
| if os.path.isfile('audio'): | |
| os.remove('audio') | |
| if os.path.isfile('audio.mp3'): | |
| os.remove('audio.mp3') | |
| 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'): | |
| clean_files() | |
| error_code, info = download_video(url) | |
| 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') and st.session_state.get('latest_video'): | |
| video_url = st.session_state.get('latest_video', '/') | |
| video_title = st.session_state.get('latest_title', '/') | |
| st.write(f"Last downloaded video is: {video_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"{video_title.replace(' ', '-')}.mp3", | |
| mime="audio/mp3") | |
| if __name__ == '__main__': | |
| main() |