File size: 13,994 Bytes
44bafb2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
import random
import argparse
import gzip
import json
import logging
import os
import shutil
import sys
import datetime as dt
import subprocess  # nosec
from typing import List, Optional

import pytubefix.exceptions as exceptions
from pytubefix import __version__
from pytubefix import CaptionQuery, Playlist, Stream
from pytubefix.helpers import safe_filename, setup_logger
from pytubefix import YouTube

logger = logging.getLogger(__name__)

def build_playback_report(youtube: YouTube) -> None:
    """Serialize the request data to json for offline debugging.
    
    :param YouTube youtube:
        A YouTube object.
    """
    ts = int(dt.datetime.now(dt.timezone.utc).timestamp())
    fp = os.path.join(os.getcwd(), f"yt-video-{youtube.video_id}-{ts}.json.gz")

    js = youtube.js
    watch_html = youtube.watch_html
    vid_info = youtube.vid_info

    with gzip.open(fp, "wb") as fh:
        fh.write(
            json.dumps(
                {
                    "url": youtube.watch_url,
                    "js": js,
                    "watch_html": watch_html,
                    "video_info": vid_info,
                }
            ).encode("utf8"),
        )

def display_progress_bar(bytes_received: int, filesize: int, ch: str = "β–ˆ", scale: float = 0.55) -> None:
    """Display a simple, pretty progress bar.

    Example:
    ~~~~~~~~
    PSY - GANGNAM STYLE(ᄀᅑᆼᄂᅑᆷ스ᄐᅑ알) MV.mp4
    ↳ |β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 100.0%

    :param int bytes_received:
        The delta between the total file size (bytes) and bytes already
        written to disk.
    :param int filesize:
        File size of the media stream in bytes.
    :param str ch:
        Character to use for presenting progress segment.
    :param float scale:
        Scale multiplier to reduce progress bar size.
    """
    columns = shutil.get_terminal_size().columns
    max_width = int(columns * scale)

    filled = int(round(max_width * bytes_received / float(filesize)))
    remaining = max_width - filled
    progress_bar = ch * filled + " " * remaining
    percent = round(100.0 * bytes_received / float(filesize), 1)
    text = f" ↳ |{progress_bar}| {percent}%\r"
    sys.stdout.write(text)
    sys.stdout.flush()

def on_progress(stream: Stream, chunk: bytes, bytes_remaining: int) -> None:  # pylint: disable=W0613
    filesize = stream.filesize
    bytes_received = filesize - bytes_remaining
    display_progress_bar(bytes_received, filesize)

def _download(stream: Stream, target: Optional[str] = None, filename: Optional[str] = None) -> None:
    filesize_megabytes = stream.filesize // 1048576
    print(f"{filename or stream.default_filename} | {filesize_megabytes} MB")
    file_path = stream.get_file_path(filename=filename, output_path=target)
    if stream.exists_at_path(file_path):
        print(f"Already downloaded at:\n{file_path}")
        return

    stream.download(output_path=target, filename=filename)
    sys.stdout.write("\n")

def _unique_name(base: str, subtype: str, media_type: str, target: str) -> str:
    """
    Given a base name, the file format, and the target directory, will generate
    a filename unique for that directory and file format.
    
    :param str base:
        The given base-name.
    :param str subtype:
        The filetype of the video which will be downloaded.
    :param str media_type:
        The media_type of the file, ie. "audio" or "video"
    :param Path target:
        Target directory for download.
    """
    counter = 0
    while True:
        file_name = f"{base}_{media_type}_{counter}"
        file_path = os.path.join(target, f"{file_name}.{subtype}")
        if not os.path.exists(file_path):
            return file_name
        counter += 1

