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,686 @@
1
+ """Draw a scan as one interactive page that works offline.
2
+
3
+ The page is a set of views, every one laid out here in Python and written
4
+ into the file as plain markup:
5
+
6
+ - a top view per grouping (by store, format, family or kind);
7
+ - a view per group, where the group's records fill the square;
8
+ - a view per record, where its individual files fill the square.
9
+
10
+ Clicking a tile opens the view below it, down to the files. The script in
11
+ the page only shows and hides views, moves a tooltip and copies text; it
12
+ creates no markup, so a model name can never become code. The page loads
13
+ nothing from the network.
14
+
15
+ The page deletes nothing itself. For each record it shows where the files
16
+ are, which other records use them, and the ``modelmap rm`` command that
17
+ removes the record, or why it cannot.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import shlex
23
+
24
+ from modelmap import palette
25
+ from modelmap.mapdata import MapData, build
26
+ from modelmap.records import FileEntry, ModelRecord, Scan
27
+ from modelmap.removal import plan, target_of
28
+ from modelmap.render_svg import (
29
+ DISPLAY_NAMES,
30
+ MIN_FRACTION,
31
+ _notes,
32
+ _num,
33
+ _summary,
34
+ _tooltip,
35
+ _xml,
36
+ label_markup,
37
+ )
38
+ from modelmap.treemap import Item, Rect, layout
39
+ from modelmap.units import format_count, format_size
40
+
41
+ CANVAS = Rect(0, 0, 1000, 1000)
42
+ GROUPINGS = {"provider": "Store", "format": "Format", "family": "Family", "kind": "Kind"}
43
+
44
+
45
+ def _group_of(record: ModelRecord, by: str) -> str:
46
+ return str(getattr(record, by) or "unknown")
47
+
48
+
49
+ def _group_label(name: str, by: str) -> str:
50
+ return DISPLAY_NAMES.get(name, name) if by == "provider" else name
51
+
52
+
53
+ def _slug(provider: str) -> str:
54
+ """CSS class suffix for a provider's color."""
55
+ return provider if provider in palette.PROVIDER_COLORS else "other"
56
+
57
+
58
+ def _short(name: str) -> str:
59
+ return name.rsplit("/", 1)[-1]
60
+
61
+
62
+ class _Page:
63
+ """Collects the views and their side panels."""
64
+
65
+ def __init__(self, data: MapData, use_disk: bool, ollama_stores: list[str]) -> None:
66
+ self.data = data
67
+ self.use_disk = use_disk
68
+ self.ollama_stores = ollama_stores
69
+ self.views: list[str] = []
70
+ self.panels: list[str] = []
71
+ self.clips = 0
72
+
73
+ def size_of(self, record: ModelRecord) -> int:
74
+ return record.disk_bytes if self.use_disk else record.size_bytes
75
+
76
+ def file_size(self, entry: FileEntry) -> int:
77
+ return entry.disk_bytes if self.use_disk else entry.size_bytes
78
+
79
+ def clip(self) -> str:
80
+ self.clips += 1
81
+ return f"clip{self.clips}"
82
+
83
+ # ------------------------------------------------------------- tiles
84
+
85
+ def tile(
86
+ self,
87
+ rect: Rect,
88
+ provider: str,
89
+ size: int,
90
+ tip: str,
91
+ name: str,
92
+ lines: tuple[str, str, str, str],
93
+ go: str = "",
94
+ ) -> list[str]:
95
+ """One tile: a focusable group holding the rectangle and its label.
96
+
97
+ A tile that opens a record takes its tooltip from that record's
98
+ panel, so the text is in the page once, not once per view.
99
+ """
100
+ slug = _slug(provider)
101
+ attrs = f'class="t" data-name="{_xml(name.lower())}"'
102
+ attrs += f' data-tip-of="p-{go}"' if go.startswith("rec-") else f' data-tip="{_xml(tip)}"'
103
+ if go:
104
+ label = _xml(f"{name}, {format_size(size)}")
105
+ attrs += f' data-go="{go}" tabindex="0" role="button" aria-label="{label}"'
106
+ short, detail, extra, tag = lines
107
+ return [
108
+ f"<g {attrs}>",
109
+ f'<rect class="tile p-{slug}" x="{_num(rect.x)}" y="{_num(rect.y)}" '
110
+ f'width="{_num(rect.w)}" height="{_num(rect.h)}" rx="3" data-size="{size}"/>',
111
+ *label_markup(rect, self.clip(), f'class="i-{slug}"', short, detail, extra, tag),
112
+ "</g>",
113
+ ]
114
+
115
+ def record_tile(self, index: int, rect: Rect, size: int, tag: str) -> list[str]:
116
+ record = self.data.records[index]
117
+ detail = " ".join(part for part in (format_size(size), record.quant) if part)
118
+ count = format_count(record.params, record.params_exact)
119
+ lines = (_short(record.name), detail, f"{count} parameters" if count else "", tag)
120
+ return self.tile(rect, record.provider, size, "", record.name, lines, f"rec-{index}")
121
+
122
+ # ------------------------------------------------------------- views
123
+
124
+ def view(self, view_id: str, title: str, parents: dict[str, str], body: list[str]) -> None:
125
+ attrs = "".join(f' data-{key}="{_xml(value)}"' for key, value in parents.items())
126
+ self.views += [
127
+ # The id differs from the name used in links, so that following
128
+ # a link never makes the browser scroll to the element.
129
+ f'<g class="view" id="v-{view_id}" data-view="{view_id}" '
130
+ f'data-title="{_xml(title)}"{attrs}>',
131
+ *body,
132
+ "</g>",
133
+ ]
134
+
135
+ def panel(self, view_id: str, body: list[str], tip: str = "") -> None:
136
+ attr = f' data-tip="{_xml(tip)}"' if tip else ""
137
+ self.panels += [
138
+ f'<section class="panel" id="p-{view_id}"{attr} hidden>',
139
+ *body,
140
+ "</section>",
141
+ ]
142
+
143
+ def top(self, by: str) -> dict[str, str]:
144
+ """The top view of one grouping; returns each group's view id."""
145
+ data = self.data
146
+ items = [
147
+ Item(item.key, _group_of(data.records[int(item.key)], by), item.size, item.label)
148
+ for item in data.items
149
+ ]
150
+ groups = layout(items, CANVAS, min_fraction=MIN_FRACTION)
151
+ ids = {group.name: f"grp-{by}-{n}" for n, group in enumerate(groups)}
152
+ body: list[str] = []
153
+ rows: list[str] = []
154
+ for group in groups:
155
+ label = _group_label(group.name, by)
156
+ for position, tile in enumerate(group.tiles):
157
+ tag = f"{label.upper()} {format_size(int(group.size))}" if position == 0 else ""
158
+ if tile.members:
159
+ count = len(tile.members)
160
+ names = sorted(data.records[int(k)].name for k in tile.members)
161
+ shown = names[:12] + ([f"and {count - 12} more"] if count > 12 else [])
162
+ tip = "\n".join(
163
+ [f"{count} smaller entries, {format_size(int(tile.size))}", label, *shown]
164
+ )
165
+ provider = (
166
+ data.records[int(tile.members[0])].provider
167
+ if by != "provider"
168
+ else group.name
169
+ )
170
+ lines = (f"{count} smaller", format_size(int(tile.size)), "", tag)
171
+ body += self.tile(
172
+ tile.rect,
173
+ provider,
174
+ int(tile.size),
175
+ tip + "\nClick to see them",
176
+ f"{count} smaller in {label}",
177
+ lines,
178
+ ids[group.name],
179
+ )
180
+ else:
181
+ body += self.record_tile(int(tile.key), tile.rect, int(tile.size), tag)
182
+ g = group.rect
183
+ body.append(
184
+ f'<rect class="block" x="{_num(g.x)}" y="{_num(g.y)}" width="{_num(g.w)}" '
185
+ f'height="{_num(g.h)}"/>'
186
+ )
187
+ count = sum(len(t.members) or 1 for t in group.tiles)
188
+ swatch = f'<span class="sw p-{_slug(group.name)}"></span>' if by == "provider" else ""
189
+ rows.append(
190
+ f'<tr data-name="{_xml(label.lower())}"><td>{swatch}'
191
+ f'<button class="link" data-go="{ids[group.name]}">{_xml(label)}</button></td>'
192
+ f'<td class="n">{format_size(int(group.size))}</td>'
193
+ f'<td class="n">{100 * group.size / data.total:.0f}%</td><td class="n">{count}</td></tr>'
194
+ )
195
+ self.group(by, ids[group.name], group.name, [t for t in items if t.group == group.name])
196
+ self.view(f"top-{by}", "All models", {"by": by}, body)
197
+
198
+ panel = [
199
+ f"<h2>By {GROUPINGS[by].lower()}</h2>",
200
+ '<table><thead><tr><th scope="col">Group</th><th scope="col" class="n">Size</th>'
201
+ '<th scope="col" class="n">Share</th><th scope="col" class="n">Entries</th></tr></thead>',
202
+ "<tbody>",
203
+ *rows,
204
+ "</tbody></table>",
205
+ *self.problems(),
206
+ ]
207
+ self.panel(f"top-{by}", panel)
208
+ return ids
209
+
210
+ def group(self, by: str, view_id: str, name: str, items: list[Item]) -> None:
211
+ """One group's records filling the square, nothing merged."""
212
+ label = _group_label(name, by)
213
+ total = sum(item.size for item in items)
214
+ body: list[str] = []
215
+ rows: list[str] = []
216
+ for group in layout([Item(i.key, "", i.size, i.label) for i in items], CANVAS):
217
+ for tile in group.tiles:
218
+ index = int(tile.key)
219
+ body += self.record_tile(index, tile.rect, int(tile.size), "")
220
+ rows.append(self.record_row(index, int(tile.size)))
221
+ self.view(view_id, label, {"by": by, "parent": f"top-{by}"}, body)
222
+ self.panel(
223
+ view_id,
224
+ [
225
+ f"<h2>{_xml(label)}</h2>",
226
+ f'<p class="sub">{format_size(int(total))} in {len(items)} '
227
+ f"{'entry' if len(items) == 1 else 'entries'}. Click one to see its files.</p>",
228
+ '<table><thead><tr><th scope="col">Name</th><th scope="col" class="n">Size</th>'
229
+ '<th scope="col">Quantization</th><th scope="col" class="n">Parameters</th></tr></thead>',
230
+ "<tbody>",
231
+ *rows,
232
+ "</tbody></table>",
233
+ ],
234
+ )
235
+
236
+ def record_row(self, index: int, size: int) -> str:
237
+ record = self.data.records[index]
238
+ flag = ' <span class="flag">problem</span>' if record.issues else ""
239
+ return (
240
+ f'<tr data-name="{_xml(record.name.lower())}"><td>'
241
+ f'<span class="sw p-{_slug(record.provider)}"></span>'
242
+ f'<button class="link" data-go="rec-{index}">{_xml(record.name)}</button>{flag}</td>'
243
+ f'<td class="n">{format_size(size)}</td><td>{_xml(record.quant or "")}</td>'
244
+ f'<td class="n">{format_count(record.params, record.params_exact)}</td></tr>'
245
+ )
246
+
247
+ def problems(self) -> list[str]:
248
+ """Records with a problem, and those with nothing to draw, as lists.
249
+
250
+ A problem must be findable without finding its tile: a broken
251
+ download can be too small to see.
252
+ """
253
+ data = self.data
254
+ out: list[str] = []
255
+ flagged = [i for i, record in enumerate(data.records) if record.issues]
256
+ if flagged:
257
+ out.append(f'<h3>Problems ({len(flagged)})</h3><ul class="plain">')
258
+ for index in flagged:
259
+ record = data.records[index]
260
+ out.append(
261
+ f'<li data-name="{_xml(record.name.lower())}">'
262
+ f'<button class="link" data-go="rec-{index}">{_xml(record.name)}</button>'
263
+ f'<span class="sub"> {_xml("; ".join(record.issues))}</span></li>'
264
+ )
265
+ out.append("</ul>")
266
+ if data.not_drawn:
267
+ out.append(
268
+ f'<h3>No size, not on the map ({len(data.not_drawn)})</h3><ul class="plain">'
269
+ )
270
+ for index in data.not_drawn:
271
+ record = data.records[index]
272
+ out.append(
273
+ f'<li data-name="{_xml(record.name.lower())}">'
274
+ f'<button class="link" data-go="rec-{index}">{_xml(record.name)}</button></li>'
275
+ )
276
+ out.append("</ul>")
277
+ return out
278
+
279
+ def record(self, index: int, parents: dict[str, str]) -> None:
280
+ """One record's files filling the square, and its details."""
281
+ record = self.data.records[index]
282
+ entries = record.file_list
283
+ sized = [(n, self.file_size(e)) for n, e in enumerate(entries) if self.file_size(e) > 0]
284
+ total = sum(size for _, size in sized)
285
+ items = [Item(str(n), "", size, entries[n].label) for n, size in sized]
286
+ body: list[str] = []
287
+ for group in layout(items, CANVAS, min_fraction=MIN_FRACTION):
288
+ for tile in group.tiles:
289
+ if tile.members:
290
+ count = len(tile.members)
291
+ tip = f"{count} smaller files, {format_size(int(tile.size))}\nListed beside the map"
292
+ lines = (f"{count} smaller files", format_size(int(tile.size)), "", "")
293
+ body += self.tile(
294
+ tile.rect,
295
+ record.provider,
296
+ int(tile.size),
297
+ tip,
298
+ f"{count} smaller files",
299
+ lines,
300
+ )
301
+ continue
302
+ entry = entries[int(tile.key)]
303
+ extra = entry.note or ("also used elsewhere" if entry.used_by else "")
304
+ lines = (_short(entry.label), format_size(int(tile.size)), extra, "")
305
+ body += self.tile(
306
+ tile.rect,
307
+ record.provider,
308
+ int(tile.size),
309
+ _file_tip(entry, int(tile.size), total),
310
+ entry.label,
311
+ lines,
312
+ )
313
+ if not body:
314
+ body.append(
315
+ '<text class="empty" x="500" y="500" text-anchor="middle">No files to draw</text>'
316
+ )
317
+ self.view(f"rec-{index}", record.name, parents, body)
318
+ notes = [self.data.records[i] for i in self.data.attached.get(index, [])]
319
+ tip = _tooltip(record, self.size_of(record), max(self.data.total, 1), notes)
320
+ self.panel(f"rec-{index}", self.record_panel(index), tip + "\nClick to see its files")
321
+
322
+ def record_panel(self, index: int) -> list[str]:
323
+ record = self.data.records[index]
324
+ facts = [
325
+ ("Store", DISPLAY_NAMES.get(record.provider, record.provider)),
326
+ ("Kind", record.kind),
327
+ ("Format", record.format),
328
+ ("Quantization", record.quant or ""),
329
+ ("Parameters", format_count(record.params, record.params_exact)),
330
+ ("Size", format_size(record.size_bytes)),
331
+ ("On disk", format_size(record.disk_bytes)),
332
+ ("Also known as", ", ".join(record.aliases)),
333
+ ]
334
+ out = [f"<h2>{_xml(record.name)}</h2>", "<dl>"]
335
+ out += [f"<dt>{label}</dt><dd>{_xml(value)}</dd>" for label, value in facts if value]
336
+ out.append("</dl>")
337
+ if record.issues:
338
+ out.append('<ul class="issues">')
339
+ out += [f"<li>{_xml(issue)}</li>" for issue in record.issues]
340
+ out.append("</ul>")
341
+ attached = [self.data.records[i] for i in self.data.attached.get(index, [])]
342
+ if attached:
343
+ names = ", ".join(
344
+ f"{r.name} ({DISPLAY_NAMES.get(r.provider, r.provider)})" for r in attached
345
+ )
346
+ out.append(f'<p class="sub">The same files are also stored as: {_xml(names)}</p>')
347
+
348
+ out += ["<h3>Location</h3>", _copyable(record.path, "Copy path")]
349
+ step = plan(record, self.ollama_stores, check_disk=False)
350
+ out.append("<h3>To remove</h3>")
351
+ if step.action != "refuse":
352
+ target = target_of(record, self.data.records)
353
+ out.append(_copyable(f"modelmap rm {shlex.quote(target)}", "Copy command"))
354
+ note = f"{step.note} It lists what will go and asks first."
355
+ else:
356
+ note = step.note
357
+ out.append(f'<p class="sub">{_xml(note)}</p>')
358
+ users = sorted({user for entry in record.file_list for user in entry.used_by})
359
+ if users:
360
+ out.append(
361
+ '<p class="warn">Some of these files are also used by: '
362
+ f"{_xml(', '.join(users))}. Removing them breaks those too.</p>"
363
+ )
364
+ out.append(
365
+ '<p class="sub">The page itself deletes nothing: run the command in a terminal. Sharing is '
366
+ "known only among what this scan covered: a file may also be used by a store that "
367
+ "was not scanned.</p>"
368
+ f"<h3>Files ({len(record.file_list)})</h3>"
369
+ )
370
+ out.append('<ul class="files">')
371
+ order = sorted(range(len(record.file_list)), key=lambda n: -record.file_list[n].size_bytes)
372
+ for n in order:
373
+ entry = record.file_list[n]
374
+ remarks = [entry.note] if entry.note else []
375
+ if not entry.charged:
376
+ remarks.append("counted under another record")
377
+ if entry.used_by:
378
+ remarks.append("also used by " + ", ".join(entry.used_by))
379
+ remark = f'<span class="sub"> {_xml("; ".join(remarks))}</span>' if remarks else ""
380
+ out.append(
381
+ f'<li data-name="{_xml(entry.label.lower())}"><div class="row">'
382
+ f"<strong>{_xml(entry.label)}</strong>"
383
+ f'<span class="n">{format_size(self.file_size(entry))}</span></div>'
384
+ f"{remark}{_copyable(entry.path, 'Copy path')}</li>"
385
+ )
386
+ out.append("</ul>")
387
+ return out
388
+
389
+
390
+ def _copyable(text: str, label: str) -> str:
391
+ """Text shown in full, selectable, with a button that copies it."""
392
+ return (
393
+ f'<div class="copy"><code>{_xml(text)}</code>'
394
+ f'<button data-copy data-label="{label}">{label}</button></div>'
395
+ )
396
+
397
+
398
+ def _file_tip(entry: FileEntry, size: int, total: int) -> str:
399
+ lines = [entry.label, f"{format_size(size)}, {100 * size / total:.1f}% of this model"]
400
+ if entry.note:
401
+ lines.append(entry.note)
402
+ if not entry.charged:
403
+ lines.append("Counted under another record")
404
+ if entry.used_by:
405
+ lines.append("Also used by: " + ", ".join(entry.used_by))
406
+ lines.append(entry.path)
407
+ return "\n".join(lines)
408
+
409
+
410
+ def _colors() -> str:
411
+ """CSS variables for both modes, and the rules that apply them."""
412
+
413
+ def variables(mode: str) -> str:
414
+ parts = [
415
+ f"--surface:{palette.SURFACE[mode]}",
416
+ f"--page:{'#f9f9f7' if mode == 'light' else '#0d0d0d'}",
417
+ f"--text:{palette.TEXT_PRIMARY[mode]}",
418
+ f"--text2:{palette.TEXT_SECONDARY[mode]}",
419
+ f"--line:{'#e1e0d9' if mode == 'light' else '#2c2c2a'}",
420
+ f"--warn:{'#a13a00' if mode == 'light' else '#f0a070'}",
421
+ ]
422
+ for name in [*palette.PROVIDER_COLORS, "other"]:
423
+ color = palette.fill(name, mode)
424
+ parts += [f"--c-{name}:{color}", f"--i-{name}:{palette.ink_on(color)}"]
425
+ return ";".join(parts)
426
+
427
+ rules = [
428
+ f":root{{{variables('light')}}}",
429
+ "@media (prefers-color-scheme:dark){:root:not([data-theme=light]){"
430
+ f"{variables('dark')};color-scheme:dark}}}}",
431
+ f":root[data-theme=dark]{{{variables('dark')};color-scheme:dark}}",
432
+ ]
433
+ for name in [*palette.PROVIDER_COLORS, "other"]:
434
+ rules.append(f".p-{name}{{fill:var(--c-{name});background:var(--c-{name})}}")
435
+ rules.append(f".i-{name}{{fill:var(--i-{name})}}")
436
+ return "\n".join(rules)
437
+
438
+
439
+ _CSS = """
440
+ *{box-sizing:border-box}
441
+ body{margin:0;background:var(--page);color:var(--text);
442
+ font:14px/1.45 system-ui,-apple-system,"Segoe UI",sans-serif;
443
+ padding:20px max(16px,env(safe-area-inset-right,0px)) 32px max(16px,env(safe-area-inset-left,0px))}
444
+ header{display:flex;flex-wrap:wrap;gap:12px 24px;align-items:end;margin-bottom:12px}
445
+ h1{font-size:15px;font-weight:600;margin:0;color:var(--text2)}
446
+ .hero{font-size:34px;font-weight:600;line-height:1.1}
447
+ .sub{color:var(--text2);font-size:13px}
448
+ .controls{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin-left:auto}
449
+ .seg{display:flex;border:1px solid var(--line);border-radius:8px;overflow:hidden}
450
+ .seg button{border:0;background:var(--surface);color:var(--text);padding:6px 12px;font:inherit;cursor:pointer}
451
+ .seg button[aria-pressed=true]{background:var(--text);color:var(--surface)}
452
+ input[type=search]{font:inherit;padding:6px 10px;border:1px solid var(--line);border-radius:8px;
453
+ background:var(--surface);color:var(--text);min-width:0;width:14em}
454
+ #crumbs{display:flex;flex-wrap:wrap;gap:4px;align-items:center;min-height:28px;margin-bottom:8px}
455
+ #crumbs .sep{color:var(--text2)}
456
+ .layout{display:grid;grid-template-columns:minmax(0,min(100%,calc(100vh - 150px))) minmax(0,1fr);
457
+ gap:24px;align-items:start}
458
+ @media (max-width:900px){.layout{grid-template-columns:minmax(0,1fr)}}
459
+ .map{position:relative;background:var(--surface);border-radius:6px}
460
+ .map svg{display:block;width:100%;height:auto;aspect-ratio:1}
461
+ .view{display:none}.view.on{display:inline}
462
+ .tile{stroke:var(--surface);stroke-width:2}
463
+ .block{fill:none;stroke:var(--surface);stroke-width:6;pointer-events:none}
464
+ .t[data-go]{cursor:pointer}
465
+ .t:focus{outline:none}.t:focus-visible .tile{stroke:var(--text);stroke-width:4}
466
+ .t.dim{opacity:.18}
467
+ svg text{font-family:system-ui,-apple-system,"Segoe UI",sans-serif}
468
+ .tag{font-size:10px;font-weight:700;letter-spacing:.08em}.name{font-weight:600}
469
+ .empty{fill:var(--text2);font-size:28px}
470
+ #tip{position:fixed;z-index:5;max-width:min(460px,90vw);padding:8px 10px;border-radius:6px;
471
+ background:var(--text);color:var(--surface);font-size:12px;white-space:pre-line;
472
+ overflow-wrap:anywhere;pointer-events:none}
473
+ .panels{min-width:0}
474
+ .panel h2{font-size:20px;margin:0 0 6px;overflow-wrap:anywhere;text-wrap:balance}
475
+ .panel h3{font-size:13px;margin:18px 0 6px;color:var(--text2);text-transform:uppercase;letter-spacing:.06em}
476
+ table{border-collapse:collapse;width:100%}
477
+ th,td{text-align:left;padding:5px 8px 5px 0;border-bottom:1px solid var(--line);vertical-align:top}
478
+ th{font-weight:600;font-size:12px;color:var(--text2)}
479
+ .n{text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap}
480
+ tr.dim,li.dim{opacity:.25}
481
+ .sw{display:inline-block;width:10px;height:10px;border-radius:2px;margin-right:6px}
482
+ button.link{display:inline;border:0;background:none;color:inherit;font:inherit;padding:0;cursor:pointer;
483
+ text-align:left;text-decoration:underline;text-decoration-color:var(--line);
484
+ text-underline-offset:3px;overflow-wrap:anywhere}
485
+ button.link:hover{text-decoration-color:currentColor}
486
+ button:focus-visible,input:focus-visible{outline:2px solid var(--c-hf);outline-offset:2px}
487
+ dl{display:grid;grid-template-columns:max-content minmax(0,1fr);gap:2px 16px;margin:8px 0}
488
+ dt{color:var(--text2)}dd{margin:0;overflow-wrap:anywhere}
489
+ .copy{display:flex;gap:8px;align-items:start;margin:4px 0}
490
+ .copy code{flex:1;min-width:0;font:12px/1.4 ui-monospace,Menlo,Consolas,monospace;
491
+ background:var(--surface);border:1px solid var(--line);border-radius:6px;padding:5px 8px;
492
+ overflow-wrap:anywhere;user-select:all}
493
+ .copy button{flex:none;font:inherit;font-size:12px;padding:4px 8px;border:1px solid var(--line);
494
+ border-radius:6px;background:var(--surface);color:var(--text);cursor:pointer}
495
+ ul.plain,ul.files{list-style:none;margin:0;padding:0}
496
+ ul.files li{padding:8px 0;border-bottom:1px solid var(--line)}
497
+ .row{display:flex;gap:12px;justify-content:space-between}.row strong{overflow-wrap:anywhere;min-width:0}
498
+ .issues,.warn,.flag{color:var(--warn)}.flag{font-size:11px;font-weight:600;margin-left:6px}
499
+ .issues{padding-left:18px;margin:6px 0}
500
+ footer{margin-top:20px}
501
+ @media (prefers-reduced-motion:no-preference){.t,tr,li{transition:opacity .12s}}
502
+ """
503
+
504
+ _JS = """
505
+ (function () {
506
+ "use strict";
507
+ var views = {}, current = null, by = "provider";
508
+ var tip = document.getElementById("tip");
509
+ var crumbs = document.getElementById("crumbs");
510
+ var search = document.getElementById("search");
511
+ Array.prototype.forEach.call(document.querySelectorAll(".view"), function (v) { views[v.dataset.view] = v; });
512
+
513
+ function parentOf(view) {
514
+ var key = "parent" + by.charAt(0).toUpperCase() + by.slice(1);
515
+ return view.dataset[key] || view.dataset.parent || "";
516
+ }
517
+ function filter() {
518
+ var q = search.value.trim().toLowerCase();
519
+ var scope = [current, document.getElementById("p-" + current.dataset.view)];
520
+ scope.forEach(function (root) {
521
+ Array.prototype.forEach.call(root.querySelectorAll("[data-name]"), function (el) {
522
+ el.classList.toggle("dim", q !== "" && el.dataset.name.indexOf(q) === -1);
523
+ });
524
+ });
525
+ }
526
+ function show(id) {
527
+ var view = views[id] || views["top-" + by];
528
+ if (view.dataset.by) { by = view.dataset.by; }
529
+ if (current) {
530
+ current.classList.remove("on");
531
+ document.getElementById("p-" + current.dataset.view).hidden = true;
532
+ }
533
+ current = view;
534
+ view.classList.add("on");
535
+ document.getElementById("p-" + view.dataset.view).hidden = false;
536
+ Array.prototype.forEach.call(document.querySelectorAll("[data-by]"), function (b) {
537
+ if (b.tagName === "BUTTON") { b.setAttribute("aria-pressed", String(b.dataset.by === by)); }
538
+ });
539
+ var chain = [], at = view;
540
+ while (at) { chain.unshift(at); at = views[parentOf(at)]; }
541
+ crumbs.textContent = "";
542
+ chain.forEach(function (v, n) {
543
+ if (n) {
544
+ var sep = document.createElement("span");
545
+ sep.className = "sep"; sep.textContent = "/";
546
+ crumbs.appendChild(sep);
547
+ }
548
+ var last = n === chain.length - 1;
549
+ var el = document.createElement(last ? "strong" : "button");
550
+ el.textContent = v.dataset.title;
551
+ if (!last) { el.className = "link"; el.dataset.go = v.dataset.view; }
552
+ crumbs.appendChild(el);
553
+ });
554
+ tip.hidden = true;
555
+ filter();
556
+ }
557
+ function go(id) {
558
+ if (location.hash.slice(1) === id) { show(id); } else { location.hash = id; }
559
+ }
560
+ function copy(button) {
561
+ var done = function () {
562
+ button.textContent = "Copied";
563
+ setTimeout(function () { button.textContent = button.dataset.label; }, 1500);
564
+ };
565
+ var select = function () {
566
+ var range = document.createRange();
567
+ range.selectNodeContents(button.parentNode.querySelector("code"));
568
+ var selection = window.getSelection();
569
+ selection.removeAllRanges();
570
+ selection.addRange(range);
571
+ button.textContent = "Selected";
572
+ };
573
+ if (navigator.clipboard && navigator.clipboard.writeText) {
574
+ var text = button.parentNode.querySelector("code").textContent;
575
+ navigator.clipboard.writeText(text).then(done, select);
576
+ } else { select(); }
577
+ }
578
+
579
+ document.addEventListener("click", function (event) {
580
+ var target = event.target.closest("[data-copy],[data-go],button[data-by]");
581
+ if (!target) { return; }
582
+ if (target.dataset.copy !== undefined) { copy(target); }
583
+ else if (target.dataset.go) { go(target.dataset.go); }
584
+ else { by = target.dataset.by; go("top-" + by); }
585
+ });
586
+ document.addEventListener("keydown", function (event) {
587
+ if (event.key === "Escape" && current && parentOf(current)) { go(parentOf(current)); return; }
588
+ var target = event.target.closest && event.target.closest("g[data-go]");
589
+ if (target && (event.key === "Enter" || event.key === " ")) {
590
+ event.preventDefault();
591
+ go(target.dataset.go);
592
+ }
593
+ });
594
+ document.addEventListener("pointermove", function (event) {
595
+ var target = event.target.closest && event.target.closest("svg [data-tip],[data-tip-of]");
596
+ if (!target) { tip.hidden = true; return; }
597
+ var source = target.dataset.tipOf ? document.getElementById(target.dataset.tipOf) : target;
598
+ tip.textContent = source.dataset.tip;
599
+ tip.hidden = false;
600
+ var box = tip.getBoundingClientRect();
601
+ var x = Math.min(event.clientX + 14, window.innerWidth - box.width - 8);
602
+ var y = event.clientY + 16;
603
+ if (y + box.height > window.innerHeight - 8) { y = event.clientY - box.height - 12; }
604
+ tip.style.left = Math.max(8, x) + "px";
605
+ tip.style.top = Math.max(8, y) + "px";
606
+ });
607
+ search.addEventListener("input", filter);
608
+ window.addEventListener("hashchange", function () { show(location.hash.slice(1)); });
609
+ show(location.hash.slice(1));
610
+ })();
611
+ """
612
+
613
+
614
+ def render_html(scan: Scan, *, use_disk: bool = False) -> str:
615
+ """Draw a scan as a self-contained interactive page.
616
+
617
+ :param scan: The scan to draw.
618
+ :param use_disk: Size tiles by bytes allocated on disk, not apparent size.
619
+ :return: The HTML text, ending with a newline.
620
+ """
621
+ data = build(scan, use_disk=use_disk)
622
+ # `ollama rm` acts on the running Ollama's store: its provider roots, not
623
+ # an Ollama store that was only recognized by its layout somewhere else.
624
+ live = [r.resolved for r in scan.roots if r.provider == "ollama" and r.source != "layout"]
625
+ page = _Page(data, use_disk, live)
626
+ parents: dict[int, dict[str, str]] = {i: {} for i in range(len(data.records))}
627
+ drawn = {int(item.key) for item in data.items}
628
+ for by in GROUPINGS:
629
+ ids = page.top(by)
630
+ for index in drawn:
631
+ group = ids[_group_of(data.records[index], by)]
632
+ parents[index][f"parent-{by}"] = group
633
+ for index in range(len(data.records)):
634
+ # A record with no tile is reached from the lists; it hangs off the top.
635
+ links = parents[index] or {"parent": "top-provider"}
636
+ page.record(index, links)
637
+
638
+ models = sum(1 for r in data.records if r.kind in ("model", "auxiliary"))
639
+ buttons = "".join(
640
+ f'<button data-by="{by}" aria-pressed="false">{label}</button>'
641
+ for by, label in GROUPINGS.items()
642
+ )
643
+ out = [
644
+ "<!doctype html>",
645
+ '<html lang="en">',
646
+ "<head>",
647
+ '<meta charset="utf-8">',
648
+ '<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">',
649
+ "<title>Local models</title>",
650
+ # An empty icon, so a browser does not go looking for one.
651
+ '<link rel="icon" href="data:,">',
652
+ "<style>",
653
+ _colors(),
654
+ _CSS.strip(),
655
+ "</style>",
656
+ "</head>",
657
+ "<body>",
658
+ "<header>",
659
+ f'<div><h1>Local models</h1><div class="hero">{_xml(format_size(data.total))}</div>'
660
+ f'<div class="sub">{_xml(_summary(data, models))}</div></div>',
661
+ '<div class="controls">',
662
+ f'<div class="seg" role="group" aria-label="Group by">{buttons}</div>',
663
+ '<input type="search" id="search" placeholder="Filter by name" aria-label="Filter by name">',
664
+ "</div>",
665
+ "</header>",
666
+ '<nav id="crumbs" aria-label="Where you are"></nav>',
667
+ '<div class="layout">',
668
+ '<div class="map"><svg viewBox="0 0 1000 1000" role="group" aria-label="Map of models by size">',
669
+ *page.views,
670
+ "</svg></div>",
671
+ '<div class="panels">',
672
+ *page.panels,
673
+ "</div>",
674
+ "</div>",
675
+ "<footer>",
676
+ *[f'<p class="sub">{_xml(note)}</p>' for note in _notes(data, use_disk)],
677
+ '<p class="sub">Click a tile to open it, down to its files. Press Escape to go back up.</p>',
678
+ "</footer>",
679
+ '<div id="tip" hidden></div>',
680
+ "<script>",
681
+ _JS.strip(),
682
+ "</script>",
683
+ "</body>",
684
+ "</html>",
685
+ ]
686
+ return "\n".join(out) + "\n"