-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnfn
executable file
·63 lines (53 loc) · 2.07 KB
/
nfn
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
#!/usr/bin/env python3
# nfn - Normalize File Name
# Made in conversation with ChatGPT / GPT-4
# 2023-05-12 tzatko
#
# dependences:
# pip install unidecode
#
import os
import argparse
from unidecode import unidecode
def sanitize_filename(filename):
# Convert to closest ASCII representation, remove leading/trailing spaces
filename = unidecode(filename).strip()
# Replace problematic characters and spaces with underscore
for char in r' <>:"/\|?*':
filename = filename.replace(char, '_')
# Trim the filename length to 200 characters, ensuring not to cut the file extension
name, ext = os.path.splitext(filename)
if len(filename) > 200:
name = name[:200-len(ext)]
filename = name + ext
return filename
def reverse_sanitize_filename(filename):
# Convert underscores to spaces
return filename.replace('_', ' ')
def normalize_filenames(root_dir, reverse=False):
for dirpath, dirnames, filenames in os.walk(root_dir, topdown=False):
for filename in filenames:
if reverse:
new_filename = reverse_sanitize_filename(filename)
else:
new_filename = sanitize_filename(filename)
if filename != new_filename:
os.rename(
os.path.join(dirpath, filename),
os.path.join(dirpath, new_filename)
)
for dirname in dirnames:
if reverse:
new_dirname = reverse_sanitize_filename(dirname)
else:
new_dirname = sanitize_filename(dirname)
if dirname != new_dirname:
os.rename(
os.path.join(dirpath, dirname),
os.path.join(dirpath, new_dirname)
)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Normalize or reverse normalize filenames")
parser.add_argument("-r", "--reverse", action="store_true", help="Reverse the renaming by changing underscores to spaces")
args = parser.parse_args()
normalize_filenames('.', reverse=args.reverse)