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.
- imagent/__init__.py +0 -0
- imagent/__main__.py +5 -0
- imagent/cli.py +128 -0
- imagent/commands/__init__.py +0 -0
- imagent/commands/after_add.py +82 -0
- imagent/commands/delete.py +200 -0
- imagent/commands/failed.py +24 -0
- imagent/commands/forget.py +63 -0
- imagent/commands/help.py +82 -0
- imagent/commands/menu.py +155 -0
- imagent/commands/scan.py +1394 -0
- imagent/commands/search.py +432 -0
- imagent/commands/settings.py +139 -0
- imagent/commands/setup.py +1409 -0
- imagent/commands/uninstall.py +379 -0
- imagent/config.py +331 -0
- imagent/db/__init__.py +1 -0
- imagent/db/connection.py +237 -0
- imagent/db/operations.py +683 -0
- imagent/db/schema.sql +454 -0
- imagent/image_processing/__init__.py +14 -0
- imagent/image_processing/convert.py +48 -0
- imagent/image_processing/features.py +88 -0
- imagent/image_processing/hashing.py +49 -0
- imagent/image_processing/memory.py +101 -0
- imagent/image_processing/metadata.py +122 -0
- imagent/image_processing/ocr.py +129 -0
- imagent/image_processing/preprocess.py +33 -0
- imagent/image_processing/problems.py +53 -0
- imagent/image_processing/sample_pictures.py +214 -0
- imagent/os_specific/__init__.py +15 -0
- imagent/os_specific/convert.py +34 -0
- imagent/os_specific/files.py +64 -0
- imagent/os_specific/locking.py +31 -0
- imagent/os_specific/memory.py +153 -0
- imagent/os_specific/process.py +19 -0
- imagent/os_specific/storage.py +102 -0
- imagent/pipeline/__init__.py +1 -0
- imagent/pipeline/console.py +111 -0
- imagent/pipeline/discovery.py +107 -0
- imagent/pipeline/error_logger.py +69 -0
- imagent/pipeline/error_messages.py +56 -0
- imagent/pipeline/failure.py +51 -0
- imagent/pipeline/folder_picker.py +289 -0
- imagent/pipeline/locking.py +44 -0
- imagent/pipeline/progress.py +243 -0
- imagent/pipeline/serialisation.py +20 -0
- imagent/pipeline/storage.py +30 -0
- imagent/pipeline/validation.py +68 -0
- imagent/pipeline/versions.py +56 -0
- imagent/prompts/analysis_prompt.txt +8 -0
- imagent/prompts/analysis_schema.json +12 -0
- imagent/prompts/query_prompt.txt +14 -0
- imagent/text_processing/__init__.py +1 -0
- imagent/text_processing/cleaners.py +32 -0
- imagent/text_processing/formatters.py +79 -0
- imagent/vlm/__init__.py +1 -0
- imagent/vlm/analyzer.py +348 -0
- imagent/vlm/calibration.py +288 -0
- imagent/vlm/client.py +302 -0
- imagent/vlm/reply_validation.py +72 -0
- imagent/vlm/response_format.py +7 -0
- imagent_cli-0.1.0.dist-info/METADATA +171 -0
- imagent_cli-0.1.0.dist-info/RECORD +68 -0
- imagent_cli-0.1.0.dist-info/WHEEL +5 -0
- imagent_cli-0.1.0.dist-info/entry_points.txt +2 -0
- imagent_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
- imagent_cli-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""
|
|
2
|
+
imagent/pipeline/error_logger.py — Insert structured error records into the ``error_logs`` table.
|
|
3
|
+
|
|
4
|
+
Designed to be called inside ``except`` blocks throughout the pipeline. This
|
|
5
|
+
function is intentionally silent: it never raises an exception of its own, because
|
|
6
|
+
error logging must not interrupt processing of remaining images.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import sqlite3
|
|
13
|
+
import traceback
|
|
14
|
+
from datetime import datetime, timezone
|
|
15
|
+
|
|
16
|
+
from imagent import config
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def log_error(
|
|
20
|
+
conn: sqlite3.Connection,
|
|
21
|
+
*,
|
|
22
|
+
stage: str,
|
|
23
|
+
exc: Exception,
|
|
24
|
+
file_id: int | None = None,
|
|
25
|
+
file_path: str | None = None,
|
|
26
|
+
metadata: dict | None = None,
|
|
27
|
+
) -> None:
|
|
28
|
+
"""Insert a structured error record into ``error_logs``.
|
|
29
|
+
|
|
30
|
+
Args:
|
|
31
|
+
conn: Open database connection. The insert is committed immediately
|
|
32
|
+
using its own transaction so it is persisted even if the caller
|
|
33
|
+
later rolls back a broader transaction.
|
|
34
|
+
stage: Where the error occurred (e.g. ``pipeline``, ``search``,
|
|
35
|
+
``query_understanding``, ``scan``).
|
|
36
|
+
exc: The caught exception instance.
|
|
37
|
+
file_id: The image_data file_id, only if the image already has a row (the column is a foreign key).
|
|
38
|
+
file_path: The file path being processed at the time of the error.
|
|
39
|
+
metadata: Optional dict of additional context (model names, timings, etc.).
|
|
40
|
+
Will be stored as JSON.
|
|
41
|
+
"""
|
|
42
|
+
try:
|
|
43
|
+
conn.execute(
|
|
44
|
+
"""
|
|
45
|
+
INSERT INTO error_logs
|
|
46
|
+
(file_id, file_path, stage, error_type, error_message, stack_trace, metadata, created_at)
|
|
47
|
+
VALUES
|
|
48
|
+
(?, ?, ?, ?, ?, ?, ?, ?)
|
|
49
|
+
""",
|
|
50
|
+
(
|
|
51
|
+
file_id,
|
|
52
|
+
file_path,
|
|
53
|
+
stage,
|
|
54
|
+
type(exc).__name__,
|
|
55
|
+
str(exc),
|
|
56
|
+
traceback.format_exc(),
|
|
57
|
+
json.dumps(metadata) if metadata else None,
|
|
58
|
+
datetime.now(timezone.utc).isoformat(),
|
|
59
|
+
),
|
|
60
|
+
)
|
|
61
|
+
# Keep only the newest rows so repeated failures cannot grow the table without limit.
|
|
62
|
+
conn.execute(
|
|
63
|
+
"DELETE FROM error_logs WHERE id <= (SELECT MAX(id) FROM error_logs) - ?",
|
|
64
|
+
(config.ERROR_LOG_MAX_ROWS,),
|
|
65
|
+
)
|
|
66
|
+
conn.commit()
|
|
67
|
+
except Exception:
|
|
68
|
+
# Swallow any failure here — logging must never crash the pipeline.
|
|
69
|
+
pass
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""
|
|
2
|
+
imagent/pipeline/error_messages.py — What the user is told when an image cannot be indexed, one entry per error id.
|
|
3
|
+
|
|
4
|
+
The database keeps only the id of the error and the values that fill its gaps (``backlog.error_id`` and
|
|
5
|
+
``backlog.error_params``), never the wording: the wording is built from this table when it is shown, so
|
|
6
|
+
it can be improved without touching what is stored. A message may have gaps written as ``{name}``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
MESSAGES: dict[str, str] = {
|
|
12
|
+
# The picture itself
|
|
13
|
+
"damaged_picture": "The picture file is damaged or incomplete. Copy it again from the original.",
|
|
14
|
+
"unsupported_format": "Imagent cannot open {suffix} pictures on this computer. "
|
|
15
|
+
"Convert the picture to JPEG or PNG and keep the copy in the same folder.",
|
|
16
|
+
"no_memory_to_open": "There was not enough memory to open the picture. Close other programs, then scan again.",
|
|
17
|
+
"picture_too_large": "The picture has {megapixels} megapixels, more than the memory free right now allows. "
|
|
18
|
+
"Close other programs, then scan again.",
|
|
19
|
+
"picture_too_large_memory_unknown": "The picture has {megapixels} megapixels, this computer does not say how much memory is free, "
|
|
20
|
+
"so only a picture that is not very large can be read. "
|
|
21
|
+
"Save a smaller copy of it from a photo app, then scan again.",
|
|
22
|
+
"no_permission": "Imagent is not allowed to read this file. Change its permissions so that you can open it, then scan again.",
|
|
23
|
+
"not_downloaded": "The picture is kept in cloud storage and is not on this computer, and Imagent does not use the internet. "
|
|
24
|
+
"Make it available offline (download it), then scan again.",
|
|
25
|
+
"changed_since_scan": "The file changed after it was scanned, so it may still be being written. It is tried again later.",
|
|
26
|
+
"text_unreadable": "The text in the image could not be read, in any of the ways tried: {steps}",
|
|
27
|
+
# The model and Ollama
|
|
28
|
+
"reply_cut_off": "The model could not finish describing this picture, even after trying again with different settings "
|
|
29
|
+
"and with more room. Saving the picture again from a photo app, as a new file, gives it a fresh try.",
|
|
30
|
+
"reply_invalid": "The model's answer was not in the expected form, even after it was told what was wrong. "
|
|
31
|
+
"Saving the picture again from a photo app, as a new file, gives it a fresh try.",
|
|
32
|
+
"model_timeout": "The model did not reply in time, even after waiting longer.",
|
|
33
|
+
"model_out_of_memory": "Ollama ran out of memory, even after other models were unloaded.",
|
|
34
|
+
"model_stopped": "Ollama stopped responding, and starting it again did not help.",
|
|
35
|
+
# Anything not foreseen: the kind of error and what it said
|
|
36
|
+
"unexpected": "{type}: {text}",
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
# Added after the message of trouble with the machine that was tried ``tries`` times in a row (see commands/scan.py).
|
|
40
|
+
TRIED_SEVERAL_TIMES = "Imagent tried {tries} times without success. Close other apps that use a lot of memory, then scan again."
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def all_messages() -> dict[str, str]:
|
|
44
|
+
"""Every message as stored in the ``error_messages`` table: ``MESSAGES`` and the sentence added after a message that was tried several times."""
|
|
45
|
+
return {**MESSAGES, "tried_several_times": TRIED_SEVERAL_TIMES}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def describe(error_id: str | None, params: dict | None = None) -> str:
|
|
49
|
+
"""The message for ``error_id``, its gaps filled from ``params``; empty when there is no id. Raises ``KeyError`` for an id not in ``MESSAGES``."""
|
|
50
|
+
if error_id is None:
|
|
51
|
+
return ""
|
|
52
|
+
params = params or {}
|
|
53
|
+
message = MESSAGES[error_id].format(**params)
|
|
54
|
+
if "tries" in params:
|
|
55
|
+
message += " " + TRIED_SEVERAL_TIMES.format(**params)
|
|
56
|
+
return message
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""
|
|
2
|
+
imagent/pipeline/failure.py — What the indexing loop is told when one image cannot be indexed, or the whole run cannot go on.
|
|
3
|
+
|
|
4
|
+
Each kind of trouble does its own retrying where it happens (reading the image, reading its text, asking the model).
|
|
5
|
+
When that is not enough, it raises one of these, and the loop only has to know what to do with the file:
|
|
6
|
+
set it aside (``park``), or leave it queued without using up one of its attempts.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from imagent.pipeline.error_messages import describe
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class IndexingFailure(Exception):
|
|
15
|
+
"""One image could not be indexed, even after the steps for its kind of trouble.
|
|
16
|
+
|
|
17
|
+
``kind`` what went wrong, in a word (``cut_off``, ``unreadable``, ``timeout`` ...).
|
|
18
|
+
``error_id`` which message in ``pipeline/error_messages.py`` tells the user why, and ``params`` the values for its gaps.
|
|
19
|
+
Only these are stored; ``str(failure)`` is the message built from them.
|
|
20
|
+
``attempts`` the record of what was tried, stored in ``failure_history``.
|
|
21
|
+
``park`` True: set the file aside (it is queued again when it changes); False: leave it queued, no attempt used.
|
|
22
|
+
``retry_when`` what would make another try worthwhile: ``file_changed``, ``model_changed`` or ``on_request``.
|
|
23
|
+
``service`` True when the trouble is not the file's but the machine's or Ollama's: several in a row stop the run.
|
|
24
|
+
``model_trouble`` True when the model's reply was the problem: many of these stop the run too (see config.RETRY_RATE_*).
|
|
25
|
+
``report`` True: once the file is left (set aside, or queued for the next run) the user is told it could not be indexed, and why.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
def __init__(self, kind: str, error_id: str, attempts: list[dict] | None = None, *, params: dict | None = None,
|
|
29
|
+
park: bool = True, retry_when: str = "on_request", service: bool = False, model_trouble: bool = False,
|
|
30
|
+
report: bool = True):
|
|
31
|
+
super().__init__(describe(error_id, params))
|
|
32
|
+
self.kind = kind
|
|
33
|
+
self.error_id = error_id
|
|
34
|
+
self.params = params or {}
|
|
35
|
+
self.attempts = attempts or []
|
|
36
|
+
self.park = park
|
|
37
|
+
self.retry_when = retry_when
|
|
38
|
+
self.service = service
|
|
39
|
+
self.model_trouble = model_trouble
|
|
40
|
+
self.report = report
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class RunStopped(Exception):
|
|
44
|
+
"""Something is wrong for every image, not for this one: the run stops and the file stays queued, untouched."""
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def attempt_record(step: str, kind: str | None, detail: str = "", options: dict | None = None, raw_reply: str | None = None,
|
|
48
|
+
done_reason: str | None = None, eval_count: int | None = None, prompt_eval_count: int | None = None) -> dict:
|
|
49
|
+
"""One entry of an ``attempts`` list, in the form ``db.operations.add_failure_history`` stores."""
|
|
50
|
+
return {"step": step, "kind": kind, "options": options or {}, "detail": detail, "raw_reply": raw_reply,
|
|
51
|
+
"done_reason": done_reason, "eval_count": eval_count, "prompt_eval_count": prompt_eval_count}
|
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
"""
|
|
2
|
+
imagent/pipeline/folder_picker.py — Ask which folder to add: type part of a folder name and pick it from the folders that match.
|
|
3
|
+
|
|
4
|
+
The folders are listed by walking the home folder (pipeline/discovery.py, with the same pruning as a scan) in a background thread that
|
|
5
|
+
``start_listing`` can start as soon as the command starts, so the list is usually ready by the time the user has typed a few letters.
|
|
6
|
+
|
|
7
|
+
The matches are ordered from the end of the path: a folder whose own name matches comes first, then one whose parent matches, and so
|
|
8
|
+
on, because a folder is remembered by its own name more than by what holds it.
|
|
9
|
+
|
|
10
|
+
A typed path (one that starts with "~" or is absolute) is completed like in a shell instead: the folders inside the folder typed so far
|
|
11
|
+
whose names start with what follows its last separator are suggested, read from the disk as the user types.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import os
|
|
17
|
+
import threading
|
|
18
|
+
import unicodedata
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import NamedTuple
|
|
21
|
+
|
|
22
|
+
from imagent.os_specific.files import comparable_path, is_hidden_folder
|
|
23
|
+
from imagent.pipeline.discovery import _skip_folder, list_folders
|
|
24
|
+
from imagent.pipeline.validation import find_overlapping_root
|
|
25
|
+
|
|
26
|
+
ROWS = 8 # matches shown at once
|
|
27
|
+
MIN_QUERY = 3 # characters typed before any folder is suggested: one or two match most of the folders
|
|
28
|
+
PLACEHOLDER = f"enter at least {MIN_QUERY} characters of a folder name to get suggestions"
|
|
29
|
+
PLACEHOLDER_STYLE = "fg:#808080" # a fixed mid grey: the terminal's own "bright black" can look the same as normal text in some themes
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class Candidate(NamedTuple):
|
|
33
|
+
path: str # as the system gave it
|
|
34
|
+
shown: str # "~/Pictures/Trips"
|
|
35
|
+
key: str # what the typed text is compared with: below the home folder, "/" between folders, any upper or lower case
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class _Listing:
|
|
39
|
+
"""The folders below one folder, being listed in a thread that starts at once."""
|
|
40
|
+
|
|
41
|
+
def __init__(self, home: str):
|
|
42
|
+
self.home = home
|
|
43
|
+
self.folders: list[str] = []
|
|
44
|
+
self.thread = threading.Thread(target=self._run, daemon=True)
|
|
45
|
+
self.thread.start()
|
|
46
|
+
|
|
47
|
+
def _run(self) -> None:
|
|
48
|
+
self.folders = list_folders(self.home)
|
|
49
|
+
|
|
50
|
+
def wait(self) -> list[str]:
|
|
51
|
+
self.thread.join()
|
|
52
|
+
return self.folders
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
_listing: _Listing | None = None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _listing_of(home: str) -> _Listing:
|
|
59
|
+
"""The listing of ``home`` that is under way, or a new one."""
|
|
60
|
+
global _listing
|
|
61
|
+
if _listing is None or _listing.home != home:
|
|
62
|
+
_listing = _Listing(home)
|
|
63
|
+
return _listing
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def start_listing() -> None:
|
|
67
|
+
"""Start listing the folders below the home folder now, so the picker finds them ready."""
|
|
68
|
+
_listing_of(os.path.expanduser("~"))
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _folders_below(home: str) -> list[str]:
|
|
72
|
+
"""The folders below ``home``, waiting for the listing if it is not done. A listing is used once: the next call lists again, as folders may have changed."""
|
|
73
|
+
global _listing
|
|
74
|
+
listing = _listing_of(home)
|
|
75
|
+
folders = listing.wait()
|
|
76
|
+
if _listing is listing:
|
|
77
|
+
_listing = None
|
|
78
|
+
return folders
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _normalize(text: str) -> str:
|
|
82
|
+
return unicodedata.normalize("NFC", text).casefold()
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def candidates(folders: list[str], home: str, added: list[str]) -> list[Candidate]:
|
|
86
|
+
"""The folders of ``folders`` below ``home`` that can be added.
|
|
87
|
+
|
|
88
|
+
Left out: a folder the scan itself skips, and any folder inside one (hidden by a leading dot or by the operating system,
|
|
89
|
+
``node_modules`` and the like: see pipeline/discovery.py); and a folder that is one of ``added`` or overlaps one,
|
|
90
|
+
since adding it would be refused or be a rescan."""
|
|
91
|
+
skipped: dict[str, bool] = {} # a folder -> it is one the scan skips
|
|
92
|
+
added_keys = {comparable_path(path) for path in added}
|
|
93
|
+
found = []
|
|
94
|
+
for path in folders:
|
|
95
|
+
relative = os.path.relpath(path, home)
|
|
96
|
+
if relative == "." or relative.startswith(".."):
|
|
97
|
+
continue
|
|
98
|
+
names = relative.split(os.sep)
|
|
99
|
+
here = home
|
|
100
|
+
for name in names:
|
|
101
|
+
here = os.path.join(here, name)
|
|
102
|
+
if here not in skipped:
|
|
103
|
+
skipped[here] = _skip_folder(name) or is_hidden_folder(here)
|
|
104
|
+
if skipped[here]:
|
|
105
|
+
break
|
|
106
|
+
else:
|
|
107
|
+
if added and (comparable_path(path) in added_keys or find_overlapping_root(Path(path), added)):
|
|
108
|
+
continue
|
|
109
|
+
found.append(Candidate(path, "~" + os.sep + relative, _normalize("/".join(names))))
|
|
110
|
+
return found
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def rank(found: list[Candidate], query: str) -> list[Candidate]:
|
|
114
|
+
"""The folders of ``found`` that contain ``query``, the best match first.
|
|
115
|
+
|
|
116
|
+
The deeper in the path the last match lies the further back a folder goes, so what matches in the folder's own name comes
|
|
117
|
+
before what matches only in its parent. Within the same depth a name that is the query comes first, then one that starts with it,
|
|
118
|
+
then one that contains it; after that the shorter path, then the path in alphabetical order.
|
|
119
|
+
Fewer than ``MIN_QUERY`` characters match nothing."""
|
|
120
|
+
wanted = _normalize(query).strip().replace(os.sep, "/")
|
|
121
|
+
if len(wanted) < MIN_QUERY:
|
|
122
|
+
return []
|
|
123
|
+
scored = []
|
|
124
|
+
for candidate in found:
|
|
125
|
+
key = candidate.key
|
|
126
|
+
start = key.rfind(wanted)
|
|
127
|
+
if start < 0:
|
|
128
|
+
continue
|
|
129
|
+
end = start + len(wanted)
|
|
130
|
+
starts_name = start == 0 or key[start - 1] == "/"
|
|
131
|
+
ends_name = end == len(key) or key[end] == "/"
|
|
132
|
+
kind = 0 if starts_name and ends_name else 1 if starts_name else 2
|
|
133
|
+
scored.append(((key.count("/", end), kind, len(key), key), candidate))
|
|
134
|
+
scored.sort()
|
|
135
|
+
return [candidate for _, candidate in scored]
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _looks_like_path(text: str) -> bool:
|
|
139
|
+
return text.startswith("~") or os.path.isabs(text)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
_SEPARATORS = tuple({os.sep, os.altsep} - {None})
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _ends_with_separator(text: str) -> bool:
|
|
146
|
+
return text.endswith(_SEPARATORS)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def path_matches(text: str, added: list[str]) -> list[Candidate]:
|
|
150
|
+
"""The folders that complete the typed path ``text``: those inside the folder up to its last separator whose names start with what follows it.
|
|
151
|
+
|
|
152
|
+
The exact name comes first, then the rest in alphabetical order. Left out are the folders that ``candidates`` leaves out (skipped or hidden
|
|
153
|
+
ones, and ones that are added or overlap an added one). A folder that is not there or cannot be read gives nothing. Each ``shown`` keeps the
|
|
154
|
+
way the path was typed ("~/Pic" gives "~/Pictures"), each ``path`` is the whole path."""
|
|
155
|
+
typed = text.strip()
|
|
156
|
+
cut = max(typed.rfind(separator) for separator in _SEPARATORS) + 1
|
|
157
|
+
if not cut: # no folder to look in yet: "~" alone, or a drive letter
|
|
158
|
+
return []
|
|
159
|
+
parent_text, wanted = typed[:cut], _normalize(typed[cut:])
|
|
160
|
+
added_keys = {comparable_path(path) for path in added}
|
|
161
|
+
found = []
|
|
162
|
+
try:
|
|
163
|
+
with os.scandir(os.path.expanduser(parent_text)) as entries:
|
|
164
|
+
for entry in entries:
|
|
165
|
+
key = _normalize(entry.name)
|
|
166
|
+
if _skip_folder(entry.name) or not key.startswith(wanted) or not entry.is_dir() or is_hidden_folder(entry.path):
|
|
167
|
+
continue
|
|
168
|
+
if added and (comparable_path(entry.path) in added_keys or find_overlapping_root(Path(entry.path), added)):
|
|
169
|
+
continue
|
|
170
|
+
found.append(Candidate(entry.path, parent_text + entry.name, key))
|
|
171
|
+
except OSError:
|
|
172
|
+
return []
|
|
173
|
+
return sorted(found, key=lambda candidate: (candidate.key != wanted, candidate.key))
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
class _Picker:
|
|
177
|
+
"""The prompt: a line to type in and, under it, the matching folders to choose from."""
|
|
178
|
+
|
|
179
|
+
def __init__(self, added: list[str]):
|
|
180
|
+
self.home = os.path.expanduser("~")
|
|
181
|
+
self.added = added
|
|
182
|
+
self.found: list[Candidate] | None = None # None until the folders have been listed
|
|
183
|
+
self.matches: list[Candidate] = []
|
|
184
|
+
self.selected = 0
|
|
185
|
+
self.app = None
|
|
186
|
+
from prompt_toolkit.buffer import Buffer
|
|
187
|
+
self.buffer = Buffer(on_text_changed=lambda _: self._refresh())
|
|
188
|
+
|
|
189
|
+
def _refresh(self) -> None:
|
|
190
|
+
text = self.buffer.text.strip()
|
|
191
|
+
if _looks_like_path(text):
|
|
192
|
+
self.matches = path_matches(text, self.added)
|
|
193
|
+
# Right after a separator nothing is named yet, so nothing is highlighted and Enter adds the folder typed so far.
|
|
194
|
+
self.selected = -1 if _ends_with_separator(text) else 0
|
|
195
|
+
else:
|
|
196
|
+
self.matches = rank(self.found, text) if self.found else []
|
|
197
|
+
self.selected = 0
|
|
198
|
+
|
|
199
|
+
def _load(self) -> None:
|
|
200
|
+
self.found = candidates(_folders_below(self.home), self.home, self.added)
|
|
201
|
+
self._refresh()
|
|
202
|
+
if self.app is not None:
|
|
203
|
+
self.app.invalidate() # safe from this thread
|
|
204
|
+
|
|
205
|
+
def _render(self) -> list[tuple[str, str]]:
|
|
206
|
+
text = self.buffer.text.strip()
|
|
207
|
+
if not text:
|
|
208
|
+
return []
|
|
209
|
+
if _looks_like_path(text):
|
|
210
|
+
if not self.matches:
|
|
211
|
+
return [("class:instruction", "Press Enter to add this path.")]
|
|
212
|
+
else:
|
|
213
|
+
if len(text) < MIN_QUERY:
|
|
214
|
+
return []
|
|
215
|
+
if self.found is None:
|
|
216
|
+
return [("class:instruction", "Looking for folders...")]
|
|
217
|
+
if not self.matches:
|
|
218
|
+
return [("class:instruction", "No folder matches. You can paste its path instead.")]
|
|
219
|
+
lines: list[tuple[str, str]] = []
|
|
220
|
+
for number, candidate in enumerate(self.matches[:ROWS]):
|
|
221
|
+
chosen = number == self.selected
|
|
222
|
+
lines.append(("class:highlighted" if chosen else "", ("» " if chosen else " ") + candidate.shown + "\n"))
|
|
223
|
+
if len(self.matches) > ROWS:
|
|
224
|
+
lines.append(("class:instruction", f" ...and {len(self.matches) - ROWS} more: keep typing to narrow them down"))
|
|
225
|
+
return lines
|
|
226
|
+
|
|
227
|
+
def ask(self, style) -> str | None:
|
|
228
|
+
"""Run the prompt; the folder chosen or typed, or None on Ctrl+C."""
|
|
229
|
+
from prompt_toolkit.application import Application
|
|
230
|
+
from prompt_toolkit.filters import Condition
|
|
231
|
+
from prompt_toolkit.formatted_text import FormattedText
|
|
232
|
+
from prompt_toolkit.key_binding import KeyBindings
|
|
233
|
+
from prompt_toolkit.layout import HSplit, Layout, Window
|
|
234
|
+
from prompt_toolkit.layout.controls import BufferControl, FormattedTextControl
|
|
235
|
+
from prompt_toolkit.layout.processors import AfterInput, BeforeInput, ConditionalProcessor
|
|
236
|
+
from prompt_toolkit.shortcuts import print_formatted_text
|
|
237
|
+
|
|
238
|
+
typing = Window(BufferControl(self.buffer, input_processors=[
|
|
239
|
+
BeforeInput([("class:qmark", "▌ "), ("class:question", "Folder to add: ")]),
|
|
240
|
+
ConditionalProcessor(AfterInput(PLACEHOLDER, style=PLACEHOLDER_STYLE), Condition(lambda: not self.buffer.text)),
|
|
241
|
+
]), height=1)
|
|
242
|
+
keys = KeyBindings()
|
|
243
|
+
|
|
244
|
+
def move(step: int) -> None:
|
|
245
|
+
shown = min(len(self.matches), ROWS)
|
|
246
|
+
if shown:
|
|
247
|
+
self.selected = (0 if step > 0 else shown - 1) if self.selected < 0 else (self.selected + step) % shown
|
|
248
|
+
|
|
249
|
+
@keys.add("down")
|
|
250
|
+
@keys.add("c-n")
|
|
251
|
+
def _(event):
|
|
252
|
+
move(1)
|
|
253
|
+
|
|
254
|
+
@keys.add("up")
|
|
255
|
+
@keys.add("c-p")
|
|
256
|
+
def _(event):
|
|
257
|
+
move(-1)
|
|
258
|
+
|
|
259
|
+
@keys.add("enter")
|
|
260
|
+
def _(event):
|
|
261
|
+
text = self.buffer.text.strip()
|
|
262
|
+
if self.matches and self.selected >= 0:
|
|
263
|
+
event.app.exit(result=self.matches[self.selected].path)
|
|
264
|
+
elif text and (self.found is not None or _looks_like_path(text)): # not while the folders are still being listed
|
|
265
|
+
event.app.exit(result=text)
|
|
266
|
+
|
|
267
|
+
@keys.add("c-c")
|
|
268
|
+
def _(event):
|
|
269
|
+
event.app.exit(result=None)
|
|
270
|
+
|
|
271
|
+
self.app = Application(
|
|
272
|
+
layout=Layout(HSplit([typing, Window(FormattedTextControl(self._render), height=ROWS + 1)]), focused_element=typing),
|
|
273
|
+
key_bindings=keys, style=style, erase_when_done=True)
|
|
274
|
+
print() # a gap above the heading
|
|
275
|
+
threading.Thread(target=self._load, daemon=True).start()
|
|
276
|
+
folder = self.app.run()
|
|
277
|
+
if folder is None:
|
|
278
|
+
print("Cancelled by user")
|
|
279
|
+
return None
|
|
280
|
+
print_formatted_text(FormattedText([("class:qmark", "▌ "), ("class:question", "Folder to add: "), ("class:answer", folder)]),
|
|
281
|
+
style=style)
|
|
282
|
+
return folder
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def ask_for_folder(added: list[str], style=None) -> str | None:
|
|
286
|
+
"""Ask which folder to add, suggesting the folders that match what is typed.
|
|
287
|
+
|
|
288
|
+
``added`` are the folders added before (they are not suggested). Returns what was chosen or typed, or None on Ctrl+C."""
|
|
289
|
+
return _Picker(added).ask(style)
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""
|
|
2
|
+
imagent/pipeline/locking.py — Keep two copies of the same Imagent job from running at once.
|
|
3
|
+
|
|
4
|
+
The lock is held by the operating system on an open file, so it is released the moment the program
|
|
5
|
+
ends, however it ends (a crash, a power cut, a killed terminal). There is no stale lock to clean up.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from contextlib import contextmanager
|
|
11
|
+
|
|
12
|
+
from imagent import config
|
|
13
|
+
from imagent.os_specific.locking import lock, unlock
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class AlreadyRunning(RuntimeError):
|
|
17
|
+
"""The job is already running in another window; the message says so in plain words."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def is_running(name: str) -> bool:
|
|
21
|
+
"""True if another process holds the lock called ``name`` (this one must not hold it itself)."""
|
|
22
|
+
try:
|
|
23
|
+
with single_instance(name, ""):
|
|
24
|
+
return False
|
|
25
|
+
except AlreadyRunning:
|
|
26
|
+
return True
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@contextmanager
|
|
30
|
+
def single_instance(name: str, what: str):
|
|
31
|
+
"""Hold the lock called ``name`` while the block runs; raise ``AlreadyRunning`` if someone else holds it.
|
|
32
|
+
|
|
33
|
+
``what`` names the job in the error message, e.g. "Indexing".
|
|
34
|
+
"""
|
|
35
|
+
config.IMAGENT_HOME.mkdir(parents=True, exist_ok=True)
|
|
36
|
+
with open(config.IMAGENT_HOME / f"{name}.lock", "a+b") as handle:
|
|
37
|
+
try:
|
|
38
|
+
lock(handle)
|
|
39
|
+
except OSError as exc:
|
|
40
|
+
raise AlreadyRunning(f"{what} is already running in another window. Wait for it to finish, then try again.") from exc
|
|
41
|
+
try:
|
|
42
|
+
yield
|
|
43
|
+
finally:
|
|
44
|
+
unlock(handle)
|