imagent-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. imagent/__init__.py +0 -0
  2. imagent/__main__.py +5 -0
  3. imagent/cli.py +128 -0
  4. imagent/commands/__init__.py +0 -0
  5. imagent/commands/after_add.py +82 -0
  6. imagent/commands/delete.py +200 -0
  7. imagent/commands/failed.py +24 -0
  8. imagent/commands/forget.py +63 -0
  9. imagent/commands/help.py +82 -0
  10. imagent/commands/menu.py +155 -0
  11. imagent/commands/scan.py +1394 -0
  12. imagent/commands/search.py +432 -0
  13. imagent/commands/settings.py +139 -0
  14. imagent/commands/setup.py +1409 -0
  15. imagent/commands/uninstall.py +379 -0
  16. imagent/config.py +331 -0
  17. imagent/db/__init__.py +1 -0
  18. imagent/db/connection.py +237 -0
  19. imagent/db/operations.py +683 -0
  20. imagent/db/schema.sql +454 -0
  21. imagent/image_processing/__init__.py +14 -0
  22. imagent/image_processing/convert.py +48 -0
  23. imagent/image_processing/features.py +88 -0
  24. imagent/image_processing/hashing.py +49 -0
  25. imagent/image_processing/memory.py +101 -0
  26. imagent/image_processing/metadata.py +122 -0
  27. imagent/image_processing/ocr.py +129 -0
  28. imagent/image_processing/preprocess.py +33 -0
  29. imagent/image_processing/problems.py +53 -0
  30. imagent/image_processing/sample_pictures.py +214 -0
  31. imagent/os_specific/__init__.py +15 -0
  32. imagent/os_specific/convert.py +34 -0
  33. imagent/os_specific/files.py +64 -0
  34. imagent/os_specific/locking.py +31 -0
  35. imagent/os_specific/memory.py +153 -0
  36. imagent/os_specific/process.py +19 -0
  37. imagent/os_specific/storage.py +102 -0
  38. imagent/pipeline/__init__.py +1 -0
  39. imagent/pipeline/console.py +111 -0
  40. imagent/pipeline/discovery.py +107 -0
  41. imagent/pipeline/error_logger.py +69 -0
  42. imagent/pipeline/error_messages.py +56 -0
  43. imagent/pipeline/failure.py +51 -0
  44. imagent/pipeline/folder_picker.py +289 -0
  45. imagent/pipeline/locking.py +44 -0
  46. imagent/pipeline/progress.py +243 -0
  47. imagent/pipeline/serialisation.py +20 -0
  48. imagent/pipeline/storage.py +30 -0
  49. imagent/pipeline/validation.py +68 -0
  50. imagent/pipeline/versions.py +56 -0
  51. imagent/prompts/analysis_prompt.txt +8 -0
  52. imagent/prompts/analysis_schema.json +12 -0
  53. imagent/prompts/query_prompt.txt +14 -0
  54. imagent/text_processing/__init__.py +1 -0
  55. imagent/text_processing/cleaners.py +32 -0
  56. imagent/text_processing/formatters.py +79 -0
  57. imagent/vlm/__init__.py +1 -0
  58. imagent/vlm/analyzer.py +348 -0
  59. imagent/vlm/calibration.py +288 -0
  60. imagent/vlm/client.py +302 -0
  61. imagent/vlm/reply_validation.py +72 -0
  62. imagent/vlm/response_format.py +7 -0
  63. imagent_cli-0.1.0.dist-info/METADATA +171 -0
  64. imagent_cli-0.1.0.dist-info/RECORD +68 -0
  65. imagent_cli-0.1.0.dist-info/WHEEL +5 -0
  66. imagent_cli-0.1.0.dist-info/entry_points.txt +2 -0
  67. imagent_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
  68. imagent_cli-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,15 @@
