File size: 1,629 Bytes
41f49f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
from pytube import YouTube
import validators
import os

class YouTubeDownloader:
    def __init__(self):
        st.set_page_config(page_title="YouTube Video Downloader", layout="wide")
        self.output_dir = "downloads"
        os.makedirs(self.output_dir, exist_ok=True)

    def run(self):
        st.title("YouTube Video Downloader")
        url = st.text_input("Enter YouTube URL to download:")
        if url:
            if self.validate_url(url):
                video, file_size = self.download_video(url)
                if video:
                    self.display_video(video)
                    self.cleanup(video)
                else:
                    st.error("Download failed. Please try again.")

    def validate_url(self, url):
        if not validators.url(url):
            st.error("Invalid URL. Please enter a valid YouTube URL.")
            return False
        return True

    def download_video(self, url):
        st.info("Downloading... Please wait.")
        try:
            yt = YouTube(url)
            stream = yt.streams.get_highest_resolution()
            video = stream.download(output_path=self.output_dir, filename="video")
            st.success("Downloaded successfully!")

            return video, os.path.getsize(video)
        except Exception as e:
            st.error(f"An error occurred: {str(e)}")
            return None, 0

    def display_video(self, video_path):
        st.video(video_path)

    def cleanup(self, video_path):
        os.remove(video_path)

if __name__ == "__main__":
    downloader = YouTubeDownloader()
    downloader.run()