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
imagent/__init__.py ADDED
File without changes
imagent/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ """imagent/__main__.py — ``python -m imagent``: the same as the ``imagent`` command."""
2
+
3
+ from imagent.cli import main
4
+
5
+ main()
imagent/cli.py ADDED
@@ -0,0 +1,128 @@
1
+ """imagent/cli.py — The ``imagent`` command: read the command line and run the command it names.
2
+
3
+ ``imagent`` with no command opens the menu. The menu, like every command except ``setup``, ``uninstall`` and ``help``, runs setup first if it has not been done, so it only opens once Imagent is set up. Each command is a module in ``imagent/commands``; it is imported only when it is
4
+ run, so ``imagent --help`` and a mistyped command answer at once, without loading the image and model libraries.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import sys
11
+
12
+ from imagent import config
13
+ from imagent.pipeline.console import leave_a_gap, run_cli
14
+
15
+
16
+ def build_parser() -> argparse.ArgumentParser:
17
+ parser = argparse.ArgumentParser(
18
+ prog="imagent",
19
+ description="Index your pictures and find them again by describing them. Everything runs on this computer. "
20
+ "Run it with no command to open a menu.")
21
+ parser.add_argument("--version", action="version", version=f"imagent {config.APP_VERSION}")
22
+ commands = parser.add_subparsers(dest="command", metavar="command", title="commands")
23
+
24
+ search = commands.add_parser("search", help="find pictures by describing them", description="Show the pictures that best match a description.")
25
+ search.add_argument("query", nargs="*", help="what to look for, for example: red car at night. "
26
+ "Leave it out to keep searching until you type exit")
27
+ detail = search.add_mutually_exclusive_group()
28
+ detail.add_argument("--full", dest="full", action="store_const", const=True, default=None,
29
+ help="show each picture's full description instead of its one-line summary (for this search; the usual one is set in settings)")
30
+ detail.add_argument("--short", dest="full", action="store_const", const=False, default=None,
31
+ help="show each picture's one-line summary instead of its full description (for this search; the usual one is set in settings)")
32
+
33
+ scan = commands.add_parser("scan", help="scan the folders you added and index their pictures",
34
+ description="Scan every folder you added for new or changed pictures, then index them. "
35
+ "Add a folder with: add \"folder path\".")
36
+ add = commands.add_parser("add", help="add a folder, then scan and index it",
37
+ description="Add a folder to the folders that are scanned, scan it, then index its pictures. "
38
+ "A folder added before is scanned again.")
39
+ add.add_argument("folder", nargs="?", help="the folder to add (without it you pick one from a list of suggestions)")
40
+
41
+ commands.add_parser("failed", help="list the pictures that could not be indexed",
42
+ description="List the pictures that could not be indexed, with the reason for each.")
43
+ commands.add_parser("forget", help="forget the deleted pictures Imagent remembers",
44
+ description="Delete what Imagent remembers about pictures that were deleted (their descriptions and search data), after two confirmations. "
45
+ "Your indexed pictures are not touched.")
46
+ delete = commands.add_parser("delete", help="remove folders from the scan list, and what was indexed from them",
47
+ description="Remove folders from the scan list and delete what was indexed from them, after showing what will be lost and two questions. "
48
+ "Your pictures are never touched. You can choose to keep the analysis, so adding a folder again does not analyse its pictures again.")
49
+ delete.add_argument("folder", nargs="*", help="the folders to remove from the scan list; put a path with spaces in quotes (without any, you choose from the folders you added)")
50
+ commands.add_parser("settings", help="change how Imagent behaves, or uninstall it",
51
+ description="Open a menu to change how many deleted pictures Imagent remembers, and whether a search shows the summary or the full description. "
52
+ "It also holds Uninstall.")
53
+ commands.add_parser("setup", help="choose the models and prepare this computer (once)",
54
+ description="Check Ollama, download and lock the three models, and measure this computer. "
55
+ "Run it once after installing. Run again, it shows the models and restores a missing one.")
56
+ commands.add_parser("help", help="explain each command briefly",
57
+ description="Explain each command briefly, with an example of how to run it.")
58
+ commands.add_parser("uninstall", help="remove Imagent's data and models",
59
+ description="Delete the index, Imagent's data folder and the models it downloaded, after three confirmations.")
60
+ return parser
61
+
62
+
63
+ def _set_up_first() -> None:
64
+ """Run setup before the command (or the menu) if it has not been done, so the user is told at the start, not after the command has done its work.
65
+
66
+ Setup ends the program if it fails or is cancelled, so the command or menu only runs once Imagent is set up."""
67
+ from imagent.commands import menu
68
+ if menu.needs_setup():
69
+ from imagent.commands import setup
70
+ setup.say("Imagent is not set up yet, so setup starts now.")
71
+ run_cli(setup.main, cancelled=setup.CANCELLED)
72
+
73
+
74
+ def main(argv: list[str] | None = None) -> None:
75
+ """Run the command, and however it ends (done, a message, Ctrl+C, ``--help``) leave a blank line before the shell's prompt."""
76
+ try:
77
+ _run(argv)
78
+ except SystemExit as stop:
79
+ if sys.stdout.isatty() and isinstance(stop.code, str): # Python would print this message after the gap, so it is printed here, before it
80
+ print(stop.code, file=sys.stderr)
81
+ stop = SystemExit(1)
82
+ leave_a_gap()
83
+ raise stop
84
+ leave_a_gap()
85
+
86
+
87
+ def _run(argv: list[str] | None = None) -> None:
88
+ args = build_parser().parse_args(argv)
89
+ if args.command == "add" and not args.folder and sys.stdin.isatty():
90
+ from imagent.pipeline import folder_picker
91
+ folder_picker.start_listing() # the folders are listed while setup (if it runs) and the user's typing go on
92
+ if args.command not in ("setup", "uninstall", "help"): # setup is the fix itself, uninstall must work on a broken install, and help needs nothing
93
+ _set_up_first()
94
+ if args.command == "search":
95
+ from imagent.commands import search
96
+ run_cli(lambda: search.main(" ".join(args.query), full=args.full), cancelled="Search cancelled.")
97
+ elif args.command == "add":
98
+ from imagent.commands import scan
99
+ run_cli(lambda: scan.add(args.folder))
100
+ elif args.command == "scan":
101
+ from imagent.commands import scan
102
+ run_cli(scan.main)
103
+ elif args.command == "delete":
104
+ from imagent.commands import delete
105
+ run_cli(lambda: delete.main(args.folder), cancelled=delete.CANCELLED)
106
+ elif args.command == "failed":
107
+ from imagent.commands import failed
108
+ run_cli(failed.main)
109
+ elif args.command == "forget":
110
+ from imagent.commands import forget
111
+ run_cli(forget.main, cancelled=forget.CANCELLED)
112
+ elif args.command == "settings":
113
+ from imagent.commands import settings
114
+ run_cli(settings.main, cancelled=settings.CANCELLED)
115
+ elif args.command == "setup":
116
+ from imagent.commands import setup
117
+ run_cli(setup.main, cancelled=setup.CANCELLED)
118
+ from imagent.commands import menu # setup ends the program if it fails or is cancelled, so the menu opens only once it is done
119
+ run_cli(menu.main)
120
+ elif args.command == "help":
121
+ from imagent.commands import help as show_help
122
+ run_cli(show_help.main)
123
+ elif args.command == "uninstall":
124
+ from imagent.commands import uninstall
125
+ run_cli(uninstall.main, cancelled=uninstall.CANCELLED)
126
+ else:
127
+ from imagent.commands import menu
128
+ run_cli(menu.main)
File without changes
@@ -0,0 +1,82 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ imagent/commands/after_add.py — What to do after a folder was added: a menu that comes back after each choice, until Exit.
4
+
5
+ Shown by ``imagent add`` (and by ``imagent scan`` when no folder was added yet) when there is a terminal to answer in. The folder
6
+ has only been added, nothing is scanned yet. From here the user can add another folder, scan and index the folder just added, scan every
7
+ folder and index what is pending (as ``imagent scan`` does), delete folders (as ``imagent delete`` does) or search the pictures (once some are indexed).
8
+ A choice that ends with a message or Ctrl+C brings the user back to the menu instead of ending the program.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import sys
14
+ from pathlib import Path
15
+
16
+ import questionary
17
+
18
+ from imagent.commands import delete, scan, search
19
+ from imagent.commands.menu import STYLE, has_indexed_images
20
+ from imagent.os_specific.files import comparable_path
21
+
22
+ ADD, SCAN_THIS, SCAN_ALL, DELETE, SEARCH, EXIT = "add", "scan this", "scan all", "delete", "search", "exit"
23
+
24
+
25
+ def choices(folder: Path | None, indexed: bool = True) -> list:
26
+ """The menu; ``folder`` is the folder added last (None if it is not there any more), which "scan and index" is about.
27
+ "Search your images" is only offered when some image is indexed (``indexed``)."""
28
+ entries = [("Add another folder", ADD)]
29
+ if folder is not None:
30
+ entries.append((f"Scan and index this folder ({folder})", SCAN_THIS))
31
+ entries += [("Scan all folders and index the pictures waiting", SCAN_ALL), ("Delete folders", DELETE),
32
+ *([("Search your images", SEARCH)] if indexed else []), ("Exit", EXIT)]
33
+ return [questionary.Choice(title, value=value) for title, value in entries]
34
+
35
+
36
+ def _attempt(action):
37
+ """Run ``action`` and return what it returns. Whatever ends it early (a message, Ctrl+C) is shown and ends only the action; None is returned."""
38
+ try:
39
+ return action()
40
+ except SystemExit as stop:
41
+ if isinstance(stop.code, str):
42
+ print(stop.code, file=sys.stderr)
43
+ except KeyboardInterrupt:
44
+ print("\nCancelled.", file=sys.stderr)
45
+ return None
46
+
47
+
48
+ def _scan_all() -> None:
49
+ if not scan.added_folders(): # scan.main would ask for a folder to add, which would open this menu again inside itself
50
+ print("No folders have been added, so there is nothing to scan.")
51
+ return
52
+ scan.main()
53
+
54
+
55
+ def _is_added(folder: Path) -> bool:
56
+ return comparable_path(str(folder)) in {comparable_path(path) for path in scan.added_folders()}
57
+
58
+
59
+ def run(folder: Path) -> None:
60
+ """Offer what to do next, again after each choice, until Exit; ``folder`` is the folder that was just added."""
61
+ current: Path | None = folder
62
+ while True:
63
+ if current is not None and not _is_added(current): # deleted from this menu
64
+ current = None
65
+ print()
66
+ # The blank separator is skipped by the arrow keys; it only leaves a gap between the question and the entries.
67
+ choice = questionary.select("What would you like to do next?", choices=[questionary.Separator(" ")] + choices(current, has_indexed_images()), qmark="▌",
68
+ pointer="»", instruction=" ", style=STYLE).ask()
69
+ if choice is None: # Ctrl+C; questionary already said so
70
+ sys.exit(1)
71
+ if choice == EXIT:
72
+ return
73
+ if choice == ADD:
74
+ current = _attempt(scan.add_folder) or current
75
+ elif choice == SCAN_THIS:
76
+ _attempt(lambda: scan.scan_and_index(current))
77
+ elif choice == SCAN_ALL:
78
+ _attempt(_scan_all)
79
+ elif choice == DELETE:
80
+ _attempt(lambda: delete.main([]))
81
+ elif choice == SEARCH:
82
+ _attempt(search.main)
@@ -0,0 +1,200 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ imagent/commands/delete.py — Imagent: remove folders that were added, and what was indexed from them, after two questions.
4
+
5
+ Run by ``imagent delete``, with the folders to remove or, without any, choosing them from the folders that were added. It shows what will be
6
+ lost (the pictures indexed, the time spent analysing them, their size), asks whether to keep the analysis of the pictures (so adding a
7
+ folder again does not analyse its pictures again: the same kept analyses a scan keeps for deleted pictures, up to the number chosen at
8
+ setup), asks once more whether to delete, then deletes. The pictures themselves are never touched.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import sys
14
+ from pathlib import Path
15
+
16
+ import questionary
17
+ from prompt_toolkit.keys import Keys
18
+ from questionary.prompts.common import InquirerControl
19
+
20
+ from imagent import config
21
+ from imagent.commands.menu import STYLE
22
+ from imagent.commands.uninstall import _fmt_bytes
23
+ from imagent.db.connection import init_db
24
+ from imagent.db.operations import (
25
+ count_deleted_analyses, count_keepable_analyses, delete_roots, get_keep_deleted, image_ids_in_roots, keep_analyses_of,
26
+ list_roots, root_stats,
27
+ )
28
+ from imagent.os_specific.files import comparable_path
29
+ from imagent.pipeline.console import make_output_safe
30
+ from imagent.pipeline.locking import AlreadyRunning, is_running, single_instance
31
+ from imagent.pipeline.progress import format_duration
32
+
33
+ # The menu style without the highlight on a row: no underline or bold under the pointer, and no reverse video on the row a question
34
+ # starts on (questionary draws the ``default`` row as "selected", which is reverse video unless a style says otherwise).
35
+ PICKER_STYLE = questionary.Style([rule for rule in STYLE.style_rules if rule[0] not in ("highlighted", "selected")]
36
+ + [("highlighted", "noreverse nobold nounderline"), ("selected", "noreverse nobold nounderline")])
37
+ CANCELLED = "Cancelled. Nothing was deleted."
38
+ KEEP, DISCARD, DELETE, EXIT, CONFIRM = "keep", "discard", "delete", "exit", "confirm"
39
+
40
+
41
+ def match_folders(paths: list[str], roots: list[dict]) -> tuple[list[dict], list[str]]:
42
+ """The added folders (rows of ``list_roots``) that ``paths`` name, each once, and the paths that are not an added folder."""
43
+ by_path = {comparable_path(root["path"]): root for root in roots}
44
+ chosen, unknown = [], []
45
+ for raw in paths:
46
+ root = by_path.get(comparable_path(str(Path(raw).expanduser().resolve())))
47
+ if root is None:
48
+ unknown.append(raw)
49
+ elif root not in chosen:
50
+ chosen.append(root)
51
+ return chosen, unknown
52
+
53
+
54
+ def _ask(question):
55
+ answer = question.ask()
56
+ if answer is None: # Ctrl+C; questionary already said so
57
+ sys.exit(f"\n{CANCELLED}")
58
+ return answer
59
+
60
+
61
+ def choose_folders(conn, roots: list[dict], **prompt_options) -> list[dict]:
62
+ """Let the user tick the folders to remove from those that were added: Enter ticks or unticks the folder under the pointer, and
63
+ Confirm, below the list, ends the choice (it is only offered once a folder is ticked). Exit, below Confirm, deletes nothing.
64
+
65
+ It is one prompt that stays open: Enter redraws the row in place, so nothing flickers (a new prompt for each Enter would erase and
66
+ draw the whole list again). ``prompt_options`` go to the prompt (the tests give it a fake keyboard and screen)."""
67
+ indexed = {root["root_id"]: root_stats(conn, root["root_id"])["images"] for root in roots}
68
+ ticked: set[int] = set()
69
+ rows = {root["root_id"]: questionary.Choice("", value=root["root_id"]) for root in roots}
70
+ confirm = questionary.Choice("Confirm", value=CONFIRM, disabled="tick a folder first")
71
+ leave = questionary.Choice("Exit: delete nothing", value=EXIT)
72
+
73
+ def draw() -> None:
74
+ for root in roots:
75
+ mark = "x" if root["root_id"] in ticked else " "
76
+ rows[root["root_id"]].title = f"[{mark}] {root['path']} ({indexed[root['root_id']]:,} indexed)"
77
+ confirm.disabled = None if ticked else "tick a folder first"
78
+
79
+ draw()
80
+ questionary.print("")
81
+ questionary.print("▌Which folders do you want to remove from the scan list?", style="bold") # the message below is blank: it is the gap under this line
82
+ question = questionary.select("", choices=[*rows.values(), questionary.Separator(" "), confirm, leave], qmark=" ", pointer="»", instruction=" ",
83
+ style=PICKER_STYLE, **prompt_options)
84
+ application = question.application
85
+ control = next(control for control in application.layout.find_all_controls() if isinstance(control, InquirerControl))
86
+
87
+ @application.key_bindings.add(Keys.ControlM, eager=True) # added last, so it is used instead of the prompt's own Enter
88
+ def press_enter(event):
89
+ choice = control.get_pointed_at()
90
+ if choice.value in (CONFIRM, EXIT):
91
+ control.is_answered = True
92
+ event.app.exit(result=choice.value)
93
+ return
94
+ ticked.symmetric_difference_update({choice.value})
95
+ draw()
96
+ event.app.invalidate()
97
+
98
+ application.erase_when_done = True
99
+ if _ask(question) == EXIT:
100
+ sys.exit(f"\n{CANCELLED}")
101
+ return [root for root in roots if root["root_id"] in ticked]
102
+
103
+
104
+ def show_what_is_lost(conn, folders: list[dict]) -> dict:
105
+ """Print what will be lost, folder by folder; returns the totals."""
106
+ total = {"images": 0, "bytes": 0, "analysis_ms": 0, "queued": 0}
107
+ print("\n This removes the folders from the scan list and what was indexed from them.")
108
+ for folder in folders:
109
+ stats = root_stats(conn, folder["root_id"])
110
+ for key in total:
111
+ total[key] += stats[key]
112
+ print(f"\n {folder['path']}")
113
+ _print_stats(stats)
114
+ if len(folders) > 1:
115
+ print(f"\n All {len(folders)} folders")
116
+ _print_stats(total)
117
+ print("\n Your pictures are not touched, only what Imagent stored about them (descriptions and search data).")
118
+ return total
119
+
120
+
121
+ def _print_stats(stats: dict) -> None:
122
+ print(f" Pictures indexed {stats['images']:,}")
123
+ print(f" Analysis time {format_duration(stats['analysis_ms'] / 1000)} (the time spent describing them)")
124
+ print(f" Pictures' size {_fmt_bytes(stats['bytes'])} (on your disk, they stay there)")
125
+ if stats["queued"]:
126
+ print(f" Waiting to index {stats['queued']:,}")
127
+
128
+
129
+ def ask_keep(keepable: int, limit: int | None) -> bool | None:
130
+ """Ask whether to keep the analysis of the pictures; True to keep it, False not to, None when the user chose to exit.
131
+
132
+ Nothing is asked when nothing can be kept: ``limit`` is how many deleted pictures Imagent was set up to remember."""
133
+ if not keepable:
134
+ return False
135
+ if not limit:
136
+ print("\n Imagent was set up to remember no deleted pictures, so none of this can be kept.")
137
+ return False
138
+ kept = min(keepable, limit)
139
+ reach = (f"{kept:,} of the {keepable:,} pictures (the most Imagent was set up to remember)" if kept < keepable
140
+ else f"all {keepable:,} pictures") # what adding the folders again will recognise
141
+ questionary.print("") # a gap above the question
142
+ choice = _ask(questionary.select(
143
+ "Keep the analysis of these pictures?\n",
144
+ choices=[
145
+ questionary.Choice(f"Keep it: {reach} are not analysed again if you add the folders back", value=KEEP),
146
+ questionary.Choice("Don't keep it: every picture is analysed again if you add the folders back", value=DISCARD),
147
+ questionary.Choice("Exit: delete nothing", value=EXIT),
148
+ ], qmark="▌", pointer="»", instruction=" ", style=PICKER_STYLE))
149
+ return None if choice == EXIT else choice == KEEP
150
+
151
+
152
+ def main(paths: list[str] | None = None) -> None:
153
+ make_output_safe()
154
+ if not sys.stdin.isatty():
155
+ sys.exit('Deleting needs an interactive terminal. Run: imagent delete "folder path"')
156
+ if is_running("indexing"): # said now, not after the questions: the lock is checked again when it is taken, in case one starts meanwhile
157
+ sys.exit("Indexing is already running in another window. Wait for it to finish, then try again. Nothing was deleted.")
158
+ conn = init_db(str(config.DB_PATH))
159
+ try:
160
+ roots = list_roots(conn)
161
+ if not roots:
162
+ print("No folders have been added, so there is nothing to delete.")
163
+ return
164
+ if paths:
165
+ folders, unknown = match_folders(paths, roots)
166
+ if unknown:
167
+ sys.exit(f"These are not folders you added: {', '.join(unknown)}\n"
168
+ 'If the path has spaces, put it in quotes: imagent delete "folder path"\n'
169
+ "Run imagent delete without a folder to choose from the folders you added.\n"
170
+ "Nothing was deleted.")
171
+ else:
172
+ folders = choose_folders(conn, roots)
173
+ show_what_is_lost(conn, folders)
174
+ ids = [folder["root_id"] for folder in folders]
175
+ limit = get_keep_deleted(conn)
176
+ keep = ask_keep(count_keepable_analyses(conn, ids), limit)
177
+ if keep is None:
178
+ sys.exit(f"\n{CANCELLED}")
179
+ noun = "folder" if len(folders) == 1 else "folders"
180
+ questionary.print("") # a gap above the question
181
+ choice = _ask(questionary.select(
182
+ f"Are you sure you want to remove {len(folders)} {noun} from the scan list and delete what was indexed from {'it' if len(folders) == 1 else 'them'}?\n",
183
+ choices=[questionary.Choice("Yes, delete", value=DELETE), questionary.Choice("Exit: delete nothing", value=EXIT)],
184
+ default=EXIT, qmark="▌", pointer="»", instruction=" ", style=PICKER_STYLE))
185
+ if choice != DELETE:
186
+ sys.exit(f"\n{CANCELLED}")
187
+ try:
188
+ with single_instance("indexing", "Indexing"): # a scan or an indexing run could be adding to these folders meanwhile
189
+ with conn:
190
+ image_ids = image_ids_in_roots(conn, ids)
191
+ keep_analyses_of(conn, image_ids, limit if keep else 0)
192
+ delete_roots(conn, ids)
193
+ except AlreadyRunning as exc:
194
+ sys.exit(f"\n{exc} Nothing was deleted.")
195
+ print(f"\n ✓ Removed {len(folders)} {noun} from the scan list and the index of {len(image_ids):,} picture(s). Your pictures were not touched.")
196
+ if keep:
197
+ print(f" ✓ Imagent remembers {count_deleted_analyses(conn):,} deleted picture(s). Add a folder again with "
198
+ f'{config.ADD_COMMAND} "folder path" and the ones it recognises are not analysed again.')
199
+ finally:
200
+ conn.close()
@@ -0,0 +1,24 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ imagent/commands/failed.py — Imagent: list the images that could not be indexed, with the reason for each and what can be done about it.
4
+
5
+ An image is listed only after every try for its kind of failure is over. It leaves the list by itself once it is indexed.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from imagent import config
11
+ from imagent.db.connection import init_db
12
+ from imagent.pipeline.console import make_output_safe
13
+ from imagent.commands.scan import print_failed
14
+
15
+
16
+ def main() -> None:
17
+ make_output_safe()
18
+ conn = init_db(str(config.DB_PATH))
19
+ try:
20
+ if not print_failed(conn, limit=None):
21
+ print("No image has failed to index.")
22
+ finally:
23
+ conn.close()
24
+
@@ -0,0 +1,63 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ imagent/commands/forget.py — Imagent: delete what it remembers about pictures that were deleted, after two confirmations.
4
+
5
+ Run by ``imagent forget``, and offered by the menu when something is remembered. It deletes the kept analyses of deleted pictures
6
+ (``deleted_analyses``). The indexed pictures, the folders and the user's choice of how many deleted pictures to remember are not touched,
7
+ so pictures deleted from now on are remembered again, up to that number.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import sys
13
+
14
+ from imagent import config
15
+ from imagent.db.connection import init_db
16
+ from imagent.db.operations import clear_deleted_analyses, count_deleted_analyses
17
+ from imagent.pipeline.console import make_output_safe
18
+ from imagent.pipeline.locking import AlreadyRunning, is_running, single_instance
19
+
20
+ CANCELLED = "Cancelled. Nothing was deleted."
21
+
22
+
23
+ def confirm_twice(remembered: int) -> bool:
24
+ """Ask two different questions; any wrong answer cancels everything."""
25
+ if input("\n Confirmation 1 of 2. Do you want to forget everything above? Type yes: ").strip().lower() != "yes":
26
+ return False
27
+ if input(" Confirmation 2 of 2. How many deleted pictures will be forgotten? (see above): ").strip() != str(remembered):
28
+ print(" That is not the number above.")
29
+ return False
30
+ return True
31
+
32
+
33
+ def main() -> None:
34
+ make_output_safe()
35
+ if not sys.stdin.isatty():
36
+ sys.exit("Forgetting needs an interactive terminal. Run: imagent forget")
37
+ if is_running("indexing"): # said now, not after the confirmations: the lock is checked again when it is taken, in case one starts meanwhile
38
+ sys.exit("Indexing is already running in another window. Wait for it to finish, then try again. Nothing was deleted.")
39
+
40
+ conn = init_db(str(config.DB_PATH))
41
+ try:
42
+ remembered = count_deleted_analyses(conn)
43
+ if not remembered:
44
+ print("Imagent does not remember any deleted pictures.")
45
+ return
46
+ print("\n" + "=" * 64)
47
+ print(" THIS DELETES WHAT IMAGENT REMEMBERS ABOUT DELETED PICTURES")
48
+ print("=" * 64)
49
+ print(f" Deleted pictures remembered {remembered} (their descriptions and search data)")
50
+ print("=" * 64)
51
+ print(" If one of them comes back later, it will be analysed again. Your indexed pictures and your choice")
52
+ print(" of how many deleted pictures to remember are not touched.")
53
+ if not confirm_twice(remembered):
54
+ sys.exit(f"\n{CANCELLED}")
55
+ try:
56
+ with single_instance("indexing", "Indexing"): # a scan running now could remember more while this deletes
57
+ with conn:
58
+ forgotten = clear_deleted_analyses(conn)
59
+ except AlreadyRunning as exc:
60
+ sys.exit(f"\n{exc} Nothing was deleted.")
61
+ print(f"\n ✓ Forgot {forgotten} deleted picture(s).")
62
+ finally:
63
+ conn.close()
@@ -0,0 +1,82 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ imagent/commands/help.py — Imagent: explain each command briefly.
4
+
5
+ Run by ``imagent help``, and offered by the menu. It needs no setup, no database and no model, so it works on a computer where Imagent is not set up yet.
6
+ The text is written here by hand: when a command is added to ``cli.py`` it must be added to ``COMMANDS`` too (a test checks that none is missing).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import shutil
13
+ import sys
14
+ import textwrap
15
+
16
+ from imagent.pipeline.console import make_output_safe
17
+
18
+ INTRO = "Imagent indexes your pictures and finds them again when you describe them. Everything runs on this computer."
19
+ MENU_NOTE = "Run {} with no command to open a menu of the common ones."
20
+ MORE_NOTE = "For the details of one command, run: {}"
21
+
22
+ # (name, example of how to run it, what it does): shown as a table, the name on the left, the example and the explanation on the right
23
+ COMMANDS = [
24
+ ("search", 'imagent search "red car at night" --full',
25
+ "Show the pictures that best match a description. With no description it keeps asking until you type exit. Add --full for each picture's full description, or --short for its one-line summary; settings holds the usual choice."),
26
+ ("add", 'imagent add "folder path"',
27
+ "Add a folder of pictures to Imagent. You then choose what to do next, usually to scan the folder so its pictures are indexed. Leave out the folder to pick one from a list."),
28
+ ("scan", "imagent scan",
29
+ "Scan every folder you added for new, changed, moved or removed pictures, then index what is pending."),
30
+ ("delete", 'imagent delete "folder path"',
31
+ "Remove folders from the scan list and what was indexed from them. Your pictures are never touched. You can keep the analysis, so adding the folder again is quick."),
32
+ ("failed", "imagent failed",
33
+ "List the pictures that could not be indexed, with the reason for each."),
34
+ ("forget", "imagent forget",
35
+ "When you delete a picture, Imagent keeps its description, so if the picture comes back it is not analysed again. This command erases those kept descriptions, after two confirmations. Your indexed pictures are not touched."),
36
+ ("settings", "imagent settings",
37
+ "Change how many deleted pictures Imagent remembers, whether a search shows the one-line summary or the full description (add --full or --short to one search to change it just once), and how long the scan waits before it runs again by itself. Uninstall is here too."),
38
+ ("setup", "imagent setup",
39
+ "Check Ollama, download and lock the three models, and measure this computer. It runs by itself the first time it is needed; run it again to see or restore the models."),
40
+ ("uninstall", "imagent uninstall",
41
+ "Delete the index, Imagent's data folder and the models it downloaded, after three confirmations."),
42
+ ("help", "imagent help",
43
+ "Show this explanation."),
44
+ ]
45
+
46
+ WIDTH = 100 # the widest a line is, on a wide terminal
47
+ MIN_TEXT = 30 # the least room kept for the descriptions on a narrow one
48
+ INDENT = 2 # before the names
49
+ GAP = 4 # between the names and the commands and descriptions
50
+ NAME_WIDTH = max(len(name) for name, _, _ in COMMANDS)
51
+ RIGHT = INDENT + NAME_WIDTH + GAP # where the right column starts
52
+
53
+ BOLD = "1" # the heading, the names and what to type to run a command
54
+
55
+
56
+ def _style(text: str, code: str) -> str:
57
+ """``text`` with the ANSI style ``code`` when printing to a terminal that understands it, otherwise unchanged."""
58
+ if not sys.stdout.isatty() or os.environ.get("TERM") == "dumb" or "NO_COLOR" in os.environ:
59
+ return text
60
+ return f"\033[{code}m{text}\033[0m"
61
+
62
+
63
+ def _width() -> int:
64
+ """How wide a line may be: the terminal's width (its last column is left empty so a line never wraps by itself), at most ``WIDTH``."""
65
+ return max(min(shutil.get_terminal_size((WIDTH, 24)).columns - 1, WIDTH), RIGHT + MIN_TEXT)
66
+
67
+
68
+ def render() -> str:
69
+ width = _width()
70
+ lines = ["", textwrap.fill(INTRO, width), "", MENU_NOTE.format(_style("imagent", BOLD)), "", _style("imagent <command>", BOLD)]
71
+ for name, example, explanation in COMMANDS:
72
+ # break_on_hyphens is off so a flag such as --full is never split between two lines
73
+ right = [_style(example, BOLD), *textwrap.wrap(explanation, width - RIGHT, break_on_hyphens=False)]
74
+ left = " " * INDENT + _style(name, BOLD) + " " * (NAME_WIDTH - len(name) + GAP) # padded by the plain length: the style codes show nothing
75
+ lines += [""] + [((left if row == 0 else " " * RIGHT) + line).rstrip() for row, line in enumerate(right)]
76
+ lines += ["", MORE_NOTE.format(_style("imagent <command> --help", BOLD))]
77
+ return "\n".join(lines)
78
+
79
+
80
+ def main() -> None:
81
+ make_output_safe()
82
+ print(render())