def ffmpeg_process(youtube: YouTube, resolution: str, target: Optional[str] = None) -> None:
    """
    Decides the correct video stream to download, then calls _ffmpeg_downloader.

    :param YouTube youtube:
        A valid YouTube object.
    :param str resolution:
        YouTube video resolution.
    :param str target:
        Target directory for download
    """
    youtube.register_on_progress_callback(on_progress)
    target = target or os.getcwd()

    if resolution == None or resolution == "best":
        highest_quality_stream = youtube.streams.filter(progressive=False).order_by("resolution").last()
        mp4_stream = youtube.streams.filter(progressive=False, subtype="mp4").order_by("resolution").last()
        if highest_quality_stream.resolution == mp4_stream.resolution:
            video_stream = mp4_stream
        else:
            video_stream = highest_quality_stream
    else:
        video_stream = youtube.streams.filter(progressive=False, resolution=resolution).first()

    if not video_stream:
        print(f"No streams found for resolution {resolution}")
        return

    audio_stream = youtube.streams.filter(progressive=False).order_by("abr").last()

    video_file_name = _unique_name(youtube.title, "mp4", "video", target)
    audio_file_name = _unique_name(youtube.title, "mp4", "audio", target)

    video_path = video_stream.get_file_path(filename=video_file_name, output_path=target)
    audio_path = audio_stream.get_file_path(filename=audio_file_name, output_path=target)

    if os.path.exists(video_path) and os.path.exists(audio_path):
        print("Already downloaded both video and audio.")
        return

    _download(video_stream, target=target, filename=video_file_name)
    _download(audio_stream, target=target, filename=audio_file_name)

    # Construct the command to run ffmpeg
    command = ["ffmpeg", "-i", video_path, "-i", audio_path, "-c:v", "copy", "-c:a", "aac", "-strict", "experimental", f"{target}/{youtube.title}.mp4"]

    # Execute the command
    subprocess.run(command)

def download_by_resolution(youtube: YouTube, resolution: str, target: Optional[str] = None) -> None:
    """Download a stream by the specified resolution.

    :param YouTube youtube:
        A valid YouTube object.
    :param str resolution:
        The desired resolution of the stream.
    :param Optional[str] target:
        The target directory for the download.
    """
    print(f"Downloading {resolution}...")
    stream = youtube.streams.filter(resolution=resolution).first()
    if stream is None:
        print(f"No stream found for resolution {resolution}")
    else:
        _download(stream, target)

def download_audio(youtube: YouTube, filetype: Optional[str] = "mp4", target: Optional[str] = None) -> None:
    """Download audio stream of a YouTube video.

    :param YouTube youtube:
        A valid YouTube object.
    :param Optional[str] filetype:
        The filetype for the audio. Defaults to "mp4".
    :param Optional[str] target:
        The target directory for the download.
    """
    print("Downloading audio...")
    stream = youtube.streams.filter(progressive=False, subtype=filetype).order_by("abr").last()
    if stream is None:
        print(f"No audio stream found for filetype {filetype}")
    else:
        _download(stream, target)

def download_highest_resolution_progressive(youtube: YouTube, resolution: str, target: Optional[str] = None) -> None:
    """Download a YouTube video stream at the highest resolution.

    :param YouTube youtube:
        A valid YouTube object.
    :param str resolution:
        The resolution of the stream.
    :param Optional[str] target:
        The target directory for the download.
    """
    print("Downloading highest resolution progressive stream...")
    stream = youtube.streams.filter(progressive=True).order_by("resolution").last()
    if stream is None:
        print("No progressive stream found.")
    else:
        _download(stream, target)

def download_by_itag(youtube: YouTube, itag: int, target: Optional[str] = None) -> None:
    """Download a YouTube stream by its itag.

    :param YouTube youtube:
        A valid YouTube object.
    :param int itag:
        The itag of the desired stream.
    :param Optional[str] target:
        The target directory for the download.
    """
    stream = youtube.streams.get_by_itag(itag)
    if stream is None:
        print(f"No stream found with itag {itag}.")
    else:
        print(f"Downloading stream with itag {itag}...")
        _download(stream, target)

def download_caption(youtube: YouTube, lang_code: str, target: Optional[str] = None) -> None:
    """Download captions for a given YouTube video.

    :param YouTube youtube:
        A valid YouTube object.
    :param str lang_code:
        The language code for the desired captions.
    :param Optional[str] target:
        The target directory for the downloaded captions.
    """
    print(f"Downloading captions for language: {lang_code}...")
    caption = youtube.captions.get_by_language_code(lang_code)
    if caption is None:
        print(f"No captions found for language code: {lang_code}.")
    else:
        caption.download(target)

def _print_available_captions(captions: List[CaptionQuery]) -> None:
    """Print available captions for a YouTube video.

    :param List[CaptionQuery] captions:
        The list of available captions.
    """
    print("Available captions:")
    for caption in captions:
        print(f" - {caption.language_code}: {caption.name}")

