filesweep-cli 3.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- clustering.py +390 -0
- filesweep_cli-3.0.0.dist-info/METADATA +173 -0
- filesweep_cli-3.0.0.dist-info/RECORD +8 -0
- filesweep_cli-3.0.0.dist-info/WHEEL +5 -0
- filesweep_cli-3.0.0.dist-info/entry_points.txt +2 -0
- filesweep_cli-3.0.0.dist-info/licenses/LICENSE +22 -0
- filesweep_cli-3.0.0.dist-info/top_level.txt +2 -0
- sweep.py +1782 -0
clustering.py
ADDED
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
"""Filename-only tokenisation, noise filtering, and cluster discovery for Sweep."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections import defaultdict
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
import os
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import re
|
|
10
|
+
from typing import Callable, Collection
|
|
11
|
+
|
|
12
|
+
WINDOWS_RESERVED_NAMES = frozenset({
|
|
13
|
+
"CON", "PRN", "AUX", "NUL",
|
|
14
|
+
*(f"COM{i}" for i in range(1, 10)),
|
|
15
|
+
*(f"LPT{i}" for i in range(1, 10)),
|
|
16
|
+
})
|
|
17
|
+
ILLEGAL_NTFS_CHARS = frozenset('<>:"/\\|?*')
|
|
18
|
+
|
|
19
|
+
STOPWORD_TOKENS = frozenset({
|
|
20
|
+
"a", "an", "and", "as", "at", "by", "com", "d", "edu", "for", "from",
|
|
21
|
+
"gov", "http", "https", "in", "info", "io", "is", "it", "net", "of",
|
|
22
|
+
"on", "or", "org", "s", "the", "to", "with", "www",
|
|
23
|
+
})
|
|
24
|
+
MEDIA_RELEASE_TOKENS = frozenset({
|
|
25
|
+
"480p", "720p", "1080p", "2160p", "4k", "aac", "ac3", "bdrip", "bluray",
|
|
26
|
+
"dvdrip", "flac", "h264", "h265", "hdrip", "hdtv", "hevc", "mkv", "mp3",
|
|
27
|
+
"mp4", "webrip", "x264", "x265",
|
|
28
|
+
})
|
|
29
|
+
VERSION_COPY_TOKENS = frozenset({
|
|
30
|
+
"backup", "bak", "copy", "draft", "edited", "final", "new", "old", "rev",
|
|
31
|
+
"temp", "tmp", "update", "updated",
|
|
32
|
+
})
|
|
33
|
+
GENERIC_DOC_CAPTURE_TOKENS = frozenset({
|
|
34
|
+
"aud", "audio", "clip", "clips", "desktop", "doc", "docs", "document",
|
|
35
|
+
"documents", "dsc", "file", "files", "idea", "ideas", "image", "images",
|
|
36
|
+
"img", "note", "notes", "paper", "prompt", "prompts", "pxl", "recording",
|
|
37
|
+
"scan", "scanned", "screen", "screenshot", "screenshots", "untitled",
|
|
38
|
+
"vid", "video", "whatsapp",
|
|
39
|
+
})
|
|
40
|
+
MONTH_AND_TITLE_TOKENS = frozenset({
|
|
41
|
+
"jan", "january", "feb", "february", "mar", "march", "apr", "april",
|
|
42
|
+
"may", "jun", "june", "jul", "july", "aug", "august", "sep", "sept",
|
|
43
|
+
"september", "oct", "october", "nov", "november", "dec", "december",
|
|
44
|
+
"mr", "mrs", "ms", "dr",
|
|
45
|
+
})
|
|
46
|
+
NOISE_TOKENS = (
|
|
47
|
+
STOPWORD_TOKENS
|
|
48
|
+
| MEDIA_RELEASE_TOKENS
|
|
49
|
+
| VERSION_COPY_TOKENS
|
|
50
|
+
| GENERIC_DOC_CAPTURE_TOKENS
|
|
51
|
+
| MONTH_AND_TITLE_TOKENS
|
|
52
|
+
)
|
|
53
|
+
FOLDER_NOISE_TOKENS = frozenset({"work", "misc", "folder", "folders", "stuff"})
|
|
54
|
+
FOLDER_PROJECT_MARKERS = frozenset({
|
|
55
|
+
".git", "package.json", "pyproject.toml", "requirements.txt", ".venv", "venv",
|
|
56
|
+
})
|
|
57
|
+
PROJECT_MARKER_EXTS = frozenset({".blend", ".aep", ".prproj"})
|
|
58
|
+
CLOUD_SYNC_FOLDER_NAMES = frozenset({
|
|
59
|
+
"onedrive", "dropbox", "google drive", "googledrive", "iclouddrive", "icloud drive",
|
|
60
|
+
})
|
|
61
|
+
DEFAULT_FALLBACK_CATEGORIES = frozenset({
|
|
62
|
+
"documents", "images", "video", "audio", "archives", "installers", "other",
|
|
63
|
+
})
|
|
64
|
+
_SYSTEM_FOLDER_NAMES = frozenset({
|
|
65
|
+
"$recycle.bin", "system volume information", "appdata", "windows",
|
|
66
|
+
"program files", "program files (x86)",
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
_EPISODE_RE = re.compile(r"^s\d{2}e\d{2}$", re.IGNORECASE)
|
|
70
|
+
_VERSION_RE = re.compile(r"^v\d+$", re.IGNORECASE)
|
|
71
|
+
_REV_RE = re.compile(r"^rev\d+$", re.IGNORECASE)
|
|
72
|
+
_ORDINAL_RE = re.compile(r"^\d+(?:st|nd|rd|th)$", re.IGNORECASE)
|
|
73
|
+
_TIME_MERIDIEM_RE = re.compile(r"^\d{1,2}(?:am|pm)$", re.IGNORECASE)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass(frozen=True)
|
|
77
|
+
class CandidateCluster:
|
|
78
|
+
"""Auto-discovered filename cluster scoped to one target folder."""
|
|
79
|
+
|
|
80
|
+
target: Path
|
|
81
|
+
label: str
|
|
82
|
+
keywords: tuple[str, ...]
|
|
83
|
+
item_indices: tuple[int, ...]
|
|
84
|
+
sample_names: tuple[str, ...]
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def validate_folder_name(name: str, field_name: str = "folder") -> str:
|
|
88
|
+
"""Validate and return a safe Windows/NTFS folder name."""
|
|
89
|
+
if not isinstance(name, str) or not name:
|
|
90
|
+
raise ValueError(f"Invalid {field_name} name: {name!r}")
|
|
91
|
+
if name != name.strip(" ."):
|
|
92
|
+
raise ValueError(f"Invalid {field_name} name (leading/trailing space or dot): {name!r}")
|
|
93
|
+
if ".." in name:
|
|
94
|
+
raise ValueError(f"Invalid {field_name} name (parent reference): {name!r}")
|
|
95
|
+
if any(ord(ch) < 32 or ch in ILLEGAL_NTFS_CHARS for ch in name):
|
|
96
|
+
raise ValueError(f"Invalid {field_name} name (illegal NTFS character): {name!r}")
|
|
97
|
+
stem = name.split(".", 1)[0].upper()
|
|
98
|
+
if stem in WINDOWS_RESERVED_NAMES:
|
|
99
|
+
raise ValueError(f"Invalid {field_name} name (Windows reserved device name): {name!r}")
|
|
100
|
+
return name
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def normalise_kebab_stem(stem: str) -> str:
|
|
104
|
+
"""Return a lowercase kebab-case stem, or '' if empty or Windows-reserved."""
|
|
105
|
+
cleaned = "".join(ch if ch.isalnum() else "-" for ch in stem.lower())
|
|
106
|
+
normalised = re.sub(r"-+", "-", cleaned).strip("-")
|
|
107
|
+
if not normalised or normalised.upper() in WINDOWS_RESERVED_NAMES:
|
|
108
|
+
return ""
|
|
109
|
+
return normalised
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def normalise_kebab_filename(filename: str) -> str:
|
|
113
|
+
"""Normalise filename stem to kebab-case and lowercase its extension."""
|
|
114
|
+
path = Path(filename)
|
|
115
|
+
stem = normalise_kebab_stem(path.stem)
|
|
116
|
+
if not stem:
|
|
117
|
+
return filename
|
|
118
|
+
return f"{stem}{path.suffix.lower()}"
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def normalise_kebab_folder_name(name: str) -> str:
|
|
122
|
+
"""Normalise a folder name to kebab-case, or keep original if empty or reserved."""
|
|
123
|
+
stem = normalise_kebab_stem(name)
|
|
124
|
+
return stem if stem else name
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def is_noise_token(token: str) -> bool:
|
|
128
|
+
"""Return True if a lowercase token is generic noise, numeric, or a tag."""
|
|
129
|
+
low = token.lower()
|
|
130
|
+
if len(low) < 2 or low.isdigit() or low in NOISE_TOKENS:
|
|
131
|
+
return True
|
|
132
|
+
return bool(
|
|
133
|
+
_EPISODE_RE.match(low)
|
|
134
|
+
or _VERSION_RE.match(low)
|
|
135
|
+
or _REV_RE.match(low)
|
|
136
|
+
or _ORDINAL_RE.match(low)
|
|
137
|
+
or _TIME_MERIDIEM_RE.match(low)
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def tokenise_stem(stem: str) -> list[str]:
|
|
142
|
+
"""Split a filename stem on separators and letter/digit boundaries, dropping noise."""
|
|
143
|
+
tokens: list[str] = []
|
|
144
|
+
for chunk in re.findall(r"[A-Za-z0-9]+", stem):
|
|
145
|
+
if is_noise_token(chunk):
|
|
146
|
+
continue
|
|
147
|
+
for subtok in re.findall(r"[A-Za-z]+|[0-9]+", chunk):
|
|
148
|
+
if not is_noise_token(subtok):
|
|
149
|
+
tokens.append(subtok.lower())
|
|
150
|
+
return tokens
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def is_cloud_sync_folder_name(name: str) -> bool:
|
|
154
|
+
"""Return True if folder name matches a known cloud-sync root folder."""
|
|
155
|
+
low = name.strip().lower()
|
|
156
|
+
return low in CLOUD_SYNC_FOLDER_NAMES or low.startswith("onedrive - ")
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def detect_folder_project_marker(folder: Path) -> tuple[str | None, str | None]:
|
|
160
|
+
"""Inspect folder for project markers; return (marker_name, error_reason)."""
|
|
161
|
+
try:
|
|
162
|
+
entries = sorted(os.scandir(folder), key=lambda e: e.name.lower())
|
|
163
|
+
except OSError as exc:
|
|
164
|
+
return None, f"Unable to inspect folder: {exc}"
|
|
165
|
+
for entry in entries:
|
|
166
|
+
lower = entry.name.lower()
|
|
167
|
+
if lower in FOLDER_PROJECT_MARKERS:
|
|
168
|
+
return entry.name, None
|
|
169
|
+
if entry.is_file(follow_symlinks=False) and Path(lower).suffix in PROJECT_MARKER_EXTS:
|
|
170
|
+
return entry.name, None
|
|
171
|
+
return None, None
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def tokenise_folder_name(name: str) -> frozenset[str]:
|
|
175
|
+
"""Tokenise an existing folder name, dropping noise and vague folder tokens."""
|
|
176
|
+
tokens = [tok for tok in tokenise_stem(name) if tok not in FOLDER_NOISE_TOKENS]
|
|
177
|
+
unique = frozenset(tokens)
|
|
178
|
+
if not unique:
|
|
179
|
+
return frozenset()
|
|
180
|
+
if len(unique) == 1 and len(next(iter(unique))) < 3:
|
|
181
|
+
return frozenset()
|
|
182
|
+
return unique
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def build_existing_folder_index(
|
|
186
|
+
target: Path,
|
|
187
|
+
ignored_categories: Collection[str] | None = None,
|
|
188
|
+
is_system_path_fn: Callable[[Path], bool] | None = None,
|
|
189
|
+
) -> list[tuple[str, frozenset[str]]]:
|
|
190
|
+
"""Scan target for safe, non-generic top-level subfolders eligible for matching."""
|
|
191
|
+
ignored_set = (
|
|
192
|
+
{str(cat).casefold() for cat in ignored_categories}
|
|
193
|
+
if ignored_categories is not None
|
|
194
|
+
else set(DEFAULT_FALLBACK_CATEGORIES)
|
|
195
|
+
)
|
|
196
|
+
try:
|
|
197
|
+
entries = sorted(os.scandir(target), key=lambda e: e.name.lower())
|
|
198
|
+
except OSError:
|
|
199
|
+
return []
|
|
200
|
+
|
|
201
|
+
candidates: list[tuple[str, frozenset[str]]] = []
|
|
202
|
+
for entry in entries:
|
|
203
|
+
if not entry.is_dir(follow_symlinks=False) or entry.is_symlink():
|
|
204
|
+
continue
|
|
205
|
+
name = entry.name
|
|
206
|
+
lower = name.lower()
|
|
207
|
+
if name.startswith(".") or name.startswith("~$"):
|
|
208
|
+
continue
|
|
209
|
+
if lower in _SYSTEM_FOLDER_NAMES or lower in {".venv", "venv"} or is_cloud_sync_folder_name(name):
|
|
210
|
+
continue
|
|
211
|
+
sub_path = Path(entry.path)
|
|
212
|
+
if is_system_path_fn is not None and is_system_path_fn(sub_path):
|
|
213
|
+
continue
|
|
214
|
+
if name.casefold() in ignored_set:
|
|
215
|
+
continue
|
|
216
|
+
marker, inspect_err = detect_folder_project_marker(sub_path)
|
|
217
|
+
if marker is not None or inspect_err is not None:
|
|
218
|
+
continue
|
|
219
|
+
folder_tokens = tokenise_folder_name(name)
|
|
220
|
+
if not folder_tokens:
|
|
221
|
+
continue
|
|
222
|
+
candidates.append((name, folder_tokens))
|
|
223
|
+
return candidates
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def match_existing_folder(
|
|
227
|
+
file_stem: str,
|
|
228
|
+
candidates: list[tuple[str, frozenset[str]]],
|
|
229
|
+
) -> str | None:
|
|
230
|
+
"""Return the unique most-specific matching folder name, or None on miss or tie."""
|
|
231
|
+
if not candidates:
|
|
232
|
+
return None
|
|
233
|
+
file_tokens = set(tokenise_stem(file_stem))
|
|
234
|
+
if not file_tokens:
|
|
235
|
+
return None
|
|
236
|
+
matches = [(name, toks) for name, toks in candidates if toks.issubset(file_tokens)]
|
|
237
|
+
if not matches:
|
|
238
|
+
return None
|
|
239
|
+
best_count = max(len(toks) for _, toks in matches)
|
|
240
|
+
winners = [name for name, toks in matches if len(toks) == best_count]
|
|
241
|
+
return winners[0] if len(winners) == 1 else None
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def match_existing_folders(
|
|
245
|
+
target: Path,
|
|
246
|
+
filenames: Collection[str],
|
|
247
|
+
ignored_categories: Collection[str] | None = None,
|
|
248
|
+
is_system_path_fn: Callable[[Path], bool] | None = None,
|
|
249
|
+
) -> dict[str, str]:
|
|
250
|
+
"""Map eligible filenames in target to unique matching pre-existing subfolders."""
|
|
251
|
+
candidates = build_existing_folder_index(
|
|
252
|
+
target, ignored_categories=ignored_categories, is_system_path_fn=is_system_path_fn
|
|
253
|
+
)
|
|
254
|
+
if not candidates:
|
|
255
|
+
return {}
|
|
256
|
+
matched: dict[str, str] = {}
|
|
257
|
+
for filename in filenames:
|
|
258
|
+
folder_name = match_existing_folder(Path(filename).stem, candidates)
|
|
259
|
+
if folder_name is not None:
|
|
260
|
+
matched[filename] = folder_name
|
|
261
|
+
return matched
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _format_cluster_label(tokens: tuple[str, ...], kebab_case: bool = False) -> str:
|
|
265
|
+
"""Format cluster tokens into Title Case, or kebab-case when enabled."""
|
|
266
|
+
title_label = " ".join(tok.upper() if len(tok) <= 2 else tok.capitalize() for tok in tokens)
|
|
267
|
+
if kebab_case:
|
|
268
|
+
return normalise_kebab_folder_name(title_label)
|
|
269
|
+
return title_label
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
_PROTECTED_RULE_PREFIXES = ("Title: ", "Existing folder: ")
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def discover_clusters(
|
|
276
|
+
items: list[dict],
|
|
277
|
+
min_files: int = 3,
|
|
278
|
+
max_samples: int = 3,
|
|
279
|
+
kebab_case: bool = False,
|
|
280
|
+
) -> list[CandidateCluster]:
|
|
281
|
+
"""Discover per-target 1- or 2-token clusters from planned fallback items only."""
|
|
282
|
+
by_target: dict[str, tuple[Path, list[tuple[int, str, list[str]]]]] = {}
|
|
283
|
+
for idx, item in enumerate(items):
|
|
284
|
+
if item.get("status") != "planned":
|
|
285
|
+
continue
|
|
286
|
+
if str(item.get("rule", "")).startswith(_PROTECTED_RULE_PREFIXES):
|
|
287
|
+
continue
|
|
288
|
+
src = Path(item["source"])
|
|
289
|
+
tokens = tokenise_stem(src.stem)
|
|
290
|
+
if not tokens:
|
|
291
|
+
continue
|
|
292
|
+
target = src.parent
|
|
293
|
+
t_key = os.path.normcase(str(target)).casefold()
|
|
294
|
+
if t_key not in by_target:
|
|
295
|
+
by_target[t_key] = (target, [])
|
|
296
|
+
by_target[t_key][1].append((idx, src.name, tokens))
|
|
297
|
+
|
|
298
|
+
clusters: list[CandidateCluster] = []
|
|
299
|
+
for target, entries in by_target.values():
|
|
300
|
+
two_tok_groups: dict[tuple[str, str], list[tuple[int, str]]] = defaultdict(list)
|
|
301
|
+
one_tok_groups: dict[tuple[str], list[tuple[int, str]]] = defaultdict(list)
|
|
302
|
+
for idx, name, tokens in entries:
|
|
303
|
+
one_tok_groups[(tokens[0],)].append((idx, name))
|
|
304
|
+
if len(tokens) >= 2:
|
|
305
|
+
two_tok_groups[(tokens[0], tokens[1])].append((idx, name))
|
|
306
|
+
|
|
307
|
+
candidates: list[tuple[tuple[str, ...], list[tuple[int, str]]]] = []
|
|
308
|
+
for kw_pair, group in two_tok_groups.items():
|
|
309
|
+
if len(group) >= min_files:
|
|
310
|
+
candidates.append((kw_pair, group))
|
|
311
|
+
for kw_single, group in one_tok_groups.items():
|
|
312
|
+
if len(group) >= min_files:
|
|
313
|
+
candidates.append((kw_single, group))
|
|
314
|
+
|
|
315
|
+
# Prefer larger groups; break ties by 2-token specificity so overlapping duplicates disappear.
|
|
316
|
+
candidates.sort(key=lambda item: (-len(item[1]), -len(item[0]), item[0]))
|
|
317
|
+
claimed_indices: set[int] = set()
|
|
318
|
+
for kw_tuple, group in candidates:
|
|
319
|
+
remaining = [(idx, name) for idx, name in group if idx not in claimed_indices]
|
|
320
|
+
if len(remaining) < min_files:
|
|
321
|
+
continue
|
|
322
|
+
label = _format_cluster_label(kw_tuple, kebab_case=kebab_case)
|
|
323
|
+
try:
|
|
324
|
+
validate_folder_name(label, "cluster")
|
|
325
|
+
except ValueError:
|
|
326
|
+
continue
|
|
327
|
+
claimed_indices.update(idx for idx, _ in remaining)
|
|
328
|
+
clusters.append(
|
|
329
|
+
CandidateCluster(
|
|
330
|
+
target=target,
|
|
331
|
+
label=label,
|
|
332
|
+
keywords=kw_tuple,
|
|
333
|
+
item_indices=tuple(idx for idx, _ in remaining),
|
|
334
|
+
sample_names=tuple(name for _, name in remaining[:max_samples]),
|
|
335
|
+
)
|
|
336
|
+
)
|
|
337
|
+
|
|
338
|
+
clusters.sort(key=lambda c: (-len(c.item_indices), os.path.normcase(str(c.target)), c.label.casefold()))
|
|
339
|
+
return clusters
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def apply_clusters_to_plan(
|
|
343
|
+
items: list[dict],
|
|
344
|
+
approved_clusters: list[CandidateCluster],
|
|
345
|
+
resolve_collision_fn: Callable[[Path, set[str]], Path],
|
|
346
|
+
kebab_case: bool = False,
|
|
347
|
+
) -> list[dict]:
|
|
348
|
+
"""Apply approved clusters to planned items and recalculate all collisions."""
|
|
349
|
+
if not approved_clusters:
|
|
350
|
+
return items
|
|
351
|
+
|
|
352
|
+
ordered = sorted(approved_clusters, key=lambda c: (-len(c.keywords), -len(c.item_indices)))
|
|
353
|
+
assigned: dict[int, CandidateCluster] = {}
|
|
354
|
+
for cluster in ordered:
|
|
355
|
+
c_tkey = os.path.normcase(str(cluster.target)).casefold()
|
|
356
|
+
for idx in cluster.item_indices:
|
|
357
|
+
if idx in assigned or not (0 <= idx < len(items)):
|
|
358
|
+
continue
|
|
359
|
+
item = items[idx]
|
|
360
|
+
if item.get("status") != "planned":
|
|
361
|
+
continue
|
|
362
|
+
if str(item.get("rule", "")).startswith(_PROTECTED_RULE_PREFIXES):
|
|
363
|
+
continue
|
|
364
|
+
if os.path.normcase(str(Path(item["source"]).parent)).casefold() != c_tkey:
|
|
365
|
+
continue
|
|
366
|
+
assigned[idx] = cluster
|
|
367
|
+
|
|
368
|
+
for idx, cluster in assigned.items():
|
|
369
|
+
folder_label = normalise_kebab_folder_name(cluster.label) if kebab_case else cluster.label
|
|
370
|
+
items[idx]["category"] = folder_label
|
|
371
|
+
items[idx]["rule"] = f"Cluster: {folder_label}"
|
|
372
|
+
|
|
373
|
+
canonical_folders: dict[tuple[str, str], str] = {}
|
|
374
|
+
reserved: set[str] = set()
|
|
375
|
+
for item in items:
|
|
376
|
+
if item.get("status") != "planned":
|
|
377
|
+
continue
|
|
378
|
+
src = Path(item["source"])
|
|
379
|
+
target = src.parent
|
|
380
|
+
t_key = os.path.normcase(str(target)).casefold()
|
|
381
|
+
raw_cat = str(item.get("category") or "Other")
|
|
382
|
+
is_existing_folder = str(item.get("rule", "")).startswith("Existing folder: ")
|
|
383
|
+
if kebab_case and not is_existing_folder:
|
|
384
|
+
raw_cat = normalise_kebab_folder_name(raw_cat)
|
|
385
|
+
folder_key = (t_key, raw_cat.casefold())
|
|
386
|
+
canonical_cat = canonical_folders.setdefault(folder_key, raw_cat)
|
|
387
|
+
item["category"] = canonical_cat
|
|
388
|
+
dest_name = normalise_kebab_filename(src.name) if kebab_case else src.name
|
|
389
|
+
item["destination"] = str(resolve_collision_fn(target / canonical_cat / dest_name, reserved))
|
|
390
|
+
return items
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: filesweep-cli
|
|
3
|
+
Version: 3.0.0
|
|
4
|
+
Summary: Safe, reversible Windows command-line file organiser.
|
|
5
|
+
Author: Emmanuelaudu
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Joshemmy/sweep-cli
|
|
8
|
+
Project-URL: Repository, https://github.com/Joshemmy/sweep-cli
|
|
9
|
+
Project-URL: Issues, https://github.com/Joshemmy/sweep-cli/issues
|
|
10
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Topic :: Utilities
|
|
18
|
+
Requires-Python: >=3.11
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
License-File: LICENSE
|
|
21
|
+
Dynamic: license-file
|
|
22
|
+
|
|
23
|
+
# Sweep
|
|
24
|
+
|
|
25
|
+
A safe, reversible Windows command-line file organiser built purely with the Python 3.11+ standard library.
|
|
26
|
+
|
|
27
|
+
<!--  -->
|
|
28
|
+
|
|
29
|
+
Sweep tidies loose top-level files in your user folders without deleting or overwriting anything. Every run previews the exact move plan first (dry-run by default), records every intent in a write-ahead undo log before moving files, and reverses any run with a single command.
|
|
30
|
+
|
|
31
|
+
## Key Principles
|
|
32
|
+
|
|
33
|
+
* **Dry-run by default:** CLI runs are strictly read-only unless `--apply` is passed explicitly.
|
|
34
|
+
* **Write-ahead undo log:** Each planned move is recorded atomically as `pending` in `%USERPROFILE%\.sweep\logs\<run_id>.json` before `shutil.move` runs, then updated to `committed`, `skipped`, or `failed` for reliable crash recovery.
|
|
35
|
+
* **Zero deletions or overwrites:** Sweep never deletes files or folders. Existing destination filenames trigger Windows-style numbering (`report (1).pdf`, `report (2).pdf`).
|
|
36
|
+
* **Zero third-party dependencies:** Runs using Python's built-in modules only.
|
|
37
|
+
|
|
38
|
+
## Requirements
|
|
39
|
+
|
|
40
|
+
* Windows 10 or Windows 11
|
|
41
|
+
* Python 3.11 or newer (zero third-party runtime dependencies)
|
|
42
|
+
|
|
43
|
+
## Installation
|
|
44
|
+
|
|
45
|
+
Install the `sweep` command globally from PyPI:
|
|
46
|
+
|
|
47
|
+
```powershell
|
|
48
|
+
pip install filesweep-cli
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
To upgrade an existing installation:
|
|
52
|
+
|
|
53
|
+
```powershell
|
|
54
|
+
pip install --upgrade filesweep-cli
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
From a local clone, you can also run `python sweep.py` directly or install in editable mode with `pip install -e .` (which loads `rules.json` from the repository directory).
|
|
58
|
+
|
|
59
|
+
## Quick Start
|
|
60
|
+
|
|
61
|
+
Run `sweep` from any folder (or `python sweep.py` from the repository root):
|
|
62
|
+
|
|
63
|
+
```powershell
|
|
64
|
+
# Launch the interactive menu (when run with no arguments in a terminal)
|
|
65
|
+
sweep
|
|
66
|
+
|
|
67
|
+
# Preview planned moves without modifying disk (dry-run)
|
|
68
|
+
sweep --target "%USERPROFILE%\Downloads"
|
|
69
|
+
|
|
70
|
+
# Apply planned moves across default targets (Downloads, Desktop, Documents)
|
|
71
|
+
sweep --apply
|
|
72
|
+
|
|
73
|
+
# Preview or apply with opt-in kebab-case filename and folder normalisation
|
|
74
|
+
sweep --kebab --target "%USERPROFILE%\Downloads"
|
|
75
|
+
sweep --kebab --apply
|
|
76
|
+
|
|
77
|
+
# Preview or apply in-place kebab-case renaming without moving into category folders
|
|
78
|
+
sweep --rename-only --target "%USERPROFILE%\Downloads" --target "%USERPROFILE%\Desktop"
|
|
79
|
+
sweep --rename-only --rename-folders --target "%USERPROFILE%\Projects" --apply
|
|
80
|
+
|
|
81
|
+
# Target specific folders (repeatable) and optionally override rules or log paths
|
|
82
|
+
sweep --target "%USERPROFILE%\Downloads" --target "%USERPROFILE%\Desktop" --rules rules.json --log-dir "%USERPROFILE%\.sweep\logs" --apply
|
|
83
|
+
|
|
84
|
+
# List recent runs, preview a rollback, undo the most recent run, or reverse a specific run ID
|
|
85
|
+
sweep undo --list
|
|
86
|
+
sweep undo --dry-run
|
|
87
|
+
sweep undo
|
|
88
|
+
sweep undo --run 20260101T120000Z_ab12cd34
|
|
89
|
+
|
|
90
|
+
# Show the installed Sweep version
|
|
91
|
+
sweep --version
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
### Interactive Mode
|
|
95
|
+
|
|
96
|
+
Running `sweep` (or `python sweep.py`) with no arguments in an interactive terminal runs an immediate read-only scan and displays a compact dashboard (target folders, scan summary, top extensions, any smart file groups spotted, and the active naming mode, which defaults to `Original names (kebab-case: OFF)`), followed by a 6-option menu:
|
|
97
|
+
|
|
98
|
+
1. Guided sort (review groups, preview plan, then apply)
|
|
99
|
+
2. Switch folder (`Downloads`, `Desktop`, `Documents`, all defaults, or a custom path)
|
|
100
|
+
3. Toggle kebab-case naming (currently OFF/ON; opt-in, defaults to OFF)
|
|
101
|
+
4. Undo a previous run (list the 10 most recent runs with status, relative time, action summary, and target folder, preview up to 5 items to restore, then confirm)
|
|
102
|
+
5. Batch rename files or folders (kebab-case) (pick one or more folders, choose files only, subfolders only, or folders and files inside them, preview plan, then confirm)
|
|
103
|
+
6. Exit
|
|
104
|
+
|
|
105
|
+
Redirected or piped output (`sweep > plan.txt`) automatically bypasses interactive mode and prints the read-only dry-run table.
|
|
106
|
+
|
|
107
|
+
### CLI Options
|
|
108
|
+
|
|
109
|
+
| Command / Flag | Description | Default |
|
|
110
|
+
|---|---|---|
|
|
111
|
+
| `--version` | Show the Sweep version and exit | - |
|
|
112
|
+
| `--apply` | Execute planned moves or renames | Dry-run only |
|
|
113
|
+
| `--kebab` | Normalise destination filenames and auto-created category/cluster folders to lowercase kebab-case when sorting | Off (preserve original names and Title Case folders) |
|
|
114
|
+
| `--rename-only` | Rename eligible loose files in place to lowercase kebab-case without moving into category folders | Off (sort into folders) |
|
|
115
|
+
| `--rename-folders` | Opt-in: rename safe top-level subfolders (and eligible files inside them when combined with `--rename-only`) to lowercase kebab-case | Off (never rename folders) |
|
|
116
|
+
| `--target <path>` | Target folder to scan (repeatable) | `Downloads`, `Desktop`, `Documents` |
|
|
117
|
+
| `--rules <path>` | Path to `rules.json` | `rules.json` alongside `sweep.py` |
|
|
118
|
+
| `--log-dir <path>` | Directory for write-ahead undo logs | `%USERPROFILE%\.sweep\logs` |
|
|
119
|
+
| `undo` | Reverse the latest non-undone run | Latest active log |
|
|
120
|
+
| `undo --run <id>` | Reverse a specific logged run ID | Latest active log |
|
|
121
|
+
| `undo --list` | Display up to 10 recent logged runs with status, timestamp, action summary, and target folder | - |
|
|
122
|
+
| `undo --dry-run` | Preview items that would be restored for the selected run without modifying disk | - |
|
|
123
|
+
|
|
124
|
+
## Smart Sorting
|
|
125
|
+
|
|
126
|
+
Sweep evaluates eligible loose files in four ordered stages:
|
|
127
|
+
|
|
128
|
+
1. **Title rules (`title_rules`):** Keywords in `rules.json` are matched first against filename stems using word-boundary patterns, routing matching files into named buckets (such as `Receipts`, `Presentations`, `Transcripts`, or `Diagrams`) before other checks run.
|
|
129
|
+
2. **Existing-folder matching:** Scans safe top-level subfolders in the target folder (ignoring hidden/dot folders, system folders, generic fallback categories from `rules.json`, project-marker folders, and short or vague names such as `new`, `work`, `misc`, `temp`, `files`, `folder`, `stuff`, `final`). A loose file matches an existing folder only when all meaningful tokens of that folder appear in the filename stem, picking the unique most-specific match (leaving ties unmatched) while preserving the existing folder's exact on-disk name.
|
|
130
|
+
3. **Auto-discovered file groups (in Guided sort, option `1`):** Inspects remaining eligible `planned` filenames (never skipped files, title-rule matches, existing-folder matches, or file contents), strips noise words (stopwords, media tags, versions, months, short titles, and standalone numbers), and surfaces non-overlapping 1- or 2-token groups of 3 or more files within the same target folder. Approved groups apply to the current run and can optionally be saved to `rules.json`.
|
|
131
|
+
4. **Extension rules (`rules`):** Remaining files are sorted in order into `Documents`, `Images`, `Video`, `Audio`, `Archives`, `Installers`, or `Other` (`*`).
|
|
132
|
+
|
|
133
|
+
## Built-in Safety Guards
|
|
134
|
+
|
|
135
|
+
* **Top-level loose files by default:** Scans only the top level of target folders. Folder renaming is strictly opt-in (`--rename-folders` or interactive option `5`). When combined with `--rename-only` (or interactive scope `c`), Sweep also renames eligible files directly inside safe top-level subfolders (applying inner-file renames before parent-folder renames so WAL undo reverses them cleanly) without recursing deeper or following symbolic links.
|
|
136
|
+
* **Protected system paths:** Blocks `C:\Windows`, `Program Files`, `Program Files (x86)`, and `AppData` (subdirectories under `%TEMP%` are permitted only when explicitly targeted for sandboxing).
|
|
137
|
+
* **Excluded file types:** Always skips `.lnk`, `.url`, `.ini`, `.rdp`, `.key`, and `.pem` files.
|
|
138
|
+
* **Partial downloads:** Skips `.crdownload`, `.part`, `.tmp`, and `.opdownload` files.
|
|
139
|
+
* **Temporary Office files:** Skips lock/temp files whose names begin with `~$`.
|
|
140
|
+
* **24-hour safety buffer:** Skips files modified within the last 24 hours.
|
|
141
|
+
* **Locked files and folders:** Checks sharing access via `CreateFileW` and skips locked items (as well as folders or rename-mode files that raise `PermissionError` during rename) without crashing.
|
|
142
|
+
* **OneDrive cloud placeholders:** Checks `FILE_ATTRIBUTE_OFFLINE` and `FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS` via `GetFileAttributesW` before opening handles, avoiding unwanted cloud hydration.
|
|
143
|
+
* **Project-safe mode and folder guards:** Skips loose files in any target folder that directly contains `.git`, `pyproject.toml`, `package.json`, `.blend`, `.aep`, or `.prproj`. In `--rename-folders` mode, also skips hidden/dot folders (starting with `.`), cloud-sync root folders (`OneDrive`, `OneDrive - ...`, `Dropbox`, `Google Drive`, `iCloudDrive`), and subfolders containing `.git`, `package.json`, `pyproject.toml`, `requirements.txt`, `.venv`, or `venv`.
|
|
144
|
+
* **Safe folder names and collision numbering:** Rejects Windows reserved device names (`CON`, `PRN`, `AUX`, `NUL`, `COM1`-`COM9`, `LPT1`-`LPT9`), illegal NTFS characters, and leading or trailing dots/spaces. Keeps original names untouched if kebab-case normalisation yields an empty string or reserved name, and resolves collisions using Windows-style numbering (`(1)`, `(2)`).
|
|
145
|
+
|
|
146
|
+
## Customising `rules.json`
|
|
147
|
+
|
|
148
|
+
Edit [rules.json](rules.json) to adjust sorting without changing Python code:
|
|
149
|
+
|
|
150
|
+
* `title_rules`: Ordered list of `{"bucket": "<FolderName>", "keywords": ["..."]}` entries evaluated first against filename stems (multi-word keywords match across spaces, hyphens, and underscores).
|
|
151
|
+
* `rules`: Ordered list of `{"category": "<FolderName>", "extensions": [".ext", ...]}` entries evaluated when no title rule matches, ending with `"*"` as a catch-all.
|
|
152
|
+
|
|
153
|
+
## Running the Test Suite
|
|
154
|
+
|
|
155
|
+
All automated tests run inside isolated temporary directories and never touch your real user folders:
|
|
156
|
+
|
|
157
|
+
```powershell
|
|
158
|
+
python -m unittest discover -s tests -v
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
## Project Layout
|
|
162
|
+
|
|
163
|
+
```text
|
|
164
|
+
filesweep-cli/
|
|
165
|
+
├── LICENSE
|
|
166
|
+
├── README.md
|
|
167
|
+
├── clustering.py
|
|
168
|
+
├── pyproject.toml
|
|
169
|
+
├── rules.json
|
|
170
|
+
├── sweep.py
|
|
171
|
+
└── tests/
|
|
172
|
+
└── test_sweep.py
|
|
173
|
+
```
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
clustering.py,sha256=aW9AjizBhbCYsh8YLttZVvCW4G7ixQZoep4GwnZViNQ,15420
|
|
2
|
+
sweep.py,sha256=eKAChdTNvlLP3mOM4jNO4iHjUEuRLpNMtRpA1ve2Law,69646
|
|
3
|
+
filesweep_cli-3.0.0.dist-info/licenses/LICENSE,sha256=bUPS3RF1vigzN_uMkU3YoUcJER-uIXYbJ7hYOei8l8E,1070
|
|
4
|
+
filesweep_cli-3.0.0.dist-info/METADATA,sha256=AMjGFmmso831w2PZnSigVyTTX0cMSj6lIPKBUdUEUuc,10922
|
|
5
|
+
filesweep_cli-3.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
6
|
+
filesweep_cli-3.0.0.dist-info/entry_points.txt,sha256=-tgKhdV0p0dcpWiEnad9Vrc7egokihFmndFFW5uoYzM,37
|
|
7
|
+
filesweep_cli-3.0.0.dist-info/top_level.txt,sha256=T3VUchX23cvCgC-_NPtAkPdin9xI__fBfO1ai2Gf3RM,17
|
|
8
|
+
filesweep_cli-3.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Emmanuelaudu
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|