1
+ """
2
+ os_specific — Everything that has to be done differently on macOS, Windows and Linux, in one place.
3
+
4
+ The rest of Imagent calls the functions here and never asks which operating system it runs on. Each module answers one
5
+ question (how much memory is free, is this folder on the computer's own disk, how is a picture converted, how is a file
6
+ locked, how is a background process started, ...), and each says what it does where an operating system is not covered.
7
+ Standard library only: the uninstaller imports it with a Python that has none of Imagent's packages.
8
+ """
9
+
10
+ import platform
11
+
12
+
13
+ def system_name() -> str:
14
+ """The name of the operating system, for a message to the user."""
15
+ return platform.system()
@@ -0,0 +1,34 @@
1
+ """
2
+ imagent/os_specific/convert.py — The command that turns a picture Pillow cannot open into a PNG, with what the operating system has.
3
+
4
+ macOS has ``sips``; Windows can convert with the imaging components built into it (through PowerShell); Linux has no such
5
+ tool, so there nothing is converted.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import platform
11
+ import shutil
12
+
13
+ # Reads the first frame with Windows' own decoders (the same ones Photos uses) and writes it as PNG. The paths arrive in
14
+ # environment variables, so no file name can end up being read as part of the script.
15
+ _WINDOWS_SCRIPT = (
16
+ "$ErrorActionPreference = 'Stop'; "
17
+ "Add-Type -AssemblyName PresentationCore; "
18
+ "$decoder = [System.Windows.Media.Imaging.BitmapDecoder]::Create([Uri]$env:IMAGENT_IN, 'None', 'OnLoad'); "
19
+ "$encoder = New-Object System.Windows.Media.Imaging.PngBitmapEncoder; "
20
+ "$encoder.Frames.Add($decoder.Frames[0]); "
21
+ "$stream = [System.IO.File]::Create($env:IMAGENT_OUT); "
22
+ "try { $encoder.Save($stream) } finally { $stream.Close() }"
23
+ )
24
+
25
+
26
+ def command(source: str, target: str) -> tuple[list[str], dict] | None:
27
+ """The command that converts ``source`` to a PNG at ``target`` on this operating system, and its extra environment; None if there is none."""
28
+ system = platform.system()
29
+ if system == "Darwin" and shutil.which("sips"):
30
+ return ["sips", "-s", "format", "png", source, "--out", target], {}
31
+ if system == "Windows" and shutil.which("powershell"):
32
+ return (["powershell", "-NoProfile", "-NonInteractive", "-Command", _WINDOWS_SCRIPT],
33
+ {"IMAGENT_IN": source, "IMAGENT_OUT": target})
34
+ return None
@@ -0,0 +1,64 @@
1
+ """
2
+ imagent/os_specific/files.py — What each operating system says about a file or a folder that Python's ``os`` module does not.
3
+
4
+ * a folder the user hid (Windows' hidden attribute, macOS's hidden flag): it holds the system's own caches, not pictures;
5
+ * a file whose content is in cloud storage and not on this computer (an iCloud or OneDrive placeholder): reading it makes
6
+ the system download it, and Imagent never uses the internet while it runs;
7
+ * how two folder paths are compared: whether upper and lower case, or two ways of writing an accented letter, name the same folder.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ import platform
14
+ import stat
15
+ import unicodedata
16
+
17
+ # Python's ``stat`` module has no names for these.
18
+ _UF_HIDDEN = 0x00008000 # macOS: the "hidden" flag of a file or folder (chflags hidden); ~/Library has it
19
+ _SF_DATALESS = 0x40000000 # macOS: the file's content is in iCloud (sys/stat.h)
20
+ _FILE_ATTRIBUTE_RECALL_ON_OPEN = 0x00040000 # Windows: the content is fetched from the cloud when the file is opened
21
+ _FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS = 0x00400000 # Windows: ... when its content is read (OneDrive "online-only")
22
+
23
+
24
+ def is_hidden_folder(path: str) -> bool:
25
+ """True if the folder at ``path`` is hidden by the operating system's own attribute (not by a leading dot, which is the caller's to check).
26
+
27
+ False where the system has no such attribute, or when the folder cannot be examined."""
28
+ system = platform.system()
29
+ if system not in ("Windows", "Darwin"):
30
+ return False
31
+ try:
32
+ status = os.stat(path)
33
+ except OSError:
34
+ return False
35
+ if system == "Windows":
36
+ return bool(getattr(status, "st_file_attributes", 0) & stat.FILE_ATTRIBUTE_HIDDEN)
37
+ return bool(getattr(status, "st_flags", 0) & _UF_HIDDEN)
38
+
39
+
40
+ def is_not_downloaded(status: os.stat_result) -> bool:
41
+ """True if the file's content is kept in cloud storage and is not on this computer, from the ``os.stat`` of the file.
42
+
43
+ Examining the file does not download it; opening or reading it does. False where the system has no such files."""
44
+ system = platform.system()
45
+ if system == "Windows":
46
+ recalled = _FILE_ATTRIBUTE_RECALL_ON_OPEN | _FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS | stat.FILE_ATTRIBUTE_OFFLINE
47
+ return bool(getattr(status, "st_file_attributes", 0) & recalled)
48
+ if system == "Darwin":
49
+ return bool(getattr(status, "st_flags", 0) & _SF_DATALESS)
50
+ return False
51
+
52
+
53
+ def comparable_path(path: str) -> str:
54
+ """``path`` in the form in which this operating system's file system tells two folder paths apart, for comparing them.
55
+
56
+ Windows and macOS file systems do not tell upper from lower case; macOS also treats an accented letter written as one
57
+ character or as two as the same. Linux's file systems tell them all apart, so nothing is changed there. Never use the result
58
+ to open a file: only the spelling the file system gave is certain to open it."""
59
+ system = platform.system()
60
+ if system == "Darwin":
61
+ path = unicodedata.normalize("NFC", path).casefold()
62
+ elif system == "Windows":
63
+ path = os.path.normcase(path).casefold()
64
+ return path.rstrip(os.sep)
@@ -0,0 +1,31 @@
1
+ """
2
+ imagent/os_specific/locking.py — Lock an open file so that no other process can lock it too, the way each operating system does it.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import os
8
+
9
+
10
+ def lock(handle) -> None:
11
+ """Lock the open file ``handle`` without waiting. Raises ``OSError`` when another process holds the lock.
12
+
13
+ The operating system releases the lock when the file is closed or the program ends, however it ends."""
14
+ if os.name == "nt":
15
+ import msvcrt
16
+ handle.seek(0)
17
+ msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
18
+ else:
19
+ import fcntl
20
+ fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
21
+
22
+
23
+ def unlock(handle) -> None:
24
+ """Release the lock taken with ``lock``."""
25
+ if os.name == "nt":
26
+ import msvcrt
27
+ handle.seek(0)
28
+ msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
29
+ else:
30
+ import fcntl
31
+ fcntl.flock(handle, fcntl.LOCK_UN)
@@ -0,0 +1,153 @@
1
+ """
2
+ imagent/os_specific/memory.py — How much memory a program can use right now, as each operating system tells it.
3
+
4
+ Linux counts what the kernel says is available (``MemAvailable``), and, when the program runs in a container or under a
5
+ memory limit (a cgroup), also what is left of that limit: ``/proc/meminfo`` shows the whole computer, so without this a
6
+ program in a 2 GB container would count on the free memory of a 64 GB host. The smaller of the two is used.
7
+
8
+ It also says which programs use the most memory right now, so a person can close them: ``ps`` on macOS and Linux, ``tasklist`` on Windows.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import csv
14
+ import ctypes
15
+ import platform
16
+ import re
17
+ import subprocess
18
+ from pathlib import Path
19
+
20
+ _CGROUP_ROOT = Path("/sys/fs/cgroup")
21
+ _PROC_CGROUP = Path("/proc/self/cgroup")
22
+ _NO_LIMIT = 2 ** 60 # cgroup v1 writes "no limit" as a number a little below 2**63; v2 writes "max"
23
+
24
+
25
+ def _parse_meminfo(text: str) -> int | None:
26
+ for line in text.splitlines():
27
+ if line.startswith("MemAvailable:"):
28
+ return int(line.split()[1]) * 1024
29
+ return None
30
+
31
+
32
+ def _parse_vm_stat(text: str) -> int | None:
33
+ size = re.search(r"page size of (\d+) bytes", text)
34
+ pages = {name: int(count) for name, count in re.findall(r"Pages (free|inactive|speculative):\s+(\d+)", text)}
35
+ if not size or len(pages) < 3:
36
+ return None
37
+ return (pages["free"] + pages["inactive"] + pages["speculative"]) * int(size.group(1))
38
+
39
+
40
+ def _parse_ps(text: str) -> dict[str, int]:
41
+ """Bytes of memory by program from ``ps -axo rss=,comm=`` (rss is in KiB). The processes of one program are added together: a
42
+ browser runs many. A macOS app is named by its bundle (``Google Chrome``), not by each of its helpers."""
43
+ totals: dict[str, int] = {}
44
+ for line in text.splitlines():
45
+ size, _, command = line.strip().partition(" ")
46
+ command = command.strip()
47
+ if not size.isdigit() or not command:
48
+ continue
49
+ app = re.search(r"([^/]+)\.app/", command)
50
+ name = app.group(1) if app else command.rsplit("/", 1)[-1]
51
+ totals[name] = totals.get(name, 0) + int(size) * 1024
52
+ return totals
53
+
54
+
55
+ def _parse_tasklist(text: str) -> dict[str, int]:
56
+ """Bytes of memory by program from ``tasklist /FO CSV /NH`` (the last column reads like ``"123,456 K"``, a count of KiB)."""
57
+ totals: dict[str, int] = {}
58
+ for row in csv.reader(text.splitlines()):
59
+ kib = re.sub(r"\D", "", row[4]) if len(row) >= 5 else ""
60
+ if kib:
61
+ totals[row[0]] = totals.get(row[0], 0) + int(kib) * 1024
62
+ return totals
63
+
64
+
65
+ class _MemoryStatus(ctypes.Structure):
66
+ _fields_ = [("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong), ("ullTotalPhys", ctypes.c_ulonglong),
67
+ ("ullAvailPhys", ctypes.c_ulonglong), ("ullTotalPageFile", ctypes.c_ulonglong),
68
+ ("ullAvailPageFile", ctypes.c_ulonglong), ("ullTotalVirtual", ctypes.c_ulonglong),
69
+ ("ullAvailVirtual", ctypes.c_ulonglong), ("ullAvailExtendedVirtual", ctypes.c_ulonglong)]
70
+
71
+
72
+ def _read_int(path: Path) -> int | None:
73
+ """The number in a cgroup file, or None if the file is missing or holds something else (v2 writes ``max`` for no limit)."""
74
+ try:
75
+ return int(path.read_text().strip())
76
+ except (OSError, ValueError):
77
+ return None
78
+
79
+
80
+ def _read_stat(path: Path, key: str) -> int:
81
+ """The value of ``key`` in a cgroup ``memory.stat`` file, or 0."""
82
+ try:
83
+ for line in path.read_text().splitlines():
84
+ name, _, value = line.partition(" ")
85
+ if name == key:
86
+ return int(value)
87
+ except (OSError, ValueError):
88
+ pass
89
+ return 0
90
+
91
+
92
+ def _cgroup_available(root: Path = _CGROUP_ROOT, proc_cgroup: Path = _PROC_CGROUP) -> int | None:
93
+ """Bytes left under the tightest memory limit that applies to this process, or None when no limit is set or it cannot be read.
94
+
95
+ The limit may sit on the process's own cgroup or on any cgroup above it (a container, a systemd slice), so each is
96
+ looked at, up to the top. What is used leaves out the cache the kernel can take back (``inactive_file``), the way
97
+ ``docker stats`` counts it. Both cgroup versions are read: v2 (``memory.max``) and v1 (``memory.limit_in_bytes``)."""
98
+ try:
99
+ lines = [line.split(":", 2) for line in proc_cgroup.read_text().splitlines()]
100
+ except OSError:
101
+ return None
102
+ if (root / "cgroup.controllers").exists(): # v2: one tree for every controller
103
+ base = root
104
+ own = next((parts[2] for parts in lines if len(parts) == 3 and parts[0] == "0"), "/")
105
+ limit_file, used_file, stat_key = "memory.max", "memory.current", "inactive_file"
106
+ else: # v1: a tree for each controller
107
+ base = root / "memory"
108
+ own = next((parts[2] for parts in lines if len(parts) == 3 and "memory" in parts[1].split(",")), "/")
109
+ limit_file, used_file, stat_key = "memory.limit_in_bytes", "memory.usage_in_bytes", "total_inactive_file"
110
+ folder = base / own.strip().lstrip("/")
111
+ if not folder.is_dir(): # inside a container the cgroup is often mounted as the top of the tree
112
+ folder = base
113
+ left = None
114
+ while True:
115
+ limit = _read_int(folder / limit_file)
116
+ used = _read_int(folder / used_file)
117
+ if limit is not None and used is not None and limit < _NO_LIMIT:
118
+ free = max(limit - max(used - _read_stat(folder / "memory.stat", stat_key), 0), 0)
119
+ left = free if left is None else min(left, free)
120
+ if folder == base or base not in folder.parents:
121
+ return left
122
+ folder = folder.parent
123
+
124
+
125
+ def available_memory() -> int | None:
126
+ """Bytes of memory free for a program to use right now, or None if this computer will not say."""
127
+ try:
128
+ system = platform.system()
129
+ if system == "Linux":
130
+ counts = [count for count in (_parse_meminfo(Path("/proc/meminfo").read_text()), _cgroup_available()) if count is not None]
131
+ return min(counts) if counts else None
132
+ if system == "Darwin":
133
+ return _parse_vm_stat(subprocess.run(["vm_stat"], capture_output=True, text=True, timeout=5).stdout)
134
+ if system == "Windows":
135
+ status = _MemoryStatus()
136
+ status.dwLength = ctypes.sizeof(status)
137
+ ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(status))
138
+ return int(status.ullAvailPhys)
139
+ except Exception:
140
+ pass
141
+ return None
142
+
143
+
144
+ def top_memory_users(count: int) -> list[tuple[str, int]]:
145
+ """The ``count`` programs using the most memory right now, largest first, as (name, bytes); empty if this computer will not say."""
146
+ try:
147
+ if platform.system() == "Windows":
148
+ totals = _parse_tasklist(subprocess.run(["tasklist", "/FO", "CSV", "/NH"], capture_output=True, text=True, timeout=15).stdout)
149
+ else:
150
+ totals = _parse_ps(subprocess.run(["ps", "-axo", "rss=,comm="], capture_output=True, text=True, timeout=15).stdout)
151
+ except Exception:
152
+ return []
153
+ return sorted(totals.items(), key=lambda item: item[1], reverse=True)[:count]
@@ -0,0 +1,19 @@
1
+ """
2
+ imagent/os_specific/process.py — Start a background process that outlives the terminal's own signals, the way each operating system does it.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import platform
8
+
9
+ _CREATE_NEW_PROCESS_GROUP = 0x00000200 # Windows: the process does not get this console's Ctrl+C
10
+ _CREATE_NO_WINDOW = 0x08000000 # Windows: the process has a console of its own that is never shown, and the programs it starts share it
11
+ # Not DETACHED_PROCESS (no console at all): every console program a detached process starts, such as the model runners of
12
+ # ``ollama serve``, would get a new visible console window of its own, opening and closing as models load.
13
+
14
+
15
+ def background_process_options() -> dict:
16
+ """Keyword arguments for ``subprocess.Popen`` that start the process in the background, apart from this program's terminal."""
17
+ if platform.system() == "Windows":
18
+ return {"creationflags": _CREATE_NEW_PROCESS_GROUP | _CREATE_NO_WINDOW}
19
+ return {"start_new_session": True}
@@ -0,0 +1,102 @@
1
+ """
2
+ imagent/os_specific/storage.py — Tell what kind of drive a folder is on, from what each operating system says about its mounts and disks.
3
+
4
+ Each system says it differently, and none says it perfectly, so this only names what it is sure of: it returns None when the
5
+ answer cannot be found, and the caller decides what that means.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import ctypes
11
+ import os
12
+ import platform
13
+ import plistlib
14
+ import re
15
+ import subprocess
16
+ from pathlib import Path
17
+
18
+ NETWORK = "network"
19
+ EXTERNAL = "external"
20
+
21
+ NETWORK_FILESYSTEMS = frozenset({
22
+ "nfs", "nfs4", "cifs", "smb", "smb2", "smb3", "smbfs", "afpfs", "afs", "webdav", "davfs", "9p", "ceph", "glusterfs",
23
+ "lustre", "ncpfs", "sshfs", "fuse.sshfs", "fuse.rclone",
24
+ })
25
+
26
+
27
+ def _parse_mount_output(text: str) -> list[tuple[str, str, str]]:
28
+ """The ``(mount point, file system, source)`` of each line of macOS's ``mount``: ``source on /mount/point (fstype, options)``."""
29
+ found = []
30
+ for line in text.splitlines():
31
+ match = re.match(r"^(.+?) on (/.*?) \(([^,)]+)", line)
32
+ if match:
33
+ found.append((match.group(2), match.group(3), match.group(1)))
34
+ return found
35
+
36
+
37
+ def _parse_mountinfo(text: str) -> list[tuple[str, str, str]]:
38
+ """The ``(mount point, file system, source)`` of each line of Linux's ``/proc/self/mountinfo``."""
39
+ found = []
40
+ for line in text.splitlines():
41
+ if " - " not in line:
42
+ continue
43
+ left, right = line.split(" - ", 1)
44
+ fields, rest = left.split(), right.split()
45
+ if len(fields) >= 5 and len(rest) >= 2:
46
+ mount_point = re.sub(r"\\([0-7]{3})", lambda m: chr(int(m.group(1), 8)), fields[4])
47
+ found.append((mount_point, rest[0], rest[1]))
48
+ return found
49
+
50
+
51
+ def _owner(path: str, mounts: list[tuple[str, str, str]]) -> tuple[str, str, str] | None:
52
+ """The mount that holds ``path``: the one whose mount point is the longest start of it."""
53
+ best = None
54
+ for mount in mounts: # mount points come from macOS and Linux, which always write them with "/"; Windows never gets here
55
+ point = mount[0].rstrip("/") or "/"
56
+ if path == point or path.startswith(point.rstrip("/") + "/"):
57
+ if best is None or len(point) > len(best[0].rstrip("/") or "/"):
58
+ best = mount
59
+ return best
60
+
61
+
62
+ def _macos_is_external(mount_point: str) -> bool:
63
+ info = plistlib.loads(subprocess.run(["diskutil", "info", "-plist", mount_point], capture_output=True, timeout=20).stdout)
64
+ return info.get("Internal") is False
65
+
66
+
67
+ def _linux_is_external(source: str) -> bool:
68
+ """True if the device behind ``source`` hangs off a USB port or is marked removable."""
69
+ name = os.path.basename(os.path.realpath(source))
70
+ real = os.path.realpath(f"/sys/class/block/{name}")
71
+ if "/usb" in real:
72
+ return True
73
+ disk = os.path.basename(os.path.dirname(real)) if os.path.exists(os.path.join(real, "partition")) else name
74
+ try:
75
+ return Path(f"/sys/block/{disk}/removable").read_text().strip() == "1"
76
+ except OSError:
77
+ return False
78
+
79
+
80
+ def classify(path: str) -> str | None:
81
+ """``NETWORK``, ``EXTERNAL`` or None (the computer's own disk, or not known) for a folder."""
82
+ system = platform.system()
83
+ if system == "Windows":
84
+ if path.startswith("\\\\"):
85
+ return NETWORK
86
+ kind = ctypes.windll.kernel32.GetDriveTypeW(os.path.splitdrive(path)[0] + "\\") # 2 removable, 4 network, 5 optical
87
+ return {4: NETWORK, 2: EXTERNAL, 5: EXTERNAL}.get(kind)
88
+ if system == "Darwin":
89
+ mounts = _parse_mount_output(subprocess.run(["mount"], capture_output=True, text=True, timeout=10).stdout)
90
+ elif system == "Linux":
91
+ mounts = _parse_mountinfo(Path("/proc/self/mountinfo").read_text())
92
+ else:
93
+ return None
94
+ owner = _owner(path, mounts)
95
+ if owner is None:
96
+ return None
97
+ mount_point, file_system, source = owner
98
+ if file_system.lower() in NETWORK_FILESYSTEMS:
99
+ return NETWORK
100
+ if system == "Darwin":
101
+ return EXTERNAL if _macos_is_external(mount_point) else None
102
+ return EXTERNAL if source.startswith("/dev/") and _linux_is_external(source) else None
@@ -0,0 +1 @@
1
+ # pipeline package
@@ -0,0 +1,111 @@
1
+ """imagent/pipeline/console.py — Make printing safe on every terminal, and end a command-line program politely."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import errno
6
+ import os
7
+ import sqlite3
8
+ import sys
9
+ import traceback
10
+ from datetime import datetime
11
+ from pathlib import Path
12
+ from typing import Callable
13
+
14
+ from imagent import config
15
+ from imagent.db.connection import DatabaseProblem, describe_db_error
16
+
17
+
18
+ def make_output_safe() -> None:
19
+ """Replace characters the terminal cannot show instead of raising UnicodeEncodeError.
20
+
21
+ Windows consoles with a legacy code page (and redirected output) cannot encode symbols
22
+ such as ✓ or ─, and file names can hold any character.
23
+ """
24
+ for stream in (sys.stdout, sys.stderr):
25
+ reconfigure = getattr(stream, "reconfigure", None)
26
+ if reconfigure is not None:
27
+ reconfigure(errors="replace")
28
+
29
+
30
+ def file_link(text: str, path: str | Path, stream=None) -> str:
31
+ """``text`` as a link that opens the file ``path`` in the system's default viewer when clicked
32
+ (Cmd+click or Ctrl+click in most terminals). Plain ``text`` when ``stream`` is not a terminal.
33
+
34
+ The terminal is told exactly which file the text stands for, so a click does not depend on it guessing
35
+ where a path starts and ends (spaces, non-ASCII names and wrapped lines defeat that guess)."""
36
+ stream = stream or sys.stdout
37
+ if not stream.isatty() or os.environ.get("TERM") == "dumb":
38
+ return text
39
+ try:
40
+ uri = Path(path).absolute().as_uri()
41
+ except ValueError:
42
+ return text
43
+ return f"\033]8;;{uri}\033\\{text}\033]8;;\033\\"
44
+
45
+
46
+ def _save_traceback() -> str | None:
47
+ """Keep the traceback of an unforeseen error in a file the user can attach to a report; None if it cannot be written."""
48
+ path = config.IMAGENT_HOME / "last_error.log"
49
+ try:
50
+ config.IMAGENT_HOME.mkdir(parents=True, exist_ok=True)
51
+ path.write_text(f"{datetime.now().isoformat()}\n{traceback.format_exc()}", encoding="utf-8")
52
+ return str(path)
53
+ except OSError:
54
+ return None
55
+
56
+
57
+ gap_shown = False # set once the blank line that ends a program has been printed, so it is never printed twice
58
+
59
+
60
+ def leave_a_gap() -> None:
61
+ """End a program on a terminal with a blank line, so the shell's prompt does not touch the last line of output. Only once, and not when
62
+ the output is redirected."""
63
+ global gap_shown
64
+ if gap_shown or not sys.stdout.isatty():
65
+ return
66
+ gap_shown = True
67
+ print()
68
+
69
+
70
+ def run_cli(main: Callable[[], None], cancelled: str = "Cancelled.") -> None:
71
+ """Run a command-line ``main`` so that whatever goes wrong ends as a short, plain message, not a traceback.
72
+
73
+ Ctrl+C, a question with no terminal to answer it, a database that cannot be used, and anything
74
+ unforeseen (its traceback is saved to a file) each get their own message and a non-zero exit code.
75
+ """
76
+ try:
77
+ main()
78
+ except KeyboardInterrupt:
79
+ sys.exit(f"\n{cancelled}")
80
+ except EOFError:
81
+ sys.exit("\nAn answer is needed here but there is no terminal to type it in. "
82
+ "Run this from a terminal, or give the value on the command line.")
83
+ except DatabaseProblem as exc:
84
+ sys.exit(f"{exc}")
85
+ except sqlite3.Error as exc:
86
+ sys.exit(f"{describe_db_error(exc)}")
87
+ except OSError as exc:
88
+ if exc.errno in _TERMINAL_ERRORS and not _terminal_is_there(): # the window was closed (or there never was one): not a fault of Imagent's
89
+ sys.exit("\nThe terminal is not there any more (it was closed, or this was not run in a terminal). Nothing more was done; "
90
+ "run the command again from a terminal.")
91
+ _exit_unexpected(exc)
92
+ except Exception as exc:
93
+ _exit_unexpected(exc)
94
+
95
+
96
+ _TERMINAL_ERRORS = (errno.EIO, errno.ENOTTY, errno.EBADF, errno.EINVAL) # what reading a closed or missing terminal fails with
97
+
98
+
99
+ def _terminal_is_there() -> bool:
100
+ try:
101
+ return os.isatty(sys.stdin.fileno())
102
+ except (OSError, ValueError, AttributeError): # the descriptor is closed, or stdin was replaced by something with none
103
+ return False
104
+
105
+
106
+ def _exit_unexpected(exc: BaseException) -> None:
107
+ """End with the plain message for an error nobody foresaw; its traceback is saved to a file."""
108
+ saved = _save_traceback()
109
+ where = "Details were saved to last_error.log in Imagent's data folder." if saved else "The details could not be saved."
110
+ sys.exit(f"Something unexpected went wrong ({type(exc).__name__}: {exc}). {where} "
111
+ "Running it again may work; if it keeps happening, please report it with that file.")
@@ -0,0 +1,107 @@
1
+ """imagent/pipeline/discovery.py — Recursively discover supported image files under a root directory."""
2
+
3
+ import os
4
+ from pathlib import Path
5
+ from typing import NamedTuple
6
+
7
+ from imagent.os_specific.files import is_hidden_folder
8
+
9
+ # Extensions that Imagent can process. All comparisons are done case-insensitively.
10
+ SUPPORTED_EXTENSIONS: frozenset[str] = frozenset({
11
+ ".jpg", ".jpeg",
12
+ ".png",
13
+ ".webp",
14
+ ".heic", ".heif",
15
+ ".bmp",
16
+ ".tiff", ".tif",
17
+ ".gif",
18
+ ".avif",
19
+ })
20
+
21
+ # Folders that hold no pictures of the user's own, only copies, caches or system files. Names are compared
22
+ # case-insensitively; a folder whose name starts with "." (.git, .Trash, .thumbnails, ...) is skipped too, and so is
23
+ # one the operating system itself marks as hidden (AppData on Windows, ~/Library on macOS: see os_specific/files.py),
24
+ # and one that ends in a suffix of SKIPPED_FOLDER_SUFFIXES (program bundles and the photo libraries and previews of photo programs).
25
+ # The names are listed even where the hidden mark would catch them, because a disk written by Windows and read on a Mac or Linux
26
+ # computer shows no such mark. A name that a person could also give to a folder of their own pictures ("windows", "recovery",
27
+ # "build", "venv") is left out on purpose.
28
+ SKIPPED_FOLDERS: frozenset[str] = frozenset({
29
+ "node_modules", "__pycache__", "site-packages", "bower_components", # what programs install: Python and JavaScript packages
30
+ "@eadir", "#recycle", "#snapshot", "@recycle", # Synology thumbnails, recycle bin and snapshots; QNAP recycle bin
31
+ "$recycle.bin", "recycler", "system volume information", # Windows: recycle bins and restore points
32
+ "$windows.~bt", "$windows.~ws", "$getcurrent", "$sysreset", "$winreagent", "windows.old", # Windows: upgrade, reset and recovery leftovers
33
+ "program files", "program files (x86)", "programdata", # Windows: installed programs
34
+ "__macosx", # left behind by unzipping on a Mac
35
+ })
36
+ # ".app": a macOS program (its icons and pictures are the program's); ".lrdata": Lightroom's previews;
37
+ # the others are libraries that hold their pictures in a package of their own.
38
+ SKIPPED_FOLDER_SUFFIXES: tuple[str, ...] = (".photoslibrary", ".aplibrary", ".migratedphotolibrary", ".photolibrary", ".lrdata", ".app")
39
+
40
+
41
+ class Discovery(NamedTuple):
42
+ """What a folder walk found."""
43
+ images: list[Path] # sorted
44
+ unreadable_dirs: list[Path] # folders that could not be listed; what is in them is unknown, not gone
45
+ bad_names: list[str] # files whose name is not valid text (stored paths must be); shown with unprintable characters replaced
46
+
47
+
48
+ def _skip_folder(name: str) -> bool:
49
+ lowered = name.lower()
50
+ return name.startswith(".") or lowered in SKIPPED_FOLDERS or lowered.endswith(SKIPPED_FOLDER_SUFFIXES)
51
+
52
+
53
+ def _skip_file(name: str) -> bool:
54
+ # "._photo.jpg" is the metadata companion that macOS writes next to "photo.jpg" on drives it cannot store it on; it is not an image.
55
+ return name.startswith("._") or Path(name).suffix.lower() not in SUPPORTED_EXTENSIONS
56
+
57
+
58
+ def list_folders(root: str) -> list[str]:
59
+ """Every folder below *root* that a scan would look inside, in no particular order; unreadable folders are left out.
60
+
61
+ It prunes with the same rules as ``discover``, so a folder is listed exactly when a scan of its parent would reach it. A link to a
62
+ folder is listed but not followed, as ``discover`` does not follow it. The folders are read from the disk itself, so none is
63
+ missing or out of date."""
64
+ found: list[str] = []
65
+ pending = [root]
66
+ while pending:
67
+ try:
68
+ with os.scandir(pending.pop()) as entries:
69
+ for entry in entries:
70
+ try:
71
+ if not entry.is_dir() or _skip_folder(entry.name) or is_hidden_folder(entry.path):
72
+ continue
73
+ found.append(entry.path)
74
+ if not entry.is_symlink():
75
+ pending.append(entry.path)
76
+ except OSError:
77
+ continue # gone while being read
78
+ except OSError:
79
+ continue # not readable: what is in it is unknown
80
+ return found
81
+
82
+
83
+ def discover(root: Path) -> Discovery:
84
+ """Walk *root* recursively and report its images, the folders it could not read and the files with unusable names."""
85
+ images: list[Path] = []
86
+ unreadable: list[Path] = []
87
+ bad_names: list[str] = []
88
+
89
+ def on_error(exc: OSError) -> None:
90
+ if exc.filename:
91
+ unreadable.append(Path(os.fsdecode(exc.filename)))
92
+
93
+ for folder, subfolders, files in os.walk(root, onerror=on_error):
94
+ subfolders[:] = sorted(name for name in subfolders # pruning in place steers the walk
95
+ if not _skip_folder(name) and not is_hidden_folder(os.path.join(folder, name)))
96
+ for name in files:
97
+ if _skip_file(name):
98
+ continue
99
+ path = Path(folder) / name
100
+ try:
101
+ str(path).encode("utf-8")
102
+ except UnicodeEncodeError:
103
+ bad_names.append(os.fsdecode(path).encode("utf-8", "replace").decode("utf-8"))
104
+ continue
105
+ if path.is_file(): # not a broken link or a folder with an image-like name
106
+ images.append(path)
107
+ return Discovery(sorted(images), sorted(unreadable), sorted(bad_names))