def display_streams(youtube: YouTube) -> None:
    """Display available streams for the given YouTube video.

    :param YouTube youtube:
        A valid YouTube object.
    """
    print(f"Available streams for {youtube.title}:")
    for stream in youtube.streams:
        print(f" - {stream}")


def _parse_args(parser: argparse.ArgumentParser, args: Optional[List] = None) -> argparse.Namespace:
    parser.add_argument("url", help="The YouTube /watch or /playlist url", nargs="?")
    parser.add_argument("-V", "--version", action="version", version=f"%(prog)s {__version__}")
    parser.add_argument("--itag", type=int, help="The itag for the desired stream")
    parser.add_argument("-r", "--resolution", type=str, help="The resolution for the desired stream")
    parser.add_argument("-l", "--list", action="store_true", help="The list option causes pytubefix cli to return a list of streams available to download")
    parser.add_argument("--oauth", action="store_true", help="use oauth token")
    parser.add_argument("-v", "--verbose", action="store_true", dest="verbose", help="Set logger output to verbose output.")
    parser.add_argument("--logfile", action="store", help="logging debug and error messages into a log file")
    parser.add_argument("--build-playback-report", action="store_true", help="Save the html and js to disk")
    parser.add_argument("-c", "--caption-code", type=str, help="Download srt captions for given language code. Prints available language codes if no argument given")
    parser.add_argument('-lc', '--list-captions', action='store_true', help="List available caption codes for a video")
    parser.add_argument("-t", "--target", help="The output directory for the downloaded stream. Default is current working directory")
    parser.add_argument("-a", "--audio", const="mp4", nargs="?", help="Download the audio for a given URL at the highest bitrate available. Defaults to mp4 format if none is specified")
    parser.add_argument("-f", "--ffmpeg", const="best", nargs="?", help="Downloads the audio and video stream for resolution provided. If no resolution is provided, downloads the best resolution. Runs the command line program ffmpeg to combine the audio and video")

    return parser.parse_args(args)

def _perform_args_on_youtube(youtube: YouTube, args: argparse.Namespace) -> None:
    if len(sys.argv) == 2:
        download_highest_resolution_progressive(youtube=youtube, resolution="highest", target=args.target)

    if args.list_captions:
        _print_available_captions(youtube.captions)
    if args.list:
        display_streams(youtube)

    if args.itag:
        download_by_itag(youtube=youtube, itag=args.itag, target=args.target)
    elif args.caption_code:
        download_caption(youtube=youtube, lang_code=args.caption_code, target=args.target)
    elif args.resolution:
        download_by_resolution(youtube=youtube, resolution=args.resolution, target=args.target)
    elif args.audio:
        download_audio(youtube=youtube, filetype=args.audio, target=args.target)
    
    if args.ffmpeg:
        ffmpeg_process(youtube=youtube, resolution=args.resolution, target=args.target)

    if args.build_playback_report:
        build_playback_report(youtube)

    oauth = False
    cache = False

    if args.oauth:
        oauth = True
        cache = True

        print("Loading video...")
        youtube = YouTube(args.url, use_oauth=oauth, allow_oauth_cache=cache)

        download_highest_resolution_progressive(youtube=youtube, resolution="highest", target=args.target)


def main():
    parser = argparse.ArgumentParser(description=main.__doc__)
    args = _parse_args(parser)

    log_filename = args.logfile if args.verbose else None
    setup_logger(logging.DEBUG if args.verbose else logging.INFO, log_filename=log_filename)

    if args.verbose:
        logger.debug(f'Pytubefix version: {__version__}')

    if not args.url or "youtu" not in args.url:
        parser.print_help()
        sys.exit(0)

    if "/playlist" in args.url:
        print("Loading playlist...")
        playlist = Playlist(args.url)
        args.target = args.target or safe_filename(playlist.title)

        for youtube_video in playlist.videos:
            try:
                _perform_args_on_youtube(youtube_video, args)
            except exceptions.PytubeFixError as e:
                print(f"There was an error with video: {youtube_video}")
                print(e)

    else:
        print("Loading video...")
        youtube = YouTube(args.url)
        _perform_args_on_youtube(youtube, args)

if __name__ == "__main__":
    main()