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.
@@ -0,0 +1,235 @@
1
+ """The Ollama model store.
2
+
3
+ Layout, from Ollama's source (``manifest/paths.go``, ``manifest/layer.go``,
4
+ ``envconfig/config.go`` at commit 924cc28) and a real 0.40 store:
5
+
6
+ - ``manifests/<host>/<namespace>/<model>/<tag>`` is a Docker v2 manifest:
7
+ JSON with a ``config`` descriptor and a ``layers`` list, each entry
8
+ ``{mediaType, digest, size}``. ``manifests-v2/`` is a newer tree with the
9
+ same shape that Ollama reads first; an entry there may be a manifest list
10
+ whose ``manifests`` are child manifests, inline or by digest.
11
+ - ``blobs/sha256-<hex>`` holds the content of digest ``sha256:<hex>``.
12
+ - ``metadata/`` caches GGUF header fields per blob and is regenerated on
13
+ demand.
14
+ - Weights are the ``model`` layers (several for a split GGUF) or, for a
15
+ safetensors model, one ``tensor`` layer per tensor. ``projector``,
16
+ ``adapter`` and ``draft`` layers are further weight files of the same
17
+ model. Template, params, license and system layers are small.
18
+
19
+ Several tags often point at one set of weights (``qwen3:8b`` and
20
+ ``qwen3:latest``; a tag made only to change the context length). Such tags
21
+ are one record, named for the first tag, with the rest as aliases, so the
22
+ map shows one tile per model actually on disk.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import json
28
+ import os
29
+ from pathlib import Path
30
+ from typing import Any
31
+
32
+ from modelmap.headers import sniff
33
+ from modelmap.providers.base import Context, Tally, files_under, listdir
34
+ from modelmap.providers.describe import Description, describe_gguf, guess_family
35
+ from modelmap.records import ModelRecord, ScanRoot
36
+
37
+ NAME = "ollama"
38
+ _PREFIX = "application/vnd.ollama.image."
39
+ _PRIMARY = (_PREFIX + "model", _PREFIX + "tensor")
40
+ _DEFAULT_HOSTS = ("registry.ollama.ai", "ollama.com")
41
+ # Read in this order; a tag found in both trees is taken from the first.
42
+ _MANIFEST_TREES = ("manifests-v2", "manifests")
43
+
44
+
45
+ def roots(ctx: Context) -> list[ScanRoot]:
46
+ """``OLLAMA_MODELS`` if set, else the per-user and service defaults.
47
+
48
+ The Linux installer runs Ollama as a service user whose home is
49
+ ``/usr/share/ollama``, so its models are not under the caller's home.
50
+ """
51
+ override = ctx.first_env("OLLAMA_MODELS")
52
+ if override:
53
+ return [ctx.root(NAME, ctx.expand(override[1]), override[0])]
54
+ found = [ctx.root(NAME, ctx.home / ".ollama" / "models", "default")]
55
+ if ctx.platform == "linux":
56
+ found.append(ctx.root(NAME, "/usr/share/ollama/.ollama/models", "default (service)"))
57
+ return found
58
+
59
+
60
+ def tag_name(parts: tuple[str, ...]) -> str:
61
+ """Turn a manifest path into the name ``ollama list`` shows.
62
+
63
+ ``registry.ollama.ai/library/qwen3/8b`` is ``qwen3:8b``; another
64
+ namespace keeps it (``user/model:tag``); another host keeps the host.
65
+ """
66
+ *repo, tag = parts
67
+ if repo:
68
+ # manifests-v2 writes a host's port separator as %3A.
69
+ repo[0] = repo[0].replace("%3A", ":").replace("%3a", ":")
70
+ if repo and repo[0].lower() in _DEFAULT_HOSTS:
71
+ repo = repo[1:]
72
+ if repo[:1] == ["library"]:
73
+ repo = repo[1:]
74
+ return f"{'/'.join(repo)}:{tag}"
75
+
76
+
77
+ def _layer_kind(layer: dict[str, Any]) -> str:
78
+ """What a blob is, from its media type: ``weights``, ``template``..."""
79
+ media = str(layer.get("mediaType", ""))
80
+ if media.startswith(_PREFIX):
81
+ kind = media[len(_PREFIX) :]
82
+ return "weights" if kind == "model" else kind
83
+ return "config" if "container.image" in media else "manifest"
84
+
85
+
86
+ def _blob(store: str, digest: str) -> str:
87
+ return os.path.join(store, "blobs", digest.replace(":", "-"))
88
+
89
+
90
+ def _load_json(path: str) -> Any:
91
+ with open(path, encoding="utf-8") as fh:
92
+ return json.load(fh)
93
+
94
+
95
+ def _layers(store: str, manifest: Any) -> list[dict[str, Any]]:
96
+ """Every blob descriptor a manifest, or a manifest list, refers to."""
97
+ found: list[dict[str, Any]] = []
98
+ for child in manifest.get("manifests") or []:
99
+ if "layers" not in child and "digest" in child:
100
+ # A child held by reference: the manifest itself is a blob.
101
+ found.append(child)
102
+ try:
103
+ child = _load_json(_blob(store, child["digest"]))
104
+ except (OSError, ValueError):
105
+ continue
106
+ found += _layers(store, child)
107
+ found += [layer for layer in manifest.get("layers") or [] if "digest" in layer]
108
+ config = manifest.get("config")
109
+ if isinstance(config, dict) and config.get("digest"):
110
+ found.append(config)
111
+ return found
112
+
113
+
114
+ def _read_manifests(ctx: Context, store: str) -> dict[str, list[tuple[str, list[dict[str, Any]]]]]:
115
+ """Group tags by their weights: ``{weights key: [(tag, descriptors)]}``."""
116
+ groups: dict[str, list[tuple[str, list[dict[str, Any]]]]] = {}
117
+ seen: set[str] = set()
118
+ for tree in _MANIFEST_TREES:
119
+ base = os.path.join(store, tree)
120
+ if not os.path.isdir(base):
121
+ continue
122
+ for path in files_under(ctx, base):
123
+ if os.path.basename(path).startswith("."):
124
+ continue
125
+ name = tag_name(tuple(os.path.relpath(path, base).split(os.sep)))
126
+ if name in seen:
127
+ continue
128
+ try:
129
+ layers = _layers(store, _load_json(path))
130
+ except (OSError, ValueError, AttributeError, TypeError) as exc:
131
+ ctx.warn(path, f"unreadable manifest: {exc}")
132
+ continue
133
+ seen.add(name)
134
+ weights = [d["digest"] for d in layers if d.get("mediaType") in _PRIMARY]
135
+ key = "+".join(weights) if weights else f"manifest:{name}"
136
+ groups.setdefault(key, []).append((name, layers))
137
+ return groups
138
+
139
+
140
+ def _describe(store: str, layers: list[dict[str, Any]]) -> tuple[Description, str | None]:
141
+ """Describe a model from its primary weight layers; also its main file."""
142
+ models = [_blob(store, d["digest"]) for d in layers if d.get("mediaType") == _PRIMARY[0]]
143
+ present = [p for p in models if os.path.exists(p)]
144
+ if present and all(sniff(p) == "gguf" for p in present):
145
+ return describe_gguf(present), present[0]
146
+ if any(d.get("mediaType") == _PRIMARY[1] for d in layers):
147
+ return Description(format="safetensors"), None
148
+ kind = sniff(present[0]) if present else None
149
+ return Description(format=kind or "unknown"), None
150
+
151
+
152
+ def variants(store: str, tag: str) -> list[str]:
153
+ """Tags sharing a tag's weights but not its other layers.
154
+
155
+ Such a tag is a model of its own, usually made with ``ollama create`` to
156
+ change a setting such as the context length. Removing it loses that
157
+ setting, which cannot be pulled again.
158
+
159
+ :param store: Resolved Ollama models directory.
160
+ :param tag: Any tag of the group, as ``ollama list`` shows it.
161
+ :return: The other tags whose non-weight layers differ from ``tag``'s.
162
+ """
163
+ ctx = Context(home=Path(store), env={}, platform="")
164
+ for tags in _read_manifests(ctx, store).values():
165
+ names = {name: layers for name, layers in tags}
166
+ if tag not in names:
167
+ continue
168
+
169
+ def setting(layers: list[dict[str, Any]]) -> set[str]:
170
+ return {d["digest"] for d in layers if d.get("mediaType") not in _PRIMARY}
171
+
172
+ own = setting(names[tag])
173
+ return sorted(name for name, layers in tags if name != tag and setting(layers) != own)
174
+ return []
175
+
176
+
177
+ def scan(root: ScanRoot, ctx: Context) -> list[ModelRecord]:
178
+ """One record per unique set of weights, plus any unreferenced blobs."""
179
+ store = root.resolved
180
+ records = []
181
+ groups = _read_manifests(ctx, store)
182
+ for tags in sorted(groups.values(), key=lambda tags: min(tag for tag, _ in tags)):
183
+ tags.sort(key=lambda tag: tag[0])
184
+ name, first_layers = tags[0]
185
+ issues: list[str] = []
186
+ paths: list[str] = []
187
+ labels: dict[str, tuple[str, str]] = {}
188
+ for _, layers in tags:
189
+ for layer in layers:
190
+ path = _blob(store, layer["digest"])
191
+ if path in paths:
192
+ continue
193
+ if os.path.exists(path):
194
+ paths.append(path)
195
+ labels[path] = (_layer_kind(layer), "")
196
+ elif layer.get("mediaType", "").startswith(_PREFIX):
197
+ issues.append(
198
+ f"missing blob {layer['digest'][:19]} "
199
+ f"({layer.get('size', 'unknown')} bytes declared)"
200
+ )
201
+ tally = Tally()
202
+ tally.charge(ctx, f"{NAME}:{name}", paths, labels)
203
+ description, main = _describe(store, first_layers)
204
+ records.append(
205
+ tally.record(
206
+ issues=issues + description.issues,
207
+ name=name,
208
+ provider=NAME,
209
+ format=description.format,
210
+ path=main or store,
211
+ family=guess_family(name, description.architecture),
212
+ quant=description.quant,
213
+ params=description.params,
214
+ params_exact=description.params_exact,
215
+ aliases=[tag for tag, _ in tags[1:]],
216
+ )
217
+ )
218
+
219
+ orphans = Tally()
220
+ blobs = os.path.join(store, "blobs")
221
+ if os.path.isdir(blobs):
222
+ for entry in listdir(ctx, blobs):
223
+ if ctx.ledger.owner(entry.path) is None:
224
+ orphans.charge(ctx, f"{NAME}:unreferenced blobs", [entry.path])
225
+ if orphans.files:
226
+ records.append(
227
+ orphans.record(
228
+ name="unreferenced blobs",
229
+ provider=NAME,
230
+ format="files",
231
+ path=blobs,
232
+ kind="unattributed",
233
+ )
234
+ )
235
+ return records
@@ -0,0 +1,66 @@
1
+ """The oMLX model directories.
2
+
3
+ From oMLX's ``omlx/settings.py`` (commit 30a896a) and a real install:
4
+
5
+ - The base directory is ``OMLX_BASE_PATH``, else the path in the one-line
6
+ file ``~/Library/Application Support/oMLX/base-path`` that the macOS app
7
+ writes when the user moves its data, else ``~/.omlx``.
8
+ - Model directories are ``OMLX_MODEL_DIR`` (comma separated), else
9
+ ``model.model_dirs`` in ``<base>/settings.json``, else the deprecated
10
+ ``model.model_dir``, else ``<base>/models``.
11
+
12
+ Each model is a directory, optionally under an organization directory:
13
+ ``mlx-community/Qwen3-8B-4bit/`` with ``config.json`` and ``*.safetensors``.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ from pathlib import Path
20
+
21
+ from modelmap.providers.base import Context
22
+ from modelmap.providers.generic import scan_tree
23
+ from modelmap.records import ModelRecord, ScanRoot
24
+
25
+ NAME = "omlx"
26
+
27
+
28
+ def _base(ctx: Context) -> tuple[Path, str]:
29
+ override = ctx.first_env("OMLX_BASE_PATH")
30
+ if override:
31
+ return ctx.expand(override[1]), override[0]
32
+ bootstrap = ctx.home / "Library" / "Application Support" / "oMLX" / "base-path"
33
+ try:
34
+ moved = bootstrap.read_text(encoding="utf-8").strip()
35
+ except OSError:
36
+ moved = ""
37
+ if moved:
38
+ return ctx.expand(moved), "base-path"
39
+ return ctx.home / ".omlx", "default"
40
+
41
+
42
+ def roots(ctx: Context) -> list[ScanRoot]:
43
+ """The oMLX model directories, by the precedence in the module docstring."""
44
+ override = ctx.first_env("OMLX_MODEL_DIR")
45
+ if override:
46
+ dirs = [d.strip() for d in override[1].split(",") if d.strip()]
47
+ return [ctx.root(NAME, ctx.expand(d), override[0]) for d in dirs]
48
+
49
+ base, source = _base(ctx)
50
+ settings = base / "settings.json"
51
+ try:
52
+ model = json.loads(settings.read_text(encoding="utf-8")).get("model")
53
+ except (OSError, ValueError, AttributeError) as exc:
54
+ if settings.exists():
55
+ ctx.warn(settings, f"unreadable settings: {exc}")
56
+ model = None
57
+ if isinstance(model, dict):
58
+ dirs = model.get("model_dirs") or ([model["model_dir"]] if model.get("model_dir") else [])
59
+ if isinstance(dirs, list) and dirs:
60
+ return [ctx.root(NAME, ctx.expand(str(d)), "settings.json") for d in dirs]
61
+ return [ctx.root(NAME, base / "models", source)]
62
+
63
+
64
+ def scan(root: ScanRoot, ctx: Context) -> list[ModelRecord]:
65
+ """Every model directory under an oMLX model directory."""
66
+ return scan_tree(root.resolved, ctx, provider=NAME, max_depth=3, config_marks_model=True)
@@ -0,0 +1,160 @@
1
+ """Tools whose store is a plain tree of model files.
2
+
3
+ Each needs only a rule for where the tree is; the generic tree scanner
4
+ does the rest. Sources for the locations:
5
+
6
+ - LM Studio: ``findLMStudioHome.ts`` in lmstudio-js and ``lmstudioPaths.ts``
7
+ and ``importCmd.ts`` in the ``lms`` CLI. The home is the path in
8
+ ``~/.lmstudio-home-pointer``, else ``~/.cache/lm-studio`` if it exists
9
+ (installs older than 0.3.6), else ``~/.lmstudio``. Models are in the
10
+ ``downloadsFolder`` of ``<home>/settings.json``, else ``<home>/models``,
11
+ laid out ``publisher/model/file.gguf``.
12
+ - llama.cpp: ``fs_get_cache_directory`` in ``common/common.cpp`` and
13
+ ``get_cache_directory`` in ``common/hf-cache.cpp``. ``LLAMA_CACHE`` is
14
+ used as given. Otherwise flat files live in ``%LOCALAPPDATA%\\llama.cpp``,
15
+ ``~/Library/Caches/llama.cpp`` or ``$XDG_CACHE_HOME/llama.cpp``. Since
16
+ 2026-03 ``-hf`` downloads go to the Hugging Face hub cache instead, which
17
+ the ``hf`` provider reads; under ``LLAMA_CACHE`` the same hub layout
18
+ appears in this directory.
19
+ - GPT4All: the desktop settings documentation (download path) and
20
+ ``gpt4all.py`` in the Python bindings (``~/.cache/gpt4all``).
21
+ - Jan: the data-folder documentation and ``resolve_jan_data_folder`` in
22
+ ``src-tauri``: ``JAN_DATA_FOLDER``, else ``data_folder`` in
23
+ ``<data dir>/Jan/settings.json``, else ``<data dir>/Jan/data``. Models are
24
+ in ``llamacpp/models`` and ``mlx/models`` under the data folder.
25
+ - Whisper: ``load_model`` in ``whisper/__init__.py``.
26
+
27
+ Only llama.cpp's flat cache rule was checked against a local checkout. No
28
+ store for LM Studio, GPT4All, Jan or Whisper was on the development machine,
29
+ so these rest on the sources above and on fixtures.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import json
35
+ from collections.abc import Callable
36
+ from pathlib import Path
37
+ from typing import Any
38
+
39
+ from modelmap.providers import hf
40
+ from modelmap.providers.base import Context
41
+ from modelmap.providers.generic import scan_tree
42
+ from modelmap.records import ModelRecord, ScanRoot
43
+
44
+ Found = list[tuple[Path, str]]
45
+
46
+
47
+ class TreeStore:
48
+ """A provider whose models are found by walking a directory tree.
49
+
50
+ :param name: Provider name.
51
+ :param find: Returns ``(path, source)`` for each place to look.
52
+ :param options: Extra arguments for :func:`scan_tree`.
53
+ """
54
+
55
+ def __init__(self, name: str, find: Callable[[Context], Found], **options: Any) -> None:
56
+ self.NAME = name
57
+ self._find = find
58
+ self._options = options
59
+
60
+ def roots(self, ctx: Context) -> list[ScanRoot]:
61
+ return [ctx.root(self.NAME, path, source) for path, source in self._find(ctx)]
62
+
63
+ def scan(self, root: ScanRoot, ctx: Context) -> list[ModelRecord]:
64
+ return scan_tree(root.resolved, ctx, provider=self.NAME, **self._options)
65
+
66
+
67
+ def _data_dir(ctx: Context) -> Path:
68
+ """The per-user application data directory of the platform."""
69
+ if ctx.platform == "darwin":
70
+ return ctx.home / "Library" / "Application Support"
71
+ if ctx.platform == "win32":
72
+ return ctx.expand(ctx.env.get("APPDATA") or str(ctx.home / "AppData" / "Roaming"))
73
+ return ctx.expand(ctx.env.get("XDG_DATA_HOME") or str(ctx.home / ".local" / "share"))
74
+
75
+
76
+ def _cache_dir(ctx: Context) -> Path:
77
+ return ctx.expand(ctx.env.get("XDG_CACHE_HOME") or str(ctx.home / ".cache"))
78
+
79
+
80
+ def _lmstudio(ctx: Context) -> Found:
81
+ pointer = ctx.home / ".lmstudio-home-pointer"
82
+ try:
83
+ pointed = pointer.read_text(encoding="utf-8").strip()
84
+ except OSError:
85
+ pointed = ""
86
+ if pointed:
87
+ home, source = ctx.expand(pointed), pointer.name
88
+ else:
89
+ legacy = ctx.home / ".cache" / "lm-studio"
90
+ home, source = (
91
+ (legacy, "default (legacy)")
92
+ if legacy.is_dir()
93
+ else (
94
+ ctx.home / ".lmstudio",
95
+ "default",
96
+ )
97
+ )
98
+ try:
99
+ folder = json.loads((home / "settings.json").read_text(encoding="utf-8"))["downloadsFolder"]
100
+ except (OSError, ValueError, KeyError, TypeError):
101
+ folder = None
102
+ if isinstance(folder, str) and folder:
103
+ return [(ctx.expand(folder), "settings.json")]
104
+ return [(home / "models", source)]
105
+
106
+
107
+ def _llamacpp(ctx: Context) -> Found:
108
+ override = ctx.first_env("LLAMA_CACHE")
109
+ if override:
110
+ return [(ctx.expand(override[1]), override[0])]
111
+ if ctx.platform == "darwin":
112
+ return [(ctx.home / "Library" / "Caches" / "llama.cpp", "default")]
113
+ if ctx.platform == "win32":
114
+ local = ctx.env.get("LOCALAPPDATA") or str(ctx.home / "AppData" / "Local")
115
+ return [(ctx.expand(local) / "llama.cpp", "default")]
116
+ return [(_cache_dir(ctx) / "llama.cpp", "default")]
117
+
118
+
119
+ def _gpt4all(ctx: Context) -> Found:
120
+ if ctx.platform == "win32":
121
+ local = ctx.env.get("LOCALAPPDATA") or str(ctx.home / "AppData" / "Local")
122
+ desktop = ctx.expand(local) / "nomic.ai" / "GPT4All"
123
+ else:
124
+ desktop = _data_dir(ctx) / "nomic.ai" / "GPT4All"
125
+ return [(desktop, "default"), (ctx.home / ".cache" / "gpt4all", "default (python)")]
126
+
127
+
128
+ def _jan(ctx: Context) -> Found:
129
+ app = _data_dir(ctx) / "Jan"
130
+ override = ctx.first_env("JAN_DATA_FOLDER")
131
+ if override:
132
+ data, source = ctx.expand(override[1]), override[0]
133
+ else:
134
+ try:
135
+ folder = json.loads((app / "settings.json").read_text(encoding="utf-8"))["data_folder"]
136
+ except (OSError, ValueError, KeyError, TypeError):
137
+ folder = None
138
+ if isinstance(folder, str) and folder:
139
+ data, source = ctx.expand(folder), "settings.json"
140
+ else:
141
+ data, source = app / "data", "default"
142
+ return [(data / "llamacpp" / "models", source), (data / "mlx" / "models", source)]
143
+
144
+
145
+ def _whisper(ctx: Context) -> Found:
146
+ return [(_cache_dir(ctx) / "whisper", "default")]
147
+
148
+
149
+ class _LlamaCpp(TreeStore):
150
+ """llama.cpp's cache: loose GGUF files, and hub-layout repositories."""
151
+
152
+ def scan(self, root: ScanRoot, ctx: Context) -> list[ModelRecord]:
153
+ return hf.scan_hub(root.resolved, ctx, self.NAME) + super().scan(root, ctx)
154
+
155
+
156
+ lmstudio = TreeStore("lmstudio", _lmstudio, max_depth=3, config_marks_model=True)
157
+ llamacpp = _LlamaCpp("llamacpp", _llamacpp, max_depth=0)
158
+ gpt4all = TreeStore("gpt4all", _gpt4all, max_depth=1)
159
+ jan = TreeStore("jan", _jan, max_depth=3, config_marks_model=True)
160
+ whisper = TreeStore("whisper", _whisper, max_depth=0, min_size=0)
modelmap/records.py ADDED
@@ -0,0 +1,187 @@
1
+ """The scan result: what was found, where, and what went wrong.
2
+
3
+ A :class:`Scan` serializes to JSON so an inventory made on one machine can
4
+ be mapped on another. ``schema_version`` changes when a field is removed or
5
+ changes meaning. Adding a field does not change it: a reader ignores keys it
6
+ does not know, so an older modelmap can map a newer inventory.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from dataclasses import asdict, dataclass, field, fields
13
+ from typing import Any
14
+
15
+ SCHEMA_VERSION = 1
16
+
17
+
18
+ def _load(cls: Any, data: dict[str, Any]) -> Any:
19
+ """Build a dataclass from a dict, ignoring keys it does not declare."""
20
+ known = {f.name for f in fields(cls)}
21
+ return cls(**{k: v for k, v in data.items() if k in known})
22
+
23
+
24
+ @dataclass
25
+ class FileEntry:
26
+ """One file of a record.
27
+
28
+ :param path: Real path of the file, with symlinks resolved.
29
+ :param label: What the file is within its model: its path inside the
30
+ model directory or snapshot, or the kind of an Ollama layer.
31
+ :param size_bytes: Apparent size of the file itself.
32
+ :param disk_bytes: Bytes allocated on disk.
33
+ :param charged: False when another record was charged for this file,
34
+ so it adds nothing to this record's size.
35
+ :param note: A remark such as ``not in the current revision``.
36
+ :param used_by: Other records that use the same file. Deleting the
37
+ file would break them too.
38
+ """
39
+
40
+ path: str
41
+ label: str
42
+ size_bytes: int
43
+ disk_bytes: int
44
+ charged: bool = True
45
+ note: str = ""
46
+ used_by: list[str] = field(default_factory=list)
47
+
48
+
49
+ @dataclass
50
+ class ModelRecord:
51
+ """One model, dataset or cache entry found on disk.
52
+
53
+ :param name: Display name, for example ``mlx-community/Qwen3-8B-4bit``.
54
+ :param provider: Tool that owns the files: ``hf``, ``ollama``, ``omlx``,
55
+ ``lmstudio``, ``llamacpp`` or ``generic``.
56
+ :param format: ``gguf``, ``safetensors``, ``mlx``, ``pytorch`` and so on.
57
+ :param path: Directory or file that holds the model.
58
+ :param size_bytes: Apparent size, with shared files charged once.
59
+ :param disk_bytes: Bytes allocated on disk, with shared files charged once.
60
+ :param kind: ``model``, ``auxiliary`` (a file that cannot run alone, such
61
+ as a multimodal projector), ``dataset``, ``cache`` or ``unattributed``.
62
+ :param family: Model family guessed from the name, such as ``qwen``.
63
+ :param quant: Quantization label, such as ``Q4_K_M`` or ``4bit``.
64
+ :param params: Parameter count, or None when unknown.
65
+ :param params_exact: False when ``params`` is an estimate.
66
+ :param mtime: Newest modification time among the files, as a POSIX time.
67
+ :param files: Number of files.
68
+ :param file_list: The files themselves, in the order they were found.
69
+ :param aliases: Other names for the same files, such as further Ollama
70
+ tags that point at the same weights.
71
+ :param shared_with: Names of records that share a file with this one.
72
+ :param issues: Problems with this entry, such as a truncated header.
73
+ """
74
+
75
+ name: str
76
+ provider: str
77
+ format: str
78
+ path: str
79
+ size_bytes: int
80
+ disk_bytes: int
81
+ kind: str = "model"
82
+ family: str | None = None
83
+ quant: str | None = None
84
+ params: int | None = None
85
+ params_exact: bool = True
86
+ mtime: float | None = None
87
+ files: int = 1
88
+ file_list: list[FileEntry] = field(default_factory=list)
89
+ aliases: list[str] = field(default_factory=list)
90
+ shared_with: list[str] = field(default_factory=list)
91
+ issues: list[str] = field(default_factory=list)
92
+
93
+
94
+ @dataclass
95
+ class ScanRoot:
96
+ """A directory the scan visited.
97
+
98
+ :param provider: Provider the root belongs to, or ``user`` for a path
99
+ given on the command line.
100
+ :param path: The path as configured, before symlinks are resolved.
101
+ :param resolved: The real path that was walked.
102
+ :param source: What produced the path: an environment variable name,
103
+ ``default``, or ``argument``.
104
+ :param exists: False when the path is absent.
105
+ """
106
+
107
+ provider: str
108
+ path: str
109
+ resolved: str
110
+ source: str
111
+ exists: bool = True
112
+
113
+
114
+ @dataclass
115
+ class ScanWarning:
116
+ """Something the scan could not read or understand.
117
+
118
+ :param path: Where it happened.
119
+ :param message: What went wrong.
120
+ """
121
+
122
+ path: str
123
+ message: str
124
+
125
+
126
+ @dataclass
127
+ class Scan:
128
+ """The result of one scan.
129
+
130
+ :param records: Everything found.
131
+ :param roots: Directories visited.
132
+ :param warnings: Paths that could not be read.
133
+ :param elapsed_s: Wall-clock scan time in seconds.
134
+ :param hostname: Machine name, or None when redacted.
135
+ :param tool_version: Version of modelmap that made the scan.
136
+ :param schema_version: Version of this JSON layout.
137
+ """
138
+
139
+ records: list[ModelRecord] = field(default_factory=list)
140
+ roots: list[ScanRoot] = field(default_factory=list)
141
+ warnings: list[ScanWarning] = field(default_factory=list)
142
+ elapsed_s: float = 0.0
143
+ hostname: str | None = None
144
+ tool_version: str = ""
145
+ schema_version: int = SCHEMA_VERSION
146
+
147
+ @property
148
+ def size_bytes(self) -> int:
149
+ """Total apparent size of every record."""
150
+ return sum(r.size_bytes for r in self.records)
151
+
152
+ @property
153
+ def disk_bytes(self) -> int:
154
+ """Total allocated size of every record."""
155
+ return sum(r.disk_bytes for r in self.records)
156
+
157
+ def to_dict(self) -> dict[str, Any]:
158
+ return asdict(self)
159
+
160
+ def to_json(self, *, indent: int | None = 2) -> str:
161
+ return json.dumps(self.to_dict(), indent=indent)
162
+
163
+ @classmethod
164
+ def from_dict(cls, data: dict[str, Any]) -> Scan:
165
+ """Rebuild a scan from :meth:`to_dict` output.
166
+
167
+ :param data: Parsed JSON object.
168
+ :raises ValueError: If the schema version is not the one this
169
+ version of modelmap reads.
170
+ """
171
+ version = data.get("schema_version")
172
+ if version != SCHEMA_VERSION:
173
+ raise ValueError(
174
+ f"inventory has schema version {version!r}; "
175
+ f"this modelmap reads version {SCHEMA_VERSION}"
176
+ )
177
+ scan = _load(cls, data)
178
+ scan.records = [_load(ModelRecord, r) for r in data.get("records", [])]
179
+ for record in scan.records:
180
+ record.file_list = [_load(FileEntry, f) for f in record.file_list]
181
+ scan.roots = [_load(ScanRoot, r) for r in data.get("roots", [])]
182
+ scan.warnings = [_load(ScanWarning, w) for w in data.get("warnings", [])]
183
+ return scan
184
+
185
+ @classmethod
186
+ def from_json(cls, text: str) -> Scan:
187
+ return cls.from_dict(json.loads(text))