File size: 2,335 Bytes
c5550d7
 
 
25ab9a8
977b57d
25ab9a8
c5550d7
25ab9a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c5550d7
25ab9a8
 
 
 
 
 
 
 
c5550d7
25ab9a8
 
 
 
 
 
c5550d7
25ab9a8
c5550d7
 
25ab9a8
 
 
 
 
c5550d7
25ab9a8
 
 
 
c5550d7
 
25ab9a8
 
 
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
60
61
62
63
64
import gradio as gr
import yt_dlp
import os
import tempfile

def download_video(url, cookies, progress=gr.Progress()):
    try:
        # Get the path to the cookies file if provided
        cookies_path = cookies.get('name') if cookies else None

        with tempfile.TemporaryDirectory() as temp_dir:
            # Configure yt-dlp options
            ydl_opts = {
                'format': 'bestvideo+bestaudio/best',
                'outtmpl': os.path.join(temp_dir, '%(title)s.%(ext)s'),
                'merge_output_format': 'mp4',
                'progress_hooks': [lambda d: progress_hook(d, progress)],
                'cookies': cookies_path,
                'verbose': True,
            }

            # Download video using yt-dlp
            with yt_dlp.YoutubeDL(ydl_opts) as ydl:
                info_dict = ydl.extract_info(url, download=True)

            # Read downloaded video file into memory
            video_file = info_dict.get('filename')
            if not video_file:
                return "Download Failed: Could not retrieve video file"

            with open(video_file, 'rb') as f:
                video_bytes = f.read()

            # Return the video bytes for download
            return {'name': os.path.basename(video_file), 'data': video_bytes}

    except yt_dlp.utils.DownloadError as e:
        return f"Download Failed: {str(e)}"
    except Exception as e:
        return f"Unexpected Error: {str(e)}"

def progress_hook(d, progress):
    if d['status'] == 'downloading':
        p = (d['downloaded_bytes'] / d['total_bytes']) * 100 if d['total_bytes'] else 0
        progress.update(p, desc=f"Downloading ({d['speed'] or '...'} at {d['eta'] or '...'})")

# Gradio interface configuration
iface = gr.Interface(
    fn=download_video,
    inputs=[
        gr.Textbox(label="YouTube Video URL"),
        gr.File(label="Upload your cookies.txt file (optional)", file_types=[".txt"], optional=True),
    ],
    outputs=gr.File(label="Downloaded Video", type="binary", file_count="single"),
    title="YouTube Video Downloader",
    description="Enter a YouTube video URL and upload your cookies.txt (if required) to download the video.",
    examples=[
        ["https://www.youtube.com/watch?v=dQw4w9WgXcQ", None],
    ],
)

# Launch the Gradio interface
iface.queue()
iface.launch(share=True)