-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyoutube_download.py
256 lines (233 loc) · 8.95 KB
/
youtube_download.py
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
# coding=utf-8
import yt_dlp
import os
from moviepy import VideoFileClip, vfx
import uuid
import logging
base_dir = os.path.abspath(os.path.dirname(__file__))
DEFAULT_COOKIE_TXT_PATH = os.path.join(base_dir, "cookies.txt")
NO_DL_OPTS = {
"skip_download": True,
"quiet": False,
"no_warnings": True,
"ignoreerrors": True,
"nocheckcertificate": True,
"restrictfilenames": True,
"noplaylist": True,
"logtostderr": False,
"default_search": "auto",
"usenetrc": False,
"fixup": "detect_or_warn",
"cookiefile": DEFAULT_COOKIE_TXT_PATH
# "username": "oauth2",
# "password": "",
}
class Video:
def __init__(self, url: str, cookie_file_path: str = DEFAULT_COOKIE_TXT_PATH):
self.url = url
self.full_info = self.get_full_info(url)
self.cookie_file_path = (
cookie_file_path if cookie_file_path else DEFAULT_COOKIE_TXT_PATH
)
def download(self, file_path: str):
dl_opts = {
"format": "bestaudio/best",
"outtmpl": file_path,
"restrictfilenames": True,
"noplaylist": True,
"nocheckcertificate": True,
"logtostderr": False,
"default_search": "auto",
"usenetrc": False,
"fixup": "detect_or_warn",
"cookiefile": self.cookie_file_path,
}
with yt_dlp.YoutubeDL(dl_opts) as ydl:
return ydl.download([self.url])
def download_section(self, file_path: str, start_time: int, end_time: int):
dl_opts = {
"format": "bestaudio/best",
"outtmpl": file_path,
"restrictfilenames": True,
"noplaylist": True,
"nocheckcertificate": True,
"logtostderr": False,
"default_search": "auto",
"usenetrc": False,
"fixup": "detect_or_warn",
"external_downloader": "ffmpeg",
"external_downloader_args": {
"ffmpeg_i": ["-ss", str(start_time), "-to", str(end_time)],
},
"cookiefile": self.cookie_file_path,
# "username": "oauth2",
# "password": "",
}
with yt_dlp.YoutubeDL(dl_opts) as ydl:
return ydl.download([self.url])
def download_section_in_mp4(
self,
file_path: str,
start_time: int,
end_time: int,
use_legacy: bool = False,
keep_cache: bool = False,
):
if not use_legacy:
dl_opts = {
"merge_output_format": "mp4",
"final_ext": "mp4",
"format": "bestaudio+bestvideo/best",
"outtmpl": file_path,
"restrictfilenames": True,
"noplaylist": True,
"nocheckcertificate": True,
"logtostderr": False,
"default_search": "auto",
"usenetrc": False,
"fixup": "detect_or_warn",
"external_downloader": "ffmpeg",
"external_downloader_args": {
"ffmpeg_i": ["-ss", str(start_time), "-to", str(end_time)],
},
"cookiefile": self.cookie_file_path,
# "username": "oauth2",
# "password": "",
}
with yt_dlp.YoutubeDL(dl_opts) as ydl:
return ydl.download([self.url])
else:
cached_file_name = "cache_" + self.get_id() + ".mp4"
if not os.path.exists(cached_file_name):
self.download_in_mp4(cached_file_name)
v_obj = VideoEditor(cached_file_name, use_ffmpeg=True)
v_obj.clip(start_time, end_time)
v_obj.save_video(file_path)
if not keep_cache:
os.remove(cached_file_name)
def download_in_mp4(self, file_path: str):
dl_opts = {
"merge_output_format": "mp4",
"final_ext": "mp4",
"format": "bestaudio+bestvideo/best",
"outtmpl": file_path,
"restrictfilenames": True,
"noplaylist": True,
"nocheckcertificate": True,
"logtostderr": False,
"default_search": "auto",
"usenetrc": False,
"fixup": "detect_or_warn",
"cookiefile": self.cookie_file_path,
# "username": "oauth2",
# "password": "",
}
with yt_dlp.YoutubeDL(dl_opts) as ydl:
return ydl.download([self.url])
def get_id(self):
info_dict = self.full_info
vid = info_dict["id"]
return vid
def get_length(self):
info_dict = self.full_info
duration = info_dict["duration"]
return duration
def get_thumbnail(self):
info_dict = self.full_info
thumbnail = info_dict["thumbnail"]
return thumbnail
def get_title(self):
info_dict = self.full_info
title = info_dict["title"]
return title
def get_uploader(self):
info_dict = self.full_info
uploader = info_dict["uploader"]
return uploader
def get_extractor(self):
info_dict = self.full_info
extractor = info_dict["extractor"]
return extractor
def is_live(self) -> bool:
info_dict = self.full_info
if info_dict.get("is_live", None) is None:
return False
return info_dict["is_live"]
@staticmethod
def get_full_info(url) -> dict:
with yt_dlp.YoutubeDL(NO_DL_OPTS) as ydl:
info_dict = ydl.extract_info(url, download=False)
if info_dict is None:
raise RuntimeError(
"`get_full_info` failed. Are you blocked by YouTube?"
)
return info_dict
class VideoEditor:
def __init__(self, file_path: str, use_ffmpeg: bool = False):
self.clip_duration = None
self.file_path = file_path
if not use_ffmpeg:
self.clip_obj = VideoFileClip(file_path)
self.use_ffmpeg = use_ffmpeg
self.ffmpeg_cmds: list[str] = []
self.clip_duration: float
def __get_duration(self) -> float:
if self.clip_duration:
return self.clip_duration
return float(os.popen(f"ffprobe -i {self.file_path} -show_entries format=duration -v quiet -of csv=\"p=0\"").read())
def clip(self, start_time: float, end_time: float):
if self.use_ffmpeg:
self.ffmpeg_cmds.append(f"ffmpeg -y -i %INPUT -ss {start_time} -c copy -to {end_time} %OUTPUT")
else:
self.clip_obj = self.clip_obj.subclipped(start_time, end_time)
self.clip_duration = end_time - start_time
def fade(self, seconds: float, fade_in: bool = True, fade_out: bool = True):
if self.use_ffmpeg:
duration = self.__get_duration()
self.ffmpeg_cmds.append(
"ffmpeg -y -i %INPUT "
f"-vf fade=type=out:st={duration - seconds}:d={seconds} "
f"-af afade=type=out:st={duration - seconds}:d={seconds} "
f"-c:v libsvtav1 -c:a libopus -vbr:a off -b:a 140k %OUTPUT"
)
self.ffmpeg_cmds.append(
"ffmpeg -y -i %INPUT "
f"-vf fade=type=in:st=1:d={seconds} "
f"-af afade=type=in:st=1:d={seconds} "
f"-c:v libsvtav1 -c:a libopus -vbr:a off -b:a 140k %OUTPUT"
)
else:
if fade_in:
self.clip_obj = self.clip_obj.with_effects([vfx.FadeIn(seconds)])
if fade_out:
self.clip_obj = self.clip_obj.with_effects([vfx.FadeOut(seconds)])
def save_video(self, destination_file_path: str = None):
if destination_file_path is None:
destination_file_path = self.file_path
random_file_name = str(uuid.uuid4()).split("-")[-1] + ".mp4"
if not self.use_ffmpeg:
self.clip_obj.write_videofile(random_file_name)
self.clip_obj.close()
else:
input_file_path = self.file_path
another_random_file_name = destination_file_path
semi_products = []
for cmd in self.ffmpeg_cmds:
logging.debug("Running: " + cmd)
os.system(cmd.replace("%INPUT", input_file_path).replace("%OUTPUT", random_file_name))
another_random_file_name = str(uuid.uuid4()).split("-")[-1] + ".mp4"
os.replace(random_file_name, another_random_file_name)
input_file_path = another_random_file_name
semi_products.append(another_random_file_name)
random_file_name = another_random_file_name
semi_products.remove(random_file_name)
for f in semi_products:
os.remove(f)
os.replace(random_file_name, destination_file_path)
if __name__ == "__main__":
# v = Video(url=input("請貼上要下載的連結:"))
# v.download_in_mp4("test.mp4")
editor = VideoEditor("test.mp4", use_ffmpeg=True)
editor.clip(10, 45)
editor.fade(0.5)
editor.save_video("test_out.mp4")