跳到正文
DEV Community· D9292S·· 28 天前AI 評分51

SlothSort 以離線 AI 輔助分類及整理檔案

SlothSort 🦥 — An Offline AI File Organizer That Rewards Laziness

AI 導讀

D9292S 建立 SlothSort,一款透過 Ollama 在本機運行 llama3.2 的 CLI 工具,可按檔案副檔名及文字內容分類、整理檔名並移入分類資料夾。工具預設提供 dry-run 預覽,並支援 --watch、以 SHA-256 偵測重複檔案的 --dedupe,以及 slothsort undo 回復操作。完整程式碼、文件及自動化測試套件已在 GitHub 開源。

正文

This is a submission for the Hacktoberfest Open-Source AI Challenge Week 3: Slow and Steady

What I Built

Most developers have a Downloads folder that looks like a digital landfill: dozens of document(1).pdf, Screenshot 2026-10-21.png, and camera uploads like IMG_20241019_142356.jpg.

Organizing them manually is tedious, and simple extension-moving scripts fail because they can't understand what a file actually contains.

In honor of International Sloth Day and this week's theme — Slow and Steady: build something with open-source AI that rewards laziness — I built SlothSort.

SlothSort is a lightweight CLI that uses a local open-weight model (llama3.2) via Ollama to scan messy folders, understand file context, clean up names into readable kebab-case, and sort everything into category folders.

Core Features

  • 🧠 Contextual Sorting: Classifies files using both extensions and text header previews (peeking at the first few lines of text/CSV/code).
  • 🏷️ Clean Renaming: Standardizes messy timestamps and downloads (Screenshot 2026-10-21 000814.png → screenshot-2026-10-21-000814.png).
  • 🦥 True Sloth Mode (--watch): Runs quietly in the background, tidying up new downloads automatically while you take a nap.
  • 📑 Deduplication (--dedupe): Uses fast SHA-256 matching to isolate duplicate downloads (invoice (1).pdf) into a Duplicates/ folder.
  • 🛡️ Defensive by Default: Safe dry-run previews by default, collision protection (-1, -2), and instant 1-command rollback (slothsort undo).

Demo

Here is a live terminal session running against a messy directory:

$ slothsort ~/Downloads --dedupe

┌──────────────── 🦥 slothsort v1.0.0 ────────────────┐
│  📂 /Users/deepa/Downloads                          │
│  ⚙️   DRY-RUN  Model: llama3.2 • Offline Inference  │
└─────────────────────────────────────────────────────┘

Taxonomy Breakdown                                                          
┌────────────────────┬──────────┬────────────┬────────────┬────────────────┐
│ Category           │    Files │       Size │    Renamed │      Inference │
├────────────────────┼──────────┼────────────┼────────────┼────────────────┤
│ 📦 Archives        │        3 │    45.0 MB │          1 │      1/3 local │
│ 🎵 Audio           │        2 │    18.5 MB │          2 │          rules │
│ 💻 Code            │        5 │     0.2 MB │          2 │          rules │
│ 📊 Data            │        3 │     1.1 MB │          3 │          rules │
│ 🎨 Design          │        2 │    24.0 MB │          2 │          rules │
│ 📄 Documents       │        7 │     2.8 MB │          6 │      1/7 local │
│ 📑 Duplicates      │        2 │     1.4 MB │          0 │         dedupe │
│ 🖼️  Images         │        4 │     6.9 MB │          4 │          rules │
│ ⚙️  Installers     │        2 │   157.9 MB │          2 │          rules │
│ 🎬 Videos          │        1 │   240.0 MB │          1 │      1/1 local │
├────────────────────┼──────────┼────────────┼────────────┼────────────────┤
│ Total              │       31 │   497.8 MB │         23 │              — │
└────────────────────┴──────────┴────────────┴────────────┴────────────────┘

┌─ Proposed Directory Hierarchy ──────────────────────────────────────────────┐
│ 📁 Downloads/                                                               │
│ ├── 📄 Documents/ (7 files)                                                 │
│ │   ├── analytics_october_metrics.csv → analytics-october-metrics.csv •     │
│ │   │   Financial data report                                               │
│ │   ├── budget_forecast_q4.xlsx → budget-forecast-q4.xlsx • standardized    │
│ │   │   kebab-case                                                          │
│ │   ├── final_report_FINAL_v3_USETHISONE.docx →                             │
│ │   │   final-report-final-v3-usethisone.docx • standardized kebab-case     │
│ │   └── meeting_notes_oct.txt → meeting-notes-oct.txt • standardized        │
│ │       kebab-case                                                          │
│ ├── 📑 Duplicates/ (2 files)                                                │
│ │   ├── document(2).pdf → Duplicates/document(2).pdf • duplicate of         │
│ │   │   document(1).pdf                                                     │
│ │   └── IMG_20241020_083211.jpg → Duplicates/IMG_20241020_083211.jpg •      │
│ │       duplicate of IMG_20241019_142356.jpg                                │
│ ├── 🖼️  Images/ (4 files)                                                   │
│ │   ├── Screenshot 2026-10-21 000814.png →                                  │
│ │   │   screenshot-2026-10-21-000814.png • standardized kebab-case          │
│ │   └── wallpaper_4k_mountain.jpg → wallpaper-4k-mountain.jpg •             │
│ │       standardized kebab-case                                             │
│ └── ⚙️  Installers/ (2 files)                                               │
│     ├── ABDownloadManager_1.11.1_windows_x64.exe →                          │
│     │   abdownloadmanager-1.11.1-windows-x64.exe • standardized kebab-case  │
│     └── VSCodeUserSetup-x64-1.92.0.exe → vscodeusersetup-x64-1.92.0.exe •   │
│         standardized kebab-case                                             │
└─────────────────────────────────────────────────────────────────────────────┘

