modelmap 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.
modelmap/removal.py ADDED
@@ -0,0 +1,365 @@
1
+ """Removing a record: what would go, and doing it once confirmed.
2
+
3
+ Nothing leaves the disk that the plan did not list. A plan is one of:
4
+
5
+ - ``tool``: the store's own tool removes the record. In Ollama and the
6
+ Hugging Face cache the model is the unit of deletion, and deleting a blob
7
+ by hand leaves manifests or links pointing at nothing. The syntax was read
8
+ from ``ollama rm --help`` (Ollama 0.40) and ``hf cache rm --help`` (hf
9
+ 2.4.0), and the ``hf`` forms were run with ``--dry-run`` on a real cache.
10
+ - ``trash``: the record's files, or its folder, move to the Trash. A folder
11
+ moves whole only when every entry in it is one of the record's files;
12
+ otherwise the listed files move one by one and the rest stays.
13
+ - ``refuse``: nothing is done, and the note says why.
14
+
15
+ Paths to move are built from the record's folder and each file's label,
16
+ never from a resolved path: a file reached through a symlink must not take
17
+ the other store's file with it. A record whose files are used by another
18
+ record is refused for the same reason.
19
+
20
+ ``ollama rm`` has no store argument; it acts on the running Ollama. It is
21
+ offered only for records in the Ollama provider's own store, and only for
22
+ tags the running Ollama lists.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import os
28
+ import shlex
29
+ import shutil
30
+ import subprocess
31
+ from collections.abc import Collection, Mapping, Sequence
32
+ from dataclasses import dataclass, field
33
+
34
+ from modelmap.providers import ollama
35
+ from modelmap.records import ModelRecord
36
+
37
+ _HUB_TYPES = {"models": "model", "datasets": "dataset", "spaces": "space"}
38
+ TRASH_NOTE = "Moved to the Trash: the space is freed when the Trash is emptied."
39
+
40
+
41
+ @dataclass
42
+ class Plan:
43
+ """What removing a record would do.
44
+
45
+ :param record: The record.
46
+ :param action: ``tool``, ``trash`` or ``refuse``.
47
+ :param note: One sentence for a person: what happens, or why not.
48
+ :param argv: The command a ``tool`` plan runs.
49
+ :param paths: The files or folder a ``trash`` plan moves.
50
+ :param variants: Ollama tags removed with the record that share its
51
+ weights but differ in their settings; some may have been made with
52
+ ``ollama create``, and those settings cannot be pulled again.
53
+ """
54
+
55
+ record: ModelRecord
56
+ action: str
57
+ note: str
58
+ argv: list[str] = field(default_factory=list)
59
+ paths: list[str] = field(default_factory=list)
60
+ variants: list[str] = field(default_factory=list)
61
+
62
+
63
+ def _refuse(record: ModelRecord, note: str) -> Plan:
64
+ return Plan(record, "refuse", note)
65
+
66
+
67
+ def _shared_store(path: str) -> str | None:
68
+ """The hub cache a shared-blob path belongs to, or None."""
69
+ parts = path.split(os.sep)
70
+ if "blobs" in parts[-3:] and not any("--" in part for part in parts[-4:]):
71
+ return os.sep.join(parts[: len(parts) - parts[::-1].index("blobs") - 1])
72
+ return None
73
+
74
+
75
+ def _which(command: str, env: Mapping[str, str] | None) -> str | None:
76
+ """A command on the ``PATH`` of ``env``; never the process's own PATH."""
77
+ path = (env or {}).get("PATH")
78
+ return shutil.which(command, path=path) if path else None
79
+
80
+
81
+ def trash_command(env: Mapping[str, str] | None) -> list[str] | None:
82
+ """The command that moves files to the Trash, or None if there is none.
83
+
84
+ macOS has ``/usr/bin/trash``; on Linux the ``trash`` of trash-cli or
85
+ ``gio trash`` from GLib.
86
+ """
87
+ found = _which("trash", env)
88
+ if found:
89
+ return [found]
90
+ gio = _which("gio", env)
91
+ return [gio, "trash"] if gio else None
92
+
93
+
94
+ def _ollama_tags(env: Mapping[str, str] | None) -> set[str] | None:
95
+ """Tags the running Ollama lists, or None if it cannot be asked."""
96
+ ollama = _which("ollama", env)
97
+ if not ollama:
98
+ return None
99
+ try:
100
+ result = subprocess.run(
101
+ [ollama, "list"], env=dict(env or {}), capture_output=True, text=True, timeout=30
102
+ )
103
+ except (OSError, subprocess.SubprocessError):
104
+ return None
105
+ if result.returncode != 0:
106
+ return None
107
+ lines = result.stdout.splitlines()[1:]
108
+ return {line.split()[0] for line in lines if line.strip()}
109
+
110
+
111
+ def _inside(path: str, folder: str) -> bool:
112
+ return os.path.commonpath([path, folder]) == folder
113
+
114
+
115
+ def _unlisted(folder: str, listed: set[str]) -> str | None:
116
+ """The first entry under ``folder`` that is not a listed file, or None."""
117
+ blocked: list[str] = []
118
+
119
+ def note_error(error: OSError) -> None:
120
+ blocked.append(str(error.filename))
121
+
122
+ for dirpath, dirnames, filenames in os.walk(folder, onerror=note_error):
123
+ dirnames.sort()
124
+ for name in dirnames:
125
+ if os.path.islink(os.path.join(dirpath, name)):
126
+ return os.path.join(dirpath, name) # a link to a folder: not walked
127
+ for name in sorted(filenames):
128
+ if os.path.join(dirpath, name) not in listed:
129
+ return os.path.join(dirpath, name)
130
+ if blocked:
131
+ return blocked[0]
132
+ return blocked[0] if blocked else None
133
+
134
+
135
+ def _is_model_folder(record: ModelRecord) -> bool:
136
+ """A record that is a whole model folder, not a group of loose files.
137
+
138
+ A model folder's own files include its ``config.json`` or
139
+ ``model_index.json``; a group of loose shards never does.
140
+ """
141
+ return any(e.label in ("config.json", "model_index.json") for e in record.file_list)
142
+
143
+
144
+ def _trash_paths(record: ModelRecord, home: str) -> tuple[list[str], str]:
145
+ """The paths a ``trash`` plan moves, or an empty list and the reason.
146
+
147
+ A model folder moves whole or not at all: moving its listed files out of
148
+ a folder that holds more (a git checkout, code) would leave a broken
149
+ working tree. Loose files move one by one.
150
+ """
151
+ path = record.path
152
+ is_folder = os.path.isdir(path) and not os.path.islink(path)
153
+ base = path if is_folder else os.path.dirname(path)
154
+ if is_folder and base in (os.sep, home, os.path.realpath(home)):
155
+ return [], "The record's folder is the home folder or the disk's root."
156
+ listed = []
157
+ for entry in record.file_list:
158
+ target = os.path.normpath(os.path.join(base, entry.label))
159
+ if not _inside(target, base) or target == base:
160
+ return [], f"The file {entry.label} is not inside {base}."
161
+ if not os.path.lexists(target):
162
+ return [], f"The file {target} is no longer there. Scan again."
163
+ if os.path.isdir(target) and not os.path.islink(target):
164
+ return [], f"{target} is a folder, not one of the record's files."
165
+ listed.append(target)
166
+ if is_folder and _is_model_folder(record):
167
+ extra = _unlisted(base, set(listed))
168
+ if extra:
169
+ return [], (
170
+ f"The folder also holds {extra}, which is not part of the model. Move the "
171
+ "model's files yourself, or the folder if you mean all of it."
172
+ )
173
+ return [base], ""
174
+ return listed, ""
175
+
176
+
177
+ def plan(
178
+ record: ModelRecord,
179
+ ollama_stores: Collection[str] = (),
180
+ *,
181
+ env: Mapping[str, str] | None = None,
182
+ check_disk: bool = True,
183
+ home: str = "~",
184
+ ) -> Plan:
185
+ """Work out how a record would be removed.
186
+
187
+ :param record: The record.
188
+ :param ollama_stores: Resolved directories of the running Ollama's
189
+ stores, as the Ollama provider found them.
190
+ :param env: Environment whose ``PATH`` is searched for ``hf``,
191
+ ``ollama`` and the Trash command.
192
+ :param check_disk: Look at the disk and ask the tools. False to describe
193
+ the plan only, as in a page made from an inventory.
194
+ :param home: The home folder of the machine scanned; never moved whole.
195
+ """
196
+ name, path = record.name, record.path
197
+ # A store's own tool handles sharing inside the store. A user in another
198
+ # store (a loose file linked into this one) would be left broken.
199
+ outside = sorted(
200
+ {
201
+ user
202
+ for entry in record.file_list
203
+ for user in entry.used_by
204
+ if user.partition(":")[0] != record.provider
205
+ }
206
+ )
207
+ if record.kind == "cache":
208
+ return _refuse(record, "A cache: the tool that owns it rebuilds it when needed.")
209
+ hub = _shared_store(path) if record.provider in ("hf", "llamacpp") else None
210
+ if hub:
211
+ prune = shlex.join(["hf", "cache", "prune", "--cache-dir", hub])
212
+ return _refuse(
213
+ record,
214
+ f"No repository refers to this. `{prune}` removes it, together with everything "
215
+ "else in the cache that nothing refers to; run it with --dry-run first.",
216
+ )
217
+ if record.kind == "unattributed":
218
+ return _refuse(record, "Nothing refers to these files. modelmap does not remove them.")
219
+
220
+ base = os.path.basename(path)
221
+ repo_type = _HUB_TYPES.get(base.partition("--")[0]) if "--" in base else None
222
+ if outside and (repo_type or record.provider == "ollama"):
223
+ return _refuse(
224
+ record,
225
+ f"{', '.join(outside)} {'uses' if len(outside) == 1 else 'use'} files of this one "
226
+ "through a link, and would break.",
227
+ )
228
+ if repo_type:
229
+ argv = ["hf", "cache", "rm", f"{repo_type}/{name}", "--cache-dir", os.path.dirname(path)]
230
+ if check_disk and not _which("hf", env):
231
+ return _refuse(record, "The hf command is needed to remove this, and it is not found.")
232
+ return Plan(
233
+ record,
234
+ "tool",
235
+ f"Runs `{shlex.join(argv)}`: removes the repository from the Hugging Face cache.",
236
+ [*argv, "--yes"],
237
+ )
238
+
239
+ if record.provider == "ollama":
240
+ live = any(path == s or path.startswith(s + os.sep) for s in ollama_stores)
241
+ if not live:
242
+ return _refuse(
243
+ record,
244
+ "This Ollama store is not the one the Ollama on this machine uses, and "
245
+ "`ollama rm` acts only on that one. Delete the store's folder yourself "
246
+ "if you no longer need it.",
247
+ )
248
+ tags = [name, *record.aliases]
249
+ argv = ["ollama", "rm", *tags]
250
+ own: list[str] = []
251
+ if check_disk:
252
+ listed = _ollama_tags(env)
253
+ if listed is None:
254
+ return _refuse(record, "Ollama is not running, or the ollama command is not found.")
255
+ missing = [tag for tag in tags if tag not in listed]
256
+ if missing:
257
+ return _refuse(
258
+ record,
259
+ f"The running Ollama does not list {', '.join(missing)}. It may use another "
260
+ "store than the one scanned.",
261
+ )
262
+ store = next(s for s in ollama_stores if path == s or path.startswith(s + os.sep))
263
+ own = [tag for tag in tags if tag in ollama.variants(store, name) or tag == name]
264
+ own = own if len(own) > 1 else []
265
+ what = "every tag of these weights" if record.aliases else "the model"
266
+ note = f"Runs `{shlex.join(argv)}`: removes {what} from Ollama."
267
+ if own:
268
+ note += (
269
+ f" These tags share the weights but differ in their settings: {', '.join(own)}. "
270
+ "Settings made with `ollama create` are lost and cannot be pulled again."
271
+ )
272
+ return Plan(record, "tool", note, argv, variants=own)
273
+
274
+ shared = sorted({user for entry in record.file_list for user in entry.used_by})
275
+ if shared and not any(entry.charged for entry in record.file_list):
276
+ return _refuse(
277
+ record,
278
+ f"This is another name for files of {', '.join(shared)}: removing it would free "
279
+ "nothing. Remove that instead.",
280
+ )
281
+ if shared:
282
+ return _refuse(
283
+ record,
284
+ f"Some of its files are also used by {', '.join(shared)}. Removing them would "
285
+ "break those too.",
286
+ )
287
+ if not record.file_list:
288
+ return _refuse(record, "The record has no files.")
289
+ if not check_disk:
290
+ return Plan(record, "trash", "Moves its files to the Trash.")
291
+ if not trash_command(env):
292
+ return _refuse(record, "No command to move files to the Trash was found.")
293
+ paths, reason = _trash_paths(record, os.path.expanduser(home))
294
+ if not paths:
295
+ return _refuse(record, reason)
296
+ if paths == [path] and os.path.isdir(path):
297
+ note = f"Moves the folder, with its {len(record.file_list)} files, to the Trash."
298
+ else:
299
+ count = len(paths)
300
+ note = f"Moves {'the file' if count == 1 else f'{count} files'} to the Trash."
301
+ return Plan(record, "trash", note, paths=paths)
302
+
303
+
304
+ def find(records: Sequence[ModelRecord], target: str) -> list[ModelRecord]:
305
+ """The records a target names: ``provider:name``, a path, or a name.
306
+
307
+ An Ollama tag names the record it is an alias of. Several matches mean
308
+ the target is ambiguous.
309
+ """
310
+ exact = [
311
+ r
312
+ for r in records
313
+ if target in (f"{r.provider}:{r.name}", *(f"{r.provider}:{a}" for a in r.aliases))
314
+ ]
315
+ if exact:
316
+ return exact
317
+ if os.path.lexists(os.path.expanduser(target)):
318
+ wanted = os.path.realpath(os.path.expanduser(target))
319
+ by_path = [r for r in records if os.path.realpath(r.path) == wanted]
320
+ if by_path:
321
+ return by_path
322
+ return [r for r in records if target == r.name or target in r.aliases]
323
+
324
+
325
+ def target_of(record: ModelRecord, records: Sequence[ModelRecord]) -> str:
326
+ """The shortest target that names this record and no other."""
327
+ label = f"{record.provider}:{record.name}"
328
+ clashes = [r for r in records if r is not record and find([r], label)]
329
+ return record.path if clashes else label
330
+
331
+
332
+ def execute(plan: Plan, env: Mapping[str, str] | None) -> tuple[bool, str]:
333
+ """Carry out a ``tool`` or ``trash`` plan and check that it worked.
334
+
335
+ :return: Whether the record's files are gone, and what went wrong if not.
336
+ """
337
+ if plan.action == "tool":
338
+ command = [_which(plan.argv[0], env) or plan.argv[0], *plan.argv[1:]]
339
+ elif plan.action == "trash":
340
+ trash = trash_command(env)
341
+ if not trash:
342
+ return False, "No command to move files to the Trash was found."
343
+ command = [*trash, *plan.paths]
344
+ else:
345
+ return False, plan.note
346
+ try:
347
+ result = subprocess.run(
348
+ command, env=dict(env or {}), capture_output=True, text=True, timeout=600
349
+ )
350
+ except (OSError, subprocess.SubprocessError) as exc:
351
+ return False, str(exc)
352
+ output = (result.stderr or result.stdout).strip().splitlines()
353
+ detail = output[-1] if output else f"exit status {result.returncode}"
354
+ if result.returncode != 0:
355
+ return False, detail
356
+
357
+ if plan.action == "trash":
358
+ left = [path for path in plan.paths if os.path.lexists(path)]
359
+ return (not left, f"Still there: {', '.join(left)}" if left else "")
360
+ if plan.argv[0] == "ollama":
361
+ tags = _ollama_tags(env) or set()
362
+ left = [tag for tag in plan.argv[2:] if tag in tags]
363
+ return (not left, f"Ollama still lists {', '.join(left)}" if left else "")
364
+ gone = not os.path.lexists(plan.record.path)
365
+ return (gone, "" if gone else f"Still there: {plan.record.path}")