agent-iot / modules /paper_printer /file_finder.py
ASown's picture
Consolidate project history under ASown
f368481
Raw History Blame Contribute Delete
2.64 kB
"""Find a printable file on the PC by (partial) name — searches the user's
folders, skipping system/app junk, and returns best matches."""
from __future__ import annotations
import os
import time
from pathlib import Path
IMG_EXT = {".png", ".jpg", ".jpeg", ".bmp", ".webp", ".gif", ".tif", ".tiff"}
PRINTABLE = IMG_EXT | {".pdf"}
# Directories we never descend into (huge / system / irrelevant).
SKIP_DIRS = {
"appdata", "$recycle.bin", "windows", "program files", "program files (x86)",
"programdata", "node_modules", ".git", "__pycache__", ".cache", ".venv",
"venv", "site-packages", "application data", "temp", "tmp", ".vscode",
}
def default_roots() -> list[Path]:
"""Search the Desktop first (both the local and OneDrive-redirected one)."""
home = Path.home()
cands = [home / "OneDrive" / "Desktop", home / "Desktop"]
roots = [c for c in cands if c.exists()]
return roots or [home]
def find_files(query: str, roots: list[Path] | None = None,
max_results: int = 8, time_budget: float = 10.0) -> list[Path]:
"""Return printable files whose name matches `query` (exact name, exact stem,
or substring). Exact matches first, then most-recently-modified.
Default search scope: the Desktop."""
q = query.strip().strip('"').strip("'").lower()
qstem = Path(q).stem
want_ext = Path(q).suffix.lower() in PRINTABLE
roots = roots or default_roots()
t0 = time.time()
hits: set[Path] = set()
for root in roots:
if not root.exists():
continue
for dirpath, dirnames, filenames in os.walk(root):
if time.time() - t0 > time_budget:
break
dirnames[:] = [d for d in dirnames
if d.lower() not in SKIP_DIRS and not d.startswith(".")]
for fn in filenames:
if Path(fn).suffix.lower() not in PRINTABLE:
continue
name, stem = fn.lower(), Path(fn).stem.lower()
ok = (name == q) or (stem == qstem) or (q in name) if want_ext \
else (qstem in stem)
if ok:
hits.add(Path(dirpath) / fn)
if len(hits) >= max_results * 6:
break
def score(p: Path):
exact = 0 if (p.name.lower() == q or p.stem.lower() == qstem) else 1
try:
return (exact, -p.stat().st_mtime)
except OSError:
return (exact, 0)
return sorted(hits, key=score)[:max_results]
if __name__ == "__main__":
import sys
for m in find_files(" ".join(sys.argv[1:]) or "test"):
print(m)