-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsort_files_by_topic.py
More file actions
1722 lines (1445 loc) · 65 KB
/
Copy pathsort_files_by_topic.py
File metadata and controls
1722 lines (1445 loc) · 65 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
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
sort_files_by_topic.py
Sorts thousands of files into topic-based subdirectories using Claude AI.
Supports PDF, TXT, RTF, DOC, DOCX, XLS, XLSX, CSV, and image files
(JPG, JPEG, PNG, TIFF, BMP, GIF, WEBP — via Claude Vision API, not OCR).
Files with meaningless names (only digits, UUIDs, random char combos) are
automatically renamed to a descriptive name suggested by Claude — at no
extra API cost, since the rename is included in the same classification call.
Just run:
python sort_files_by_topic.py # does everything: submit -> wait -> collect
python sort_files_by_topic.py --dry-run # preview without moving files
python sort_files_by_topic.py --standard # real-time API (no batch, immediate)
python sort_files_by_topic.py --collect # manually collect a previously submitted batch
python sort_files_by_topic.py --wait # same as default (explicit)
Override directories if needed:
python sort_files_by_topic.py --input /other/dir --output /other/sorted
Requirements:
pip install pdfplumber anthropic tqdm python-docx openpyxl pillow striprtf
For DOC (legacy Word) support:
Linux/Mac: sudo apt install antiword / brew install antiword
For image support (resize + format conversion before Vision API):
pip install pillow --break-system-packages # required for all image types
Environment:
ANTHROPIC_API_KEY must be set.
Mac/Linux: export ANTHROPIC_API_KEY="sk-ant-..."
Windows: set ANTHROPIC_API_KEY=sk-ant-...
PowerShell: $env:ANTHROPIC_API_KEY="sk-ant-..."
Add the export line to ~/.bashrc or ~/.zshrc to make it permanent.
Never hardcode the key in this file or commit it to Git.
Costs (indicative):
17/05/2026 : EUR 0.27 for 433 pdfs
10,000 files ~ EUR 7 with Haiku + Batch API
"""
import argparse
import json
import logging
import os
import random
import re
import shutil
import subprocess
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass, field
from pathlib import Path
import anthropic
import pdfplumber
from tqdm import tqdm
# ---------------------------------------------------------------------------
# Suppress noisy library loggers (must be before basicConfig)
# ---------------------------------------------------------------------------
for _noisy in (
"pdfplumber", "pdfminer", "pdfminer.high_level", "pdfminer.layout",
"pypdf", "pypdf._reader", "pypdf._page", "pypdf.generic",
"PIL", "PIL.Image",
):
logging.getLogger(_noisy).setLevel(logging.ERROR)
# ---------------------------------------------------------------------------
# *** USER CONFIGURATION — edit these two lines, nothing else is required ***
# ---------------------------------------------------------------------------
INPUT_DIR: Path = Path(r"C:\Users\rcxsm\Documents\docx")
OUTPUT_DIR: Path = Path(r"C:\Users\rcxsm\Documents")
# INPUT_DIR: Path = Path(r"C:\Users\rcxsm\Pictures\Screenshots\unsorted")
# OUTPUT_DIR: Path = Path(r"C:\Users\rcxsm\Pictures\Screenshots\sorted")
# ---------------------------------------------------------------------------
# Topic list
# ---------------------------------------------------------------------------
DEFAULT_TOPICS: list[str] = [
"Finance & Accounting",
"Legal & Contracts",
"Medical & Health",
"Technical & Engineering",
"Science & Research",
"Business & Management",
"Education & Training",
"Government & Policy",
"Human Resources",
"Marketing & Sales",
"Real Estate",
"Sheet music",
"Travel & Tourism",
"Art & Culture",
"Spiritual & Yoga",
"Food & Beverage",
"Service Quality",
"Bank accounts",
"Manuals",
"Persons & groups",
"Maps",
"Veganism",
"Covid",
"Hospitality & Catering",
"Color palettes & Fonts",
"Other",
]
# ---------------------------------------------------------------------------
# Supported file extensions
# ---------------------------------------------------------------------------
SUPPORTED_EXTENSIONS: set[str] = {
".pdf",
".txt", ".rtf", ".csv", ".html", ".htm",
".doc", ".docx",
".xls", ".xlsx",
".jpg", ".jpeg", ".png", ".tiff", ".tif", ".bmp", ".gif", ".webp",
}
# ---------------------------------------------------------------------------
# Technical configuration
# ---------------------------------------------------------------------------
MODEL: str = "claude-haiku-4-5-20251001"
PAGES_TO_EXTRACT: int = 2 # pages to read per PDF/DOCX
MAX_CHARS_PER_FILE: int = 3_000 # max chars sent to Claude per file
BATCH_SIZE: int = 5 # files per API request (keep low: each file needs ~100 tokens of output)
MAX_WORKERS: int = 16 # parallel extraction threads
API_RETRY_ATTEMPTS: int = 3
API_RETRY_DELAY: float = 5.0 # seconds between retries
BATCH_POLL_INTERVAL: int = 60 # seconds between batch status polls
IMAGE_VISION_BATCH_SIZE: int = 20 # images per Claude Vision API call (max ~20)
INTER_BATCH_DELAY_MIN: float = 1.0 # min random pause between API calls (seconds)
INTER_BATCH_DELAY_MAX: float = 3.0 # max random pause between API calls (seconds)
PROGRESS_FILE: str = "sort_progress.json"
BATCH_STATE_FILE: str = "sort_batch_state.json"
# ---------------------------------------------------------------------------
# Logging
# ---------------------------------------------------------------------------
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
datefmt="%H:%M:%S",
)
log = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Data classes
# ---------------------------------------------------------------------------
@dataclass
class FileRecord:
"""Metadata, extracted text, and classification result for one file.
Attributes:
path: Absolute path to the file.
text: Extracted text snippet.
topic: Assigned topic after classification.
new_name: Suggested filename stem (without extension) for bad names.
error: Error message if extraction or classification failed.
custom_id: Unique ID correlating batch sub-requests with records.
"""
path: Path
text: str = ""
topic: str = ""
new_name: str = ""
error: str = ""
custom_id: str = ""
@dataclass
class SortStats:
"""Running counters for a sorting run.
Attributes:
total: Total files found.
classified: Successfully classified.
moved: Successfully moved/copied.
skipped: Already processed (resume).
failed: Extraction or API failures.
renamed: Files given a new name by Claude.
topic_counts: Counter per topic.
type_counts: Counter per file extension.
"""
total: int = 0
classified: int = 0
moved: int = 0
skipped: int = 0
failed: int = 0
renamed: int = 0
topic_counts: dict[str, int] = field(default_factory=dict)
type_counts: dict[str, int] = field(default_factory=dict)
# ---------------------------------------------------------------------------
# Filename quality check
# ---------------------------------------------------------------------------
def _is_bad_filename(stem: str) -> bool:
"""Return True if the filename stem is meaningless and should be renamed.
Catches: pure digit strings, UUIDs, random alphanumeric blobs, very short
consonant-only strings, names with fewer than 40% letter characters, and
common auto-generated names from Windows, cameras, and phones.
Args:
stem: Filename without extension.
Returns:
True if the name should be replaced with a descriptive one.
"""
if not stem:
return True
# Pure digits (e.g. "1234567890")
if stem.isdigit():
return True
# UUID pattern (with or without hyphens)
if re.fullmatch(
r"[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}",
stem, re.I,
):
return True
# Windows screenshot auto-names: "Screenshot (123)", "Screenshot_20240101_120000"
if re.fullmatch(r"screenshot[\s_(-]*\d[\d\s()_-]*", stem, re.I):
return True
if re.fullmatch(r"schermopname[\s_(-]*\d[\d\s()_-]*", stem, re.I):
return True
# Camera/phone auto-names: IMG_1234, DSC_0001, DCIM_20240101, VID_20240101_120000, etc.
if re.fullmatch(
r"(img|dsc|dscn|dcim|vid|photo|image|capture|snap|pxl|cam|mov|clip)[-_]?\d[\d_-]*",
stem, re.I,
):
return True
# WhatsApp / Telegram: IMG-20240101-WA0001, Photo_20240101_120000
if re.fullmatch(r"(img|vid|photo|audio|video)[-_]\d{8}[-_].*", stem, re.I):
return True
# Mostly non-alpha (less than 40% letters)
letters = sum(c.isalpha() for c in stem)
if len(stem) >= 4 and letters / len(stem) < 0.4:
return True
# Short and no vowels (e.g. "xkbf", "z7q3")
if len(stem) <= 6 and not any(c in "aeiouAEIOU" for c in stem):
return True
return False
def _sanitize_suggested_name(raw: str) -> str:
"""Sanitize a Claude-suggested filename stem to be filesystem-safe.
Args:
raw: Raw suggested name from Claude (no extension).
Returns:
Alphanumeric + underscore string, max 50 characters.
"""
cleaned = re.sub(r"[^\w]", "_", raw.strip())
cleaned = re.sub(r"_+", "_", cleaned).strip("_")
return cleaned[:50]
# ---------------------------------------------------------------------------
# Text extraction — per file type
# ---------------------------------------------------------------------------
def _extract_pdf(file_path: Path, max_chars: int) -> str:
with pdfplumber.open(str(file_path)) as pdf:
chunks = [page.extract_text() or "" for page in pdf.pages[:PAGES_TO_EXTRACT]]
return "\n".join(chunks).strip()[:max_chars]
def _extract_pdf_pdftotext(file_path: Path, max_chars: int) -> str:
try:
result = subprocess.run(
["pdftotext", "-l", str(PAGES_TO_EXTRACT), str(file_path), "-"],
capture_output=True, text=True, timeout=10,
)
return result.stdout.strip()[:max_chars]
except FileNotFoundError:
log.debug("pdftotext not found; falling back to pdfplumber for %s", file_path.name)
return _extract_pdf(file_path, max_chars)
def _extract_txt(file_path: Path, max_chars: int) -> str:
for encoding in ("utf-8", "latin-1", "cp1252"):
try:
return file_path.read_text(encoding=encoding)[:max_chars]
except UnicodeDecodeError:
continue
return ""
def _extract_rtf(file_path: Path, max_chars: int) -> str:
from striprtf.striprtf import rtf_to_text # type: ignore
raw = file_path.read_text(encoding="latin-1")
return rtf_to_text(raw)[:max_chars]
def _extract_docx(file_path: Path, max_chars: int) -> str:
import docx # type: ignore
doc = docx.Document(str(file_path))
text = "\n".join(p.text for p in doc.paragraphs if p.text.strip())
return text[:max_chars]
def _extract_doc(file_path: Path, max_chars: int) -> str:
try:
result = subprocess.run(
["antiword", str(file_path)],
capture_output=True, text=True, timeout=15,
)
return result.stdout.strip()[:max_chars]
except FileNotFoundError:
print("antiword not found; cannot extract .doc: %s", file_path.name)
log.debug("antiword not found; cannot extract .doc: %s", file_path.name)
return ""
def _extract_xlsx(file_path: Path, max_chars: int) -> str:
number_of_sheets = 1
import openpyxl # type: ignore
wb = openpyxl.load_workbook(str(file_path), read_only=True, data_only=True)
chunks: list[str] = []
for sheet in wb.worksheets[:number_of_sheets]:
for row in sheet.iter_rows(max_row=50, values_only=True):
row_text = " ".join(str(c) for c in row if c is not None)
if row_text.strip():
chunks.append(row_text)
return "\n".join(chunks)[:max_chars]
def _extract_image_with_pytesseract(file_path: Path, max_chars: int) -> str:
""" Not used """
try:
import pytesseract # type: ignore
from PIL import Image # type: ignore
img = Image.open(str(file_path))
return pytesseract.image_to_string(img)[:max_chars]
except ImportError:
log.debug("pytesseract/Pillow not installed; skipping OCR for %s", file_path.name)
return ""
except Exception as exc:
log.debug("OCR failed for %s: %s", file_path.name, exc)
return ""
def _extract_image(file_path: Path, max_chars: int) -> str:
"""Return a sentinel so the pipeline knows this is an image file.
Images are classified via Claude Vision (not OCR), so we return a
placeholder that signals the image path. The actual vision call is made
in classify_images_standard() / classify_images_batch_inline().
"""
return f"__IMAGE_FILE__:{file_path}"
# ---------------------------------------------------------------------------
# Image description helpers (max 50-char prefix + topic in one vision call)
# ---------------------------------------------------------------------------
IMAGE_EXTENSIONS: frozenset[str] = frozenset(
{".jpg", ".jpeg", ".png", ".tiff", ".tif", ".bmp", ".gif", ".webp"}
)
_MEDIA_TYPE_MAP: dict[str, str] = {
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".png": "image/png",
".gif": "image/gif",
".webp": "image/webp",
".tiff": "image/jpeg", # convert below
".tif": "image/jpeg",
".bmp": "image/jpeg",
}
# Anthropic API rejects images larger than ~5 MB (base64-encoded).
# We resize to fit within this budget using Pillow before encoding.
_MAX_IMAGE_BYTES: int = 4_500_000 # 4.5 MB base64 budget (conservative)
_MAX_IMAGE_DIM: int = 1024 # max long-edge in pixels (good quality, small size)
def _image_to_base64(file_path: Path) -> tuple[str, str]:
"""Return (base64_data, media_type) for an image file.
All images are processed through Pillow so we can:
- Resize large images to fit within the API size limit
- Convert TIFF / BMP (not accepted by the API) to JPEG
- Re-compress oversized JPEGs iteratively until they fit
Args:
file_path: Path to the image file.
Returns:
Tuple of (base64-encoded bytes as str, MIME type string).
Raises:
ImportError: If Pillow is not installed.
OSError: If the file cannot be read or converted.
"""
import base64
import io
from PIL import Image as _PILImage # type: ignore
img = _PILImage.open(str(file_path)).convert("RGB")
# Resize if the long edge exceeds the limit
w, h = img.size
long_edge = max(w, h)
if long_edge > _MAX_IMAGE_DIM:
scale = _MAX_IMAGE_DIM / long_edge
img = img.resize((int(w * scale), int(h * scale)), _PILImage.LANCZOS)
# Encode to JPEG and iteratively reduce quality until size fits
quality = 85
while quality >= 30:
buf = io.BytesIO()
img.save(buf, format="JPEG", quality=quality)
encoded = base64.b64encode(buf.getvalue()).decode()
if len(encoded) <= _MAX_IMAGE_BYTES:
return encoded, "image/jpeg"
quality -= 10
# Last resort: halve the resolution once more
img = img.resize((img.width // 2, img.height // 2), _PILImage.LANCZOS)
buf = io.BytesIO()
img.save(buf, format="JPEG", quality=60)
return base64.b64encode(buf.getvalue()).decode(), "image/jpeg"
def _vision_classify_batch(
client: anthropic.Anthropic,
records: list["FileRecord"],
topics: list[str],
retries: int,
retry_delay: float,
) -> None:
"""Classify a batch of image FileRecords via Claude Vision in one API call.
Sends all images in a single multi-image message. Each image gets:
- A topic from the allowed list
- A short_description (<=50 chars, plain language, no quotes) that is used
as a filename prefix when the original filename is meaningless.
Results are written back into each record's .topic and .new_name fields.
Args:
client: Anthropic client.
records: Image FileRecords whose .text starts with '__IMAGE_FILE__:'.
topics: Allowed topic strings.
retries: Number of retry attempts on API failure.
retry_delay: Seconds to wait between retries.
"""
if not records:
return
topic_list = "\n".join(f"- {t}" for t in topics)
content: list[dict] = []
# Build multi-image message; skip records that fail to encode
encodable_records: list[FileRecord] = []
for i, record in enumerate(records):
try:
b64, media_type = _image_to_base64(record.path)
except Exception as exc:
log.warning("Cannot encode image %s: %s", record.path.name, exc)
record.error = "image_encode_failed"
record.topic = "Other"
continue
content.append({
"type": "text",
"text": (
f"Image {len(encodable_records)} — filename: {record.path.name}"
+ (" [NEEDS_RENAME]" if _is_bad_filename(record.path.stem) else "")
),
})
content.append({
"type": "image",
"source": {"type": "base64", "media_type": media_type, "data": b64},
})
encodable_records.append(record)
if not encodable_records:
log.warning("No encodable images in this batch; skipping vision call.")
return
content.append({
"type": "text",
"text": (
"You are an image classifier.\n\n"
f"Allowed topics:\n{topic_list}\n\n"
"For EACH image above return a JSON object with:\n"
' "index" : integer (same order as shown above)\n'
' "topic" : exactly one topic from the allowed list\n'
' "short_description" : max 50 characters, plain language description of '
"what the image shows — always required for every image. "
"No quotes, no special chars, lowercase, suitable as a filename prefix "
"(e.g. 'sunset over amsterdam canal', 'dog playing in snow').\n\n"
"Return ONLY a JSON array — no markdown, no explanation.\n"
"Example: "
'[{"index":0,"topic":"Travel & Tourism","short_description":"sunset over amsterdam canal"}]'
),
})
for attempt in range(1, retries + 1):
try:
response = client.messages.create(
model=MODEL,
max_tokens=1024,
messages=[{"role": "user", "content": content}],
)
raw = ""
if response.content and hasattr(response.content[0], "text"):
raw = response.content[0].text
if not raw:
log.warning("Vision classify attempt %d/%d: empty response.", attempt, retries)
if attempt < retries:
time.sleep(retry_delay)
continue
try:
results = _extract_json_array(raw)
except (ValueError, json.JSONDecodeError) as exc:
log.warning("Vision parse attempt %d/%d: %s", attempt, retries, exc)
if attempt < retries:
time.sleep(retry_delay)
continue
parsed_count = 0
for item in results:
if not isinstance(item, dict):
continue
try:
idx = int(item["index"])
except (KeyError, ValueError, TypeError):
continue
if idx < 0 or idx >= len(encodable_records):
continue
topic = str(item.get("topic", "")).strip()
if not topic:
topic = "Other"
elif topic not in topics:
topic = _best_match(topic, topics)
encodable_records[idx].topic = topic
desc = str(item.get("short_description", "")).strip()
if desc:
clean_desc = _sanitize_suggested_name(desc)
orig_stem = encodable_records[idx].path.stem
# if _is_bad_filename(orig_stem):
# encodable_records[idx].new_name = clean_desc[:50]
# else:
encodable_records[idx].new_name = f"{clean_desc[:50]}_{orig_stem}"[:80]
parsed_count += 1
if parsed_count == 0:
log.warning("Vision attempt %d/%d: parsed 0 items from response.", attempt, retries)
if attempt < retries:
time.sleep(retry_delay)
continue
# Fill in any records that didn't get a result
for record in encodable_records:
if not record.topic:
record.topic = "Other"
return
except anthropic.RateLimitError:
log.warning(
"Rate limited on vision call; waiting %.0fs (attempt %d/%d)",
retry_delay * 2, attempt, retries,
)
time.sleep(retry_delay * 2)
except anthropic.APIStatusError as exc:
log.warning("Vision API error %s attempt %d/%d", exc.status_code, attempt, retries)
time.sleep(retry_delay)
if attempt < retries:
time.sleep(retry_delay)
for record in encodable_records:
if not record.topic:
record.error = "classification_failed"
record.topic = "Other"
def extract_text_from_file(file_path: Path, max_chars: int) -> str:
"""Dispatch text extraction to the correct handler based on file extension."""
suffix = file_path.suffix.lower()
try:
if suffix == ".pdf":
return _extract_pdf(file_path, max_chars)
elif suffix in (".txt", ".csv", ".htm", ".html"):
return _extract_txt(file_path, max_chars)
elif suffix == ".rtf":
return _extract_rtf(file_path, max_chars)
elif suffix == ".docx":
return _extract_docx(file_path, max_chars)
elif suffix == ".doc":
return _extract_doc(file_path, max_chars)
elif suffix in (".xlsx", ".xls"):
return _extract_xlsx(file_path, max_chars)
elif suffix in (".jpg", ".jpeg", ".png", ".tiff", ".tif", ".bmp", ".gif", ".webp"):
return _extract_image(file_path, max_chars)
except Exception as exc:
log.debug("Extraction failed for %s: %s", file_path.name, exc)
return ""
# ---------------------------------------------------------------------------
# Parallel extraction
# ---------------------------------------------------------------------------
def extract_texts_parallel(records: list[FileRecord], max_chars: int, workers: int) -> None:
"""Fill FileRecord.text for each record in-place using a thread pool."""
def _extract(record: FileRecord) -> None:
record.text = extract_text_from_file(record.path, max_chars)
if not record.text:
record.error = "empty_text"
with ThreadPoolExecutor(max_workers=workers) as pool:
futures = {pool.submit(_extract, r): r for r in records}
for future in tqdm(as_completed(futures), total=len(futures),
desc="Extracting text", unit="file"):
future.result()
# ---------------------------------------------------------------------------
# Prompt builder
# ---------------------------------------------------------------------------
def build_classification_prompt(batch: list[FileRecord], topics: list[str]) -> str:
"""Build the classification prompt, requesting a suggested name for bad filenames."""
topic_list = "\n".join(f"- {t}" for t in topics)
needs_rename = any(_is_bad_filename(r.path.stem) for r in batch)
entries: list[str] = []
for i, record in enumerate(batch):
snippet = record.text if record.text else "(no text extracted)"
ext = record.path.suffix.upper()
tag = " [NEEDS_RENAME]" if _is_bad_filename(record.path.stem) else ""
entries.append(f"### File {i} [{ext}]{tag}\nFilename: {record.path.name}\n\n{snippet}")
docs_block = "\n\n".join(entries)
rename_instruction = (
'\nFor files marked [NEEDS_RENAME], also include a "suggested_name" key: '
"a descriptive filename stem of max 50 characters, no extension, "
'use_underscores_for_spaces, no special characters. Omit "suggested_name" for other files.\n'
) if needs_rename else ""
return (
"You are a document classifier. Assign exactly one topic from the list below to each file.\n\n"
f"Allowed topics:\n{topic_list}\n\n"
f"{rename_instruction}"
'Return ONLY a JSON array — one object per file in the same order provided.\n'
'Required keys: "index" (integer), "topic" (string from list above).\n'
'Optional key: "suggested_name" (string, only for [NEEDS_RENAME] files).\n'
"No explanation, no markdown — only raw JSON.\n\n"
f"Files to classify:\n\n{docs_block}\n"
)
# ---------------------------------------------------------------------------
# JSON extraction helper
# ---------------------------------------------------------------------------
def _extract_json_array(raw: str) -> list[dict]:
"""Robustly extract a JSON array from Claude's response.
Tries multiple strategies in order, returning on first success:
1. Raw text directly
2. Content inside ```...``` fences
3. Bracket-scan: first '[' to last ']'
Args:
raw: Raw text from Claude.
Returns:
Parsed list of dicts.
Raises:
ValueError: If no valid JSON array can be extracted.
"""
def _try_parse(s: str):
s = s.strip()
if not s.startswith("["):
return None
try:
result = json.loads(s)
if isinstance(result, list):
return result
except json.JSONDecodeError:
pass
return None
text = raw.strip()
# Strategy 1: try the raw text directly
result = _try_parse(text)
if result is not None:
return result
# Strategy 2: extract content from ```...``` fences and try each block
if "```" in text:
parts = text.split("```")
for part in parts:
candidate = part.strip()
if candidate.startswith("json"):
candidate = candidate[4:].strip()
result = _try_parse(candidate)
if result is not None:
return result
# Strategy 3: find the first '[' ... last ']' bracket pair in the full text
start = text.find("[")
end = text.rfind("]")
if start != -1 and end != -1 and end > start:
result = _try_parse(text[start : end + 1])
if result is not None:
return result
raise ValueError(f"No valid JSON array found in response (length {len(raw)}): {raw[:200]!r}")
# ---------------------------------------------------------------------------
# Response parser
# ---------------------------------------------------------------------------
def _parse_classification_response(
raw: str,
batch: list[FileRecord],
topics: list[str],
) -> bool:
"""Parse Claude's JSON response and populate batch records in-place.
Args:
raw: Raw text response from Claude.
batch: Records to populate with topic and new_name.
topics: Allowed topic strings for validation.
Returns:
True if parsing succeeded; False if the response was unparseable.
"""
try:
results = _extract_json_array(raw)
except (ValueError, json.JSONDecodeError) as exc:
log.warning("Could not parse classification response: %s", exc)
return False
if not isinstance(results, list) or not results:
log.warning("Classification response is not a non-empty list.")
return False
parsed_count = 0
for item in results:
if not isinstance(item, dict):
log.warning("Skipping non-dict item in classification response: %r", item)
continue
try:
idx: int = int(item["index"])
except (KeyError, ValueError, TypeError):
log.warning("Skipping item with missing/bad 'index': %r", item)
continue
if idx < 0 or idx >= len(batch):
log.warning("Index %d out of range for batch of size %d; skipping.", idx, len(batch))
continue
topic = str(item.get("topic", "")).strip()
if not topic:
log.warning("Empty topic for index %d; defaulting to 'Other'.", idx)
topic = "Other"
elif topic not in topics:
topic = _best_match(topic, topics)
batch[idx].topic = topic
suggested = item.get("suggested_name")
if suggested:
batch[idx].new_name = _sanitize_suggested_name(str(suggested))
parsed_count += 1
if parsed_count == 0:
log.warning("Classification response parsed 0 valid items.")
return False
return True
def _best_match(topic: str, allowed: list[str]) -> str:
"""Return the best-matching allowed topic via case-insensitive substring."""
topic_lower = topic.lower()
for candidate in allowed:
if topic_lower in candidate.lower() or candidate.lower() in topic_lower:
return candidate
return "Other"
# ---------------------------------------------------------------------------
# Standard (real-time) classification
# ---------------------------------------------------------------------------
def classify_batch_standard(
client: anthropic.Anthropic,
batch: list[FileRecord],
topics: list[str],
retries: int,
retry_delay: float,
) -> None:
"""Classify a batch via the synchronous Messages API."""
prompt = build_classification_prompt(batch, topics)
for attempt in range(1, retries + 1):
try:
response = client.messages.create(
model=MODEL,
max_tokens=1024,
messages=[{"role": "user", "content": prompt}],
)
raw = ""
if response.content and hasattr(response.content[0], "text"):
raw = response.content[0].text
if raw and _parse_classification_response(raw, batch, topics):
return
log.warning("Classify attempt %d/%d: empty or unparseable response.", attempt, retries)
except (json.JSONDecodeError, KeyError, IndexError, ValueError) as exc:
log.warning("Parse error attempt %d/%d: %s", attempt, retries, exc)
except anthropic.RateLimitError:
log.warning("Rate limited; waiting %.0fs (attempt %d/%d)", retry_delay * 2, attempt, retries)
time.sleep(retry_delay * 2)
except anthropic.APIStatusError as exc:
log.warning("API error %s attempt %d/%d", exc.status_code, attempt, retries)
time.sleep(retry_delay)
if attempt < retries:
time.sleep(retry_delay)
for record in batch:
if not record.topic:
record.error = "classification_failed"
record.topic = "Other"
# ---------------------------------------------------------------------------
# Batch API — submit
# ---------------------------------------------------------------------------
def build_batch_requests(
all_records: list[FileRecord],
topics: list[str],
batch_size: int,
) -> list[dict]:
"""Build Batch API request dicts; assign custom_ids to all records."""
requests: list[dict] = []
sub_batches = [all_records[i: i + batch_size] for i in range(0, len(all_records), batch_size)]
for sub_idx, sub_batch in enumerate(sub_batches):
for rec_idx, record in enumerate(sub_batch):
record.custom_id = f"sub{sub_idx:06d}_rec{rec_idx:04d}"
prompt = build_classification_prompt(sub_batch, topics)
requests.append({
"custom_id": f"sub{sub_idx:06d}",
"params": {
"model": MODEL,
"max_tokens": 1024,
"messages": [{"role": "user", "content": prompt}],
},
})
return requests
def submit_batch(
client: anthropic.Anthropic,
all_records: list[FileRecord],
topics: list[str],
batch_size: int,
state_path: Path,
) -> str:
"""Submit all requests to the Batch API and save state for collect phase."""
log.info("Building batch requests…")
requests = build_batch_requests(all_records, topics, batch_size)
log.info("Submitting %d requests to Batch API…", len(requests))
response = client.beta.messages.batches.create(requests=requests)
batch_id: str = response.id
log.info("Batch submitted. ID: %s | Status: %s", batch_id, response.processing_status)
id_to_path: dict[str, str] = {
record.custom_id: str(record.path.resolve()) for record in all_records
}
state = {"batch_id": batch_id, "topics": topics, "batch_size": batch_size, "id_to_path": id_to_path}
with open(state_path, "w", encoding="utf-8") as fh:
json.dump(state, fh, indent=2)
log.info("Batch state saved to %s", state_path)
return batch_id
# ---------------------------------------------------------------------------
# Batch API — collect
# ---------------------------------------------------------------------------
def poll_batch_until_done(client: anthropic.Anthropic, batch_id: str, poll_interval: int) -> None:
"""Block until the batch reaches the 'ended' status."""
log.info("Polling batch %s every %ds…", batch_id, poll_interval)
while True:
batch = client.beta.messages.batches.retrieve(batch_id)
status = batch.processing_status
counts = batch.request_counts
log.info(
"Status: %-12s processing=%d succeeded=%d errored=%d",
status, counts.processing, counts.succeeded, counts.errored,
)
if status == "ended":
break
time.sleep(poll_interval)
log.info("Batch %s finished.", batch_id)
def collect_batch_results(
client: anthropic.Anthropic,
batch_id: str,
topics: list[str],
id_to_path: dict[str, str],
batch_size: int,
) -> dict[str, tuple[str, str]]:
"""Retrieve batch results; return path -> (topic, new_name) mapping."""
# Reconstruct sub-batch structure
sub_batches: dict[int, list[tuple[int, str, str]]] = {}
for custom_id, abs_path in id_to_path.items():
try:
parts = custom_id.split("_")
sub_idx = int(parts[0][3:])
rec_idx = int(parts[1][3:])
except (IndexError, ValueError):
log.warning("Malformed custom_id %r in state file; skipping.", custom_id)
continue
sub_batches.setdefault(sub_idx, []).append((rec_idx, custom_id, abs_path))
ordered: dict[int, list[tuple[int, str, str]]] = {
k: sorted(v, key=lambda x: x[0]) for k, v in sub_batches.items()
}
path_to_result: dict[str, tuple[str, str]] = {}
result_count = 0
log.info("Streaming batch results for %s…", batch_id)
for result in client.beta.messages.batches.results(batch_id):
sub_id = result.custom_id
try:
sub_idx = int(sub_id[3:])
except (ValueError, IndexError):
log.warning("Malformed sub_id %r in batch results; skipping.", sub_id)
continue
if result.result.type != "succeeded":
log.warning("Sub-batch %s failed: %s", sub_id, result.result.type)
for _, _, path in ordered.get(sub_idx, []):
path_to_result[path] = ("Other", "")
continue
# Safely extract text from response
raw = ""
try:
content = result.result.message.content
if content and hasattr(content[0], "text"):
raw = content[0].text
except (AttributeError, IndexError, TypeError) as exc:
log.warning("Could not read content from sub-batch %s: %s", sub_id, exc)
sub_entries = ordered.get(sub_idx, [])
stub_records = [FileRecord(path=Path(p), custom_id=cid) for _, cid, p in sub_entries]
if not raw:
log.warning("Empty response for sub-batch %s; defaulting all to 'Other'.", sub_id)
for record in stub_records:
path_to_result[str(record.path.resolve())] = ("Other", "")
continue
success = _parse_classification_response(raw, stub_records, topics)
if not success:
log.warning("Parse failed for sub-batch %s; defaulting all to 'Other'.", sub_id)
for record in stub_records:
topic = record.topic if record.topic else "Other"
path_to_result[str(record.path.resolve())] = (topic, record.new_name)
result_count += 1
log.info("Collected results for %d files.", result_count)
return path_to_result
# ---------------------------------------------------------------------------