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/render_svg.py ADDED
@@ -0,0 +1,330 @@
1
+ """Draw a scan as one static SVG: a square treemap with a header and legend.
2
+
3
+ The square is divided among the records by size. Tiles of one provider
4
+ form one block. Each ``<rect>`` carries the exact layout geometry (to a
5
+ thousandth of a unit); the gaps between tiles are strokes in the surface
6
+ color drawn over the edges, so no tile is shrunk to make room.
7
+
8
+ The picture adapts to a light or dark setting through
9
+ ``prefers-color-scheme``. Hovering a tile in a browser shows its details
10
+ (the SVG ``<title>``).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from modelmap import palette
16
+ from modelmap.mapdata import MapData, build
17
+ from modelmap.records import ModelRecord, Scan
18
+ from modelmap.treemap import Group, Rect, Tile, layout
19
+ from modelmap.units import format_count, format_size
20
+
21
+ MARGIN = 24
22
+ HEADER = 84
23
+ LEGEND_ROW = 22
24
+ LEGEND_COLUMNS = 3
25
+ # Tiles under a quarter of a percent of the map are merged per provider.
26
+ MIN_FRACTION = 0.0025
27
+ # Width of an average character as a share of the font size, for deciding
28
+ # what fits. Labels are also clipped to their tile, so a wrong guess can
29
+ # cost a few letters but never overflow.
30
+ _CHAR = 0.58
31
+ _PAD = 7
32
+ _TAG_FONT = 10
33
+ _TAG_LINE = 15
34
+
35
+ DISPLAY_NAMES = {
36
+ "hf": "Hugging Face",
37
+ "ollama": "Ollama",
38
+ "omlx": "oMLX",
39
+ "lmstudio": "LM Studio",
40
+ "llamacpp": "llama.cpp",
41
+ "gpt4all": "GPT4All",
42
+ "jan": "Jan",
43
+ "whisper": "Whisper",
44
+ "generic": "Loose files",
45
+ }
46
+
47
+
48
+ def _xml(text: object) -> str:
49
+ """Text safe inside XML: escaped, with characters XML forbids replaced."""
50
+ out = []
51
+ for char in str(text):
52
+ code = ord(char)
53
+ legal = code in (9, 10, 13) or 0x20 <= code <= 0xD7FF or 0xE000 <= code <= 0xFFFD
54
+ legal = legal or code >= 0x10000
55
+ out.append(char if legal else "?")
56
+ return (
57
+ "".join(out)
58
+ .replace("&", "&amp;")
59
+ .replace("<", "&lt;")
60
+ .replace(">", "&gt;")
61
+ .replace('"', "&quot;")
62
+ )
63
+
64
+
65
+ def _num(value: float) -> str:
66
+ text = f"{value:.3f}".rstrip("0").rstrip(".")
67
+ return "0" if text in ("", "-0") else text
68
+
69
+
70
+ def _fit(text: str, width: float, font: float) -> str:
71
+ """The text, shortened with ``...`` to fit a width; empty if it cannot."""
72
+ room = int(width / (font * _CHAR))
73
+ if len(text) <= room:
74
+ return text
75
+ return text[: room - 3] + "..." if room >= 6 else ""
76
+
77
+
78
+ def _short_name(record: ModelRecord) -> str:
79
+ """The last part of a name: what tells models apart in a narrow tile."""
80
+ return record.name.rsplit("/", 1)[-1]
81
+
82
+
83
+ def _tooltip(record: ModelRecord, size: int, total: int, notes: list[ModelRecord]) -> str:
84
+ lines = [record.name, DISPLAY_NAMES.get(record.provider, record.provider)]
85
+ facts = [record.format, record.quant, format_count(record.params, record.params_exact)]
86
+ facts = [fact for fact in facts if fact]
87
+ if record.params:
88
+ facts[-1] += " parameters"
89
+ if record.kind != "model":
90
+ facts.insert(0, record.kind)
91
+ lines.append(", ".join(facts))
92
+ lines.append(f"{format_size(size)}, {100 * size / total:.1f}% of the map")
93
+ if record.aliases:
94
+ lines.append("Also: " + ", ".join(record.aliases))
95
+ lines += [f"Same files as: {n.name} ({n.provider})" for n in notes]
96
+ if record.shared_with:
97
+ lines.append("Shares files with: " + ", ".join(record.shared_with))
98
+ lines += [f"Problem: {issue}" for issue in record.issues]
99
+ lines.append(record.path)
100
+ return "\n".join(lines)
101
+
102
+
103
+ def _css(groups: list[Group]) -> list[str]:
104
+ """Style rules: one set of color variables per mode."""
105
+
106
+ def variables(mode: str) -> str:
107
+ surface = palette.SURFACE[mode]
108
+ parts = [
109
+ f"--surface:{surface}",
110
+ f"--text:{palette.TEXT_PRIMARY[mode]}",
111
+ f"--text2:{palette.TEXT_SECONDARY[mode]}",
112
+ ]
113
+ for index, group in enumerate(groups):
114
+ color = palette.fill(group.name, mode)
115
+ parts += [f"--c{index}:{color}", f"--i{index}:{palette.ink_on(color)}"]
116
+ return ";".join(parts)
117
+
118
+ return [
119
+ "<style>",
120
+ f".modelmap{{{variables('light')}}}",
121
+ f"@media (prefers-color-scheme:dark){{.modelmap{{{variables('dark')}}}}}",
122
+ ".modelmap text{font-family:system-ui,-apple-system,'Segoe UI',sans-serif}",
123
+ ".modelmap .bg{fill:var(--surface)}",
124
+ ".modelmap .tile{stroke:var(--surface);stroke-width:2}",
125
+ ".modelmap .block{fill:none;stroke:var(--surface);stroke-width:6}",
126
+ ".modelmap .hero{fill:var(--text);font-size:34px;font-weight:600}",
127
+ ".modelmap .sub{fill:var(--text2);font-size:13px}",
128
+ ".modelmap .key{fill:var(--text);font-size:12px}",
129
+ ".modelmap .key2{fill:var(--text2);font-size:12px}",
130
+ ".modelmap .tag{font-size:10px;font-weight:700;letter-spacing:.08em}",
131
+ ".modelmap .name{font-weight:600}",
132
+ "</style>",
133
+ ]
134
+
135
+
136
+ def label_markup(
137
+ r: Rect, clip_id: str, ink: str, name: str, detail: str, extra: str = "", tag: str = ""
138
+ ) -> list[str]:
139
+ """The label of a tile, clipped to it; nothing if no line fits.
140
+
141
+ :param r: The tile.
142
+ :param clip_id: Document-unique id for the clip path.
143
+ :param ink: Attribute text that sets the label color, such as
144
+ ``class="ink-hf"``.
145
+ :param name: First line, in bold.
146
+ :param detail: Second line.
147
+ :param extra: Third line.
148
+ :param tag: A small heading above the name, such as the group's name.
149
+ """
150
+ font = 16 if r.w >= 220 and r.h >= 96 else 13 if r.w >= 110 and r.h >= 44 else 11
151
+ width, room = r.w - 2 * _PAD, r.h - 2 * _PAD + 2
152
+ lines: list[tuple[str, str, float, float]] = [] # class, text, font size, line height
153
+ if tag and r.w >= 96:
154
+ fitted_tag = _fit(tag, width, _TAG_FONT * 1.15)
155
+ if fitted_tag and _TAG_LINE <= room:
156
+ lines.append(("tag", fitted_tag, _TAG_FONT, _TAG_LINE))
157
+ used = sum(line[3] for line in lines)
158
+ for css, text, size in (
159
+ ("name", name, font),
160
+ ("", detail, font * 0.88),
161
+ ("", extra, font * 0.88),
162
+ ):
163
+ fitted = _fit(text, width, size) if text else ""
164
+ if not fitted or used + size * 1.3 > room:
165
+ break # a detail never appears without the lines above it
166
+ lines.append((css, fitted, size, size * 1.3))
167
+ used += size * 1.3
168
+ if not lines:
169
+ return []
170
+
171
+ out = [
172
+ f'<clipPath id="{clip_id}"><rect x="{_num(r.x)}" y="{_num(r.y)}" '
173
+ f'width="{_num(r.w)}" height="{_num(r.h)}"/></clipPath>',
174
+ f'<g clip-path="url(#{clip_id})" {ink} pointer-events="none">',
175
+ ]
176
+ y = r.y + _PAD
177
+ for css, text, size, line_height in lines:
178
+ y += line_height
179
+ attrs = f' class="{css}"' if css else ""
180
+ out.append(
181
+ f'<text{attrs} x="{_num(r.x + _PAD)}" y="{_num(y - line_height * 0.28)}" '
182
+ f'font-size="{_num(size)}">{_xml(text)}</text>'
183
+ )
184
+ out.append("</g>")
185
+ return out
186
+
187
+
188
+ def _tile(
189
+ tile: Tile, index: int, group_index: int, data: MapData, first: bool, group: Group
190
+ ) -> list[str]:
191
+ """One tile: its rectangle, its tooltip and, if it fits, its label."""
192
+ r = tile.rect
193
+ merged = bool(tile.members)
194
+ fill_var, ink_var = f"--c{group_index}", f"--i{group_index}"
195
+ if merged:
196
+ names = sorted(data.records[int(k)].name for k in tile.members)
197
+ shown = names[:12] + ([f"and {len(names) - 12} more"] if len(names) > 12 else [])
198
+ provider = DISPLAY_NAMES.get(group.name, group.name)
199
+ title = (
200
+ f"{len(names)} smaller entries, {format_size(int(tile.size))}\n{provider}\n"
201
+ + "\n".join(shown)
202
+ )
203
+ name, detail, extra = f"{len(names)} smaller", format_size(int(tile.size)), ""
204
+ else:
205
+ record = data.records[int(tile.key)]
206
+ notes = [data.records[i] for i in data.attached.get(int(tile.key), [])]
207
+ title = _tooltip(record, int(tile.size), data.total, notes)
208
+ name = _short_name(record)
209
+ detail = " ".join(part for part in (format_size(int(tile.size)), record.quant) if part)
210
+ count = format_count(record.params, record.params_exact)
211
+ extra = f"{count} parameters" if count else ""
212
+
213
+ out = [
214
+ f'<rect class="tile" x="{_num(r.x)}" y="{_num(r.y)}" width="{_num(r.w)}" '
215
+ f'height="{_num(r.h)}" rx="3" style="fill:var({fill_var})" '
216
+ f'data-size="{int(tile.size)}"><title>{_xml(title)}</title></rect>'
217
+ ]
218
+
219
+ tag = ""
220
+ if first:
221
+ label = DISPLAY_NAMES.get(group.name, group.name).upper()
222
+ tag = f"{label} {format_size(int(group.size))}"
223
+ return out + label_markup(
224
+ r, f"clip{index}", f'style="fill:var({ink_var})"', name, detail, extra, tag
225
+ )
226
+
227
+
228
+ def render_svg(scan: Scan, *, size: int = 1000, use_disk: bool = False) -> str:
229
+ """Draw a scan as an SVG document.
230
+
231
+ :param scan: The scan to draw.
232
+ :param size: Side of the square map, in SVG units.
233
+ :param use_disk: Size tiles by bytes allocated on disk, not apparent size.
234
+ :return: The SVG text, ending with a newline.
235
+ """
236
+ data = build(scan, use_disk=use_disk)
237
+ canvas = Rect(MARGIN, HEADER, size, size)
238
+ groups = layout(data.items, canvas, min_fraction=MIN_FRACTION)
239
+ rows = -(-len(groups) // LEGEND_COLUMNS)
240
+ notes = _notes(data, use_disk)
241
+ width = size + 2 * MARGIN
242
+ height = HEADER + size + 18 + rows * LEGEND_ROW + len(notes) * 18 + MARGIN
243
+
244
+ models = sum(1 for r in data.records if r.kind in ("model", "auxiliary"))
245
+ out = [
246
+ f'<svg xmlns="http://www.w3.org/2000/svg" class="modelmap" viewBox="0 0 {width} {height}" '
247
+ f'width="{width}" height="{height}" role="img" '
248
+ f'aria-label="{_xml(_summary(data, models))}">',
249
+ *_css(groups),
250
+ f'<rect class="bg" width="{width}" height="{height}"/>',
251
+ f'<text class="hero" x="{MARGIN}" y="46">{_xml(format_size(data.total))}</text>',
252
+ f'<text class="sub" x="{MARGIN}" y="68">{_xml(_summary(data, models))}</text>',
253
+ ]
254
+
255
+ index = 0
256
+ for group_index, group in enumerate(groups):
257
+ out.append(f'<g data-group="{_xml(group.name)}">')
258
+ for position, tile in enumerate(group.tiles):
259
+ out += _tile(tile, index, group_index, data, position == 0, group)
260
+ index += 1
261
+ out.append("</g>")
262
+ for group in groups:
263
+ g = group.rect
264
+ out.append(
265
+ f'<rect class="block" x="{_num(g.x)}" y="{_num(g.y)}" width="{_num(g.w)}" '
266
+ f'height="{_num(g.h)}"/>'
267
+ )
268
+
269
+ y = HEADER + size + 18
270
+ column = size / LEGEND_COLUMNS
271
+ for position, group in enumerate(groups):
272
+ x = MARGIN + (position % LEGEND_COLUMNS) * column
273
+ row_y = y + (position // LEGEND_COLUMNS) * LEGEND_ROW
274
+ count = sum(len(t.members) or 1 for t in group.tiles)
275
+ share = 100 * group.size / data.total
276
+ label = DISPLAY_NAMES.get(group.name, group.name)
277
+ out.append(
278
+ f'<rect x="{_num(x)}" y="{_num(row_y)}" width="12" height="12" rx="2" '
279
+ f'style="fill:var(--c{position})"/>'
280
+ )
281
+ out.append(
282
+ f'<text class="key" x="{_num(x + 18)}" y="{_num(row_y + 10.5)}">{_xml(label)}'
283
+ f'<tspan class="key2" dx="8">{_xml(format_size(int(group.size)))}, {share:.0f}%, '
284
+ f"{count} {'entry' if count == 1 else 'entries'}</tspan></text>"
285
+ )
286
+ y += rows * LEGEND_ROW + 6
287
+ for note in notes:
288
+ out.append(f'<text class="sub" x="{MARGIN}" y="{_num(y + 10)}">{_xml(note)}</text>')
289
+ y += 18
290
+ out.append("</svg>")
291
+ return "\n".join(out) + "\n"
292
+
293
+
294
+ def _summary(data: MapData, models: int) -> str:
295
+ drawn = len(data.items)
296
+ other = drawn - sum(
297
+ 1 for item in data.items if data.records[int(item.key)].kind in ("model", "auxiliary")
298
+ )
299
+ text = f"{drawn} {'entry' if drawn == 1 else 'entries'} with a size"
300
+ if other:
301
+ text += f": {drawn - other} models, {other} other (datasets, caches and other files)"
302
+ return text if drawn else "No models found"
303
+
304
+
305
+ def _notes(data: MapData, use_disk: bool) -> list[str]:
306
+ notes = ["Area shows " + ("space allocated on disk." if use_disk else "file size.")]
307
+ notes[0] += " A file reachable by several names is counted once."
308
+ attached = sum(len(v) for v in data.attached.values())
309
+ if attached == 1:
310
+ notes.append(
311
+ "1 more name for a file already on the map is listed on the tile that holds it."
312
+ )
313
+ elif attached:
314
+ notes.append(
315
+ f"{attached} more names for files already on the map are listed on the tiles "
316
+ "that hold them."
317
+ )
318
+ problems = sum(1 for record in data.records if record.issues)
319
+ if problems:
320
+ notes.append(
321
+ f"{problems} {'entry has' if problems == 1 else 'entries have'} a problem, "
322
+ "named in the tooltip; `modelmap list` shows them all."
323
+ )
324
+ if data.not_drawn:
325
+ count = len(data.not_drawn)
326
+ notes.append(
327
+ f"{count} {'entry has' if count == 1 else 'entries have'} no size and "
328
+ f"{'is' if count == 1 else 'are'} not drawn."
329
+ )
330
+ return notes
modelmap/scanner.py ADDED
@@ -0,0 +1,245 @@
1
+ """Run the providers and the tree scans and return one :class:`Scan`.
2
+
3
+ Order of work, which is also the order files are charged in:
4
+
5
+ 1. Each provider's stores, in the order of ``PROVIDERS``.
6
+ 2. Paths the user named.
7
+ 3. With no paths named, a sweep of the home directory for loose models.
8
+
9
+ A directory is scanned once. A root that is the same directory as one
10
+ already scanned, or lies inside one, is skipped: the ledger would keep the
11
+ totals right, but every model would be listed a second time at size 0.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import os
17
+ import socket
18
+ import time
19
+ from collections.abc import Sequence
20
+ from dataclasses import dataclass, field
21
+
22
+ from modelmap import __version__
23
+ from modelmap.providers import PROVIDERS, hf, ollama
24
+ from modelmap.providers.base import Context, finish
25
+ from modelmap.providers.generic import MIN_UNVERIFIED_SIZE, scan_file, scan_tree
26
+ from modelmap.records import ModelRecord, Scan, ScanRoot
27
+
28
+ SWEEP_DEPTH = 5
29
+ # Application data: full of files, and every store inside it is a provider root.
30
+ _SWEEP_SKIP = {"darwin": ("Library",), "win32": ("AppData",)}
31
+
32
+
33
+ @dataclass
34
+ class Options:
35
+ """What to scan.
36
+
37
+ :param paths: Files or directories the user named.
38
+ :param only: Provider names to run; None for all.
39
+ :param defaults: Scan the known stores.
40
+ :param sweep: Sweep the home directory for loose models. None means
41
+ yes when neither paths nor providers are named.
42
+ :param excludes: Glob patterns skipped in tree scans.
43
+ :param min_size: Smallest file to list when only its extension says it
44
+ is a model.
45
+ :param max_depth: Levels to descend below a named path; None for all.
46
+ """
47
+
48
+ paths: Sequence[str] = ()
49
+ only: Sequence[str] | None = None
50
+ defaults: bool = True
51
+ sweep: bool | None = None
52
+ excludes: Sequence[str] = ()
53
+ min_size: int = MIN_UNVERIFIED_SIZE
54
+ max_depth: int | None = None
55
+
56
+
57
+ def _is_ollama_store(directory: str, names: set[str]) -> bool:
58
+ """``manifests`` beside ``blobs/sha256-<hex>`` files.
59
+
60
+ Docker's model store has the same two directory names but keeps its
61
+ blobs one level down, in ``blobs/sha256/``.
62
+ """
63
+ if "blobs" not in names or not names & {"manifests", "manifests-v2"}:
64
+ return False
65
+ try:
66
+ with os.scandir(os.path.join(directory, "blobs")) as it:
67
+ return any(e.name.startswith("sha256-") for e in it)
68
+ except OSError:
69
+ return False
70
+
71
+
72
+ def _is_hub_cache(directory: str, names: set[str]) -> bool:
73
+ """A ``models--org--name`` style directory that holds ``blobs`` or ``snapshots``."""
74
+ for name in sorted(names):
75
+ if name.startswith(("models--", "datasets--", "spaces--")):
76
+ repo = os.path.join(directory, name)
77
+ if os.path.isdir(os.path.join(repo, "blobs")) or os.path.isdir(
78
+ os.path.join(repo, "snapshots")
79
+ ):
80
+ return True
81
+ return False
82
+
83
+
84
+ @dataclass
85
+ class _Run:
86
+ ctx: Context
87
+ options: Options
88
+ records: list[ModelRecord] = field(default_factory=list)
89
+ roots: list[ScanRoot] = field(default_factory=list)
90
+ done: list[str] = field(default_factory=list)
91
+
92
+ def covered(self, resolved: str) -> bool:
93
+ """True if a root already scanned is this directory or contains it."""
94
+ return any(resolved == d or resolved.startswith(d + os.sep) for d in self.done)
95
+
96
+ def claim(self, directory: str, names: set[str]) -> list[ModelRecord] | None:
97
+ """Hand a directory that is some tool's store to that tool's provider."""
98
+ if _is_ollama_store(directory, names):
99
+ root = self.ctx.root(ollama.NAME, directory, "layout")
100
+ found = ollama.scan(root, self.ctx)
101
+ elif _is_hub_cache(directory, names):
102
+ root = self.ctx.root(hf.NAME, directory, "layout")
103
+ found = hf.scan_hub(directory, self.ctx)
104
+ else:
105
+ return None
106
+ self.roots.append(root)
107
+ self.done.append(directory)
108
+ return found
109
+
110
+ def stores(self) -> None:
111
+ for provider in PROVIDERS:
112
+ if self.options.only is not None and provider.NAME not in self.options.only:
113
+ continue
114
+ for root in provider.roots(self.ctx):
115
+ self.roots.append(root)
116
+ if root.exists and not self.covered(root.resolved):
117
+ self.records += provider.scan(root, self.ctx)
118
+ self.done.append(root.resolved)
119
+
120
+ def paths(self) -> None:
121
+ for path in self.options.paths:
122
+ root = self.ctx.root("user", self.ctx.expand(path), "argument")
123
+ root.exists = os.path.exists(root.resolved)
124
+ self.roots.append(root)
125
+ if not root.exists:
126
+ self.ctx.warn(path, "no such file or directory")
127
+ elif self.covered(root.resolved):
128
+ continue
129
+ elif os.path.isdir(root.resolved):
130
+ self.records += self.tree(root.resolved, self.options.max_depth, sniff_all=True)
131
+ self.done.append(root.resolved)
132
+ else:
133
+ self.records += scan_file(root.resolved, self.ctx, min_size=0)
134
+
135
+ def sweep(self) -> None:
136
+ home = os.path.realpath(self.ctx.home)
137
+ root = self.ctx.root("sweep", home, f"home, depth {SWEEP_DEPTH}")
138
+ self.roots.append(root)
139
+ skip = [os.path.join(home, name) for name in _SWEEP_SKIP.get(self.ctx.platform, ())]
140
+ self.records += self.tree(home, SWEEP_DEPTH, sniff_all=False, skip=skip)
141
+
142
+ def tree(
143
+ self, root: str, max_depth: int | None, sniff_all: bool, skip: Sequence[str] = ()
144
+ ) -> list[ModelRecord]:
145
+ return scan_tree(
146
+ root,
147
+ self.ctx,
148
+ max_depth=max_depth,
149
+ claimed={*self.done, *skip},
150
+ min_size=self.options.min_size,
151
+ sniff_all=sniff_all,
152
+ excludes=self.options.excludes,
153
+ claim=self.claim,
154
+ root_may_be_model=True,
155
+ )
156
+
157
+
158
+ def scan(ctx: Context | None = None, options: Options | None = None) -> Scan:
159
+ """Scan a machine.
160
+
161
+ :param ctx: The machine to scan; the running one by default.
162
+ :param options: What to scan; the known stores and a home sweep by
163
+ default.
164
+ :return: Everything found. If the scan is interrupted, what was found
165
+ so far, with a warning.
166
+ """
167
+ ctx = ctx or Context.current()
168
+ options = options or Options()
169
+ run = _Run(ctx, options)
170
+ start = time.perf_counter()
171
+ try:
172
+ if options.defaults:
173
+ run.stores()
174
+ run.paths()
175
+ # Naming providers or paths says where to look; the sweep is for
176
+ # the question "what is on this machine".
177
+ wanted = not options.paths and options.only is None
178
+ sweep = options.sweep if options.sweep is not None else wanted
179
+ if sweep and options.defaults:
180
+ run.sweep()
181
+ except KeyboardInterrupt:
182
+ ctx.warn("", "interrupted: the results are partial")
183
+ # A file named on the command line is found again by the sweep. Keep the
184
+ # first record of each (provider, path); the ledger charged it already.
185
+ seen: set[tuple[str, str]] = set()
186
+ records = []
187
+ for record in run.records:
188
+ key = (record.provider, os.path.realpath(record.path))
189
+ if key not in seen:
190
+ seen.add(key)
191
+ records.append(record)
192
+ finish(records)
193
+ return Scan(
194
+ records=records,
195
+ roots=run.roots,
196
+ warnings=ctx.warnings,
197
+ elapsed_s=round(time.perf_counter() - start, 3),
198
+ hostname=socket.gethostname(),
199
+ tool_version=__version__,
200
+ )
201
+
202
+
203
+ def redact(scan: Scan, home: str | os.PathLike[str]) -> Scan:
204
+ """Remove what identifies the machine and its user, in place.
205
+
206
+ The home directory becomes ``~`` wherever it appears: in paths, in
207
+ warning and issue text, and in the names of loose records, which start
208
+ with the name of their parent directory. The host name is dropped. Use
209
+ before sending an inventory to someone else.
210
+
211
+ :param scan: The scan to change.
212
+ :param home: The home directory to hide, as configured and as resolved.
213
+ :return: The same scan.
214
+ """
215
+ prefixes = sorted({str(home), os.path.realpath(home)}, key=len, reverse=True)
216
+ users = {os.path.basename(prefix) for prefix in prefixes}
217
+
218
+ def hide(text: str) -> str:
219
+ for prefix in prefixes:
220
+ text = text.replace(prefix, "~")
221
+ return text
222
+
223
+ def hide_name(text: str) -> str:
224
+ # "user/model", or an owner such as "generic:user/model".
225
+ owner, colon, name = text.rpartition(":") if ":" in text.split("/")[0] else ("", "", text)
226
+ first, slash, rest = name.partition("/")
227
+ if slash and first in users:
228
+ name = f"~/{rest}"
229
+ return hide(f"{owner}{colon}{name}")
230
+
231
+ scan.hostname = None
232
+ for record in scan.records:
233
+ record.path = hide(record.path)
234
+ for entry in record.file_list:
235
+ entry.path = hide(entry.path)
236
+ entry.used_by = [hide_name(user) for user in entry.used_by]
237
+ record.name = hide_name(record.name)
238
+ record.aliases = [hide_name(a) for a in record.aliases]
239
+ record.shared_with = [hide_name(o) for o in record.shared_with]
240
+ record.issues = [hide(i) for i in record.issues]
241
+ for root in scan.roots:
242
+ root.path, root.resolved = hide(root.path), hide(root.resolved)
243
+ for warning in scan.warnings:
244
+ warning.path, warning.message = hide(warning.path), hide(warning.message)
245
+ return scan
modelmap/sizing.py ADDED
@@ -0,0 +1,103 @@
1
+ """File sizes that count each file once.
2
+
3
+ Two numbers per file. Apparent size (``st_size``) is what the model is.
4
+ Disk size (allocated blocks) is what it costs. They differ for sparse
5
+ files. Tools that share one file between names, as the Hugging Face cache
6
+ does with symlinks and Ollama does with layers used by several tags, would
7
+ be counted twice by a walk that adds up names; :class:`SizeLedger` charges
8
+ each inode to the first owner that claims it.
9
+
10
+ Copy-on-write clones (APFS, Btrfs, XFS reflinks) have separate inodes that
11
+ share blocks. That sharing cannot be seen through ``stat``, so disk totals
12
+ overstate on volumes that use clones.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import os
18
+ from dataclasses import dataclass
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class FileSize:
23
+ """Sizes and identity of one file.
24
+
25
+ :param apparent: ``st_size`` in bytes.
26
+ :param disk: Bytes allocated on disk.
27
+ :param key: ``(st_dev, st_ino)``, the same for every name of one file.
28
+ :param mtime: Modification time as a POSIX time.
29
+ """
30
+
31
+ apparent: int
32
+ disk: int
33
+ key: tuple[int, int]
34
+ mtime: float = 0.0
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class Charge:
39
+ """The result of charging a file to an owner.
40
+
41
+ :param apparent: Apparent bytes charged; 0 when already charged.
42
+ :param disk: Disk bytes charged; 0 when already charged.
43
+ :param shared_with: The owner charged earlier, or None on first charge.
44
+ :param file: The file's full sizes, whoever was charged for it.
45
+ """
46
+
47
+ apparent: int
48
+ disk: int
49
+ shared_with: str | None = None
50
+ file: FileSize | None = None
51
+
52
+
53
+ def stat_size(path: str | os.PathLike[str]) -> FileSize:
54
+ """Stat a file, following symlinks.
55
+
56
+ :param path: File to measure.
57
+ :return: Its sizes and inode identity.
58
+ :raises OSError: If the path cannot be read or is a broken link.
59
+ """
60
+ st = os.stat(path)
61
+ # st_blocks counts 512-byte units on every POSIX system. Windows has no
62
+ # st_blocks, so the apparent size stands in.
63
+ blocks = getattr(st, "st_blocks", None)
64
+ disk = blocks * 512 if blocks is not None else st.st_size
65
+ return FileSize(apparent=st.st_size, disk=disk, key=(st.st_dev, st.st_ino), mtime=st.st_mtime)
66
+
67
+
68
+ class SizeLedger:
69
+ """Charges each file to one owner, however many names point at it.
70
+
71
+ Use one ledger for a whole scan so a file reachable from two providers
72
+ is counted once in the grand total.
73
+ """
74
+
75
+ def __init__(self) -> None:
76
+ self._owners: dict[tuple[int, int], str] = {}
77
+
78
+ def owner(self, path: str | os.PathLike[str]) -> str | None:
79
+ """Who was charged for a file, or None if nobody was or it is unreadable."""
80
+ try:
81
+ return self._owners.get(stat_size(path).key)
82
+ except OSError:
83
+ return None
84
+
85
+ def charge(self, path: str | os.PathLike[str], owner: str) -> Charge:
86
+ """Charge a file to ``owner`` unless another owner already has it.
87
+
88
+ A second charge by the same owner costs nothing and reports no
89
+ sharing.
90
+
91
+ :param path: File to charge.
92
+ :param owner: Name of the record claiming the file.
93
+ :return: The bytes charged, and who holds the file if not ``owner``.
94
+ :raises OSError: If the path cannot be read.
95
+ """
96
+ size = stat_size(path)
97
+ first = self._owners.get(size.key)
98
+ if first is None:
99
+ self._owners[size.key] = owner
100
+ return Charge(size.apparent, size.disk, file=size)
101
+ if first == owner:
102
+ return Charge(0, 0, file=size)
103
+ return Charge(0, 0, shared_with=first, file=size)