-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsorter.py
More file actions
227 lines (203 loc) · 6.86 KB
/
sorter.py
File metadata and controls
227 lines (203 loc) · 6.86 KB
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
import os
import re
import sys
import argparse
from datetime import datetime
# Usage
# Single folder (default)
# python sorter.py Ros
#
# All subfolders with confirmation
# python sorter.py --all
#
# All subfolders auto
# python sorter.py --all-auto
#
# Dry-run example
# python sorter.py --all-auto --dry-run
# view "audit.log" for errors encountered in usage
# Given folders with the following format:
# \collection
# ├─\Azure
# │ ├── Azure-Co1.jpg
# │ ├── Azure-Co2.jpg
# │ ├── Azure-Co3.jpg
# │ ├── Azure-Li1.jpg
# │ ├── Azure-Li2.jpg
# │ ├── Azure-We1.jpg
# │ ├── Azure-We2.jpg
# │ └── Azure-We3.jpg
# └──\Verdant
# ├── Verdant-1.jpg
# ├── Verdant-2.jpg
# ├── Verdant-3.jpg
# ├── Verdant-Li1.jpg
# ├── Verdant-Li2.jpg
# ├── Verdant2-1.jpg
# ├── Verdant2-2.jpg
# ├── Verdant2-3.jpg
# ├── Verdant2-Li1.jpg
# ├── Verdant2-Li2.jpg
# ├── Verdant-We1.jpg
# ├── Verdant-We2.jpg
# └── Verdant-We3.jpg
#
# Will sort and rename numerically, based on SORT_ORDER
# \collection
# ├─\Azure
# │ ├── 000.jpg
# │ ├── 001.jpg
# │ ├── 003.jpg
# │ ├── 004.jpg
# │ ├── 005.jpg
# │ ├── 006.jpg
# │ ├── 007.jpg
# │ └── 008.jpg
# └──\Verdant
# ├── 000.jpg
# ├── 001.jpg
# ├── 002.jpg
# ├── 003.jpg
# ├── 004.jpg
# ├── 005.jpg
# ├── 006.jpg
# ├── 007.jpg
# ├── 008.jpg
# ├── 009.jpg
# ├── 010.jpg
# ├── 011.jpg
# ├── 012.jpg
# └── 013.jpg
#
# The tool will skip over folders that are already sorted numerically
# It will silently delete files with "Preview" in the title, and files named ".nomedia"
# ---------- CONFIG ----------
SORT_ORDER = ["Dr", "Cl", "Co", "WeCl", "Li", "Bi", "Top", "To", "Bo", "Nu", "Le", "Cu", "We"]
PREVIEW_TOKEN = "Preview"
WHITELIST = [".nomedia"]
NUMERIC_RE = re.compile(r"^\d{3}\..+$")
AUDIT_LOG = "audit.log"
# ----------------------------
def log_error(message):
with open(AUDIT_LOG, "a") as f:
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
f.write(f"[{timestamp}] {message}\n")
def clean_folder(folder, dry_run):
"""Delete Preview and whitelisted files silently."""
for f in os.listdir(folder):
path = os.path.join(folder, f)
if PREVIEW_TOKEN in f or f in WHITELIST:
if dry_run:
print(f"[dry-run] deleting {path}")
else:
print(f"Deleting {path}")
os.remove(path)
def parse_filename(filename):
filename = filename.strip()
# Already numeric? skip
if NUMERIC_RE.match(filename):
return {"numeric": True, "filename": filename}
# Find all letter-number sequences
matches = re.findall(r"([A-Za-z]+)(\d+)", filename)
for cat, idx in matches:
if cat in SORT_ORDER:
return {
"numeric": False,
"category": cat,
"index": int(idx),
"filename": filename
}
# If no valid SORT_ORDER token, treat as category-less
# Try to extract trailing number for ordering
m = re.search(r"(\d+)", filename)
index = int(m.group(1)) if m else 0
return {
"numeric": False,
"category": None, # category-less
"index": index,
"filename": filename
}
def sort_key(parsed):
"""Sort files: category-less first, then SORT_ORDER categories, numeric files last."""
if parsed.get("numeric", False):
return (float("inf"), parsed["filename"])
if parsed["category"] is None:
return (-1, parsed["index"]) # category-less first
return (SORT_ORDER.index(parsed["category"]), parsed["index"])
def process_folder(folder, dry_run, auto=False):
try:
clean_folder(folder, dry_run)
files = [f for f in os.listdir(folder) if os.path.isfile(os.path.join(folder, f))]
if not files:
return
parsed_list = []
for f in files:
try:
parsed = parse_filename(f)
parsed_list.append(parsed)
except ValueError as e:
msg = f"Skipping folder '{folder}' due to error: {e}"
print(msg)
log_error(msg)
return
# Filter files that need renaming
to_rename = [p for p in parsed_list if not p.get("numeric", False)]
if not to_rename:
print(f"Skipping folder '{folder}': all files numeric or nothing to rename")
return
if not auto:
# Ask for confirmation
print(f"\nFolder: {folder}")
for p in to_rename:
print(f" {p['filename']}")
resp = input("Proceed with renaming? [y/N]: ").strip().lower()
if resp != "y":
print("Skipped.")
return
# Sort and rename
to_rename.sort(key=sort_key)
for i, p in enumerate(to_rename):
ext = os.path.splitext(p["filename"])[1]
new_name = f"{i:03}{ext}"
src = os.path.join(folder, p["filename"])
dst = os.path.join(folder, new_name)
if dry_run:
print(f"[dry-run] {p['filename']} -> {new_name}")
else:
print(f"{p['filename']} -> {new_name}")
os.rename(src, dst)
except Exception as e:
msg = f"Skipping folder '{folder}' due to unexpected error: {e}"
print(msg)
log_error(msg)
return
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--dry-run", action="store_true", help="Print actions only")
parser.add_argument(
"folder", nargs="?", default=None,
help="Target folder (default: required unless --all or --all-auto)"
)
parser.add_argument(
"--all", action="store_true", help="Process all immediate subfolders with confirmation"
)
parser.add_argument(
"--all-auto", action="store_true", help="Process all immediate subfolders automatically, no confirmation"
)
args = parser.parse_args()
if args.all or args.all_auto:
base = os.getcwd()
for entry in sorted(os.listdir(base)):
path = os.path.join(base, entry)
if os.path.isdir(path):
process_folder(path, dry_run=args.dry_run, auto=args.all_auto)
else:
if args.folder is None:
print("Error: no folder specified and neither --all nor --all-auto used")
sys.exit(1)
if not os.path.isdir(args.folder):
print(f"{args.folder} is not a valid folder")
sys.exit(1)
process_folder(args.folder, dry_run=args.dry_run, auto=False)
if __name__ == "__main__":
main()