| import streamlit as st |
| from pytube import YouTube |
| import os |
| import base64 |
| import time |
|
|
| def get_binary_file_downloader_html(bin_file, file_label='File'): |
| with open(bin_file, 'rb') as f: |
| data = f.read() |
| bin_str = base64.b64encode(data).decode() |
| href = f'<a href="data:application/octet-stream;base64,{bin_str}" download="{os.path.basename(bin_file)}">Download {file_label}</a>' |
| return href |
|
|
| def on_progress(stream, chunk, bytes_remaining): |
| print(' progress:', bytes_remaining, " ", end='\r', flush=True) |
|
|
| def on_complete(stream, filename): |
| print('--- Completed ---') |
| print('stream:', stream) |
| print('filename:', filename) |
|
|
| def delete_file(filepath): |
| if os.path.exists(filepath): |
| os.remove(filepath) |
|
|
| def on_download_file_click(filepath): |
| |
| time.sleep(2) |
| delete_file(filepath) |
|
|
| def main(): |
| |
| st.title("AIconvert YouTube To MP3 Converter 🎥") |
| st.markdown('<style>h1{color: red; text-align: center;}</style>', unsafe_allow_html=True) |
| |
| |
| |
|
|
| |
| with st.expander("About the App (Works well on chrome browser)"): |
| st.write("This app allows you to download MP3 audio from YouTube video url.") |
| st.write("Enter a YouTube URL in the input box below and click on 'Submit'") |
|
|
| |
| youtube_url = st.text_input("Enter YouTube URL") |
|
|
| |
| if st.button("Submit") and youtube_url: |
| progress_bar = st.progress(0, text='Processing...') |
| yt = YouTube(youtube_url) |
| yt.register_on_progress_callback(on_progress) |
| yt.register_on_complete_callback(on_complete) |
| |
| video = yt.streams.filter(only_audio=True).first() |
|
|
| initial_filename = yt.title |
| |
| destination = '.' |
| out_file = video.download(output_path=destination, filename=str(initial_filename)) |
|
|
| |
| base, ext = os.path.splitext(out_file) |
| new_file = '-'.join(initial_filename.split(' '))[-15:] + '.mp3' |
| os.rename(out_file, new_file) |
|
|
| |
| st.video(youtube_url) |
| st.header("Audio file in MP3 format") |
| |
| |
| |
| |
|
|
| |
| with open(new_file, 'rb') as f: |
| st.download_button('Download Audio', f, file_name=new_file, on_click=on_download_file_click(new_file)) |
| |
| progress_bar.progress(100, text='DONE') |
| st.success('Successfull!!') |
|
|
| if __name__ == "__main__": |
| main() |