datahub-cli 0.2.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.
datahub/tui.py ADDED
@@ -0,0 +1,846 @@
1
+ """Full-screen data search, model comparison, and local catalog."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import asyncio
7
+ import json
8
+ import sqlite3
9
+ import subprocess
10
+ from collections import defaultdict
11
+ from dataclasses import dataclass, field
12
+ from functools import partial
13
+ from typing import ClassVar
14
+
15
+ from rich.text import Text
16
+ from textual import on
17
+ from textual.app import App, ComposeResult
18
+ from textual.binding import Binding
19
+ from textual.containers import Horizontal, Vertical, VerticalScroll
20
+ from textual.screen import ModalScreen
21
+ from textual.timer import Timer
22
+ from textual.widgets import (
23
+ Button,
24
+ Checkbox,
25
+ DataTable,
26
+ Footer,
27
+ Input,
28
+ Label,
29
+ ProgressBar,
30
+ Select,
31
+ Static,
32
+ TabbedContent,
33
+ TabPane,
34
+ )
35
+
36
+ from . import catalog, providers
37
+ from .config import Config, folder_name, resolve_config
38
+ from .hardware import detect_hardware, parse_memory
39
+ from .progress import PullProgress
40
+ from .providers import SearchItem, SearchOptions
41
+ from .scoring import QuantTier, build_quant_plan, fmt_params
42
+
43
+
44
+ def _fit_badge(verdict: str) -> Text:
45
+ styles = {
46
+ "FAST": "bold #22c55e",
47
+ "GOOD": "bold #38bdf8",
48
+ "OK(CPU)": "bold #38bdf8",
49
+ "TIGHT": "bold #eab308",
50
+ "SLOW(CPU)": "bold #eab308",
51
+ "TOO-BIG": "bold #ef4444",
52
+ "MAC-ONLY": "bold #ef4444",
53
+ "UNKNOWN": "dim",
54
+ }
55
+ return Text(verdict, style=styles.get(verdict, ""))
56
+
57
+
58
+ def _fmt_dls(count: int) -> str:
59
+ if count >= 1_000_000:
60
+ return f"{count / 1e6:.1f}M"
61
+ if count >= 1_000:
62
+ return f"{count / 1e3:.1f}k"
63
+ return str(count)
64
+
65
+
66
+ def _existing_categories(config: Config) -> list[str]:
67
+ defaults = [
68
+ "vision", "geospatial", "finance", "kaggle",
69
+ "cybersecurity", "scientific", "llm", "audio", "tabular",
70
+ ]
71
+ found: set[str] = set(defaults)
72
+ ds_dir = config.data_root / "datasets"
73
+ if ds_dir.is_dir():
74
+ for p in ds_dir.iterdir():
75
+ if p.is_dir() and not p.name.startswith("."):
76
+ found.add(p.name)
77
+ return sorted(found)
78
+
79
+
80
+
81
+ def _number(value: float | None, places: int = 1) -> str:
82
+ return f"{value:.{places}f}" if value is not None else "—"
83
+
84
+
85
+ def _disk(item: SearchItem) -> str:
86
+ return catalog.fmt_size(item.disk_bytes) if item.disk_bytes is not None else "Unknown"
87
+
88
+
89
+ @dataclass
90
+ class PullRequest:
91
+ name: str
92
+ category: str
93
+ notes: str
94
+ allow: list[str] | None
95
+
96
+
97
+ class PullModal(ModalScreen[PullRequest | None]):
98
+ BINDINGS: ClassVar = [Binding("escape", "cancel", "Cancel")]
99
+ CSS = """
100
+ PullModal { align: center middle; background: rgba(0, 0, 0, 0.8); }
101
+ #modal-box {
102
+ width: 74; max-width: 98%; height: auto; max-height: 95%;
103
+ background: #080808; border: heavy #8B0000; padding: 0 2;
104
+ }
105
+ #modal-title { text-style: bold; padding-bottom: 1; }
106
+ #modal-actions { height: 3; align: right middle; }
107
+ #modal-actions Button { margin-left: 1; }
108
+ #modal-error { color: #ff7777; height: auto; }
109
+ """
110
+
111
+ def __init__(self, kind: str, item: SearchItem, config: Config):
112
+ super().__init__()
113
+ self.kind = kind
114
+ self.config = config
115
+ self.item = item
116
+
117
+ def compose(self) -> ComposeResult:
118
+ with VerticalScroll(id="modal-box"):
119
+ yield Static(Text(f"Pull {self.item.id}"), id="modal-title")
120
+ location = self.config.data_root / self.kind
121
+ summary = f"Source {self.item.source} · Disk {_disk(self.item)}\n{location}"
122
+ if self.item.fit:
123
+ summary += f"/weights · {self.item.fit.verdict} · {_number(self.item.fit.total_gb)} GiB runtime"
124
+ if self.item.pull_ref:
125
+ summary += f"\nOllama tag {self.item.pull_ref}"
126
+ yield Static(Text(summary))
127
+ if self.kind == "datasets":
128
+ categories = _existing_categories(self.config)
129
+ default = self.item.source if self.item.source == "kaggle" else categories[0]
130
+ yield Label("Dataset category")
131
+ yield Select([(category, category) for category in categories], value=default,
132
+ allow_blank=False, id="modal-cat-select")
133
+ yield Input(placeholder="Or enter a custom category", id="modal-cat-custom")
134
+ yield Label("Local folder name")
135
+ yield Input(value=providers.default_folder(self.item), id="modal-name")
136
+ yield Label("Catalog notes")
137
+ yield Input(id="modal-notes")
138
+ if self.item.source == "hf":
139
+ yield Label("Allow file globs, separated by commas")
140
+ yield Input(placeholder="Example: *.safetensors, *.json", id="modal-allow")
141
+ yield Static("", id="modal-error")
142
+ with Horizontal(id="modal-actions"):
143
+ yield Button("Cancel [Esc]", id="btn-cancel")
144
+ yield Button("Download & Index", variant="error", id="btn-confirm")
145
+
146
+ def on_mount(self):
147
+ focus_id = "#modal-cat-select" if self.kind == "datasets" else "#modal-name"
148
+ self.query_one(focus_id).focus()
149
+
150
+ def action_cancel(self):
151
+ self.dismiss(None)
152
+
153
+ @on(Button.Pressed, "#btn-cancel")
154
+ def cancel_button(self):
155
+ self.action_cancel()
156
+
157
+ @on(Input.Submitted)
158
+ @on(Button.Pressed, "#btn-confirm")
159
+ def confirm(self):
160
+ name = self.query_one("#modal-name", Input).value.strip()
161
+ notes = self.query_one("#modal-notes", Input).value.strip()
162
+ category = ""
163
+ if self.kind == "datasets":
164
+ category = (self.query_one("#modal-cat-custom", Input).value.strip()
165
+ or str(self.query_one("#modal-cat-select", Select).value))
166
+ allow = None
167
+ if self.item.source == "hf":
168
+ patterns = self.query_one("#modal-allow", Input).value.split(",")
169
+ allow = [part.strip() for part in patterns if part.strip()] or None
170
+ try:
171
+ folder_name(name)
172
+ if category:
173
+ folder_name(category)
174
+ except ValueError as error:
175
+ self.query_one("#modal-error", Static).update(Text(str(error)))
176
+ return
177
+ self.dismiss(PullRequest(name, category, notes, allow))
178
+
179
+
180
+ class ResultsModal(ModalScreen[None]):
181
+ BINDINGS: ClassVar = [Binding("escape", "close", "Close")]
182
+ CSS = """
183
+ ResultsModal { align: center middle; background: rgba(0, 0, 0, 0.8); }
184
+ #result-box { width: 94%; height: 80%; background: #080808; border: heavy #4B0082; padding: 0 1; }
185
+ #result-title { height: auto; padding: 1; text-style: bold; }
186
+ #result-table { width: 1fr; }
187
+ """
188
+
189
+ def compose(self) -> ComposeResult:
190
+ with Vertical(id="result-box"):
191
+ yield Static(Text(self.heading), id="result-title")
192
+ yield DataTable(cursor_type="row", id="result-table")
193
+ yield Button("Close [Esc]", id="close-results")
194
+
195
+ def on_mount(self):
196
+ table = self.query_one(DataTable)
197
+ table.add_columns(*self.columns)
198
+ table.add_rows(self.rows)
199
+
200
+ def action_close(self):
201
+ self.dismiss()
202
+
203
+ @on(Button.Pressed, "#close-results")
204
+ def close_button(self):
205
+ self.action_close()
206
+
207
+
208
+ class CompareModal(ResultsModal):
209
+ def __init__(self, models: list[SearchItem]):
210
+ super().__init__()
211
+ self.heading = "Model comparison"
212
+ self.columns = ["Metric", *[item.id for item in models]]
213
+ self.rows = [
214
+ ("Parameters", *[fmt_params(item.model.params) for item in models]),
215
+ ("Active", *[fmt_params(item.model.active_params) for item in models]),
216
+ ("Quantization", *[item.fit.quant for item in models]),
217
+ ("Runtime GiB", *[_number(item.fit.total_gb, 2) for item in models]),
218
+ ("Tokens/s", *[_number(item.fit.tok_s) for item in models]),
219
+ ("Verdict", *[_fit_badge(item.fit.verdict) for item in models]),
220
+ ("Score", *[item.fit.score for item in models]),
221
+ *[(metric.title(), *[item.fit.dimensions[metric] for item in models])
222
+ for metric in ("fit", "speed", "quality", "context")],
223
+ ]
224
+
225
+
226
+ class PlanModal(ResultsModal):
227
+ def __init__(self, item: SearchItem, tiers: list[QuantTier], max_context: int):
228
+ super().__init__()
229
+ self.heading = f"Quantization plan · {item.id} · {max_context:,} context tokens"
230
+ self.columns = ("Quant", "Weights GiB", "Runtime GiB", "Tokens/s", "Quality", "Fit")
231
+ self.rows = [
232
+ (tier.quant, _number(tier.weights_gb, 2), _number(tier.total_gb, 2),
233
+ _number(tier.tok_s), f"{tier.quality}%", _fit_badge(tier.verdict))
234
+ for tier in tiers
235
+ ]
236
+
237
+
238
+ @dataclass
239
+ class BrowserState:
240
+ options: SearchOptions | None = None
241
+ cursor: str | None = None
242
+ generation: int = 0
243
+ busy: bool = False
244
+ timer: Timer | None = None
245
+ items: dict[str, SearchItem] = field(default_factory=dict)
246
+ errors: set[str] = field(default_factory=set)
247
+ cursors: set[str] = field(default_factory=set)
248
+
249
+
250
+ _BROWSER = {"m": "models", "d": "datasets"}
251
+ _TABS = {"tab-models": "m", "tab-datasets": "d", "tab-local": "l"}
252
+
253
+
254
+ class DataHubApp(App[None]):
255
+ TITLE = "DATA HUB"
256
+ BINDINGS: ClassVar = [
257
+ Binding("1", "switch_tab('tab-models')", "Models"),
258
+ Binding("2", "switch_tab('tab-datasets')", "Datasets"),
259
+ Binding("3", "switch_tab('tab-local')", "Local"),
260
+ Binding("/", "focus_search", "Search"),
261
+ Binding("escape", "focus_results", "Results", show=False),
262
+ Binding("m", "more", "More"),
263
+ Binding("p", "pull_selected", "Pull"),
264
+ Binding("c", "mark", "Mark"),
265
+ Binding("v", "compare", "Compare"),
266
+ Binding("x", "plan", "Quant plan"),
267
+ Binding("r", "refresh_active", "Refresh", show=False),
268
+ Binding("q", "quit", "Quit"),
269
+ ]
270
+
271
+ CSS = """
272
+ Screen {
273
+ background: #000000;
274
+ color: #e5e5e5;
275
+ }
276
+ #hw-bar {
277
+ height: 3;
278
+ background: #0a0a0a;
279
+ border-bottom: solid #8B0000;
280
+ padding: 0 2;
281
+ content-align: left middle;
282
+ }
283
+ TabbedContent {
284
+ height: 1fr;
285
+ background: #000000;
286
+ }
287
+ TabPane {
288
+ padding: 0 1;
289
+ background: #000000;
290
+ }
291
+ Tabs {
292
+ background: #0a0a0a;
293
+ }
294
+ Tab.-active {
295
+ background: #4B0082;
296
+ color: #ffffff;
297
+ text-style: bold;
298
+ }
299
+ Underline > .underline--bar {
300
+ color: #8B0000;
301
+ }
302
+ .filter-bar {
303
+ height: 3;
304
+ margin: 0;
305
+ align: left middle;
306
+ }
307
+ .filter-bar Input {
308
+ background: #0d0d0d;
309
+ border: solid #333333;
310
+ margin-right: 1;
311
+ }
312
+ .filter-bar Input:focus {
313
+ border: solid #8B0000;
314
+ }
315
+ .filter-bar Select {
316
+ margin-right: 1;
317
+ width: 19;
318
+ }
319
+ .filter-bar Checkbox {
320
+ background: #000000;
321
+ border: none;
322
+ margin-right: 1;
323
+ padding: 0 1;
324
+ }
325
+ .filter-bar Button {
326
+ margin-right: 1;
327
+ min-width: 10;
328
+ }
329
+ .q-input {
330
+ width: 1fr;
331
+ }
332
+ .secondary { margin-bottom: 1; }
333
+ .gb-input {
334
+ width: 12;
335
+ }
336
+ .split-body {
337
+ height: 1fr;
338
+ }
339
+ DataTable {
340
+ width: 2fr;
341
+ height: 1fr;
342
+ background: #000000;
343
+ border: solid #262626;
344
+ }
345
+ DataTable:focus {
346
+ border: solid #4B0082;
347
+ }
348
+ DataTable > .datatable--header {
349
+ background: #141414;
350
+ color: #ffffff;
351
+ text-style: bold;
352
+ }
353
+ DataTable > .datatable--cursor {
354
+ background: #4B0082;
355
+ color: #ffffff;
356
+ }
357
+ .inspector {
358
+ width: 1fr;
359
+ min-width: 23;
360
+ max-width: 56;
361
+ height: 1fr;
362
+ margin-left: 1;
363
+ background: #070707;
364
+ border: solid #262626;
365
+ padding: 1 2;
366
+ }
367
+ .inspector-title {
368
+ text-style: bold;
369
+ color: #ffffff;
370
+ border-bottom: solid #8B0000;
371
+ padding-bottom: 1;
372
+ margin-bottom: 1;
373
+ }
374
+ .inspector-body {
375
+ height: 1fr;
376
+ }
377
+ .inspector-btn {
378
+ width: 100%;
379
+ margin-top: 1;
380
+ }
381
+ #pull-progress { height: 2; background: #120000; padding: 0 2; }
382
+ #pull-progress-text { height: 1; }
383
+ #pull-progress-bar { height: 1; }
384
+ #status-bar {
385
+ height: 1;
386
+ background: #120000;
387
+ color: #f5f5f5;
388
+ padding: 0 2;
389
+ }
390
+ Footer {
391
+ background: #0a0a0a;
392
+ }
393
+ """
394
+
395
+ def __init__(self, memory: str | float | None = None, max_context: int = 8192, *,
396
+ config: Config | None = None):
397
+ super().__init__()
398
+ self.config = config or resolve_config()
399
+ self.hw = detect_hardware(memory)
400
+ self.max_context = max_context
401
+ self.active = "m"
402
+ self.browsers = {prefix: BrowserState() for prefix in _BROWSER}
403
+ self.marked: dict[str, SearchItem] = {}
404
+ self.local_items: dict[str, dict] = {}
405
+ self.local_busy = False
406
+ self.pulling = False
407
+
408
+ def compose(self) -> ComposeResult:
409
+ yield Static("", id="hw-bar")
410
+
411
+ with TabbedContent(id="tabs", initial="tab-models"):
412
+ # --- TAB 1: MODELS ---
413
+ with TabPane("1: Models", id="tab-models"):
414
+ uc_opts = [("All Use Cases", "")] + [(k, k) for k in sorted(providers.MODEL_USE_CASES)]
415
+ src_opts = [("Hugging Face", "hf"), ("Ollama", "ollama"), ("All Sources", "all")]
416
+ with Horizontal(classes="filter-bar"):
417
+ yield Input(placeholder="Search models (name, arch, keyword)...", id="m-query", classes="q-input")
418
+ yield Select(uc_opts, value="depth", allow_blank=False, id="m-usecase")
419
+ yield Select(src_opts, value="hf", allow_blank=False, id="m-source")
420
+ with Horizontal(classes="filter-bar secondary"):
421
+ yield Select([(label, key) for key, label in list(providers.SORTS.items())], value="downloads", allow_blank=False, id="m-sort")
422
+ yield Input(placeholder="Max GB", id="m-maxgb", classes="gb-input")
423
+ yield Checkbox("Fits", value=True, id="m-fits")
424
+ yield Checkbox("Ungated", value=True, id="m-ungated")
425
+ yield Button("Search", variant="error", id="m-search-btn")
426
+ yield Button("More [m]", id="m-more-btn", disabled=True)
427
+ with Horizontal(classes="split-body"):
428
+ yield DataTable(cursor_type="row", id="m-table")
429
+ with Vertical(classes="inspector"):
430
+ yield Static("Model Inspector", classes="inspector-title")
431
+ with VerticalScroll(classes="inspector-body"):
432
+ yield Static("Select a model to inspect hardware fit & details.", id="m-inspector")
433
+ yield Button("Pull model [p]", variant="error", id="m-pull-btn", classes="inspector-btn")
434
+
435
+ # --- TAB 2: DATASETS ---
436
+ with TabPane("2: Datasets", id="tab-datasets"):
437
+ duc_opts = [("All Domains", "")] + [(k, k) for k in sorted(providers.DATASET_USE_CASES)]
438
+ dsrc_opts = [("Hugging Face", "hf"), ("OpenML", "openml"), ("Kaggle", "kaggle"), ("All Sources", "all")]
439
+ dsize_opts = [("Any Scale", "")] + [(k, k) for k in providers.DATASET_SIZE_MAP]
440
+ with Horizontal(classes="filter-bar"):
441
+ yield Input(placeholder="Search datasets (topic, domain, name)...", id="d-query", classes="q-input")
442
+ yield Select(duc_opts, value="vision", allow_blank=False, id="d-usecase")
443
+ yield Select(dsrc_opts, value="hf", allow_blank=False, id="d-source")
444
+ yield Select(dsize_opts, value="", allow_blank=False, id="d-size")
445
+ with Horizontal(classes="filter-bar secondary"):
446
+ yield Select([(label, key) for key, label in providers.SORTS.items() if key != "score"], value="downloads", allow_blank=False, id="d-sort")
447
+ yield Input(placeholder="Max GB", id="d-maxgb", classes="gb-input")
448
+ yield Checkbox("Ungated", value=True, id="d-ungated")
449
+ yield Button("Search", variant="error", id="d-search-btn")
450
+ yield Button("More [m]", id="d-more-btn", disabled=True)
451
+ with Horizontal(classes="split-body"):
452
+ yield DataTable(cursor_type="row", id="d-table")
453
+ with Vertical(classes="inspector"):
454
+ yield Static("Dataset Inspector", classes="inspector-title")
455
+ with VerticalScroll(classes="inspector-body"):
456
+ yield Static("Select a dataset to inspect details.", id="d-inspector")
457
+ yield Button("Pull dataset [p]", variant="error", id="d-pull-btn", classes="inspector-btn")
458
+
459
+ # --- TAB 3: LOCAL CATALOG ---
460
+ with TabPane("3: Local Catalog", id="tab-local"):
461
+ with Horizontal(classes="filter-bar"):
462
+ yield Input(placeholder="Filter by ID, category, or note…", id="l-query", classes="q-input")
463
+ yield Checkbox("Orphans only", value=False, id="l-orphans")
464
+ yield Button("Re-Scan Disk", variant="primary", id="l-scan-btn")
465
+ yield Button("Scan Project Deps", id="l-deps-btn")
466
+ with Horizontal(classes="split-body"):
467
+ yield DataTable(cursor_type="row", id="l-table")
468
+ with Vertical(classes="inspector"):
469
+ yield Static("Catalog Schema & Usages", classes="inspector-title")
470
+ with VerticalScroll(classes="inspector-body"):
471
+ yield Static("Select any local dataset or model.", id="l-inspector")
472
+
473
+ with Vertical(id="pull-progress"):
474
+ yield Static(id="pull-progress-text")
475
+ yield ProgressBar(total=None, show_eta=False, id="pull-progress-bar")
476
+ yield Static("Ready.", id="status-bar")
477
+ yield Footer()
478
+
479
+ def on_mount(self):
480
+ self.query_one("#pull-progress").display = False
481
+ model_table = self.query_one("#m-table", DataTable)
482
+ model_table.add_column("Cmp", key="compare")
483
+ model_table.add_columns("Score", "Model ID", "Params", "Quant", "RAM", "Speed", "Fit", "DLs", "Task")
484
+ self.query_one("#d-table", DataTable).add_columns("Dataset ID", "Source", "Scale", "Size", "DLs", "Task")
485
+ self.query_one("#l-table", DataTable).add_columns("Type", "ID", "Size", "Refs", "Notes")
486
+ self.query_one("#m-table", DataTable).focus()
487
+ self._refresh_local()
488
+ self._start_search("m")
489
+
490
+ def _status(self, message: str):
491
+ self.query_one("#status-bar", Static).update(Text(message))
492
+
493
+ def _table(self, prefix: str) -> DataTable:
494
+ return self.query_one(f"#{prefix}-table", DataTable)
495
+
496
+ def _selected(self, prefix: str) -> SearchItem | None:
497
+ table = self._table(prefix)
498
+ if not table.row_count:
499
+ return None
500
+ key, _ = table.coordinate_to_cell_key(table.cursor_coordinate)
501
+ return self.browsers[prefix].items.get(key.value)
502
+
503
+ def action_switch_tab(self, tab: str):
504
+ self.query_one("#tabs", TabbedContent).active = tab
505
+ self._table(_TABS[tab]).focus()
506
+
507
+ @on(TabbedContent.TabActivated)
508
+ def tab_activated(self, event: TabbedContent.TabActivated):
509
+ self.active = _TABS[event.pane.id]
510
+ if self.active in self.browsers and self.browsers[self.active].options is None:
511
+ self._start_search(self.active)
512
+
513
+ def action_focus_results(self):
514
+ if isinstance(self.screen, ModalScreen):
515
+ return
516
+ self._table(self.active).focus()
517
+
518
+ def action_focus_search(self):
519
+ self.query_one(f"#{self.active}-query", Input).focus()
520
+
521
+ def action_more(self):
522
+ if self.active in self.browsers:
523
+ self._load_page(self.active)
524
+
525
+ def action_refresh_active(self):
526
+ if self.active == "l":
527
+ self._refresh_local()
528
+ else:
529
+ self._start_search(self.active, force=True)
530
+
531
+ def _options(self, prefix: str) -> SearchOptions:
532
+ def select(key: str) -> str:
533
+ return str(self.query_one(f"#{prefix}-{key}", Select).value)
534
+
535
+ def checked(key: str) -> bool:
536
+ return self.query_one(f"#{prefix}-{key}", Checkbox).value
537
+
538
+ limit = self.query_one(f"#{prefix}-maxgb", Input).value.strip()
539
+ return SearchOptions(query=self.query_one(f"#{prefix}-query", Input).value.strip(),
540
+ use_case=select("usecase"), source=select("source"), sort=select("sort"),
541
+ max_gb=parse_memory(limit) if limit else None, ungated=checked("ungated"),
542
+ fits=prefix == "m" and checked("fits"), size=select("size") if prefix == "d" else "")
543
+
544
+ def _start_search(self, prefix: str, *, force: bool = False):
545
+ state = self.browsers[prefix]
546
+ if state.timer is not None:
547
+ state.timer.stop()
548
+ state.timer = None
549
+ try:
550
+ options = self._options(prefix)
551
+ except ValueError as error:
552
+ self._status(str(error))
553
+ return
554
+ if not force and options == state.options:
555
+ return
556
+ state.generation += 1
557
+ state.options, state.cursor, state.busy = options, None, False
558
+ state.items.clear()
559
+ state.errors.clear()
560
+ state.cursors.clear()
561
+ self._table(prefix).clear()
562
+ self.query_one(f"#{prefix}-inspector", Static).update("Searching…")
563
+ self._load_page(prefix, first=True)
564
+
565
+ def _load_page(self, prefix: str, *, first: bool = False):
566
+ state = self.browsers[prefix]
567
+ if state.busy or state.options is None or (not first and not state.cursor):
568
+ return
569
+ state.busy = True
570
+ self.query_one(f"#{prefix}-more-btn", Button).disabled = True
571
+ self._status(f"Searching {_BROWSER[prefix]}…")
572
+ self.run_worker(self._fetch(prefix, state.generation, state.options, state.cursor),
573
+ group=f"search-{prefix}", exclusive=True)
574
+
575
+ async def _fetch(self, prefix: str, generation: int, options: SearchOptions, cursor: str | None):
576
+ try:
577
+ page = await asyncio.to_thread(providers.search, _BROWSER[prefix], options, self.hw,
578
+ self.max_context, cursor=cursor)
579
+ except (OSError, ValueError, subprocess.SubprocessError) as error:
580
+ state = self.browsers[prefix]
581
+ if state.generation == generation:
582
+ state.busy = False
583
+ self.query_one(f"#{prefix}-more-btn", Button).disabled = state.cursor is None
584
+ self._status(str(error))
585
+ if not state.items:
586
+ self.query_one(f"#{prefix}-inspector", Static).update(Text(str(error)))
587
+ return
588
+ state = self.browsers[prefix]
589
+ if state.generation != generation:
590
+ return
591
+ state.cursors.add(cursor)
592
+ state.cursor = page.next_cursor if page.next_cursor not in state.cursors else None
593
+ state.errors.update(page.errors)
594
+ table = self._table(prefix)
595
+ for item in page.items:
596
+ key = f"{item.source}:{item.id}"
597
+ if key in state.items:
598
+ continue
599
+ state.items[key] = item
600
+ if prefix == "m":
601
+ tier = item.fit
602
+ table.add_row(Text("[*]" if key in self.marked else ""), tier.score, Text(item.id),
603
+ fmt_params(item.model.params), tier.quant, _number(tier.total_gb, 2),
604
+ _number(tier.tok_s), _fit_badge(tier.verdict), _fmt_dls(item.downloads), item.task,
605
+ key=key)
606
+ else:
607
+ ident = f"{item.id} · {item.name}" if item.name else item.id
608
+ table.add_row(Text(ident), item.source, item.rows_bucket or "—", _disk(item),
609
+ _fmt_dls(item.downloads), Text(item.task), key=key)
610
+ state.busy = False
611
+ self.query_one(f"#{prefix}-more-btn", Button).disabled = state.cursor is None
612
+ detail = f" · {'; '.join(sorted(state.errors))}" if state.errors else ""
613
+ if self.active == prefix:
614
+ self._status(f"{len(state.items)} {_BROWSER[prefix]} loaded" + detail)
615
+ if not state.items:
616
+ message = "No matches on this page. Press m for more." if state.cursor else "No matching results."
617
+ self.query_one(f"#{prefix}-inspector", Static).update(Text(message + detail))
618
+
619
+ @on(Input.Changed)
620
+ @on(Select.Changed)
621
+ @on(Checkbox.Changed)
622
+ def filters_changed(self, event):
623
+ widget_id = event.control.id or ""
624
+ prefix, _, _ = widget_id.partition("-")
625
+ if prefix == "l":
626
+ self._render_local()
627
+ elif prefix == self.active and prefix in self.browsers:
628
+ state = self.browsers[prefix]
629
+ if state.timer is not None:
630
+ state.timer.stop()
631
+ state.timer = self.set_timer(0.40, partial(self._start_search, prefix))
632
+
633
+ @on(Input.Submitted)
634
+ def input_submitted(self, event: Input.Submitted):
635
+ prefix = (event.input.id or "").partition("-")[0]
636
+ if prefix in self.browsers:
637
+ self._start_search(prefix, force=True)
638
+ if prefix == self.active:
639
+ self._table(prefix).focus()
640
+
641
+ @on(Button.Pressed)
642
+ def button_pressed(self, event: Button.Pressed):
643
+ prefix, _, action = (event.button.id or "").partition("-")
644
+ if action == "search-btn":
645
+ self._start_search(prefix, force=True)
646
+ elif action == "more-btn":
647
+ self._load_page(prefix)
648
+ elif action == "pull-btn":
649
+ self.action_pull_selected()
650
+ elif action in {"scan-btn", "deps-btn"}:
651
+ self._refresh_local(action)
652
+
653
+ @on(DataTable.RowHighlighted)
654
+ def row_highlighted(self, event: DataTable.RowHighlighted):
655
+ prefix = (event.data_table.id or "").partition("-")[0]
656
+ key = event.row_key.value
657
+ if prefix == "l":
658
+ if key in self.local_items:
659
+ self._inspect_local(self.local_items[key])
660
+ return
661
+ if prefix not in self.browsers:
662
+ return
663
+ state = self.browsers[prefix]
664
+ if item := state.items.get(key):
665
+ self._inspect_remote(prefix, item)
666
+ remaining = event.data_table.row_count - event.cursor_row - 1
667
+ if prefix == self.active and remaining <= 5:
668
+ self._load_page(prefix)
669
+
670
+ @on(DataTable.RowSelected)
671
+ def row_selected(self, event: DataTable.RowSelected):
672
+ if event.data_table.id in ("m-table", "d-table"):
673
+ self.action_pull_selected()
674
+
675
+ def _inspect_remote(self, prefix: str, item: SearchItem):
676
+ lines = [item.id, "", f"Source {item.source}", f"Task {item.task or '—'}",
677
+ f"Disk {_disk(item)}", f"Downloads {item.downloads:,}", f"Likes {item.likes:,}",
678
+ f"Access {'Gated' if item.gated else 'Open'}"]
679
+ if item.note:
680
+ lines += ["", item.note]
681
+ if item.size_tags:
682
+ lines += ["Available sizes " + ", ".join(item.size_tags)]
683
+ if item.pull_ref:
684
+ lines += [f"Selected tag {item.pull_ref}"]
685
+ if item.fit:
686
+ tier = item.fit
687
+ lines += ["", f"Parameters {fmt_params(item.model.params)}",
688
+ f"Active {fmt_params(item.model.active_params)}",
689
+ f"Quant {tier.quant}", f"Runtime {_number(tier.total_gb, 2)} GiB",
690
+ f"Speed {_number(tier.tok_s)} tok/s", f"Context {self.max_context:,} tokens",
691
+ f"Fit {tier.verdict}", f"Score {tier.score}/100",
692
+ *[f" {metric.title()} {value}/100" for metric, value in tier.dimensions.items()]]
693
+ elif item.rows_bucket:
694
+ lines.append(f"Scale {item.rows_bucket}")
695
+ self.query_one(f"#{prefix}-inspector", Static).update(Text("\n".join(lines)))
696
+
697
+ def action_mark(self):
698
+ item = self._selected("m") if self.active == "m" else None
699
+ if not item:
700
+ return
701
+ key = f"{item.source}:{item.id}"
702
+ if key in self.marked:
703
+ del self.marked[key]
704
+ elif len(self.marked) < 6:
705
+ self.marked[key] = item
706
+ else:
707
+ self._status("Up to six models can be marked.")
708
+ return
709
+ self._table("m").update_cell(key, "compare", Text("[*]" if key in self.marked else ""))
710
+ self._status(f"{len(self.marked)} models marked")
711
+
712
+ def action_compare(self):
713
+ if self.marked:
714
+ self.push_screen(CompareModal(list(self.marked.values())))
715
+
716
+ def action_plan(self):
717
+ if self.active == "m" and (item := self._selected("m")):
718
+ self.push_screen(PlanModal(item, build_quant_plan(item.model, self.hw, self.max_context), self.max_context))
719
+
720
+ def action_pull_selected(self):
721
+ if self.active not in self.browsers:
722
+ return
723
+ if self.pulling:
724
+ self._status("A download is already in progress.")
725
+ return
726
+ if item := self._selected(self.active):
727
+ kind = _BROWSER[self.active]
728
+ self.push_screen(PullModal(kind, item, self.config), partial(self._begin_pull, kind, item))
729
+
730
+ def _begin_pull(self, kind: str, item: SearchItem, request: PullRequest | None):
731
+ if request is not None:
732
+ self.pulling = True
733
+ self.query_one("#pull-progress").display = True
734
+ self._show_pull_progress(PullProgress(f"Preparing {item.id}…", stage="preparing"))
735
+ self.run_worker(self._download(kind, item, request), group="download")
736
+
737
+ def _show_pull_progress(self, update: PullProgress):
738
+ if not self.pulling:
739
+ return
740
+ summary = " · ".join(part for part in (update.message, update.detail) if part)
741
+ self.query_one("#pull-progress-text", Static).update(Text(summary))
742
+ bar = self.query_one("#pull-progress-bar", ProgressBar)
743
+ bar.update(total=update.total, progress=update.completed or 0)
744
+
745
+ async def _download(self, kind: str, item: SearchItem, request: PullRequest):
746
+ loop = asyncio.get_running_loop()
747
+
748
+ def report(update: PullProgress) -> None:
749
+ if not loop.is_closed():
750
+ loop.call_soon_threadsafe(self._show_pull_progress, update)
751
+ try:
752
+ path = await asyncio.to_thread(providers.pull, kind, item, request.name, category=request.category,
753
+ notes=request.notes, allow=request.allow, config=self.config, progress=report)
754
+ except (OSError, ValueError, sqlite3.Error, subprocess.SubprocessError, SystemExit) as error:
755
+ self._status(f"Download failed · {error}")
756
+ else:
757
+ self._status(f"Downloaded and indexed {path}")
758
+ self._refresh_local()
759
+ finally:
760
+ self.pulling = False
761
+ self.query_one("#pull-progress").display = False
762
+
763
+ def _refresh_local(self, action: str = ""):
764
+ if action == "deps-btn" and self.config.projects_root is None:
765
+ self._status("Set PROJECTS_ROOT or start DataHub with --projects-root to scan dependencies.")
766
+ return
767
+ if self.local_busy:
768
+ if action:
769
+ self._status("Working on the local catalog…")
770
+ else:
771
+ self.set_timer(0.3, self._refresh_local)
772
+ return
773
+ self.local_busy = True
774
+ if action:
775
+ self._status("Scanning projects…" if action == "deps-btn" else "Scanning disk…")
776
+ self.run_worker(self._load_local(action), group="catalog")
777
+
778
+ def _read_local(self, action: str) -> dict[str, dict]:
779
+ if action == "scan-btn":
780
+ catalog.cmd_scan(argparse.Namespace(deps=False, quiet=True, config=self.config))
781
+ with catalog.database(self.config) as conn:
782
+ if action == "deps-btn":
783
+ catalog.refresh_usages(conn, self.config)
784
+ usages = defaultdict(list)
785
+ for row in conn.execute("SELECT * FROM usages ORDER BY project, file_path, line_no"):
786
+ usages[row["item_type"], row["item_id"]].append(dict(row))
787
+ return {
788
+ f"{kind}:{row['id']}": dict(row, kind=kind, usages=usages[kind, row["id"]])
789
+ for kind in ("dataset", "model")
790
+ for row in conn.execute(f"SELECT * FROM {kind}s ORDER BY id")
791
+ }
792
+
793
+ async def _load_local(self, action: str):
794
+ try:
795
+ self.local_items = await asyncio.to_thread(self._read_local, action)
796
+ except (OSError, sqlite3.Error, SystemExit) as error:
797
+ self._status(str(error))
798
+ else:
799
+ self._render_local()
800
+ if action:
801
+ self._status(f"{len(self.local_items)} catalog items indexed")
802
+ finally:
803
+ self.local_busy = False
804
+ self._render_hardware()
805
+
806
+ def _render_hardware(self):
807
+ hw = self.hw
808
+ datasets = sum(item["kind"] == "dataset" for item in self.local_items.values())
809
+ size = sum(item["size_bytes"] for item in self.local_items.values())
810
+ banner = (f"{hw.chip} · {hw.ram_gb:.1f} GiB RAM · {hw.accelerator} · "
811
+ f"{hw.vram_gb:.1f} GiB usable · ~{hw.bandwidth_gb_s:g} GB/s\n"
812
+ f"{self.config.data_root} · {datasets} datasets · {len(self.local_items) - datasets} models"
813
+ f" · {catalog.fmt_size(size)}")
814
+ self.query_one("#hw-bar", Static).update(Text(banner))
815
+
816
+ def _render_local(self):
817
+ table = self._table("l")
818
+ query = self.query_one("#l-query", Input).value.casefold().strip()
819
+ orphans = self.query_one("#l-orphans", Checkbox).value
820
+ table.clear()
821
+ for key, item in self.local_items.items():
822
+ if orphans and item["usages"]:
823
+ continue
824
+ if query not in f"{item['id']} {item['notes'] or ''} {item['rel_path']}".casefold():
825
+ continue
826
+ note = (item["notes"] or "").replace("\n", " ")
827
+ table.add_row(item["kind"], Text(item["id"]), catalog.fmt_size(item["size_bytes"]),
828
+ len(item["usages"]), Text(note[:48]), key=key)
829
+ if not table.row_count:
830
+ self.query_one("#l-inspector", Static).update("No matching catalog items.")
831
+
832
+ def _inspect_local(self, item: dict):
833
+ lines = [item["id"], str(self.config.data_root / item["rel_path"]),
834
+ catalog.fmt_size(item["size_bytes"])]
835
+ if item.get("notes"):
836
+ lines += ["", f"Notes {item['notes']}"]
837
+ if item.get("source_url"):
838
+ lines += [f"Source {item['source_url']}"]
839
+ try:
840
+ schema = json.loads(item.get("schema_json") or "{}")
841
+ except ValueError:
842
+ schema = {}
843
+ lines += ["", "Cached schema", json.dumps(schema, indent=2, ensure_ascii=False),
844
+ "", "Project usages"]
845
+ lines += [f"{ref['project']} · {ref['file_path']}:{ref['line_no']}" for ref in item["usages"]] or ["None indexed"]
846
+ self.query_one("#l-inspector", Static).update(Text("\n".join(lines)))