-
Notifications
You must be signed in to change notification settings - Fork 0
/
renamer
executable file
·297 lines (233 loc) · 8.49 KB
/
renamer
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
#!/usr/bin/env python3
from os.path import isdir, isfile
import requests
import re
import sys
import os
class Media:
def __init__(self, tmdb_api_key, dest_path, files):
self.dest_path = dest_path
self.files = files
self.tmdb_url = "https://api.themoviedb.org/3"
self.tmdb_api_key = tmdb_api_key
self.cache = {}
def ask_to_select(self, orig_filename, selection_options):
"""Interface to select from search options"""
print(orig_filename)
print("\n".join(selection_options))
try:
selection = int(input("\nSelect option using num: "))
except KeyboardInterrupt:
exit(0)
if selection < 1 or selection > len(selection_options):
print("Index out of range...")
exit(1)
return int(selection) - 1
def confirm_and_exec(self, rename_data):
if not rename_data:
return
print("\n".join(f"{old} -> {new}" for old, new in rename_data))
try:
selection = input("\nDo you want to proceed?: ")
except KeyboardInterrupt:
exit(0)
if selection == "y":
for old, new in rename_data:
os.makedirs(os.path.dirname(new), exist_ok=True)
os.rename(old, new)
def sanitize(self, name):
blacklist = set("?:!/;'\",=")
return "".join(c for c in name if c not in blacklist)
def rename(self):
pass
class Tv(Media):
def __init__(self, tmdb_api_key, dest_path, files):
super().__init__(tmdb_api_key, dest_path, files)
def get_details(self, orig_filename, show_name):
"""Returns TMDB ID, Name of Show and Release Year"""
url = f"{self.tmdb_url}/search/tv"
res = requests.get(
url, params={"api_key": self.tmdb_api_key, "query": show_name}
)
res.raise_for_status()
res = res.json()["results"]
if not res:
new_show_name = " ".join(show_name.split()[:-1])
if new_show_name:
return self.get_details(orig_filename, new_show_name)
if len(res) == 1:
res = res[0]
else:
selection_options = [
f"{i+1} {item.get('name')} ({item.get('first_air_date')}) [{item.get('id')}]"
for i, item in enumerate(res)
]
selection = self.ask_to_select(orig_filename, selection_options)
res = res[selection]
details = (
res.get("id"),
res.get("name"),
res.get("first_air_date").split("-")[0],
)
return details
def get_season_and_episode(self, file):
"""Returns season and episode number"""
res = re.findall(r"s\d{1,2}e\d{1,2}", file.lower())
if not res:
return
season, episode = re.findall(r"\d{1,2}", res[0])
return season, episode
def extract_show(self, path):
"""Extracts TV show name from file name"""
path = re.sub(r"\W+", " ", path.lower())
res = re.split(r"s\d{1,2}e\d{1,2}", path)
return res[0].strip()
def rename(self):
rename_data = []
for file in self.files:
base_path = os.path.basename(file)
show_name = self.extract_show(base_path)
if not show_name:
continue
# print(f"{show_name=}")
show_details = None
if self.cache.get(show_name):
show_details = self.cache.get(show_name)
else:
show_details = self.get_details(base_path, show_name)
self.cache[show_name] = show_details
if not show_details:
continue
tmdb_id, tmdb_name, tmdb_year = show_details
# print(f"{tmdb_id=}, {tmdb_name=}, {tmdb_year=}")
se = self.get_season_and_episode(file)
if not se:
continue
season, episode = se
# print(f"{season=}, {episode=}")
new_path = os.path.join(
self.dest_path,
f"{self.sanitize(tmdb_name)} ({tmdb_year})",
f"Season {season}",
base_path,
)
rename_data.append((file, new_path))
self.confirm_and_exec(rename_data)
class Movie(Media):
def __init__(self, tmdb_api_key, dest_path, files):
super().__init__(tmdb_api_key, dest_path, files)
def get_name(self, file):
"""Extracts movie name from file name"""
file = re.sub(r"\W+", " ", file.lower())
res = re.split(r"\d{4}", file)
return res[0].strip()
def get_year(self, file):
res = re.findall(r"\d{4}", file.lower())
return res[0]
def get_collection(self, tmdb_id):
url = f"{self.tmdb_url}/movie/{tmdb_id}"
res = requests.get(url, params={"api_key": self.tmdb_api_key})
res.raise_for_status()
res = res.json()
# print(res)
if res.get("belongs_to_collection"):
return res.get("belongs_to_collection").get("name")
return None
def get_details(self, orig_filename, name, year):
url = f"{self.tmdb_url}/search/movie"
res = requests.get(
url, params={"api_key": self.tmdb_api_key, "query": name, "year": year}
)
res.raise_for_status()
res = res.json()["results"]
if not res:
new_name = " ".join(name.split()[:-1])
if new_name:
return self.get_details(orig_filename, new_name, year)
# print(f"{name=} {year=}")
if len(res) == 1:
res = res[0]
else:
selection_options = [
f"{i+1} {item.get('original_title')} ({item.get('release_date')}) [{item.get('id')}]"
for i, item in enumerate(res)
]
selection = self.ask_to_select(orig_filename, selection_options)
res = res[selection]
movie_collection = self.get_collection(res.get("id")) or ""
return (
res.get("id"),
res.get("original_title"),
res.get("release_date").split("-")[0],
movie_collection,
)
def rename(self):
rename_data = []
for file in self.files:
base_path = os.path.basename(file)
# print(base_path)
movie_name = self.get_name(base_path)
if not movie_name:
continue
movie_year = self.get_year(base_path)
movie_details = self.get_details(base_path, movie_name, movie_year)
if not movie_details:
continue
tmdb_id, tmdb_name, tmdb_year, tmdb_col = movie_details
new_path = os.path.join(
self.dest_path, self.sanitize(tmdb_col), f"{self.sanitize(tmdb_name)} ({tmdb_year})", base_path
)
rename_data.append((file, new_path))
self.confirm_and_exec(rename_data)
if __name__ == "__main__":
tmdb_api_key = os.getenv("TMDB_API_KEY")
if not tmdb_api_key:
print("Please export TMDB_API_KEY")
exit(1)
if len(sys.argv) < 4:
print("Usage: python3 renamer.py <tv|mov> <dest_path> <files and/or dirs>")
exit(1)
def is_media_file(file):
_, ext = os.path.splitext(file)
return ext in [".mkv", ".mp4", ".avi"]
paths = []
for path in sys.argv[3:]:
if isdir(path):
paths.extend(
[
os.path.join(r, file)
for r, _, f in os.walk(path)
for file in f
if is_media_file(file)
]
)
elif isfile(path) and is_media_file(path):
paths.append(path)
if not paths:
print("No media files found in given path")
exit(1)
media = None
if sys.argv[1] == "tv":
media = Tv(tmdb_api_key, sys.argv[2], paths)
if sys.argv[1] == "mov":
media = Movie(tmdb_api_key, sys.argv[2], paths)
if not media:
print("Invalid media type")
exit(1)
media.rename()
# delete dir if its empty after rename
print("deleting empty directories...")
for path in sys.argv[3:]:
if not isdir(path):
continue
dir_tree = [
os.path.join(r, dir)
for r, d, _ in os.walk(path, topdown=False)
for dir in d
]
dir_tree.append(path)
for d in dir_tree:
try:
os.rmdir(d)
except OSError as e:
print(e)