┌─ Next Step ─────────────────────────────────────────────────────────────────┐
│  Dry-run preview complete. No files were modified on disk.                  │
│                                                                             │
│  To apply these changes, run:                                               │
│    slothsort "~/Downloads" --execute --dedupe                               │
└─────────────────────────────────────────────────────────────────────────────┘

When you pass --execute, the moves happen atomically. If you ever change your mind:

$ slothsort undo ~/Downloads

┌─ Rollback Complete ─────────────────────────────────────────────────────────┐
│  ✓ Successfully restored 31 file(s) to original locations.                  │
└─────────────────────────────────────────────────────────────────────────────┘

Code

The complete codebase, documentation, and automated test suite are open-sourced on GitHub:

👉 GitHub Repository: D9292S/slothsort

slothsort/
├── pyproject.toml              # Modern Hatchling package configuration
├── README.md                   # Full documentation and command reference
├── LICENSE                     # MIT License
├── .slothsort.toml.example     # Configuration template for user overrides
├── slothsort/
│   ├── __init__.py             # Version metadata
│   ├── config.py               # Taxonomy mapping, model configurations, defaults
│   ├── scanner.py              # Filtering, snippet extraction, SHA-256 duplicate hashing
│   ├── categorizer.py          # Ollama JSON inference + Algorithmic Hallucination Guard
│   ├── organizer.py            # Collision resolution (-1, -2), moves, atomic undo manifest
│   └── cli.py                  # Rich terminal UI, diff tree, watch mode, commands
├── demo/
│   └── simulate_mess.py        # Demo script to generate 31 realistic messy files
└── tests/
    ├── test_scanner.py         # Filtering, snippets, duplicate detection tests
    ├── test_safety.py          # Hallucination guard & name preservation tests
    ├── test_parser.py          # Resilient JSON parsing tests (lists, dicts, markdown)
    └── test_organizer.py       # Collision resolution & end-to-end rollback tests

How I Built It

SlothSort is built with Python 3.10+, Ollama, Meta Llama 3.2 (3B), Click, Rich, and Pydantic.

Technical Highlights

  1. Local Inference: Files are batched and sent to Ollama with strict JSON schemas enforced by Pydantic.
  2. Content Sniffing: For ambiguous text/code/data files under 2 MB, the scanner peeks at the first 300 characters to provide the model with grounding context.
  3. The Hallucination Guard (is_safe_rename): During testing, I caught a 3B model edge case: when given a batch containing multiple installers, Llama 3.2 occasionally cross-pollinated names (trying to rename ABDownloadManager.exe to bitdefender.exe). I wrote an algorithmic safety guard that verifies suggested names never borrow tokens from other files in the batch, falling back to safe formatting if cross-contamination is detected.
  4. Safety & Testing: Includes an atomic rollback log (.slothsort-undo.json) and 12 unit tests in pytest verifying parsing, collision handling, and hallucination rejection.

Why Does Open Innovation Matter?

For personal file management, local open-source AI is fundamentally superior to closed cloud APIs:

  • 🔒 Absolute Privacy: Your Downloads folder contains tax drafts, bank statements, and personal records. With local models, zero bytes leave your machine.
  • 💸 Zero Recurring Cost: Organizing thousands of files costs \$0.00 in API tokens.
  • ✈️ 100% Offline: Operates in airplane mode, on trains, or without internet.
  • 🎛️ Model Portability: Swap models freely based on your hardware (--model llama3.2, --model phi3, or --model mistral).
  • 🛡️ Resilient Fallback: If Ollama is offline or files exceed 500 MB, SlothSort gracefully falls back to deterministic rules. It never crashes.

My Agent Session

I built SlothSort through an iterative agent pair-programming session with an AI coding assistant. The agent helped scaffold the initial Click/Rich CLI architecture, iterate on small-model prompt engineering with Ollama, and write the 12-test pytest suite that verified the algorithmic hallucination guard.

The Lazy Payoff

Manually sorting an 800-file Downloads folder usually takes 45 minutes of tedious drag-and-drop.

With SlothSort, it takes 5 seconds with one command — or zero effort if you leave --watch running in the background.

來源:DEV Community · dev.to