-
Notifications
You must be signed in to change notification settings - Fork 0
/
thumbgrab.py
140 lines (120 loc) · 4.66 KB
/
thumbgrab.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
# Youtube-Thumbnail-Grabber
# Download HQ Thumbnails of YouTube videos in any playlist
# Resize them to your custom res
import logging
import os
import os.path
import sys
import pafy
import wget
from PIL import Image
logging.getLogger().setLevel(logging.ERROR)
def thumb_grab(playlist, size) -> None:
"""
Thumb Grab function which makes a directory based on the playlist name
:param playlist: playlist object from Pafy
:param size: Size of the playlist
"""
dir_name = playlist['title'] # Playlist title directory
if not os.path.exists(dir_name):
os.makedirs(dir_name)
os.chdir(dir_name)
download_thumbnail(playlist, size)
else:
os.chdir(dir_name)
download_thumbnail(playlist, size)
def download_thumbnail(playlist, size) -> None:
"""
Logic to download the thumbnail for each video.
Also renames titles in case they have invalid characters based on filesystem types and OS
:param playlist: playlist object from Pafy
:param size: size of playlist
"""
invalid_chars = {'<': '', '>': '', ':': '', '"': '', '/': '', "\\": '', '|': '', '?': '', '*': ''}
for video in playlist['items']: # default playlist dict obj has no
try:
video_id = video['playlist_meta']['encrypted_id'] # attribute for HQ thumb dl
video_obj = pafy.new(video_id) # so must grab vid ID & use pafy obj
video_title = str(video['playlist_meta']['title']).translate(str.maketrans(invalid_chars))
print(video_title)
name_format = video_title + ".jpg" # UNDER GIVEN NAMING CONVENTION w/ delimiter
thumb_url = video_obj.bigthumb
wget.download(thumb_url, name_format) # download and rename
print(" Downloading, Please wait...")
resize_thumbnail(video, playlist, size)
except Exception as e:
print("Error:", e.__class__, "Issue grabbing ", video_title, " thumbnail")
print(
"NOTE: Certain videos may have file output issues:"
"1.) if they have special characters no allowed in"
"file naming schemas). Please create an issue at \n"
"https://github.com/chakrakan/youtube-thumb-grab/"
"with the name of the file where the bug occurred.")
def resize_thumbnail(video, playlist, size) -> None:
"""
Logic to resize thumbnails retrieved from videos in playlists
:param video: the video object
:param playlist: playlist object
:param size: size of playlist
"""
if video['playlist_meta']['encrypted_id'] == playlist['items'][size - 1]['playlist_meta']['encrypted_id']:
print("Thumbnails downloaded!")
print("Would you like to resize images? Y/N")
rez_resp = input().lower().strip()
if rez_resp == "y": # this portion should create a resized version image along with orig
path = os.getcwd()
c_dir = os.listdir(path)
print("Please enter width: ")
width = int(input())
print("Please enter height: ")
height = int(input())
for item in c_dir:
if os.path.isfile(item):
im = Image.open(item)
f, e = os.path.splitext(item)
resize = im.resize((width, height), Image.ANTIALIAS)
resize.save(f + ' resized.jpg', 'JPEG', quality=90)
if item == c_dir[-1]:
print("Resizing Complete!")
reset()
elif rez_resp == "n":
reset()
def reset() -> None:
"""
Reset the script to run again for another playlist
"""
print("Would you like to download from another playlist? Y/N")
d = input(': ').lower().strip()
if d == "y":
os.chdir(os.path.dirname(sys.argv[0]))
thumb_grab()
else:
end_script()
def end_script() -> None:
"""
Output for end of script.
"""
print("Thanks for using Thumb Grab!")
sys.exit(0)
def main() -> None:
"""
Driver function for the script
"""
print("Enter Youtube playlist url: ")
playlist_url = input()
# grab playlist id
try:
playlist = pafy.get_playlist(playlist_url)
size = len(playlist['items'])
print("Playlist \"" + playlist['title'] + "\" has %s videos. Grab thumbnails? Y/N" % size)
init_resp = input().lower().strip()
if init_resp == "y":
thumb_grab(playlist, size)
else:
end_script()
except Exception as e:
print("Error:", e.__class__, "Please make sure Youtube Playlist URL is valid.")
sys.exit(2)
if __name__ == "__main__":
main()
# EOF