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/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """modelmap: find local LLM model files and draw them as a treemap."""
2
+
3
+ __version__ = "0.1.0"
modelmap/__main__.py ADDED
@@ -0,0 +1,7 @@
1
+ """Run ``python -m modelmap``."""
2
+
3
+ import sys
4
+
5
+ from modelmap.cli import main
6
+
7
+ sys.exit(main())
modelmap/cli.py ADDED
@@ -0,0 +1,430 @@
1
+ """The ``modelmap`` command.
2
+
3
+ ``modelmap scan`` scan and print a summary, or the inventory as JSON
4
+ ``modelmap list`` scan, or read an inventory, and print every model
5
+ ``modelmap map`` scan, or read an inventory, and write the treemap
6
+ ``modelmap providers`` show where each store is looked for on this machine
7
+ ``modelmap rm`` remove models, after showing what goes and asking
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import os
14
+ import sys
15
+ import webbrowser
16
+ from collections.abc import Callable, Iterable, Sequence
17
+ from pathlib import Path
18
+ from typing import Any, TextIO
19
+
20
+ from modelmap import __version__
21
+ from modelmap.providers import PROVIDERS
22
+ from modelmap.providers.base import Context
23
+ from modelmap.records import ModelRecord, Scan
24
+ from modelmap.removal import TRASH_NOTE, Plan, execute, find, plan
25
+ from modelmap.render_html import render_html
26
+ from modelmap.render_svg import DISPLAY_NAMES, render_svg
27
+ from modelmap.scanner import Options, redact, scan
28
+ from modelmap.units import format_count, format_size, parse_size
29
+
30
+ _SORTS: dict[str, Callable[[ModelRecord], Any]] = {
31
+ "size": lambda r: (-r.size_bytes, r.name),
32
+ "name": lambda r: r.name.lower(),
33
+ "params": lambda r: (-(r.params or 0), r.name),
34
+ "mtime": lambda r: (-(r.mtime or 0), r.name),
35
+ }
36
+ _GROUPS = ("provider", "format", "family", "kind", "none")
37
+
38
+
39
+ def _text(value: object) -> str:
40
+ """Text safe to print: a name that is not valid UTF-8 is escaped."""
41
+ return str(value).encode("utf-8", "backslashreplace").decode("utf-8")
42
+
43
+
44
+ def _table(rows: Iterable[Sequence[str]], right: Sequence[int] = ()) -> list[str]:
45
+ """Align rows into columns; ``right`` lists the right-aligned columns."""
46
+ rows = [[_text(cell) for cell in row] for row in rows]
47
+ if not rows:
48
+ return []
49
+ widths = [max(len(row[i]) for row in rows) for i in range(len(rows[0]))]
50
+ lines = []
51
+ for row in rows:
52
+ cells = [
53
+ cell.rjust(width) if i in right else cell.ljust(width)
54
+ for i, (cell, width) in enumerate(zip(row, widths))
55
+ ]
56
+ lines.append(" ".join(cells).rstrip())
57
+ return lines
58
+
59
+
60
+ def _size(record: ModelRecord) -> str:
61
+ """Size, or who was charged when the record shares all its files."""
62
+ if record.size_bytes == 0 and record.shared_with:
63
+ return "shared"
64
+ return format_size(record.size_bytes)
65
+
66
+
67
+ def _notes(record: ModelRecord) -> str:
68
+ notes = []
69
+ if record.aliases:
70
+ notes.append("also " + ", ".join(record.aliases))
71
+ if record.shared_with:
72
+ notes.append("shared with " + ", ".join(record.shared_with))
73
+ if record.kind != "model":
74
+ notes.append(record.kind)
75
+ notes += [f"! {issue}" for issue in record.issues]
76
+ return "; ".join(notes)
77
+
78
+
79
+ def _print_list(scan_result: Scan, args: argparse.Namespace, out: TextIO) -> None:
80
+ records = [r for r in scan_result.records if args.all or r.kind in ("model", "auxiliary")]
81
+ records.sort(key=_SORTS[args.sort])
82
+ groups: dict[str, list[ModelRecord]] = {}
83
+ for record in records:
84
+ key = "" if args.group == "none" else str(getattr(record, args.group) or "unknown")
85
+ groups.setdefault(key, []).append(record)
86
+ header = ["SIZE", "PARAMS", "QUANT", "FORMAT", "PROVIDER", "NAME", "NOTES"]
87
+ for key in sorted(groups, key=lambda k: -sum(r.size_bytes for r in groups[k])):
88
+ members = groups[key]
89
+ if key:
90
+ total = format_size(sum(r.size_bytes for r in members))
91
+ print(f"\n{_text(key)} {total} {len(members)} records", file=out)
92
+ rows = [header] + [
93
+ [
94
+ _size(r),
95
+ format_count(r.params, r.params_exact),
96
+ r.quant or "",
97
+ r.format,
98
+ r.provider,
99
+ r.name,
100
+ _notes(r),
101
+ ]
102
+ for r in members
103
+ ]
104
+ print("\n".join(_table(rows, right=(0, 1))), file=out)
105
+ hidden = len(scan_result.records) - len(records)
106
+ if hidden:
107
+ print(f"\n{hidden} datasets, caches and other entries not shown; use --all", file=out)
108
+
109
+
110
+ def _print_summary(scan_result: Scan, out: TextIO) -> None:
111
+ by_provider: dict[str, list[ModelRecord]] = {}
112
+ for record in scan_result.records:
113
+ by_provider.setdefault(record.provider, []).append(record)
114
+ rows = [["PROVIDER", "SIZE", "ON DISK", "MODELS", "OTHER", "ISSUES"]]
115
+ for provider, records in sorted(
116
+ by_provider.items(), key=lambda kv: -sum(r.size_bytes for r in kv[1])
117
+ ):
118
+ models = sum(1 for r in records if r.kind in ("model", "auxiliary"))
119
+ rows.append(
120
+ [
121
+ provider,
122
+ format_size(sum(r.size_bytes for r in records)),
123
+ format_size(sum(r.disk_bytes for r in records)),
124
+ str(models),
125
+ str(len(records) - models),
126
+ str(sum(1 for r in records if r.issues)),
127
+ ]
128
+ )
129
+ rows.append(
130
+ [
131
+ "total",
132
+ format_size(scan_result.size_bytes),
133
+ format_size(scan_result.disk_bytes),
134
+ str(sum(1 for r in scan_result.records if r.kind in ("model", "auxiliary"))),
135
+ "",
136
+ "",
137
+ ]
138
+ )
139
+ print("\n".join(_table(rows, right=(1, 2, 3, 4, 5))), file=out)
140
+ roots = sum(1 for r in scan_result.roots if r.exists)
141
+ print(f"\n{roots} locations scanned in {scan_result.elapsed_s:.1f} s", file=out)
142
+ for warning in scan_result.warnings:
143
+ print(_text(f"warning: {warning.path}: {warning.message}".replace(": :", ":")), file=out)
144
+
145
+
146
+ def _print_providers(ctx: Context, out: TextIO) -> None:
147
+ rows = [["PROVIDER", "FOUND", "FROM", "PATH"]]
148
+ for provider in PROVIDERS:
149
+ for root in provider.roots(ctx):
150
+ path = root.path if root.resolved == root.path else f"{root.path} -> {root.resolved}"
151
+ rows.append([provider.NAME, "yes" if root.exists else "no", root.source, path])
152
+ print("\n".join(_table(rows)), file=out)
153
+
154
+
155
+ def _size_arg(text: str) -> int:
156
+ try:
157
+ return parse_size(text)
158
+ except ValueError as exc:
159
+ raise argparse.ArgumentTypeError(str(exc)) from None
160
+
161
+
162
+ def _parser() -> argparse.ArgumentParser:
163
+ what = argparse.ArgumentParser(add_help=False)
164
+ what.add_argument("paths", nargs="*", metavar="PATH", help="files or directories to scan")
165
+ what.add_argument(
166
+ "--only", metavar="NAMES", help="comma-separated providers to run, for example hf,ollama"
167
+ )
168
+ what.add_argument(
169
+ "--no-defaults", action="store_true", help="scan only the given paths, not the known stores"
170
+ )
171
+ what.add_argument(
172
+ "--no-sweep", action="store_true", help="do not sweep the home directory for loose models"
173
+ )
174
+ what.add_argument(
175
+ "--exclude",
176
+ action="append",
177
+ default=[],
178
+ metavar="GLOB",
179
+ help="skip matching files and directories",
180
+ )
181
+ what.add_argument(
182
+ "--min-size",
183
+ type=_size_arg,
184
+ default=Options.min_size,
185
+ metavar="SIZE",
186
+ help="smallest checkpoint to list when only its extension says it is a model (default 50MB)",
187
+ )
188
+ what.add_argument(
189
+ "--max-depth", type=int, metavar="N", help="levels to descend below each given path"
190
+ )
191
+ what.add_argument(
192
+ "--redact",
193
+ action="store_true",
194
+ help="replace the home directory with ~ and drop the host name",
195
+ )
196
+ what.add_argument(
197
+ "--strict", action="store_true", help="exit with status 1 if anything could not be read"
198
+ )
199
+
200
+ parser = argparse.ArgumentParser(
201
+ prog="modelmap", description="Find local LLM model files and report them by size."
202
+ )
203
+ parser.add_argument("--version", action="version", version=f"modelmap {__version__}")
204
+ commands = parser.add_subparsers(dest="command", required=True)
205
+
206
+ scan_cmd = commands.add_parser("scan", parents=[what], help="scan and print a summary")
207
+ scan_cmd.add_argument("--json", action="store_true", help="print the inventory as JSON")
208
+
209
+ list_cmd = commands.add_parser("list", parents=[what], help="print every model found")
210
+ list_cmd.add_argument(
211
+ "--from-json", metavar="FILE", help="read an inventory instead of scanning"
212
+ )
213
+ list_cmd.add_argument("--sort", choices=sorted(_SORTS), default="size")
214
+ list_cmd.add_argument("--group", choices=_GROUPS, default="provider")
215
+ list_cmd.add_argument(
216
+ "--all", action="store_true", help="include datasets, caches and other entries"
217
+ )
218
+
219
+ map_cmd = commands.add_parser("map", parents=[what], help="write the treemap")
220
+ map_cmd.add_argument(
221
+ "--from-json", metavar="FILE", help="read an inventory instead of scanning"
222
+ )
223
+ map_cmd.add_argument(
224
+ "-o", "--output", metavar="FILE", help="file to write (default modelmap.html or .svg)"
225
+ )
226
+ map_cmd.add_argument(
227
+ "--svg", action="store_true", help="write a static picture, not the interactive page"
228
+ )
229
+ map_cmd.add_argument(
230
+ "--disk", action="store_true", help="size tiles by space allocated on disk, not file size"
231
+ )
232
+ map_cmd.add_argument("--open", action="store_true", help="open the result in a browser")
233
+
234
+ commands.add_parser("providers", help="show where each store is looked for")
235
+
236
+ rm_cmd = commands.add_parser(
237
+ "rm",
238
+ help="remove models, after showing what goes and asking",
239
+ description=(
240
+ "Remove models. Each TARGET is provider:name as `modelmap list` shows it, an "
241
+ "Ollama tag, or a path. Ollama models and Hugging Face cache repositories are "
242
+ "removed with the tool's own command; anything else moves to the Trash."
243
+ ),
244
+ )
245
+ rm_cmd.add_argument("targets", nargs="+", metavar="TARGET", help="what to remove")
246
+ rm_cmd.add_argument("--dry-run", action="store_true", help="show what would go; remove nothing")
247
+ rm_cmd.add_argument("-y", "--yes", action="store_true", help="do not ask before removing")
248
+ return parser
249
+
250
+
251
+ def _scan(args: argparse.Namespace, ctx: Context) -> Scan:
252
+ options = Options(
253
+ paths=args.paths,
254
+ only=args.only.split(",") if args.only else None,
255
+ defaults=not args.no_defaults,
256
+ sweep=False if args.no_sweep else None,
257
+ excludes=args.exclude,
258
+ min_size=args.min_size,
259
+ max_depth=args.max_depth,
260
+ )
261
+ result = scan(ctx, options)
262
+ return redact(result, ctx.home) if args.redact else result
263
+
264
+
265
+ def _write_map(result: Scan, args: argparse.Namespace, out: TextIO) -> None:
266
+ text = (
267
+ render_svg(result, use_disk=args.disk)
268
+ if args.svg
269
+ else render_html(result, use_disk=args.disk)
270
+ )
271
+ path = os.path.abspath(args.output or ("modelmap.svg" if args.svg else "modelmap.html"))
272
+ # Names that are not valid UTF-8 were replaced when the text was built.
273
+ with open(path, "w", encoding="utf-8") as fh:
274
+ fh.write(text)
275
+ print(f"Wrote {_text(path)}", file=out)
276
+ if args.open:
277
+ webbrowser.open(Path(path).as_uri())
278
+
279
+
280
+ def _describe_plan(step: Plan, out: TextIO) -> None:
281
+ record = step.record
282
+ store = DISPLAY_NAMES.get(record.provider, record.provider)
283
+ print(f" {_text(record.name)} ({store}, {format_size(record.size_bytes)})", file=out)
284
+ if step.action == "trash":
285
+ for path in step.paths: # all of them: this is what the question asks about
286
+ print(f" {_text(path)}", file=out)
287
+ else:
288
+ print(f" {_text(record.path)}", file=out)
289
+ print(f" {_text(step.note)}", file=out)
290
+
291
+
292
+ def _remove(
293
+ args: argparse.Namespace, ctx: Context, out: TextIO, ask: Callable[[str], str] | None
294
+ ) -> int:
295
+ """The ``rm`` command. Nothing is removed that was not listed first."""
296
+ paths = []
297
+ for target in args.targets:
298
+ found = os.path.expanduser(target)
299
+ if os.path.lexists(found):
300
+ # A hub repository is read with its cache, which names it.
301
+ prefix = os.path.basename(found.rstrip(os.sep)).partition("--")[0]
302
+ hub_repo = prefix in ("models", "datasets", "spaces") and "--" in found
303
+ paths.append(os.path.dirname(found.rstrip(os.sep)) if hub_repo else found)
304
+ result = scan(ctx, Options(paths=paths, sweep=True))
305
+ chosen: list[ModelRecord] = []
306
+ for target in args.targets:
307
+ matches = find(result.records, target)
308
+ if not matches:
309
+ print(f"No model matches {_text(target)}. `modelmap list` shows the names.", file=out)
310
+ return 1
311
+ if len(matches) > 1:
312
+ print(
313
+ f"{_text(target)} matches {len(matches)} entries; name one by its path:", file=out
314
+ )
315
+ for match in matches:
316
+ print(f" {_text(match.path)}", file=out)
317
+ return 1
318
+ if matches[0] not in chosen:
319
+ chosen.append(matches[0])
320
+
321
+ live = [r.resolved for r in result.roots if r.provider == "ollama" and r.source != "layout"]
322
+ steps = [plan(record, live, env=ctx.env, home=str(ctx.home)) for record in chosen]
323
+ if args.yes:
324
+ # A tag with settings of its own goes only if it was asked for by name.
325
+ typed = set(args.targets)
326
+ for n, step in enumerate(steps):
327
+ unnamed = [tag for tag in step.variants if tag not in typed]
328
+ if unnamed:
329
+ steps[n] = Plan(
330
+ step.record,
331
+ "refuse",
332
+ f"{step.note} With --yes, name each of these tags to remove it: "
333
+ f"{', '.join(unnamed)}.",
334
+ )
335
+ refused = [step for step in steps if step.action == "refuse"]
336
+ total = sum(step.record.size_bytes for step in steps)
337
+ heading = "Would remove" if args.dry_run else "Will remove"
338
+ count = len(steps)
339
+ print(
340
+ f"{heading} {count} {'entry' if count == 1 else 'entries'}, {format_size(total)}:", file=out
341
+ )
342
+ for step in steps:
343
+ print(file=out)
344
+ _describe_plan(step, out)
345
+ if refused:
346
+ print(f"\nNothing was removed: {len(refused)} of these cannot be removed.", file=out)
347
+ return 1
348
+ if args.dry_run:
349
+ print("\nNothing was removed (--dry-run).", file=out)
350
+ return 0
351
+ if not args.yes:
352
+ if ask is None:
353
+ if not sys.stdin.isatty():
354
+ print("\nNothing was removed: add --yes to remove without asking.", file=out)
355
+ return 1
356
+ ask = input
357
+ print(file=out)
358
+ out.flush()
359
+ if ask("Remove? [y/N] ").strip().lower() not in ("y", "yes"):
360
+ print("Nothing was removed.", file=out)
361
+ return 1
362
+
363
+ failed = 0
364
+ for step in steps:
365
+ done, problem = execute(step, ctx.env)
366
+ name = _text(step.record.name)
367
+ if done:
368
+ print(f"Removed {name}.", file=out)
369
+ else:
370
+ failed += 1
371
+ print(f"Could not remove {name}: {_text(problem)}", file=out)
372
+ if any(step.action == "trash" for step in steps) and failed < count:
373
+ print(TRASH_NOTE, file=out)
374
+ return 1 if failed else 0
375
+
376
+
377
+ def main(
378
+ argv: Sequence[str] | None = None,
379
+ ctx: Context | None = None,
380
+ out: TextIO | None = None,
381
+ ask: Callable[[str], str] | None = None,
382
+ ) -> int:
383
+ """Run the command line.
384
+
385
+ :param argv: Arguments; ``sys.argv[1:]`` by default.
386
+ :param ctx: The machine to scan; the running one by default.
387
+ :param out: Where to print; standard output by default.
388
+ :param ask: Asks the person a question and returns the answer; the
389
+ terminal by default, and only when standard input is one.
390
+ :return: Exit status.
391
+ """
392
+ parser = _parser()
393
+ args = parser.parse_args(argv)
394
+ ctx = ctx or Context.current()
395
+ out = out or sys.stdout
396
+ if args.command == "providers":
397
+ _print_providers(ctx, out)
398
+ return 0
399
+ if args.command == "rm":
400
+ return _remove(args, ctx, out, ask)
401
+ if args.no_defaults and not args.paths and not getattr(args, "from_json", None):
402
+ parser.error("--no-defaults needs at least one PATH to scan")
403
+ if args.command in ("list", "map") and args.from_json:
404
+ # An inventory is read as it is. It does not say what the home
405
+ # directory was, so it cannot be redacted here, only when it is made.
406
+ scanning = args.paths or args.only or args.no_sweep or args.exclude or args.redact
407
+ if scanning or args.max_depth is not None:
408
+ parser.error("--from-json reads an inventory as it is: give no PATH or scan options")
409
+ try:
410
+ with open(args.from_json, encoding="utf-8") as fh:
411
+ result = Scan.from_json(fh.read())
412
+ except (OSError, ValueError) as exc:
413
+ parser.error(f"cannot read inventory {args.from_json}: {exc}")
414
+ else:
415
+ result = _scan(args, ctx)
416
+
417
+ if args.command == "list":
418
+ _print_list(result, args, out)
419
+ elif args.command == "map":
420
+ _write_map(result, args, out)
421
+ elif args.json:
422
+ print(result.to_json(), file=out)
423
+ else:
424
+ _print_summary(result, out)
425
+ unreadable = result.warnings or any(r.issues for r in result.records)
426
+ return 1 if args.strict and unreadable else 0
427
+
428
+
429
+ if __name__ == "__main__":
430
+ sys.exit(main())