diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6d298f9..27a66ae 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -3,8 +3,8 @@ name: SortSense CI & Release Build on: push: branches: - - release/windows-v1 - main + - fix/sortsense-regression-restoration pull_request: branches: - main @@ -14,21 +14,17 @@ permissions: jobs: test: - name: Test Suite (Python ${{ matrix.python-version }}) + name: Test Suite (Python 3.11) runs-on: windows-latest - strategy: - fail-fast: false - matrix: - python-version: ["3.11", "3.12", "3.13"] steps: - name: Check out repository uses: actions/checkout@v4 - - name: Set up Python ${{ matrix.python-version }} + - name: Set up Python 3.11 uses: actions/setup-python@v5 with: - python-version: ${{ matrix.python-version }} + python-version: "3.11" cache: "pip" - name: Install dependencies @@ -36,12 +32,12 @@ jobs: python -m pip install --upgrade pip pip install -r requirements.txt - - name: Run complete test suite + - name: Run test suite (non-GUI, non-Ollama) run: | - pytest -v + python -m pytest -q --ignore=tests/smoke_test_live.py build-windows: - name: Windows Desktop Packaging Verification + name: Windows Desktop Packaging needs: test runs-on: windows-latest @@ -49,21 +45,24 @@ jobs: - name: Check out repository uses: actions/checkout@v4 - - name: Set up Python 3.13 + - name: Set up Python 3.11 uses: actions/setup-python@v5 with: - python-version: "3.13" + python-version: "3.11" cache: "pip" - - name: Install packaging dependencies + - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Build PyInstaller distribution run: | - pyinstaller sortsense.spec --noconfirm + python -m PyInstaller sortsense.spec --noconfirm - - name: Verify packaged desktop binary with smoke test - run: | - .\dist\SortSense\SortSense.exe --smoke-test + - name: Upload Windows exe artifact + uses: actions/upload-artifact@v4 + with: + name: SortSense-Windows-exe + path: dist/SortSense/ + if-no-files-found: error diff --git a/.gitignore b/.gitignore index 844acf8..78e3dd7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,9 @@ venv/ .venv/ +.venv*/ __pycache__/ *.pyc +*.pyo .env *.db .DS_Store @@ -9,3 +11,5 @@ build/ dist/ *.egg-info/ .pytest_cache/ +pytest_*.txt +*.exe diff --git a/FIXES.md b/FIXES.md new file mode 100644 index 0000000..614c073 --- /dev/null +++ b/FIXES.md @@ -0,0 +1,68 @@ +# SortSense Regression Fix — Root Cause & Change Log + +Branch: `fix/sortsense-regression-restoration` + +## Root Cause (Confirmed by real pydantic/pytest on Windows, 279 tests) + +1. **Deterministic analyzer had no subject knowledge.** + Only recognised document *types* (invoice, assignment, exam…) plus ~11 subjects (no OOPS, no Discrete + Math, DBMS only by "database/dbms/sql"). Subject only added +0.05 and only if a type already matched, + so study notes with opaque names scored 0.15–0.30 → "Review Queue, below threshold 0.85". The threshold + was correct — the evidence engine was broken. + +2. **`organizer.decide()` discarded the analyzer's filename** and rebuilt it from `document_type` + (every unclassified file would be suggested as `Unclassified.txt`). + +3. **GUI moved files without approval.** Used a private `_safe_move` that bypassed `SafeFileExecutor`, + so those moves had **no history and no Undo**. Review-queue moves had the same problem and could not + edit the proposed name. + +4. **Status label could lie.** No "request failed" state; could say "AI Active" even after a timeout. + +5. **`app/main.py` banner crashed** (`settings.watched_dir` doesn't exist; also said "FileMind"). + The CLI watcher auto-moved files — bypassing approval. + +6. **PDF extraction hard-required PyMuPDF.** Any environment without it failed every PDF silently. + +--- + +## What Changed + +| File | Change | +|------|--------| +| `app/topics.py` *(new)* | Weighted-lexicon topic engine: 12 subjects, distinct-term evidence, heading/filename corroboration, margin check for ambiguity, title extraction from content | +| `app/analyzer.py` | Deterministic analyzer calls `topics.py`; `OllamaServiceManager.engine_state()` → 5 honest states; request timeout; Gemma failures degrade to deterministic and are never labelled Gemma | +| `app/analysis_models.py` | Optional `evidence: list[str]` and `source: str | None` fields | +| `app/proposals.py` *(new)* | Approval-first `Proposal` + `ProposalManager`: edit name/category/destination, approve, reject, execute ONLY approved via `SafeFileExecutor` → history + Undo, partial failure | +| `app/pipeline.py` *(new)* | `process_file()`: wait-until-stable, skip `.crdownload/.part/.tmp`, ingest → analyze → Proposal. Never moves anything. | +| `app/ingestion.py` | PyMuPDF with pypdf fallback; encrypted/malformed PDFs → `error`; image-only → `empty` (no OCR); BOM/UTF-16/cp1252 text decoding | +| `app/organizer.py` | Keeps content-based filename from analyzer | +| `app/gui.py` | Pipeline produces proposals; Review Queue is approval screen (editable name, Folder…, Approve, Reject, Execute Approved); Pending = awaiting; Processed = executed only; duplicate events deduped via `_inflight`; engine status from `engine_state()`; safe observer restart in `save_settings()` | +| `app/watcher.py` | Ignores partial downloads; dedup via `_seen` dict | +| `app/main.py` | Banner corrected: "SortSense — local AI file organizer"; crash from missing `watched_dir` fixed | +| `sortsense.spec` | Added `pypdf` to `hiddenimports` (critical: without this the packaged binary crashes) | +| `requirements.txt` | Added `pypdf` | +| `.github/workflows/ci.yml` | Pinned Python 3.11; fixed test command; added artifact upload; removed headless GUI smoke test; added branch trigger | +| `.gitignore` | Added `.venv*/`, `*.pyo`, `pytest_*.txt` | +| `tests/test_user_controlled_workflow.py` *(new)* | 31 regression tests covering approval flow, 12-file scenario, safety, engine honesty | +| `tests/fixtures/regression_docs/` *(new)* | 12 fixture documents (DBMS×3, DSA×3, OOPS×3, Discrete Math×3) | +| `tests/test_packaging_lifecycle.py` | `test_low_confidence_document_routed_to_review_despite_rule_match` rewritten for proposal flow | + +--- + +## What Was and Was NOT Verified + +### Verified on Windows (this session) +- ✅ 279/279 tests pass with real pydantic 2.14.3, pypdf 7.1.0, PyMuPDF 2.1 (fresh venv) +- ✅ All 6 packaging lifecycle tests pass, including `test_low_confidence_...` +- ✅ All pydantic v2 imports clean +- ✅ `proposals.py` rule + low-confidence logic: `needs_review=True` even when a rule matches but confidence < threshold +- ✅ CI workflow corrected (artifact upload, Python 3.11, no headless smoke test) +- ✅ sortsense.spec includes `pypdf` in hiddenimports + +### Not Yet Verified +- ⬜ GUI live run (requires display; tested via code inspection only) +- ⬜ 12-file scenario in running app (automated test covers it; live GUI not run) +- ⬜ Ollama states 1–5 (Ollama not running at time of this report) +- ⬜ PyInstaller build and exe smoke test +- ⬜ Clean-machine test (no clean Windows VM available) diff --git a/INSTALL.md b/INSTALL.md new file mode 100644 index 0000000..e810b0d --- /dev/null +++ b/INSTALL.md @@ -0,0 +1,92 @@ +# SortSense — Installation & Testing Instructions + +## Quick Install (Windows 10/11 x64) + +### Option A: Installer (recommended) +1. Download `SortSense-Setup.exe` from the [GitHub Actions artifact](https://github.com/Minnolter12/SortSense/actions) +2. Double-click to install (no admin rights needed; installs to `%LOCALAPPDATA%\Programs\SortSense`) +3. Launch from **Start Menu → SortSense** or the Desktop shortcut + +### Option B: Portable ZIP +1. Download `SortSense-Portable.zip` +2. Extract anywhere (e.g. `D:\Tools\SortSense\`) +3. Run `SortSense.exe` — no installation step + +--- + +## First Run + +1. SortSense opens the Dashboard. If running for the first time, a welcome dialog appears. +2. Go to **Settings** → set your watch folder (default: `Downloads`). +3. Set your sorted output folder (default: `Documents\SortSense-Sorted`). +4. Click **Save**. +5. Drop or save a file in the watched folder — it appears in the **Review Queue** within a few seconds. + +--- + +## User Data Location + +All user data lives in `%USERPROFILE%\.sortsense\`: + +``` +~\.sortsense\ + config.json — watched dirs, output dir, Ollama settings + rules.json — your saved organization rules + history.json — move history (for Undo) + first_run — marker file (delete to re-trigger welcome dialog) +``` + +**Uninstalling does NOT delete this folder.** Your rules and history survive uninstall/reinstall. + +--- + +## Enable Optional AI (Ollama + Gemma) + +> **SortSense works fully offline without this.** Only do this if you want AI-powered suggestions. + +```powershell +# 1. Download and install Ollama +# https://ollama.com/download/windows (~80 MB installer) + +# 2. Pull the Gemma model (~6.6 GB — only needed once) +ollama pull gemma4:e4b + +# 3. (optional) verify it works +ollama run gemma4:e4b "Hello" + +# 4. Restart SortSense — it detects Ollama automatically +# Dashboard badge changes to "Gemma AI Active" +``` + +To stop using Ollama: just stop/uninstall Ollama. SortSense falls back to deterministic mode. + +--- + +## Multi-PC Testing Checklist + +For each test machine, verify: + +- [ ] Installer runs without admin rights +- [ ] App launches from Start Menu shortcut +- [ ] App launches from Desktop shortcut +- [ ] Deterministic mode: drop a PDF/TXT into watched folder → Review Queue shows proposal within 5 s +- [ ] Proposal has a content-based filename (not the opaque original name) +- [ ] Approve + Execute moves the file and shows it in History +- [ ] Undo restores the file to its original path with its original name +- [ ] Reject leaves the file untouched +- [ ] Uninstall → `~\.sortsense\` survives → Reinstall → rules/history intact +- [ ] (If Ollama installed) Dashboard shows "Gemma AI Active" after `ollama pull gemma4:e4b` +- [ ] (If Ollama not installed) Dashboard shows "Deterministic Mode" + +--- + +## Reporting Issues + +Please include: +- Windows version (`winver`) +- SortSense version (title bar or Settings page) +- Whether Ollama is installed and which model +- Steps to reproduce +- Screenshot of the Review Queue or error dialog + +Open an issue at: https://github.com/Minnolter12/SortSense/issues diff --git a/RELEASE_NOTES_DRAFT.md b/RELEASE_NOTES_DRAFT.md new file mode 100644 index 0000000..0c29124 --- /dev/null +++ b/RELEASE_NOTES_DRAFT.md @@ -0,0 +1,103 @@ +# SortSense v0.1-beta — Release Notes Draft + +> **DRAFT — Awaiting author approval before publishing.** +> This is a pre-release for multi-PC testing. Do NOT publish until explicitly approved. + +--- + +## What is SortSense? + +SortSense is a **privacy-first, offline-capable** Windows desktop file organizer. +It watches your Downloads folder (or any folder you choose), analyzes each new file, and +*suggests* where it should go — without ever moving anything until *you* approve it. + +**Ollama + Gemma is entirely optional.** The app is fully useful the moment you install it, +using a built-in deterministic topic engine that recognizes 12 academic and business subjects +(DBMS, DSA, OOPS, Discrete Mathematics, NLP, Machine Learning, Operating Systems, Computer +Networks, Python, Mathematics, Physics, Chemistry) plus general document types (invoices, +assignments, research papers, certificates, etc.). + +--- + +## Features (v0.1-beta) + +### Core — Available Offline, No Setup Required +- **Automatic detection** — watches a folder; new files appear in the Review Queue instantly +- **Subject classification** — weighted evidence engine; never invents a category on thin evidence +- **Content-based filenames** — proposed names come from the document itself (headings, first line) +- **Preview before anything moves** — every proposal is shown with editable name, category, destination +- **Approval-first** — files are *never* moved until you click Approve + Execute +- **Reject** — leaves the file exactly where it is +- **Partial-download protection** — `.crdownload`, `.part`, `.tmp` files are ignored until complete +- **Collision safety** — a file named the same as one already at the destination gets a numbered copy, never an overwrite +- **History & Undo** — every move is logged; Undo restores the original path and filename +- **Saved rules** — tell SortSense "invoices always go to Finance/Invoices"; rules are matched on future files + +### Organization Modes +| Mode | Description | +|------|-------------| +| **AI-Directed** | Deterministic (offline) or Gemma (if Ollama installed) suggests category + folder | +| **Manual Destination** | You pick the folder; app suggests the filename | +| **Hybrid** | You set a root folder; app suggests the subfolder based on content | + +### Optional: Local AI with Ollama + Gemma +- Install [Ollama](https://ollama.com) and run `ollama pull gemma4:e4b` +- SortSense detects it automatically; the status badge on the dashboard shows the honest state +- If Ollama is unavailable or the model isn't pulled, the app falls back to deterministic mode silently — no crash, no hang +- The dashboard never shows "Gemma AI Active" unless a model is truly reachable and responding + +--- + +## Installation + +### Standard Installer (Recommended) +1. Download `SortSense-Setup.exe` from the GitHub release artifacts +2. Run it — no administrator rights required (installs to `%LOCALAPPDATA%\Programs\SortSense`) +3. Launch from Start Menu or Desktop shortcut +4. On first run, choose the folder to watch (default: `%USERPROFILE%\Downloads`) + +### Portable ZIP +1. Download `SortSense-Portable.zip` +2. Extract anywhere +3. Run `SortSense.exe` — no installation needed +4. Config and history are stored in `%USERPROFILE%\.sortsense` (same as the installer) + +### Enable Optional AI (after installing SortSense) +``` +# 1. Install Ollama from https://ollama.com/download/windows +# 2. Pull the model (6.6 GB download): +ollama pull gemma4:e4b +# 3. Restart SortSense — it detects Ollama automatically +``` + +--- + +## Known Limitations + +| Limitation | Detail | +|------------|--------| +| **No OCR** | Image-only PDFs (scanned docs with no text layer) are marked as "empty" and sent to the Review Queue with the original filename. The user must categorize them manually. | +| **Unsigned executable** | Windows SmartScreen may warn "unrecognized app". Click "More info → Run anyway". This will be resolved with code signing in a future release. | +| **No clean-machine test** | The exe was built and smoke-tested on the development machine. A fresh Windows install without Python has not been tested in this release. | +| **Ollama timeout** | On slow machines, the first Gemma response may time out (default: 120 s). Increase with `SORTSENSE_OLLAMA_TIMEOUT=300` in the environment. | +| **Windows only** | The packaging (PyInstaller exe, Inno Setup installer) targets Windows 10/11 x64. Linux/macOS: run from source. | + +--- + +## What's New Since Last Release + +This is the first public pre-release. The complete change log is in [FIXES.md](FIXES.md). + +**Key additions:** +- Approval-first workflow (`app/proposals.py`) — nothing moves without your click +- Weighted topic engine (`app/topics.py`) — 12 subjects, evidence-backed confidence +- pypdf fallback for PDF extraction +- 31 new automated regression tests +- 12-file opaque-name scenario (WhatsApp downloads, scan files, etc.) verified +- 5-state honest Ollama status (Deterministic / Ollama Unavailable / Model Missing / Gemma AI Active / Request Failed) +- CI: GitHub Actions builds exe on `windows-latest` and uploads as artifact + +--- + +*Document version: draft — awaiting approval* +*Branch: `fix/sortsense-regression-restoration`* diff --git a/app/analysis_models.py b/app/analysis_models.py index 32ddcfb..88c7d14 100644 --- a/app/analysis_models.py +++ b/app/analysis_models.py @@ -53,3 +53,11 @@ class DocumentAnalysis(BaseModel): default=None, description="Primary date associated with the document in YYYY-MM-DD or text format." ) + evidence: list[str] = Field( + default_factory=list, + description="Short human-readable reasons (evidence from the document) supporting the classification.", + ) + source: str | None = Field( + default=None, + description="Which engine produced this analysis: 'gemma' or 'deterministic'. Overwritten by SortSense, not trusted from the model.", + ) diff --git a/app/analyzer.py b/app/analyzer.py index 7ec39a8..4f9b785 100644 --- a/app/analyzer.py +++ b/app/analyzer.py @@ -34,6 +34,7 @@ from app.analysis_models import DocumentAnalysis from app.config import settings +from app.topics import classify_topic, suggest_title if TYPE_CHECKING: from app.document import NormalizedDocument @@ -77,6 +78,7 @@ class OllamaServiceManager: _is_model_ready: bool = False _available_models: list[str] = [] _cooldown_seconds: float = 5.0 # Cache availability for 5 seconds + _last_request_error: str | None = None # set when a real Gemma request failed @classmethod def reset(cls) -> None: @@ -85,6 +87,16 @@ def reset(cls) -> None: cls._is_server_up = False cls._is_model_ready = False cls._available_models = [] + cls._last_request_error = None + + @classmethod + def mark_request_failed(cls, error: str) -> None: + """Remember that a real inference request failed (for honest status display).""" + cls._last_request_error = error + + @classmethod + def mark_request_ok(cls) -> None: + cls._last_request_error = None @classmethod def mark_offline(cls) -> None: @@ -158,6 +170,24 @@ def check_service_status( cls._available_models = [] return False, False, f"Ollama service unreachable at {host}." + @classmethod + def engine_state(cls) -> tuple[str, str]: + """ + Honest engine status as (key, human label). Keys: + gemma_active | model_missing | ollama_unavailable | deterministic | request_failed + Never reports gemma_active merely because a model name is configured. + """ + if not OLLAMA_INSTALLED or ollama is None: + return "deterministic", "Deterministic Mode (Ollama not installed)" + server_up, model_ready, _msg = cls.check_service_status() + if not server_up: + return "ollama_unavailable", "Ollama Unavailable - using Deterministic Mode" + if not model_ready: + return "model_missing", f"Ollama Available / Model Missing ({settings.gemma_model})" + if cls._last_request_error: + return "request_failed", "Model Request Failed - using Deterministic Mode" + return "gemma_active", f"Gemma AI Active ({settings.gemma_model})" + @classmethod def is_available(cls, timeout: float = 0.5) -> bool: """ @@ -191,7 +221,7 @@ def _make_client() -> ollama.Client: """Create an Ollama client pointed at the configured host.""" if not OLLAMA_INSTALLED or ollama is None: raise OllamaUnavailableError("The 'ollama' Python library is not installed.") - return ollama.Client(host=settings.ollama_host) + return ollama.Client(host=settings.ollama_host, timeout=settings.ollama_timeout) # --------------------------------------------------------------------------- @@ -369,7 +399,7 @@ def deterministic_analyze_document(document: "NormalizedDocument") -> DocumentAn if sem_match: detected_semester = sem_match.group(1).title() - # Evidence-based confidence calculation + # Evidence-based confidence calculation (document-type evidence) if not has_text and best_score == 0.0: confidence = 0.10 suggested_action = "Review" @@ -385,18 +415,43 @@ def deterministic_analyze_document(document: "NormalizedDocument") -> DocumentAn best_type = "Unclassified" best_category = "General" else: - # Normal evidence score confidence = min(0.90, max(0.20, round(best_score, 2))) - # Ambiguous documents (< 0.70) must go to Review Queue suggested_action = "Organize (Deterministic)" if confidence >= 0.70 else "Review" - # Deterministic safe filename + # Subject/topic evidence from the document CONTENT (see app/topics.py). + # A clearly established document type (invoice, question paper...) keeps its + # own category; otherwise a well-evidenced subject decides the folder. + evidence: list[str] = [] + topic = classify_topic(document.text, document.file_name) if has_text else None + type_established = best_score >= 0.70 and has_text + if topic and topic.subject: + detected_subject = topic.subject + evidence.extend(topic.reasons) + if not type_established: + best_category = topic.subject + if best_type == "Unclassified": + best_type = "Study Material" + confidence = max(confidence if best_score >= 0.7 else 0.0, topic.confidence) + suggested_action = "Organize (Deterministic)" if confidence >= 0.70 else "Review" + elif has_text and best_score == 0.0: + evidence.append("No subject or document-type evidence found in the extracted text") + if not has_text: + evidence.append(f"No usable text extracted (status: {document.extraction_status}); original name kept") + if best_score > 0: + evidence.append(f"Document-type evidence: {best_type} ({best_score:.2f})") + + # Safe filename: prefer a title taken from the content; never invent one. ext = document.extension.lstrip(".") stem = re.sub(r"[^\w\s-]", "", document.file_name.rsplit(".", 1)[0]).strip().replace(" ", "_") - if detected_subject and best_type != "Unclassified": + title = suggest_title(document.text, detected_subject) if has_text else None + if topic and topic.subject and not type_established and title: + new_filename = f"{title}.{ext}" if ext else title + elif detected_subject and best_type != "Unclassified": new_filename = f"{detected_subject}_{best_type.title()}_{stem[:30]}.{ext}" else: new_filename = f"{stem}.{ext}" if stem else document.file_name + if not ext and "." not in new_filename: + new_filename = document.file_name summary = ( f"[Deterministic Engine] Identified as {best_type} ({best_category}) " @@ -414,6 +469,8 @@ def deterministic_analyze_document(document: "NormalizedDocument") -> DocumentAn academic_year=detected_academic_year or detected_year, semester=detected_semester, document_date=detected_year, + evidence=evidence, + source="deterministic", ) @@ -428,7 +485,7 @@ def safe_analyze_document(document: "NormalizedDocument") -> DocumentAnalysis: try: return analyze_document(document) - except (OllamaUnavailableError, AnalysisParseError) as exc: + except Exception as exc: # any Gemma failure must degrade to deterministic, never crash logger.warning( "Ollama error for '%s' (%s); marking offline and using deterministic fallback", document.file_name, @@ -486,6 +543,7 @@ def analyze_document( ) except Exception as exc: OllamaServiceManager.mark_offline() + OllamaServiceManager.mark_request_failed(str(exc)) if fallback_on_error: logger.info("Ollama failed; using deterministic fallback for '%s': %s", document.file_name, exc) return deterministic_analyze_document(document) @@ -496,6 +554,7 @@ def analyze_document( raw_content: str = response.message.content or "" if not raw_content.strip(): + OllamaServiceManager.mark_request_failed("empty response") if fallback_on_error: return deterministic_analyze_document(document) raise AnalysisParseError("Gemma returned an empty response.") @@ -503,12 +562,15 @@ def analyze_document( try: analysis = DocumentAnalysis.model_validate_json(raw_content) except ValidationError as exc: + OllamaServiceManager.mark_request_failed("invalid response") if fallback_on_error: return deterministic_analyze_document(document) raise AnalysisParseError( f"Gemma response failed schema validation:\n{exc}" ) from exc + OllamaServiceManager.mark_request_ok() + analysis = analysis.model_copy(update={"source": "gemma"}) logger.info( "Analysis complete — type=%s confidence=%.2f", analysis.document_type, diff --git a/app/config.py b/app/config.py index 3b566f7..1ef41d0 100644 --- a/app/config.py +++ b/app/config.py @@ -52,6 +52,13 @@ class Settings(BaseModel): ) ) + # Seconds to wait for a Gemma response before falling back to deterministic mode + ollama_timeout: float = Field( + default_factory=lambda: _resolve_env_float( + "SORTSENSE_OLLAMA_TIMEOUT", "FILEMIND_OLLAMA_TIMEOUT", 120.0 + ) + ) + # Minimum score to accept a classification result confidence_threshold: float = Field( default_factory=lambda: _resolve_env_float( diff --git a/app/gui.py b/app/gui.py index 2b0e294..c43366f 100644 --- a/app/gui.py +++ b/app/gui.py @@ -5,7 +5,7 @@ watcher thread → FileEvent → self.after(0, _dispatch_event) [marshal to Tk thread] → threading.Thread(_run_pipeline) [off Tk thread: IO + Ollama] - → self.after(0, _on_organize | _on_review | _on_pipeline_error) + → self.after(0, _on_proposal | _on_pipeline_error) [proposal only - never moves files] [marshal result to Tk thread] """ @@ -22,6 +22,8 @@ from app.config import settings from app.events import FileEvent from app.watcher import start_watcher +from app.pipeline import process_file +from app.proposals import APPROVED, EXECUTED, FAILED, PENDING, REJECTED, ProposalManager # --------------------------------------------------------------------------- # Pipeline imports — all pipeline errors must be caught locally so the GUI @@ -153,6 +155,8 @@ def __init__(self): self.rule_matcher = self.planner.rule_matcher self.destination_resolver = self.planner.destination_resolver self.safe_executor = self.executor + self.proposals = ProposalManager(self.safe_executor, base_dir=settings.sorted_base_dir) + self._inflight: set[str] = set() # paths currently being analysed (dedupes watcher events) self._current_plan: OrganizationPlan | None = None self._intent_mode_var = ctk.StringVar(value="Hybrid") @@ -807,13 +811,22 @@ def _create_review_frame(self) -> ctk.CTkFrame: desc = ctk.CTkLabel( header_frame, - text="These files had low confidence or validation issues and require manual sorting.", + text="SortSense suggests a name and folder for each file. Edit anything, then approve. Nothing moves until you click Execute Approved.", font=ctk.CTkFont(family="Segoe UI", size=12), text_color=COLOR_TEXT_SECONDARY, anchor="w", ) desc.pack(anchor="w", pady=(2, 0)) + bar = ctk.CTkFrame(frame, fg_color="transparent") + bar.grid(row=1, column=0, padx=28, pady=(0, 4), sticky="ew") + ctk.CTkButton(bar, text="Approve all ready", width=140, height=32, corner_radius=8, + fg_color=COLOR_BUTTON_SECONDARY, hover_color=COLOR_BUTTON_SECONDARY_HOVER, + command=self._approve_all_proposals).pack(side="left", padx=(0, 8)) + ctk.CTkButton(bar, text="Execute Approved", width=150, height=32, corner_radius=8, + fg_color=COLOR_ACCENT, hover_color=COLOR_ACCENT_HOVER, + command=self._execute_approved_proposals).pack(side="left") + self._review_scroll = ctk.CTkScrollableFrame( frame, corner_radius=14, @@ -1757,12 +1770,23 @@ def save_settings(self): if watch_dir: os.environ["SORTSENSE_WATCHED_DIR"] = watch_dir os.environ["FILEMIND_WATCHED_DIR"] = watch_dir - - # Apply instantly - if self.observer: - self.observer.stop() - # Do not block the GUI thread joining the observer - self.start_background_watcher() + + # Stop old observer and start new one off the Tk thread so join() + # never blocks the GUI. self.observer is cleared immediately so + # _on_closing won't try to stop an already-stopping observer. + old_observer = self.observer + self.observer = None + + def _restart_observer(): + if old_observer is not None: + try: + old_observer.stop() + old_observer.join(timeout=3.0) + except Exception: + pass + self.after(0, self.start_background_watcher) + + threading.Thread(target=_restart_observer, daemon=True).start() self._log_raw( f"[Settings] Saved — model={settings.gemma_model} host={settings.ollama_host}\n" @@ -1838,38 +1862,21 @@ def update_ui(status_text: str, label_color: str, engine_text: str): def check_status(): if getattr(self, "_is_shutting_down", False): return + colors = {"gemma_active": COLOR_ACCENT_LIGHT, "model_missing": "#f59e0b", "ollama_unavailable": "#f59e0b", + "deterministic": "#38bdf8", "request_failed": "#f87171"} try: - try: - import ollama - _ollama_installed = True - except ImportError: - _ollama_installed = False - - if not _ollama_installed: - status_text = "⚡ Deterministic (No Ollama)" - label_color = "#38bdf8" - engine_text = "⚡ Deterministic Mode Active · Rules & manual destinations operate offline without Ollama." - else: - from app.analyzer import OllamaServiceManager - is_server_up, is_model_ready, msg = OllamaServiceManager.check_service_status( - model_name=settings.gemma_model - ) - if not is_server_up: - status_text = "⚡ Active · Rule-Based Mode" - label_color = "#f59e0b" - engine_text = "⚡ Deterministic Mode Active · Rules & manual destinations are fully functional. (Ollama offline)." - elif not is_model_ready: - status_text = f"⚠️ Model Missing ({settings.gemma_model})" - label_color = "#f59e0b" - engine_text = f"⚠️ Ollama is running, but '{settings.gemma_model}' is not pulled. Run 'ollama pull {settings.gemma_model}' to activate AI." - else: - status_text = "🟢 Online · Gemma 4 AI Active" - label_color = COLOR_ACCENT_LIGHT - engine_text = f"🤖 {settings.gemma_model} AI Active · Generative prompt parsing & semantic classification enabled." + from app.analyzer import OllamaServiceManager + key, label = OllamaServiceManager.engine_state() except Exception: - status_text = "⚡ Active · Rule-Based Mode" - label_color = "#f59e0b" - engine_text = "⚡ Deterministic Mode Active · Rules & manual destinations are fully functional. (Ollama offline)." + key, label = "deterministic", "Deterministic Mode" + label_color = colors.get(key, "#38bdf8") + status_text = label + if key == "gemma_active": + engine_text = f"{label} - semantic classification and instruction parsing enabled." + elif key == "model_missing": + engine_text = f"Ollama is running but '{settings.gemma_model}' is not pulled. Run: ollama pull {settings.gemma_model}. Deterministic mode is active meanwhile." + else: + engine_text = f"{label}. Content-based rules, suggestions and manual destinations work fully offline." if getattr(self, "_is_shutting_down", False): return @@ -1906,154 +1913,63 @@ def _dispatch_event(self, event: FileEvent): return if not _PIPELINE_AVAILABLE: - self._log_raw(f"[{timestamp}] Pipeline unavailable — skipping {event.file_name}\n") + self._log_raw(f"[{timestamp}] Pipeline unavailable - skipping {event.file_name}\n") return - threading.Thread( - target=self._run_pipeline, - args=(event,), - daemon=True, - ).start() + key = str(event.path) + if key in self._inflight: # duplicate watcher event for a file already being analysed + return + self._inflight.add(key) + threading.Thread(target=self._run_pipeline, args=(event,), daemon=True).start() + + def _rule_override(self, document, analysis): + """Saved-rule hook (worker thread; read-only). Returns (dest_dir, filename, rule_name) or None.""" + rules = self.rule_manager.get_all_rules(include_disabled=False) + match = self.rule_matcher.match(document, analysis, rules) + if match.matched_rule and not match.is_conflict: + resolved = self.destination_resolver.resolve( + document=document, analysis=analysis, matched_rule=match.matched_rule) + return resolved.target_directory, resolved.target_filename, match.matched_rule.rule_name + return None def _run_pipeline(self, event: FileEvent): - """Full pipeline for a single FileEvent. All UI updates via self.after().""" + """Worker thread: analyse one file and hand a PROPOSAL to the Tk thread. Never moves files.""" path = str(event.path) filename = event.file_name timestamp = event.timestamp.strftime("%H:%M:%S") - ext = Path(event.path).suffix.lower().lstrip(".") - try: - document = ingest_file(path) - - if document.extraction_status not in ("ok", "empty"): - reason = f"Ingestion failed: {document.extraction_status}" - self.after(0, self._on_review, timestamp, filename, reason, path, "", filename) - return - - try: - analysis = analyze_document(document) - except (OllamaUnavailableError, AnalysisParseError): - analysis = deterministic_analyze_document(document) - - # Check saved rules first (works offline and online) - active_rules = self.rule_manager.get_all_rules(include_disabled=False) - match_result = self.rule_matcher.match(document, analysis, active_rules) - if match_result.matched_rule and not match_result.is_conflict: - resolved = self.destination_resolver.resolve( - document=document, - analysis=analysis, - matched_rule=match_result.matched_rule, - ) - target_dir = resolved.target_directory - dest_filename = resolved.target_filename - - # Low-confidence documents must NOT bypass human review/approval safeguards - min_required_conf = max(match_result.matched_rule.conditions.min_confidence, settings.confidence_threshold) - if analysis.confidence < min_required_conf: - reason = f"Low confidence ({analysis.confidence:.0%} < {min_required_conf:.0%}) despite matching rule '{match_result.matched_rule.rule_name}'" - self.after(0, self._on_review, timestamp, filename, reason, - path, str(target_dir), dest_filename) - return - - try: - target_dir.mkdir(parents=True, exist_ok=True) - record = self.safe_executor.execute_move( - Path(path), target_dir, dest_filename, rule=match_result.matched_rule - ) - root_name = resolved.root_folder.name if resolved.root_folder else "Organized" - self.after( - 0, self._on_organize, - timestamp, filename, - analysis.document_type, root_name, - analysis.confidence, str(target_dir), - Path(record.destination_path).name, - ) - return - except Exception as move_exc: - self.after(0, self._on_pipeline_error, timestamp, filename, str(move_exc)) - return - - validation = validate_analysis(document, analysis) - decision = decide(analysis, validation, original_extension=ext) - - if decision.action == "organize": - # Smart folder: find existing matching folder or create new one - base = settings.sorted_base_dir - existing = _find_existing_category_folder(base, analysis.category) - target_dir = existing if existing else (base / analysis.category) - - try: - dest = _safe_move(Path(path), target_dir, analysis.new_filename) - self.after( - 0, self._on_organize, - timestamp, filename, - analysis.document_type, analysis.category, - analysis.confidence, str(target_dir), - dest.name, - ) - except Exception as move_exc: - self.after(0, self._on_pipeline_error, timestamp, filename, str(move_exc)) + proposal = process_file(path, base_dir=settings.sorted_base_dir, rule_hook=self._rule_override) + if proposal is None: + self.after(0, self._log_raw, f"[{timestamp}] Skipped (incomplete or unreadable): {filename}\n") else: - reason = decision.reason - suggested_dir = str(settings.sorted_base_dir / analysis.category) - self.after(0, self._on_review, timestamp, filename, reason, - path, suggested_dir, decision.suggested_filename) - + self.after(0, self._on_proposal, timestamp, proposal) except Exception as exc: self.after(0, self._on_pipeline_error, timestamp, filename, str(exc)) + finally: + self.after(0, self._inflight.discard, path) - def _on_organize( - self, - timestamp: str, - filename: str, - doc_type: str, - category: str, - confidence: float, - destination: str, - new_filename: str, - ): - """Called on Tk thread when a file is successfully moved and renamed.""" - self._processed_count += 1 - self._processed_var.set(str(self._processed_count)) - - line = ( - f"• {timestamp} — ✅ {filename}\n" - f" Type: {doc_type} | Category: {category} | " - f"Confidence: {confidence:.0%}\n" - f" Renamed → {new_filename}\n" - f" Moved to → {destination}\n" - ) - self._activity_lines.insert(0, line) - - self._refresh_dashboard_activity() - self._log_raw( - f"[{timestamp}] ORGANIZED: {filename} → {destination}/{new_filename} " - f"(conf={confidence:.0%})\n" - ) - - def _on_review( - self, - timestamp: str, - filename: str, - reason: str, - src_path: str = "", - suggested_dir: str = "", - suggested_name: str = "", - ): - """Called on Tk thread when a file needs human review.""" - self._pending_count += 1 + def _update_counters(self): + """Dashboard counters reflect real state: pending = awaiting approval/execution, processed = executed.""" + counts = self.proposals.counts() + self._pending_count = counts[PENDING] + counts[APPROVED] self._pending_var.set(str(self._pending_count)) + self._processed_var.set(str(self._processed_count)) - activity_line = ( - f"• {timestamp} — ⚠️ {filename} → Review Queue\n" - f" Reason: {reason}\n" + def _on_proposal(self, timestamp: str, proposal): + """Tk thread: a new suggestion is waiting for the user.""" + self.proposals.add(proposal) + dest = proposal.destination_dir if proposal.destination_dir else "(you choose)" + self._activity_lines.insert( + 0, + f"- {timestamp} - Suggestion: {proposal.original_name}\n" + f" -> {proposal.proposed_name} | {proposal.category} | confidence {proposal.confidence:.0%} " + f"({proposal.engine})\n Awaiting your approval\n", ) - self._activity_lines.insert(0, activity_line) - - self._review_items.append((filename, reason, src_path, suggested_dir, suggested_name)) + self._update_counters() self._refresh_dashboard_activity() self._refresh_review_queue() - self._log_raw(f"[{timestamp}] REVIEW: {filename} — {reason}\n") + self._log_raw(f"[{timestamp}] PROPOSED: {proposal.original_name} -> {dest}/{proposal.proposed_name} " + f"(conf={proposal.confidence:.0%}, {proposal.engine})\n") def _on_pipeline_error(self, timestamp: str, filename: str, error: str): """Called on Tk thread for unexpected pipeline exceptions.""" @@ -2067,135 +1983,130 @@ def _refresh_dashboard_activity(self): self._dashboard_activity_box.insert("end", line) self._dashboard_activity_box.configure(state="disabled") + # -- Review Queue = approval screen ------------------------------------ + + def _open_proposals(self): + return [p for p in self.proposals.items() if p.status in (PENDING, APPROVED)] + def _refresh_review_queue(self): - """Rebuild the review queue scrollable frame from self._review_items with modern styling.""" for widget in self._review_scroll.winfo_children(): widget.destroy() - - if not self._review_items: + self._name_entries = {} + items = self._open_proposals() + if not items: self._review_empty_label = ctk.CTkLabel( - self._review_scroll, - text="(Review queue is empty)", - font=ctk.CTkFont(family="Segoe UI", size=13), - text_color=COLOR_TEXT_MUTED, - ) + self._review_scroll, text="(Nothing waiting for review)", + font=ctk.CTkFont(family="Segoe UI", size=13), text_color=COLOR_TEXT_MUTED) self._review_empty_label.grid(row=0, column=0, padx=16, pady=24) return + status_color = {PENDING: "#fbbf24", APPROVED: COLOR_ACCENT_LIGHT, REJECTED: COLOR_TEXT_MUTED, FAILED: "#f87171"} + for i, p in enumerate(items): + card = ctk.CTkFrame(self._review_scroll, corner_radius=12, fg_color=COLOR_CARD_BG, + border_width=1, border_color=COLOR_CARD_BORDER) + card.grid(row=i, column=0, padx=4, pady=5, sticky="ew") + card.grid_columnconfigure(1, weight=1) + ctk.CTkLabel(card, text=f"{p.original_name}", anchor="w", + font=ctk.CTkFont(family="Segoe UI", size=12, weight="bold"), + text_color=COLOR_TEXT_PRIMARY).grid(row=0, column=0, columnspan=2, padx=12, pady=(10, 2), sticky="w") + ctk.CTkLabel(card, text=p.status.upper(), text_color=status_color.get(p.status, COLOR_TEXT_MUTED), + font=ctk.CTkFont(family="Segoe UI", size=11, weight="bold")).grid(row=0, column=2, padx=12, sticky="e") + + entry = ctk.CTkEntry(card, height=30, fg_color=COLOR_INPUT_BG) + entry.insert(0, p.proposed_name) + entry.grid(row=1, column=0, columnspan=2, padx=12, pady=2, sticky="ew") + entry.bind("", lambda _e, pid=p.id: self._commit_name(pid)) + entry.bind("", lambda _e, pid=p.id: self._commit_name(pid)) + self._name_entries[p.id] = entry + + dest = str(p.destination_dir) if p.destination_dir else "No destination yet - click Folder... to choose" + ctk.CTkLabel(card, text=f"Folder: {dest}", anchor="w", text_color=COLOR_TEXT_SECONDARY, + font=ctk.CTkFont(family="Segoe UI", size=11)).grid(row=2, column=0, columnspan=3, padx=12, sticky="w") + detail = f"{p.category} | confidence {p.confidence:.0%} | {p.engine}" + if p.evidence: + detail += " | " + p.evidence[0] + ctk.CTkLabel(card, text=detail, anchor="w", justify="left", wraplength=620, text_color=COLOR_TEXT_MUTED, + font=ctk.CTkFont(family="Segoe UI", size=11)).grid(row=3, column=0, columnspan=3, padx=12, sticky="w") + warn = " | ".join(p.warnings + ([p.error] if p.error else [])) + if warn: + ctk.CTkLabel(card, text=warn, anchor="w", justify="left", wraplength=620, text_color="#fbbf24", + font=ctk.CTkFont(family="Segoe UI", size=11)).grid(row=4, column=0, columnspan=3, padx=12, sticky="w") + + btns = ctk.CTkFrame(card, fg_color="transparent") + btns.grid(row=5, column=0, columnspan=3, padx=10, pady=(6, 10), sticky="e") + for label, cmd, color in ( + ("Folder...", lambda pid=p.id: self._choose_proposal_folder(pid), COLOR_BUTTON_SECONDARY), + ("Approve", lambda pid=p.id: self._approve_proposal(pid), COLOR_ACCENT), + ("Reject", lambda pid=p.id: self._reject_proposal(pid), COLOR_BUTTON_SECONDARY), + ): + ctk.CTkButton(btns, text=label, width=84, height=30, corner_radius=8, fg_color=color, + command=cmd).pack(side="left", padx=4) + + def _commit_name(self, pid: int): + entry = getattr(self, "_name_entries", {}).get(pid) + if entry is not None: + try: + self.proposals.set_name(pid, entry.get()) + except (KeyError, ValueError) as exc: + self._log_raw(f"[Review] {exc}\n") - for i, item in enumerate(self._review_items): - fname = item[0] - reason = item[1] - - item_frame = ctk.CTkFrame( - self._review_scroll, - corner_radius=12, - fg_color=COLOR_CARD_BG, - border_width=1, - border_color=COLOR_CARD_BORDER, - height=62, - ) - item_frame.grid(row=i, column=0, padx=4, pady=5, sticky="ew") - item_frame.grid_columnconfigure(1, weight=1) - - file_icon = ctk.CTkFrame( - item_frame, - width=34, - height=34, - corner_radius=8, - fg_color=COLOR_BUTTON_SECONDARY, - ) - file_icon.grid(row=0, column=0, padx=(14, 10), pady=12) - file_icon.grid_propagate(False) - ctk.CTkLabel( - file_icon, - text="📄", - font=ctk.CTkFont(size=14), - ).place(relx=0.5, rely=0.5, anchor="center") - - ctk.CTkLabel( - item_frame, - text=fname, - font=ctk.CTkFont(family="Segoe UI", size=13, weight="bold"), - text_color=COLOR_TEXT_PRIMARY, - ).grid(row=0, column=1, padx=4, pady=12, sticky="w") + def _choose_proposal_folder(self, pid: int): + p = self.proposals.get(pid) + if p is None: + return + initial = str(p.destination_dir) if p.destination_dir and Path(p.destination_dir).exists() else str(Path.home()) + chosen = filedialog.askdirectory(title=f"Where should '{p.original_name}' go?", initialdir=initial) + if not chosen: + return # cancelled: change nothing + try: + self.proposals.set_destination(pid, chosen) + except (KeyError, ValueError) as exc: + self._log_raw(f"[Review] Invalid destination: {exc}\n") + self._refresh_review_queue() - badge = ctk.CTkFrame( - item_frame, - corner_radius=8, - fg_color="#2b1e10", - border_width=1, - border_color="#78350f", - ) - badge.grid(row=0, column=2, padx=12, pady=12) - ctk.CTkLabel( - badge, - text=reason, - font=ctk.CTkFont(family="Segoe UI", size=11, weight="bold"), - text_color="#fbbf24", - ).pack(padx=10, pady=3) + def _approve_proposal(self, pid: int): + self._commit_name(pid) + try: + self.proposals.approve(pid) + except (KeyError, ValueError) as exc: + self._log_raw(f"[Review] Cannot approve: {exc}\n") + self._update_counters() + self._refresh_review_queue() - ctk.CTkButton( - item_frame, - text="Review", - width=84, - height=32, - corner_radius=8, - fg_color=COLOR_BUTTON_SECONDARY, - hover_color=COLOR_BUTTON_SECONDARY_HOVER, - text_color=COLOR_TEXT_PRIMARY, - border_width=1, - border_color="#263345", - font=ctk.CTkFont(family="Segoe UI", size=12, weight="bold"), - command=lambda it=item: self._manual_review(it), - ).grid(row=0, column=3, padx=(4, 14), pady=12) - - def _manual_review(self, item: tuple): - """Open folder picker, move and rename the file, remove from queue.""" - fname = item[0] - src_path = item[2] if len(item) > 2 else "" - suggested_dir = item[3] if len(item) > 3 else "" - suggested_name = item[4] if len(item) > 4 else "" - - if not src_path or not Path(src_path).exists(): - self._log_raw(f"[Review] File no longer exists: {src_path or fname}\n") - self._remove_review_item(item) - return + def _reject_proposal(self, pid: int): + try: + self.proposals.reject(pid) + except (KeyError, ValueError) as exc: + self._log_raw(f"[Review] {exc}\n") + self._update_counters() + self._refresh_review_queue() - initial_dir = suggested_dir if suggested_dir and Path(suggested_dir).exists() else str(Path.home()) - target_dir = filedialog.askdirectory( - title=f"Where should '{fname}' go?", - initialdir=initial_dir, - ) - if not target_dir: - return # user cancelled — do nothing + def _approve_all_proposals(self): + """Approve every pending suggestion that has a destination (the user still presses Execute).""" + for p in self.proposals.items(PENDING): + self._commit_name(p.id) + ready = [p.id for p in self.proposals.items(PENDING) if p.destination_dir is not None] + _done, errors = self.proposals.approve_many(ready) + for pid, err in errors.items(): + self._log_raw(f"[Review] {err}\n") + self._update_counters() + self._refresh_review_queue() - use_name = suggested_name if suggested_name else Path(src_path).name + def _execute_approved_proposals(self): + def worker(): + ok, bad, errs = self.proposals.execute_approved() + self.after(0, self._on_proposals_executed, ok, bad, errs) + threading.Thread(target=worker, daemon=True).start() - try: - dest = _safe_move(Path(src_path), Path(target_dir), use_name) - self._log_raw( - f"[Review] Manually organised: {fname}\n" - f" Renamed → {dest.name}\n" - f" Moved to → {target_dir}\n" - ) - self._processed_count += 1 - self._processed_var.set(str(self._processed_count)) - line = ( - f"• [manual] — ✅ {fname}\n" - f" Renamed → {dest.name} | Moved to → {target_dir}\n" - ) - self._activity_lines.insert(0, line) - self._refresh_dashboard_activity() - self._remove_review_item(item) - except Exception as exc: - self._log_raw(f"[Review] Error moving {fname}: {exc}\n") - - def _remove_review_item(self, item: tuple): - if item in self._review_items: - self._review_items.remove(item) - self._pending_count = max(0, self._pending_count - 1) - self._pending_var.set(str(self._pending_count)) - self._refresh_review_queue() + def _on_proposals_executed(self, ok: int, bad: int, errors: list[str]): + self._processed_count += ok + self._update_counters() + self._log_raw(f"[Execute] Moved: {ok}, Failed: {bad}\n") + for err in errors: + self._log_raw(f"[Execute] {err}\n") + self._activity_lines.insert(0, f"- Executed {ok} approved file(s); {bad} failed\n") + self._refresh_dashboard_activity() + self._refresh_review_queue() + self._refresh_history_list() def _log_raw(self, msg: str): """Append a raw message to the Activity Log textbox. Tk-thread only.""" diff --git a/app/ingestion.py b/app/ingestion.py index 48b0052..b76c885 100644 --- a/app/ingestion.py +++ b/app/ingestion.py @@ -56,50 +56,90 @@ def _make_doc(path: Path, text: str, page_count: int | None, status: str) -> Nor ) -def _ingest_pdf(path: Path) -> NormalizedDocument: - """Extract text from every page of a PDF using PyMuPDF.""" - try: - import pymupdf # imported here so the rest of the module works without it - except ImportError as exc: # pragma: no cover - raise ImportError("PyMuPDF is required for PDF ingestion: pip install pymupdf") from exc +def _extract_pdf_pymupdf(path: Path) -> tuple[str, int, bool]: + """Return (text, page_count, encrypted). Raises on unreadable files.""" + import pymupdf + doc = pymupdf.open(str(path)) try: - doc = pymupdf.open(str(path)) - except Exception as exc: - logger.warning("Could not open PDF %s: %s", path, exc) - return _make_doc(path, text="", page_count=None, status="error") - - try: - pages: list[str] = [] - for page in doc: - pages.append(page.get_text()) - text = "\n".join(pages) - page_count = len(doc) - except Exception as exc: - logger.warning("Error reading PDF pages in %s: %s", path, exc) - return _make_doc(path, text="", page_count=None, status="error") + if getattr(doc, "needs_pass", False): + return "", 0, True + pages = [page.get_text() for page in doc] + return "\n".join(pages), len(doc), False finally: doc.close() - status = "ok" if text.strip() else "empty" - return _make_doc(path, text=text, page_count=page_count, status=status) +def _extract_pdf_pypdf(path: Path) -> tuple[str, int, bool]: + from pypdf import PdfReader -def _ingest_text(path: Path) -> NormalizedDocument: - """Read a plain-text or Markdown file as UTF-8.""" + reader = PdfReader(str(path)) + if reader.is_encrypted: + try: + if not reader.decrypt(""): + return "", 0, True + except Exception: + return "", 0, True + pages = [(page.extract_text() or "") for page in reader.pages] + return "\n".join(pages), len(reader.pages), False + + +def _ingest_pdf(path: Path) -> NormalizedDocument: + """Extract text from every page of a PDF (PyMuPDF preferred, pypdf fallback).""" + extractors = [] + try: + import pymupdf # noqa: F401 + extractors.append(_extract_pdf_pymupdf) + except ImportError: + pass try: - text = path.read_text(encoding="utf-8") - except UnicodeDecodeError: - # Fall back to latin-1 for files that are not valid UTF-8 + import pypdf # noqa: F401 + extractors.append(_extract_pdf_pypdf) + except ImportError: + pass + if not extractors: + raise ImportError("A PDF library is required for PDF ingestion: pip install pymupdf (or pypdf)") + + for extract in extractors: try: - text = path.read_text(encoding="latin-1") + text, page_count, encrypted = extract(path) except Exception as exc: - logger.warning("Could not decode %s: %s", path, exc) + logger.warning("PDF extraction with %s failed for %s: %s", extract.__name__, path, exc) + continue + if encrypted: + logger.warning("Encrypted PDF cannot be read: %s", path) return _make_doc(path, text="", page_count=None, status="error") + status = "ok" if text.strip() else "empty" # image-only PDFs end up here (no OCR) + return _make_doc(path, text=text, page_count=page_count, status=status) + return _make_doc(path, text="", page_count=None, status="error") + + +def _decode_bytes(raw: bytes) -> str | None: + """Decode text bytes: BOM-aware UTF-8/UTF-16, then cp1252, then latin-1.""" + if raw.startswith((b"\xff\xfe", b"\xfe\xff")): + try: + return raw.decode("utf-16") + except UnicodeDecodeError: + pass + for enc in ("utf-8-sig", "cp1252", "latin-1"): + try: + return raw.decode(enc) + except UnicodeDecodeError: + continue + return None + + +def _ingest_text(path: Path) -> NormalizedDocument: + """Read a plain-text or Markdown file with reasonable encoding handling.""" + try: + raw = path.read_bytes() except Exception as exc: logger.warning("Could not read %s: %s", path, exc) return _make_doc(path, text="", page_count=None, status="error") - + text = _decode_bytes(raw) + if text is None or "\x00" in text[:2000]: + logger.warning("Could not decode %s as text", path) + return _make_doc(path, text="", page_count=None, status="error") status = "ok" if text.strip() else "empty" return _make_doc(path, text=text, page_count=None, status=status) diff --git a/app/main.py b/app/main.py index 8551d50..c767919 100644 --- a/app/main.py +++ b/app/main.py @@ -18,11 +18,11 @@ def print_banner() -> None: - """Print the FileMind startup banner.""" + """Print the SortSense startup banner.""" print("=" * 50) - print(" FileMind \u2014 local AI file intelligence") + print(" SortSense \u2014 local AI file organizer") print("=" * 50) - print(f" Watched directory : {settings.watched_dir}") + print(f" Watched directories : {', '.join(str(d) for d in settings.watched_dirs)}") print(f" Ollama host : {settings.ollama_host}") print(f" Gemma model : {settings.gemma_model}") print(f" Confidence threshold : {settings.confidence_threshold}") @@ -41,39 +41,19 @@ def start_watcher_blocking() -> None: from app.events import FileEvent from app.watcher import start_watcher - from app.ingestion import ingest_file - from app.analyzer import analyze_document - from app.validation import validate_analysis - from app.routing import route_file + from app.pipeline import process_file def on_event(event: FileEvent) -> None: + # CLI mode only REPORTS suggestions. Files are never moved without approval + # (use the desktop app's Review Queue to approve and execute). print(f"\n[watcher] Detected new file: {event.path}") - - # Wait a moment for file write to finish - time.sleep(1.0) - - doc = ingest_file(event.path) - if doc.extraction_status not in ("ok", "empty"): - print(f"[ingest] Skipping file ({doc.extraction_status}): {event.path}") - return - - print(f"[ingest] Extracted {doc.character_count} chars from {doc.file_name}") - - try: - analysis = analyze_document(doc) - print(f"[analyze] Classified as: {analysis.category} -> {analysis.new_filename}") - except Exception as e: - print(f"[analyze] Failed: {e}") - return - - val_result = validate_analysis(doc, analysis) - if not val_result.valid or analysis.confidence < settings.confidence_threshold: - print(f"[validate] Needs Review (Confidence {analysis.confidence:.2f}): {val_result.issues}") + proposal = process_file(event.path) + if proposal is None: + print("[skip] unsupported, incomplete or unreadable file") return - - new_path = route_file(doc, analysis) - if new_path: - print(f"[route] Moved to: {new_path}") + dest = proposal.destination_dir or "(choose a destination)" + print(f"[suggest] {proposal.original_name} -> {dest}/{proposal.proposed_name} " + f"(confidence {proposal.confidence:.2f}, {proposal.engine})") observer = start_watcher(on_event=on_event) print("Watching the following directories (Ctrl-C to stop):") diff --git a/app/organizer.py b/app/organizer.py index 33c2456..5d2dc68 100644 --- a/app/organizer.py +++ b/app/organizer.py @@ -138,9 +138,17 @@ def _build_filename(analysis: "DocumentAnalysis", original_extension: str) -> st Uses the document_type as the primary stem source because it is short and deterministic; falls back to a sanitised slice of the summary. """ + ext = original_extension.lstrip(".") + # Prefer the analyzer's content-based filename (REGRESSION FIX: it used to be + # discarded and every file was renamed after its document_type, e.g. "Unclassified.txt"). + proposed = analysis.new_filename.strip() + if proposed and not any(c in proposed for c in ("/", "\\", "\0")): + proposed_stem = proposed.rsplit(".", 1)[0] if "." in proposed else proposed + stem = _safe_stem(proposed_stem) + if stem != "document" or proposed_stem.lower() == "document": + return f"{stem}.{ext}" if ext else stem raw = analysis.document_type.strip() or analysis.summary.strip() or "document" stem = _safe_stem(raw) - ext = original_extension.lstrip(".") return f"{stem}.{ext}" if ext else stem diff --git a/app/pipeline.py b/app/pipeline.py new file mode 100644 index 0000000..b3d371e --- /dev/null +++ b/app/pipeline.py @@ -0,0 +1,74 @@ +""" +SortSense processing pipeline (no GUI): + + file -> wait until written -> ingest -> analyze (Gemma if truly available, else + deterministic) -> Proposal. It never moves anything. +""" +from __future__ import annotations + +import logging +import time +from pathlib import Path +from typing import Callable + +from app.analyzer import OllamaServiceManager, deterministic_analyze_document, safe_analyze_document +from app.ingestion import ingest_file +from app.proposals import Proposal, build_proposal + +logger = logging.getLogger(__name__) + +SUPPORTED_EXTS = {".pdf", ".txt", ".md"} +# Browser/partial-download markers: never process these. +PARTIAL_SUFFIXES = (".crdownload", ".part", ".partial", ".tmp", ".download", ".opdownload") + + +def is_partial_download(path: Path) -> bool: + return path.name.lower().endswith(PARTIAL_SUFFIXES) + + +def wait_until_stable(path: Path, checks: int = 3, interval: float = 0.4, timeout: float = 30.0) -> bool: + """True once the file size stops changing (finished writing).""" + deadline = time.monotonic() + timeout + last = -1 + stable = 0 + while time.monotonic() < deadline: + try: + size = path.stat().st_size + except OSError: + return False + stable = stable + 1 if size == last else 0 + last = size + if stable >= checks: + return True + time.sleep(interval) + return False + + +def process_file( + path: str | Path, + base_dir: Path | None = None, + rule_hook: Callable | None = None, + wait: bool = True, +) -> Proposal | None: + """Analyze one file and return a Proposal (or None if it should be ignored).""" + path = Path(path) + if path.suffix.lower() not in SUPPORTED_EXTS or is_partial_download(path): + return None + if wait and not wait_until_stable(path): + logger.warning("File never became stable, skipping: %s", path) + return None + document = ingest_file(path) + if document.extraction_status in ("missing", "unsupported"): + return None + try: + analysis = safe_analyze_document(document) + except Exception as exc: # defensive: never let one file kill the worker + logger.warning("Analysis failed for %s (%s); using deterministic", path.name, exc) + analysis = deterministic_analyze_document(document) + override = None + if rule_hook is not None: + try: + override = rule_hook(document, analysis) + except Exception as exc: + logger.warning("Rule matching failed for %s: %s", path.name, exc) + return build_proposal(document, analysis, base_dir=base_dir, override=override) diff --git a/app/proposals.py b/app/proposals.py new file mode 100644 index 0000000..c1fb5c3 --- /dev/null +++ b/app/proposals.py @@ -0,0 +1,264 @@ +""" +SortSense proposals: the approval-first layer between analysis and file moves. + +A Proposal is *only a suggestion*. Nothing touches the filesystem until the user +approves it and ``ProposalManager.execute_approved`` is called. Execution goes +through SafeFileExecutor, so path validation, collision safety, history and Undo +all apply. Pure Python: no Tk, no Ollama. +""" +from __future__ import annotations + +import itertools +import logging +import re +import threading +from dataclasses import dataclass, field +from pathlib import Path +from typing import TYPE_CHECKING, Callable + +from app.config import settings +from app.intent.path_validator import PathValidator + +if TYPE_CHECKING: + from app.analysis_models import DocumentAnalysis + from app.document import NormalizedDocument + from app.intent.executor import SafeFileExecutor + +logger = logging.getLogger(__name__) + +PENDING, APPROVED, REJECTED, EXECUTED, FAILED = "pending", "approved", "rejected", "executed", "failed" + +_ILLEGAL = re.compile(r'[<>:"/\\|?*\x00-\x1f]') +_MAX_STEM = 80 +_ids = itertools.count(1) + + +def clean_folder_name(raw: str, fallback: str = "") -> str: + """Folder name safe for Windows, spaces preserved ('Discrete Mathematics').""" + name = _ILLEGAL.sub("", (raw or "").replace("..", "")).strip(" .") + name = re.sub(r"\s+", " ", name) + if name.split(".")[0].upper() in {"CON", "PRN", "AUX", "NUL", *(f"COM{i}" for i in range(1, 10)), *(f"LPT{i}" for i in range(1, 10))}: + name = f"safe_{name}" + return name or fallback + + +def clean_filename(raw: str, original_name: str) -> str: + """Safe filename that always keeps the original file's extension.""" + ext = Path(original_name).suffix + base = (raw or "").strip() + if ext and base.lower().endswith(ext.lower()): + base = base[: -len(ext)] + base = _ILLEGAL.sub("", base.replace("..", "")) + base = re.sub(r"\s+", "_", base).strip("._ ")[:_MAX_STEM].rstrip("._ ") + if not base or base.upper() in {"CON", "PRN", "AUX", "NUL"}: + return original_name + return f"{base}{ext}" + + +@dataclass +class Proposal: + source_path: Path + original_name: str + proposed_name: str + category: str + destination_dir: Path | None # None => user must choose a destination + confidence: float + evidence: list[str] = field(default_factory=list) + warnings: list[str] = field(default_factory=list) + engine: str = "deterministic" + needs_review: bool = True + status: str = PENDING + error: str | None = None + operation_id: str | None = None + executed_path: Path | None = None + id: int = field(default_factory=lambda: next(_ids)) + + @property + def renamed(self) -> bool: + return self.proposed_name != self.original_name + + +def build_proposal( + document: "NormalizedDocument", + analysis: "DocumentAnalysis", + base_dir: Path | None = None, + threshold: float | None = None, + override: tuple[Path, str, str] | None = None, +) -> Proposal: + """ + Turn an analysis into a Proposal. Never invents a category: weak or missing + evidence keeps the original filename and leaves the destination for the user. + + override = (destination_dir, filename, rule_name) from a saved user rule. + """ + from app.validation import validate_analysis + + base = Path(base_dir or settings.sorted_base_dir) + thr = settings.confidence_threshold if threshold is None else threshold + source = Path(document.file_path) + warnings: list[str] = [] + evidence = list(analysis.evidence or []) + engine = analysis.source or "deterministic" + + val = validate_analysis(document, analysis) + for issue in val.issues: + warnings.append(f"Validation: {issue}") + + uncertain = ( + analysis.category.strip().lower() in {"", "general"} + or analysis.document_type == "Unclassified" + or analysis.confidence < 0.35 + or document.extraction_status != "ok" + ) + if document.extraction_status != "ok": + warnings.append(f"Could not read content ({document.extraction_status}); original name kept.") + + if override is not None: + dest, fname, rule_name = override + evidence.append(f"Matched saved rule '{rule_name}'") + proposal = Proposal(source, source.name, clean_filename(fname, source.name), analysis.category or "Rule", + Path(dest), analysis.confidence, evidence, warnings, engine) + elif uncertain: + warnings.append("Not confident enough to suggest a category - choose a destination yourself.") + proposal = Proposal(source, source.name, source.name, "Unclassified", None, + analysis.confidence, evidence, warnings, engine) + else: + category = clean_folder_name(analysis.category, "Unsorted") + name = clean_filename(analysis.new_filename, source.name) if val.valid or not any( + "new_filename" in i for i in val.issues) else source.name + proposal = Proposal(source, source.name, name, category, base / category, + analysis.confidence, evidence, warnings, engine) + + if analysis.confidence < thr: + proposal.warnings.append(f"Confidence {analysis.confidence:.2f} is below the review threshold {thr:.2f}.") + proposal.needs_review = bool(val.issues) or analysis.confidence < thr or proposal.destination_dir is None + if proposal.destination_dir is not None and (proposal.destination_dir / proposal.proposed_name).exists(): + proposal.warnings.append("A file with this name already exists there; a numbered copy will be created.") + return proposal + + +class ProposalManager: + """Holds proposals, applies user edits, executes only approved ones.""" + + def __init__(self, executor: "SafeFileExecutor | None" = None, base_dir: Path | None = None) -> None: + self._lock = threading.RLock() + self._items: dict[int, Proposal] = {} + self._executor = executor + self.base_dir = Path(base_dir or settings.sorted_base_dir) + + # -- queue --------------------------------------------------------------- + def add(self, proposal: Proposal) -> Proposal: + with self._lock: + for old in list(self._items.values()): + if old.source_path == proposal.source_path and old.status in (PENDING, APPROVED): + del self._items[old.id] + self._items[proposal.id] = proposal + return proposal + + def get(self, pid: int) -> Proposal | None: + with self._lock: + return self._items.get(pid) + + def items(self, status: str | None = None) -> list[Proposal]: + with self._lock: + return [p for p in self._items.values() if status is None or p.status == status] + + def counts(self) -> dict[str, int]: + with self._lock: + out = {s: 0 for s in (PENDING, APPROVED, REJECTED, EXECUTED, FAILED)} + for p in self._items.values(): + out[p.status] += 1 + return out + + def remove(self, pid: int) -> None: + with self._lock: + self._items.pop(pid, None) + + # -- user edits ---------------------------------------------------------- + def set_name(self, pid: int, name: str) -> Proposal: + with self._lock: + p = self._require_open(pid) + p.proposed_name = clean_filename(name, p.original_name) + return p + + def set_destination(self, pid: int, directory: str | Path) -> Proposal: + with self._lock: + p = self._require_open(pid) + res = PathValidator.validate_destination_path(directory) + if not res.valid: + raise ValueError("; ".join(res.issues)) + p.destination_dir = res.resolved_path + p.category = res.resolved_path.name or p.category + p.needs_review = False if p.confidence >= settings.confidence_threshold else p.needs_review + return p + + def set_category(self, pid: int, category: str) -> Proposal: + """Change the category; destination becomes /.""" + folder = clean_folder_name(category) + if not folder: + raise ValueError("Category cannot be empty.") + with self._lock: + p = self._require_open(pid) + p.category = folder + p.destination_dir = self.base_dir / folder + return p + + def approve(self, pid: int) -> Proposal: + with self._lock: + p = self._require_open(pid) + if p.destination_dir is None: + raise ValueError("Choose a destination folder before approving.") + p.status = APPROVED + return p + + def reject(self, pid: int) -> Proposal: + """Rejected files are never touched.""" + with self._lock: + p = self._require_open(pid) + p.status = REJECTED + return p + + def approve_many(self, pids: list[int]) -> tuple[list[int], dict[int, str]]: + done: list[int] = [] + errors: dict[int, str] = {} + for pid in pids: + try: + self.approve(pid) + done.append(pid) + except ValueError as exc: + errors[pid] = str(exc) + return done, errors + + def _require_open(self, pid: int) -> Proposal: + p = self._items.get(pid) + if p is None: + raise KeyError(f"Unknown proposal {pid}") + if p.status == EXECUTED: + raise ValueError("Proposal already executed.") + return p + + # -- execution ----------------------------------------------------------- + def execute_approved(self, ids: list[int] | None = None) -> tuple[int, int, list[str]]: + """Move ONLY approved proposals. Returns (succeeded, failed, errors).""" + if self._executor is None: + from app.intent.executor import SafeFileExecutor + self._executor = SafeFileExecutor() + ok = bad = 0 + errors: list[str] = [] + with self._lock: + targets = [p for p in self._items.values() + if p.status == APPROVED and (ids is None or p.id in ids)] + for p in targets: + try: + if p.destination_dir is None: + raise ValueError("No destination chosen.") + record = self._executor.execute_move( + p.source_path, Path(p.destination_dir), p.proposed_name, mode_name="approved") + p.status, p.operation_id = EXECUTED, record.operation_id + p.executed_path = Path(record.destination_path) + ok += 1 + except Exception as exc: # partial failure: keep going, report it + p.status, p.error = FAILED, str(exc) + errors.append(f"{p.original_name}: {exc}") + bad += 1 + return ok, bad, errors diff --git a/app/topics.py b/app/topics.py new file mode 100644 index 0000000..d75482c --- /dev/null +++ b/app/topics.py @@ -0,0 +1,192 @@ +""" +SortSense deterministic topic engine (offline, no LLM). + +Scores extracted text against a general subject taxonomy using weighted, +word-boundary term matches. Evidence is counted per *distinct* term so a +repeated word cannot inflate confidence. Headings and filenames add +corroboration. The result carries the matched terms so the UI can show why. +""" +from __future__ import annotations + +import re +from dataclasses import dataclass, field + +# subject -> {term: weight}. Weight 3 = near-unique to the subject, 2 = strong, 1 = supporting. +_LEXICON: dict[str, dict[str, int]] = { + "DBMS": { + "dbms": 3, "database management system": 3, "database management systems": 3, + "normalization": 2, "normalisation": 2, "1nf": 3, "2nf": 3, "3nf": 3, "bcnf": 3, + "functional dependency": 3, "functional dependencies": 3, "candidate key": 2, + "primary key": 2, "foreign key": 2, "sql": 2, "join": 1, "inner join": 2, "left join": 2, + "acid": 2, "transaction": 1, "transactions": 1, "commit": 1, "rollback": 2, "savepoint": 2, + "er diagram": 3, "entity relationship": 3, "relational": 1, "relation": 1, "schema": 1, + "database": 2, "databases": 2, "query": 1, "select": 1, "index": 1, "concurrency control": 2, + }, + "DSA": { + "dsa": 3, "data structure": 3, "data structures": 3, "algorithm": 2, "algorithms": 2, + "binary search tree": 3, "bst": 3, "linked list": 3, "stack": 1, "queue": 1, + "breadth first search": 3, "depth first search": 3, "bfs": 3, "dfs": 3, + "merge sort": 3, "quick sort": 3, "heap sort": 3, "sorting": 1, "time complexity": 3, + "space complexity": 3, "big o": 2, "adjacency list": 3, "adjacency matrix": 2, + "dijkstra": 3, "dynamic programming": 3, "recursion": 1, "hash table": 3, + "binary search": 2, "inorder traversal": 2, "subtree": 1, "pivot": 1, "heap": 1, + }, + "OOPS": { + "oops": 3, "oop": 3, "object oriented": 3, "object-oriented": 3, "inheritance": 3, + "polymorphism": 3, "encapsulation": 3, "abstraction": 2, "abstract class": 3, + "interface": 1, "method overriding": 3, "overloading": 2, "constructor": 2, + "class": 1, "object": 1, "objects": 1, "access modifier": 3, "access modifiers": 3, + "private": 1, "protected": 1, "public": 1, "java": 1, "data hiding": 3, "instance": 1, + }, + "Discrete Mathematics": { + "discrete mathematics": 3, "discrete math": 3, "propositional logic": 3, "proposition": 2, + "truth table": 3, "logical connectives": 3, "biconditional": 3, "implication": 2, + "set theory": 3, "relations": 1, "reflexive": 3, "symmetric": 2, "antisymmetric": 3, + "transitive": 2, "partial order": 3, "partial orders": 3, "cartesian product": 3, + "graph theory": 3, "vertices": 1, "edges": 1, "spanning tree": 2, "spanning trees": 2, + "combinatorics": 3, "permutation": 2, "combination": 1, "pigeonhole": 3, "induction": 2, + "cycles": 1, "connectedness": 2, "acyclic": 2, "predicate logic": 3, "boolean algebra": 2, + }, + "Operating Systems": { + "operating system": 3, "operating systems": 3, "process scheduling": 3, "deadlock": 3, + "semaphore": 3, "mutex": 3, "paging": 3, "virtual memory": 3, "context switch": 3, + "kernel": 2, "thread": 1, "threads": 1, "cpu scheduling": 3, "round robin": 2, + "page replacement": 3, "file system": 1, "inode": 3, "race condition": 2, + }, + "Computer Networks": { + "computer network": 3, "computer networks": 3, "tcp": 3, "udp": 3, "ip address": 3, + "osi model": 3, "routing": 2, "subnet": 3, "dns": 3, "http": 2, "ethernet": 3, + "router": 2, "packet": 2, "bandwidth": 2, "latency": 1, "protocol": 1, "firewall": 2, + }, + "Machine Learning": { + "machine learning": 3, "neural network": 3, "neural networks": 3, "gradient descent": 3, + "overfitting": 3, "regression": 2, "classification": 1, "training set": 3, + "supervised learning": 3, "unsupervised learning": 3, "backpropagation": 3, + "random forest": 3, "decision tree": 2, "feature": 1, "loss function": 3, "clustering": 2, + }, + "NLP": { + "nlp": 3, "natural language processing": 3, "tokenization": 3, "tokenisation": 3, + "named entity": 3, "part of speech": 3, "language model": 2, "word embedding": 3, + "sentiment analysis": 3, "stemming": 2, "lemmatization": 3, "corpus": 2, + }, + "Python": {"python": 3, "pandas": 3, "numpy": 3, "list comprehension": 3, "pip install": 3, "def ": 1}, + "Mathematics": { + "calculus": 3, "linear algebra": 3, "matrix": 2, "matrices": 2, "eigenvalue": 3, + "derivative": 2, "integral": 2, "differential equation": 3, "probability": 2, + "statistics": 2, "theorem": 1, "mathematics": 2, "limit": 1, + }, + "Physics": { + "physics": 3, "quantum": 3, "electrodynamics": 3, "thermodynamics": 3, "velocity": 2, + "momentum": 2, "newton": 2, "electric field": 3, "magnetic field": 3, "wavelength": 2, + }, + "Chemistry": { + "chemistry": 3, "organic chemistry": 3, "molecule": 2, "molecules": 2, "periodic table": 3, + "reaction": 1, "covalent": 3, "ionic bond": 3, "stoichiometry": 3, "acid": 1, "electron": 1, + }, +} + +_COMPILED: dict[str, list[tuple[str, int, re.Pattern[str]]]] = { + subj: [ + (term, w, re.compile(r"(? list[str]: + return [ln.strip() for ln in text.splitlines() if ln.strip()] + + +def classify_topic(text: str, filename: str = "") -> TopicResult: + """Return the best subject for *text*, or subject=None when evidence is too thin.""" + body = text[:8000] + head = " \n".join(_lines(body)[:3]) + fname = re.sub(r"[_\-.]+", " ", filename) + scores: dict[str, float] = {} + hits: dict[str, list[str]] = {} + head_hits: dict[str, int] = {} + for subj, entries in _COMPILED.items(): + total = 0.0 + for term, w, pat in entries: + in_body = bool(pat.search(body)) + in_head = bool(pat.search(head)) + in_name = bool(pat.search(fname)) + if not (in_body or in_head or in_name): + continue + total += w + (1.5 * w if in_head else 0) + (0.5 * w if in_name else 0) + hits.setdefault(subj, []).append(term.strip()) + if in_head and w >= 2: + head_hits[subj] = head_hits.get(subj, 0) + 1 + if total: + scores[subj] = total + if not scores: + return TopicResult(None, 0.0) + ranked = sorted(scores.items(), key=lambda kv: kv[1], reverse=True) + best, top = ranked[0] + second_name, second = ranked[1] if len(ranked) > 1 else (None, 0.0) + distinct = len(hits[best]) + strong = sum(1 for t in hits[best] if any(t == tt.strip() and w >= 2 for tt, w, _ in _COMPILED[best])) + if distinct < 2 or strong < 1: + return TopicResult(None, 0.0, hits[best], best, top) + margin = (top - second) / top if top else 0.0 + strength = min(1.0, top / 18.0) + conf = 0.30 + 0.38 * strength + 0.22 * margin + (0.04 if head_hits.get(best) else 0.0) + if margin < 0.15: + conf = min(conf, 0.60) # genuinely ambiguous between two subjects + conf = round(min(0.92, conf), 2) + reasons = [f"Matched {distinct} {best} terms: " + ", ".join(hits[best][:6])] + if head_hits.get(best): + reasons.append("Subject terms appear in the document heading") + if second_name and second: + reasons.append(f"Next closest subject: {second_name}") + return TopicResult(best, conf, hits[best], second_name, top, reasons) + + +def suggest_title(text: str, subject: str | None = None) -> str | None: + """Pick a concise human title from the document content (no filename hardcoding).""" + lines = _lines(text[:3000]) + for ln in lines[:12]: + m = _TITLE_LINE_RE.match(ln) + if m: + return _clean_title(m.group(1)) + for ln in lines[:6]: + md = re.match(r"^#{1,3}\s+(.+)$", ln) + if md: + return _clean_title(md.group(1)) + if lines: + first = lines[0] + if 3 <= len(first) <= 80 and not first.endswith((".", ",", ";")): + return _clean_title(first) + return None + + +def _clean_title(raw: str) -> str | None: + raw = re.sub(r"[`*_#>]+", "", raw) + raw = re.sub(r"[^\w\s&+\-]", " ", raw) + words = raw.split()[:8] + if not words: + return None + small = {"and", "or", "of", "the", "in", "to", "a", "an", "for", "with"} + out = [] + for i, w in enumerate(words): + if w.isupper() and len(w) <= 4 and w.upper() in {"BST", "BFS", "DFS", "SQL", "ACID", "DBMS", "DSA", "OOP", "OOPS", "NLP", "TCP", "UDP", "ER", "1NF", "2NF", "3NF"}: + out.append(w) + elif w.lower() in small and i: + out.append(w.lower()) + else: + out.append(w.capitalize() if not w[0].isdigit() else w.upper()) + title = "_".join(out) + return title[:60].rstrip("_") or None diff --git a/app/watcher.py b/app/watcher.py index e02c379..ed4b45b 100644 --- a/app/watcher.py +++ b/app/watcher.py @@ -22,10 +22,13 @@ # Prefixes that identify hidden or temporary files we should ignore _IGNORED_PREFIXES: tuple[str, ...] = (".", "~$") +_IGNORED_SUFFIXES: tuple[str, ...] = (".crdownload", ".part", ".partial", ".tmp", ".download", ".opdownload") + + def _should_ignore(path: Path) -> bool: - """Return True if *path* should be silently skipped.""" + """Return True if *path* is hidden, temporary or an unfinished download.""" name = path.name - return any(name.startswith(prefix) for prefix in _IGNORED_PREFIXES) + return any(name.startswith(prefix) for prefix in _IGNORED_PREFIXES) or name.lower().endswith(_IGNORED_SUFFIXES) import time class _SortSenseHandler(FileSystemEventHandler): diff --git a/requirements.txt b/requirements.txt index d263d9c..335784b 100644 --- a/requirements.txt +++ b/requirements.txt @@ -9,3 +9,4 @@ pytest-mock customtkinter pillow pyinstaller +pypdf diff --git a/sortsense.spec b/sortsense.spec index 82df292..5c5ccd4 100644 --- a/sortsense.spec +++ b/sortsense.spec @@ -27,6 +27,7 @@ hidden_imports = ( + collect_submodules('watchdog') + collect_submodules('app.intent') + [ + 'pypdf', 'pymupdf', 'fitz', 'PIL', diff --git a/tests/fixtures/regression_docs/164729.txt b/tests/fixtures/regression_docs/164729.txt new file mode 100644 index 0000000..56f648a --- /dev/null +++ b/tests/fixtures/regression_docs/164729.txt @@ -0,0 +1,5 @@ +DSA - GRAPH ALGORITHMS +Topic: Breadth First Search and Depth First Search +BFS explores level by level using a queue. DFS explores deeply using recursion +or a stack. With an adjacency-list representation, both traversals take +O(V + E) time. \ No newline at end of file diff --git a/tests/fixtures/regression_docs/219765.txt b/tests/fixtures/regression_docs/219765.txt new file mode 100644 index 0000000..19245e9 --- /dev/null +++ b/tests/fixtures/regression_docs/219765.txt @@ -0,0 +1,5 @@ +DISCRETE MATHEMATICS +Topic: Graph Theory and Trees +A graph consists of vertices and edges. A tree is a connected acyclic graph. +For a tree with n vertices, the number of edges is n - 1. Review degree, +paths, cycles, connectedness, and spanning trees. \ No newline at end of file diff --git a/tests/fixtures/regression_docs/295841.txt b/tests/fixtures/regression_docs/295841.txt new file mode 100644 index 0000000..7c7350a --- /dev/null +++ b/tests/fixtures/regression_docs/295841.txt @@ -0,0 +1,6 @@ +DATABASE TRANSACTIONS +Topic: ACID Properties +Atomicity means all operations succeed or none do. Consistency preserves +database constraints. Isolation controls interference between concurrent +transactions. Durability ensures committed changes survive failures. +Review COMMIT, ROLLBACK, and SAVEPOINT. \ No newline at end of file diff --git a/tests/fixtures/regression_docs/374192.txt b/tests/fixtures/regression_docs/374192.txt new file mode 100644 index 0000000..3260e95 --- /dev/null +++ b/tests/fixtures/regression_docs/374192.txt @@ -0,0 +1,5 @@ +DISCRETE MATHEMATICS +Topic: Propositional Logic +A proposition is a declarative statement that is either true or false. +Study logical connectives AND, OR, NOT, implication, and biconditional. +A truth table lists truth values for every assignment to its variables. \ No newline at end of file diff --git a/tests/fixtures/regression_docs/407216.txt b/tests/fixtures/regression_docs/407216.txt new file mode 100644 index 0000000..df3cd5f --- /dev/null +++ b/tests/fixtures/regression_docs/407216.txt @@ -0,0 +1,5 @@ +OBJECT ORIENTED PROGRAMMING WITH JAVA +Topic: Inheritance and Polymorphism +Inheritance lets a class acquire fields and methods from another class. +Polymorphism allows the same interface or method call to behave differently +depending on the object. Method overriding is a runtime polymorphism example. \ No newline at end of file diff --git a/tests/fixtures/regression_docs/483920.txt b/tests/fixtures/regression_docs/483920.txt new file mode 100644 index 0000000..f5d0230 --- /dev/null +++ b/tests/fixtures/regression_docs/483920.txt @@ -0,0 +1,6 @@ +UNIVERSITY DATABASE MANAGEMENT SYSTEMS +Topic: Database Normalization +1NF requires atomic attribute values. 2NF requires 1NF and no partial dependency +of a non-prime attribute on a candidate key. 3NF requires 2NF and no transitive +dependency of non-prime attributes on candidate keys. +Example relation: STUDENT(StudentID, StudentName, DepartmentID, DepartmentName). \ No newline at end of file diff --git a/tests/fixtures/regression_docs/592638.txt b/tests/fixtures/regression_docs/592638.txt new file mode 100644 index 0000000..5311c2c --- /dev/null +++ b/tests/fixtures/regression_docs/592638.txt @@ -0,0 +1,5 @@ +ALGORITHM ANALYSIS +Topic: Sorting Algorithms +Merge Sort divides an array, sorts each half, and merges the results. Its time +complexity is O(n log n) in best, average, and worst cases. Quick Sort partitions +around a pivot; average time is O(n log n), while worst case is O(n squared). \ No newline at end of file diff --git a/tests/fixtures/regression_docs/628450.txt b/tests/fixtures/regression_docs/628450.txt new file mode 100644 index 0000000..99c46ad --- /dev/null +++ b/tests/fixtures/regression_docs/628450.txt @@ -0,0 +1,5 @@ +JAVA OOPS - ABSTRACTION +Topic: Abstract Classes and Interfaces +Abstraction exposes essential behavior while hiding implementation details. +An abstract class may contain abstract and concrete methods. An interface +defines a contract that implementing classes agree to follow. \ No newline at end of file diff --git a/tests/fixtures/regression_docs/716305.txt b/tests/fixtures/regression_docs/716305.txt new file mode 100644 index 0000000..ec955b0 --- /dev/null +++ b/tests/fixtures/regression_docs/716305.txt @@ -0,0 +1,7 @@ +DBMS LAB - SQL JOINS +Topic: Inner Join and Left Outer Join +INNER JOIN returns rows with matching values in both tables. LEFT JOIN returns +all rows from the left table and matching rows from the right table; unmatched +right-side columns are NULL. +SELECT s.name, e.course_id FROM Student s LEFT JOIN Enrollment e +ON s.student_id = e.student_id; \ No newline at end of file diff --git a/tests/fixtures/regression_docs/806531.txt b/tests/fixtures/regression_docs/806531.txt new file mode 100644 index 0000000..6167606 --- /dev/null +++ b/tests/fixtures/regression_docs/806531.txt @@ -0,0 +1,5 @@ +DISCRETE MATHEMATICS - SET THEORY +Topic: Sets, Relations, and Functions +A set is a collection of distinct elements. A relation from A to B is a subset +of the Cartesian product A x B. A function assigns exactly one output to each +input in its domain. Review reflexive, symmetric, antisymmetric, and transitive. \ No newline at end of file diff --git a/tests/fixtures/regression_docs/830174.txt b/tests/fixtures/regression_docs/830174.txt new file mode 100644 index 0000000..bfd6c6c --- /dev/null +++ b/tests/fixtures/regression_docs/830174.txt @@ -0,0 +1,5 @@ +DATA STRUCTURES AND ALGORITHMS +Topic: Binary Search Tree +A BST stores smaller keys in the left subtree and larger keys in the right. +Inorder traversal visits keys in sorted order. Average search time is O(log n) +for a balanced tree; worst case is O(n). \ No newline at end of file diff --git a/tests/fixtures/regression_docs/951083.txt b/tests/fixtures/regression_docs/951083.txt new file mode 100644 index 0000000..220acff --- /dev/null +++ b/tests/fixtures/regression_docs/951083.txt @@ -0,0 +1,5 @@ +OOPS - ENCAPSULATION +Topic: Classes, Objects, and Data Hiding +A class defines the state and behavior of objects. An object is an instance +of a class. Encapsulation bundles data with methods and restricts direct access +using access modifiers such as private, protected, and public. \ No newline at end of file diff --git a/tests/test_packaging_lifecycle.py b/tests/test_packaging_lifecycle.py index 231f7c5..b064863 100644 --- a/tests/test_packaging_lifecycle.py +++ b/tests/test_packaging_lifecycle.py @@ -119,22 +119,21 @@ def test_low_confidence_document_routed_to_review_despite_rule_match(self, tmp_p confidence=0.45, suggested_action="Review" ) - # Ingestion produces valid document - from app.ingestion import ingest_file - norm_doc = ingest_file(str(doc_file)) - + app._inflight = set() with pytest.MonkeyPatch.context() as mp: - mp.setattr("app.gui.ingest_file", lambda p: norm_doc) - mp.setattr("app.gui.analyze_document", lambda d: low_conf_analysis) + mp.setattr("app.pipeline.safe_analyze_document", lambda d: low_conf_analysis) + mp.setattr("app.pipeline.wait_until_stable", lambda *a, **k: True) app._run_pipeline(event) - # Must call _on_review, NEVER execute_move! + # Nothing may move: the file becomes a PROPOSAL flagged for review, never execute_move. app.safe_executor.execute_move.assert_not_called() app.executor.execute_move.assert_not_called() - assert app.after.call_count >= 1 - # Check that one of the self.after calls dispatched _on_review - review_dispatched = any(call_args[0][1] == app._on_review for call_args in app.after.call_args_list) - assert review_dispatched, "Low-confidence document did not get routed to _on_review" + assert doc_file.exists() + proposal_calls = [c for c in app.after.call_args_list if c[0][1] == app._on_proposal] + assert proposal_calls, "Low-confidence document did not produce a proposal" + proposal = proposal_calls[0][0][3] + assert proposal.needs_review is True + assert proposal.status == "pending" def test_smoke_test_does_not_modify_user_home_sortsense(self, tmp_path, monkeypatch): from sortsense import run_smoke_test diff --git a/tests/test_user_controlled_workflow.py b/tests/test_user_controlled_workflow.py new file mode 100644 index 0000000..900b55c --- /dev/null +++ b/tests/test_user_controlled_workflow.py @@ -0,0 +1,428 @@ +""" +Regression tests for the approval-first, deterministic (no Ollama) workflow. + +No test here needs Ollama, the network, or a display. Gemma is mocked. +Documents are generic fixtures; nothing is keyed on their file names. +""" +from __future__ import annotations + +import json +import shutil +from pathlib import Path +from unittest.mock import MagicMock, patch + +import pytest + +from app.analyzer import OllamaServiceManager, deterministic_analyze_document, safe_analyze_document +from app.document import NormalizedDocument +from app.ingestion import ingest_file +from app.intent.executor import HistoryManager, SafeFileExecutor +from app.pipeline import is_partial_download, process_file, wait_until_stable +from app.proposals import APPROVED, EXECUTED, FAILED, PENDING, REJECTED, ProposalManager + +FIXTURES = Path(__file__).parent / "fixtures" / "regression_docs" + +# What each fixture document is about (judged from its content, used only as test oracle) +EXPECTED = { + "164729": "DSA", "592638": "DSA", "830174": "DSA", + "219765": "Discrete Mathematics", "374192": "Discrete Mathematics", "806531": "Discrete Mathematics", + "295841": "DBMS", "483920": "DBMS", "716305": "DBMS", + "407216": "OOPS", "628450": "OOPS", "951083": "OOPS", +} +# Realistic opaque download names, mixed extensions (content is identical, only the name differs) +OPAQUE = [ + "DOC-WA0879845", "WhatsApp Document 2026-11-12", "download_3", "DOC-WA0926714", + "assignment_final", "IMG-WA0048217", "Notes_28112026", "DOC-WA0765319", + "WhatsApp Document 2026-11-15", "file (7)", "scan001", "new_document", +] + + +@pytest.fixture(autouse=True) +def no_ollama(monkeypatch): + """Everything here must work with Ollama absent.""" + OllamaServiceManager.reset() + monkeypatch.setattr(OllamaServiceManager, "is_available", classmethod(lambda cls, timeout=0.5: False)) + yield + OllamaServiceManager.reset() + + +def make_pdf(path: Path, pages: list[list[str]]) -> None: + """Write a tiny valid text PDF (no third-party library needed).""" + objs: list[bytes] = [] + n_pages = len(pages) + kids = " ".join(f"{3 + 2 * i} 0 R" for i in range(n_pages)) + objs.append(b"<< /Type /Catalog /Pages 2 0 R >>") + objs.append(f"<< /Type /Pages /Kids [{kids}] /Count {n_pages} >>".encode()) + font_id = 3 + 2 * n_pages + for i, lines in enumerate(pages): + content_id = 4 + 2 * i + objs.append( + f"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents {content_id} 0 R " + f"/Resources << /Font << /F1 {font_id} 0 R >> >> >>".encode()) + text = "BT /F1 12 Tf 50 740 Td 16 TL " + " ".join( + f"({ln.replace('(', '[').replace(')', ']')}) Tj T*" for ln in lines) + " ET" + objs.append(f"<< /Length {len(text)} >>\nstream\n{text}\nendstream".encode()) + objs.append(b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>") + out = b"%PDF-1.4\n" + offsets = [] + for i, body in enumerate(objs, start=1): + offsets.append(len(out)) + out += f"{i} 0 obj\n".encode() + body + b"\nendobj\n" + xref = len(out) + out += f"xref\n0 {len(objs) + 1}\n0000000000 65535 f \n".encode() + for off in offsets: + out += f"{off:010d} 00000 n \n".encode() + out += f"trailer\n<< /Size {len(objs) + 1} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF".encode() + path.write_bytes(out) + + +def stage_twelve(downloads: Path) -> dict[str, str]: + """Copy the 12 fixtures into a 'Downloads' folder under opaque names. Returns name -> expected subject.""" + downloads.mkdir(parents=True, exist_ok=True) + mapping = {} + for (num, subject), opaque in zip(EXPECTED.items(), OPAQUE): + src = FIXTURES / f"{num}.txt" + text = src.read_text(encoding="utf-8") + if opaque.startswith(("DOC-WA", "IMG-WA", "download", "scan")): + dest = downloads / f"{opaque}.pdf" + make_pdf(dest, [text.splitlines()[:3], text.splitlines()[3:]]) # multi-page PDF + elif opaque.startswith("Notes"): + dest = downloads / f"{opaque}.md" + dest.write_text("# " + text, encoding="utf-8") + else: + dest = downloads / f"{opaque}.txt" + shutil.copy(src, dest) + mapping[dest.name] = subject + return mapping + + +# --------------------------------------------------------------------------- +# The 12-file scenario, end to end +# --------------------------------------------------------------------------- + +class TestTwelveFileScenario: + def test_classification_titles_and_nothing_moves_before_approval(self, tmp_path): + downloads, sorted_dir = tmp_path / "Downloads", tmp_path / "Sorted" + mapping = stage_twelve(downloads) + before = sorted(p.name for p in downloads.iterdir()) + + proposals = {} + for name, subject in mapping.items(): + prop = process_file(downloads / name, base_dir=sorted_dir, wait=False) + assert prop is not None, name + proposals[name] = prop + assert prop.category == subject, f"{name}: {prop.category} != {subject} ({prop.evidence})" + assert prop.proposed_name != name, "should be renamed from content" + assert prop.proposed_name.endswith(Path(name).suffix), "extension must be preserved" + assert prop.evidence, "reasons must be shown" + assert prop.destination_dir == sorted_dir / subject + + # Nothing moved, nothing created + assert sorted(p.name for p in downloads.iterdir()) == before + assert not sorted_dir.exists() + + def test_full_flow_approve_execute_history_undo(self, tmp_path): + downloads, sorted_dir = tmp_path / "Downloads", tmp_path / "Sorted" + mapping = stage_twelve(downloads) + history = HistoryManager(history_file=tmp_path / "history.json") + mgr = ProposalManager(SafeFileExecutor(history), base_dir=sorted_dir) + for name in mapping: + mgr.add(process_file(downloads / name, base_dir=sorted_dir, wait=False)) + + assert mgr.counts()[PENDING] == 12 and mgr.counts()[EXECUTED] == 0 + done, errors = mgr.approve_many([p.id for p in mgr.items()]) + assert len(done) == 12 and not errors + ok, bad, errs = mgr.execute_approved() + assert (ok, bad, errs) == (12, 0, []) + assert mgr.counts()[EXECUTED] == 12 + + for subject in ("DBMS", "DSA", "OOPS", "Discrete Mathematics"): + assert len(list((sorted_dir / subject).iterdir())) == 3, subject + assert list(downloads.iterdir()) == [] + + records = history.get_history() + assert len(records) == 12 and all(r.can_undo for r in records) + + undo = SafeFileExecutor(history) + for rec in records: + ok, msg = undo.undo_operation(rec.operation_id) + assert ok, msg + assert sorted(p.name for p in downloads.iterdir()) == sorted(mapping) # original names restored + + +# --------------------------------------------------------------------------- +# User control +# --------------------------------------------------------------------------- + +class TestUserControl: + def _setup(self, tmp_path, n=3): + downloads, sorted_dir = tmp_path / "Downloads", tmp_path / "Sorted" + downloads.mkdir() + mgr = ProposalManager(SafeFileExecutor(HistoryManager(tmp_path / "h.json")), base_dir=sorted_dir) + names = [] + for i, num in enumerate(list(EXPECTED)[:n]): + f = downloads / f"DOC-{i}.txt" + shutil.copy(FIXTURES / f"{num}.txt", f) + names.append(f) + mgr.add(process_file(f, base_dir=sorted_dir, wait=False)) + return downloads, sorted_dir, mgr + + def test_edit_name_destination_and_category(self, tmp_path): + downloads, sorted_dir, mgr = self._setup(tmp_path, 1) + p = mgr.items()[0] + mgr.set_name(p.id, "My Graph Notes") + assert p.proposed_name == "My_Graph_Notes.txt" + custom = tmp_path / "Competitive Programming" + mgr.set_destination(p.id, custom) + mgr.approve(p.id) + ok, bad, _ = mgr.execute_approved() + assert (ok, bad) == (1, 0) + assert (custom / "My_Graph_Notes.txt").exists() + + def test_changing_category_changes_destination(self, tmp_path): + _, sorted_dir, mgr = self._setup(tmp_path, 1) + p = mgr.items()[0] + mgr.set_category(p.id, "Semester 3") + assert p.destination_dir == sorted_dir / "Semester 3" + + def test_rejected_untouched_and_only_selected_executed(self, tmp_path): + downloads, sorted_dir, mgr = self._setup(tmp_path, 3) + a, b, c = mgr.items() + mgr.approve(a.id) + mgr.reject(b.id) # c stays pending + ok, bad, _ = mgr.execute_approved() + assert (ok, bad) == (1, 0) + assert b.source_path.exists() and c.source_path.exists() and not a.source_path.exists() + counts = mgr.counts() + assert counts[EXECUTED] == 1 and counts[REJECTED] == 1 and counts[PENDING] == 1 + + def test_pending_is_not_counted_as_executed(self, tmp_path): + _, _, mgr = self._setup(tmp_path, 2) + assert mgr.counts()[EXECUTED] == 0 + mgr.approve(mgr.items()[0].id) + assert mgr.counts()[EXECUTED] == 0 # approved is still not executed + + def test_unapproved_never_executes(self, tmp_path): + downloads, _, mgr = self._setup(tmp_path, 2) + assert mgr.execute_approved() == (0, 0, []) + assert len(list(downloads.iterdir())) == 2 + + +# --------------------------------------------------------------------------- +# Uncertain / empty / unsupported +# --------------------------------------------------------------------------- + +class TestUncertainDocuments: + def test_empty_file_keeps_name_and_requires_manual_destination(self, tmp_path): + f = tmp_path / "blank.txt" + f.write_text("", encoding="utf-8") + prop = process_file(f, base_dir=tmp_path / "S", wait=False) + assert prop.proposed_name == "blank.txt" and prop.destination_dir is None and prop.needs_review + mgr = ProposalManager(SafeFileExecutor(HistoryManager(tmp_path / "h.json")), base_dir=tmp_path / "S") + mgr.add(prop) + with pytest.raises(ValueError): + mgr.approve(prop.id) + mgr.set_destination(prop.id, tmp_path / "Mine") + mgr.approve(prop.id) + assert mgr.execute_approved()[0] == 1 + assert (tmp_path / "Mine" / "blank.txt").exists() + + def test_unrelated_text_gets_no_invented_category(self, tmp_path): + f = tmp_path / "x1.txt" + f.write_text("Grandma's banana bread recipe: mix flour, sugar and bananas, then bake for an hour.", encoding="utf-8") + prop = process_file(f, base_dir=tmp_path / "S", wait=False) + assert prop.destination_dir is None and prop.category == "Unclassified" + assert prop.proposed_name == "x1.txt" + + def test_mixed_subject_is_ambiguous_not_forced(self): + doc = _doc("mix.txt", "Notes on graph and tree traversal. Also relations and sets.") + a = deterministic_analyze_document(doc) + assert a.confidence < 0.85 # never auto-confident on thin/mixed evidence + + def test_unsupported_extension_is_ignored(self, tmp_path): + f = tmp_path / "photo.jpg" + f.write_bytes(b"\xff\xd8\xff") + assert process_file(f, wait=False) is None + + +def _doc(name, text, status="ok", ext="txt"): + return NormalizedDocument(file_path=f"/tmp/{name}", file_name=name, extension=ext, + content_type="text/plain", text=text, character_count=len(text), + page_count=None, extraction_status=status) + + +# --------------------------------------------------------------------------- +# Ingestion +# --------------------------------------------------------------------------- + +class TestIngestion: + def test_multipage_pdf_text_reaches_analyzer(self, tmp_path): + f = tmp_path / "DOC-WA0001.pdf" + make_pdf(f, [["DATABASE NORMALIZATION", "1NF 2NF 3NF"], ["functional dependency and candidate key"]]) + doc = ingest_file(f) + assert doc.extraction_status == "ok" and doc.page_count == 2 + assert "functional dependency" in doc.text.lower() + assert deterministic_analyze_document(doc).category == "DBMS" + + def test_blank_pdf_is_empty_not_crash(self, tmp_path): + f = tmp_path / "scan.pdf" + make_pdf(f, [[]]) + assert ingest_file(f).extraction_status == "empty" + + def test_malformed_pdf_is_error_not_crash(self, tmp_path): + f = tmp_path / "broken.pdf" + f.write_bytes(b"%PDF-1.4 this is not really a pdf") + assert ingest_file(f).extraction_status in ("error", "empty") + + def test_text_encodings(self, tmp_path): + (tmp_path / "a.txt").write_bytes("caf\u00e9 \u2013 notes".encode("utf-8-sig")) + (tmp_path / "b.txt").write_bytes("caf\u00e9 notes".encode("cp1252")) + (tmp_path / "c.txt").write_bytes("hello world".encode("utf-16")) + for n in "abc": + doc = ingest_file(tmp_path / f"{n}.txt") + assert doc.extraction_status == "ok" and "notes" in doc.text or "hello" in doc.text + + def test_markdown_headings_and_code_blocks_kept(self, tmp_path): + f = tmp_path / "n.md" + f.write_text("# Binary Search Tree\n\n```python\nclass Node: pass\n```\nInorder traversal, subtree, time complexity.\n", encoding="utf-8") + doc = ingest_file(f) + assert "# Binary Search Tree" in doc.text and "class Node" in doc.text + assert deterministic_analyze_document(doc).category == "DSA" + + def test_long_document_not_truncated_by_ingestion(self, tmp_path): + f = tmp_path / "big.txt" + f.write_text("filler line\n" * 20000 + "the end", encoding="utf-8") + assert ingest_file(f).text.endswith("the end") + + +# --------------------------------------------------------------------------- +# Safety +# --------------------------------------------------------------------------- + +class TestSafety: + def _mgr(self, tmp_path): + return ProposalManager(SafeFileExecutor(HistoryManager(tmp_path / "h.json")), base_dir=tmp_path / "S") + + def _prop(self, tmp_path, name="a.txt", text="x"): + f = tmp_path / name + f.write_text(text, encoding="utf-8") + mgr = self._mgr(tmp_path) + return mgr, mgr.add(process_file(f, base_dir=tmp_path / "S", wait=False)) + + def test_traversal_destination_rejected(self, tmp_path): + mgr, p = self._prop(tmp_path) + with pytest.raises(ValueError): + mgr.set_destination(p.id, str(tmp_path / "S" / ".." / ".." / "etc")) + + def test_reserved_and_illegal_names_sanitized(self, tmp_path): + mgr, p = self._prop(tmp_path) + mgr.set_name(p.id, "../../evil<>:|?.txt") + assert "/" not in p.proposed_name and ".." not in p.proposed_name and p.proposed_name.endswith(".txt") + mgr.set_name(p.id, "CON") + assert p.proposed_name.upper() != "CON.TXT" or p.proposed_name == "a.txt" + mgr.set_category(p.id, "NUL") + assert p.destination_dir.name.upper() != "NUL" + + def test_name_collision_never_overwrites(self, tmp_path): + dest = tmp_path / "Out" + dest.mkdir() + (dest / "a.txt").write_text("existing", encoding="utf-8") + mgr, p = self._prop(tmp_path, text="new") + mgr.set_destination(p.id, dest) + mgr.set_name(p.id, "a.txt") + mgr.approve(p.id) + assert mgr.execute_approved()[0] == 1 + assert (dest / "a.txt").read_text(encoding="utf-8") == "existing" + assert (dest / "a_1.txt").read_text(encoding="utf-8") == "new" + + def test_partial_failure_is_reported_and_others_proceed(self, tmp_path): + mgr = self._mgr(tmp_path) + files = [] + for i in range(3): + f = tmp_path / f"f{i}.txt" + f.write_text(f"doc {i}", encoding="utf-8") + pr = mgr.add(process_file(f, base_dir=tmp_path / "S", wait=False)) + mgr.set_destination(pr.id, tmp_path / "Out") + mgr.approve(pr.id) + files.append(f) + files[1].unlink() # vanishes before execution + ok, bad, errors = mgr.execute_approved() + assert (ok, bad) == (2, 1) and len(errors) == 1 + assert mgr.counts()[FAILED] == 1 and mgr.counts()[EXECUTED] == 2 + + def test_long_names_are_truncated(self, tmp_path): + mgr, p = self._prop(tmp_path) + mgr.set_name(p.id, "x" * 400) + assert len(p.proposed_name) <= 90 + + +# --------------------------------------------------------------------------- +# Engine honesty / Gemma (mocked) +# --------------------------------------------------------------------------- + +class TestEngineStatus: + def test_not_installed_is_deterministic(self, monkeypatch): + import app.analyzer as az + monkeypatch.setattr(az, "OLLAMA_INSTALLED", False) + assert OllamaServiceManager.engine_state()[0] == "deterministic" + + def test_states(self, monkeypatch): + import app.analyzer as az + monkeypatch.setattr(az, "OLLAMA_INSTALLED", True) + monkeypatch.setattr(az, "ollama", MagicMock()) + cases = [((False, False, ""), "ollama_unavailable"), ((True, False, ""), "model_missing"), + ((True, True, ""), "gemma_active")] + for ret, expected in cases: + OllamaServiceManager.reset() + monkeypatch.setattr(OllamaServiceManager, "check_service_status", + classmethod(lambda cls, model_name=None, timeout=0.5, r=ret: r)) + assert OllamaServiceManager.engine_state()[0] == expected + OllamaServiceManager.mark_request_failed("boom") + assert OllamaServiceManager.engine_state()[0] == "request_failed" + + def _gemma(self, monkeypatch, content): + import app.analyzer as az + monkeypatch.setattr(OllamaServiceManager, "is_available", classmethod(lambda cls, timeout=0.5: True)) + client = MagicMock() + client.chat.return_value.message.content = content + monkeypatch.setattr(az, "_make_client", lambda: client) + + def test_valid_gemma_response_is_labelled_gemma(self, monkeypatch): + good = {"document_type": "Notes", "category": "DBMS", "new_filename": "ACID.txt", "summary": "s", + "confidence": 0.95, "suggested_action": "Archive"} + self._gemma(monkeypatch, json.dumps(good)) + assert safe_analyze_document(_doc("q.txt", "some text")).source == "gemma" + + @pytest.mark.parametrize("bad", ["", "not json {", '{"category": 1}']) + def test_bad_gemma_output_falls_back_and_is_not_labelled_gemma(self, monkeypatch, bad): + self._gemma(monkeypatch, bad) + a = safe_analyze_document(_doc("q.txt", "Database normalization 1NF 2NF 3NF functional dependency")) + assert a.source == "deterministic" and a.category == "DBMS" + + def test_gemma_exception_falls_back(self, monkeypatch): + import app.analyzer as az + monkeypatch.setattr(OllamaServiceManager, "is_available", classmethod(lambda cls, timeout=0.5: True)) + client = MagicMock() + client.chat.side_effect = TimeoutError("timed out") + monkeypatch.setattr(az, "_make_client", lambda: client) + assert safe_analyze_document(_doc("q.txt", "hello")).source == "deterministic" + + +# --------------------------------------------------------------------------- +# Watcher helpers +# --------------------------------------------------------------------------- + +class TestWatcherHelpers: + def test_partial_downloads_ignored(self, tmp_path): + for n in ("a.pdf.crdownload", "b.part", "c.tmp"): + assert is_partial_download(tmp_path / n) + f = tmp_path / "x.crdownload" + f.write_text("data", encoding="utf-8") + assert process_file(f, wait=False) is None + assert not is_partial_download(tmp_path / "ok.pdf") + + def test_stable_file_detected(self, tmp_path): + f = tmp_path / "s.txt" + f.write_text("done", encoding="utf-8") + assert wait_until_stable(f, checks=2, interval=0.01, timeout=2) + assert not wait_until_stable(tmp_path / "missing.txt", checks=2, interval=0.01, timeout=1)