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/__init__.py +46 -0
- datahub/catalog.py +1152 -0
- datahub/cli.py +251 -0
- datahub/config.py +101 -0
- datahub/hardware.py +148 -0
- datahub/ollama_search.py +97 -0
- datahub/progress.py +44 -0
- datahub/providers.py +702 -0
- datahub/py.typed +0 -0
- datahub/scoring.py +172 -0
- datahub/tui.py +846 -0
- datahub_cli-0.2.0.dist-info/METADATA +130 -0
- datahub_cli-0.2.0.dist-info/RECORD +16 -0
- datahub_cli-0.2.0.dist-info/WHEEL +4 -0
- datahub_cli-0.2.0.dist-info/entry_points.txt +4 -0
- datahub_cli-0.2.0.dist-info/licenses/LICENSE +21 -0
datahub/cli.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
"""Command-line entry points for search, downloads, and the local catalog."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import math
|
|
8
|
+
import sqlite3
|
|
9
|
+
import subprocess
|
|
10
|
+
import sys
|
|
11
|
+
from dataclasses import asdict
|
|
12
|
+
from time import monotonic
|
|
13
|
+
|
|
14
|
+
from rich.console import Console
|
|
15
|
+
from rich.progress import BarColumn, Progress, TaskProgressColumn, TextColumn
|
|
16
|
+
|
|
17
|
+
from . import __version__, catalog, providers
|
|
18
|
+
from .config import create_directories, resolve_config, save_config, shell_exports
|
|
19
|
+
from .hardware import detect_hardware, parse_memory
|
|
20
|
+
from .progress import PullProgress
|
|
21
|
+
from .providers import SearchItem, SearchOptions
|
|
22
|
+
from .scoring import fmt_params
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _positive_int(text: str) -> int:
|
|
26
|
+
value = int(text)
|
|
27
|
+
if value <= 0:
|
|
28
|
+
raise argparse.ArgumentTypeError("must be greater than zero")
|
|
29
|
+
return value
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _positive_float(text: str) -> float:
|
|
33
|
+
value = float(text)
|
|
34
|
+
if not math.isfinite(value) or value <= 0:
|
|
35
|
+
raise argparse.ArgumentTypeError("must be finite and greater than zero")
|
|
36
|
+
return value
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _memory(text: str) -> float:
|
|
40
|
+
try:
|
|
41
|
+
return parse_memory(text)
|
|
42
|
+
except ValueError as error:
|
|
43
|
+
raise argparse.ArgumentTypeError(str(error)) from error
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _hw(args: argparse.Namespace) -> None:
|
|
47
|
+
hw = detect_hardware(args.memory)
|
|
48
|
+
if args.json:
|
|
49
|
+
print(json.dumps(asdict(hw), indent=2))
|
|
50
|
+
return
|
|
51
|
+
print(f"{hw.chip} · {hw.cpu_cores} CPU cores · {hw.os_name} {hw.arch}")
|
|
52
|
+
print(f"RAM {hw.ram_gb:.1f} GiB · {hw.accelerator}"
|
|
53
|
+
f"{f' ({hw.gpu_name})' if hw.gpu_name else ''}")
|
|
54
|
+
print(f"Usable {hw.vram_gb:.1f} GiB · comfortable {hw.comfortable_gb:.1f} GiB"
|
|
55
|
+
f" · estimated bandwidth {hw.bandwidth_gb_s:g} GB/s")
|
|
56
|
+
print(hw.notes)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _search(args: argparse.Namespace) -> None:
|
|
60
|
+
models = args.kind == "models"
|
|
61
|
+
hw = detect_hardware(args.memory) if models else None
|
|
62
|
+
options = SearchOptions(**{key: getattr(args, key) for key in SearchOptions.__dataclass_fields__
|
|
63
|
+
if hasattr(args, key)})
|
|
64
|
+
items = []
|
|
65
|
+
seen, errors, visited = set(), set(), set()
|
|
66
|
+
cursor = args.cursor
|
|
67
|
+
if not args.json:
|
|
68
|
+
if models:
|
|
69
|
+
print(f"{'MODEL':<48} {'PARAMS':>8} {'QUANT':<10} {'RAM GiB':>8} {'TOK/S':>8} {'SCORE':>5} {'FIT':<10} {'PULLS':>10} TASK")
|
|
70
|
+
else:
|
|
71
|
+
print(f"{'DATASET':<58} {'DOWNLOADS':>10} {'SCALE':<19} TASK")
|
|
72
|
+
while len(items) < args.limit and cursor not in visited:
|
|
73
|
+
visited.add(cursor)
|
|
74
|
+
page = providers.search(args.kind, options, hw, args.max_context, cursor=cursor,
|
|
75
|
+
page_size=min(50, args.limit - len(items)))
|
|
76
|
+
for item in page.items:
|
|
77
|
+
key = (item.source, item.id)
|
|
78
|
+
if key not in seen:
|
|
79
|
+
items.append(item)
|
|
80
|
+
seen.add(key)
|
|
81
|
+
for error in page.errors:
|
|
82
|
+
if error not in errors:
|
|
83
|
+
print(error, file=sys.stderr)
|
|
84
|
+
errors.add(error)
|
|
85
|
+
cursor = page.next_cursor
|
|
86
|
+
if args.one_page or cursor is None:
|
|
87
|
+
break
|
|
88
|
+
if options.sort == "score":
|
|
89
|
+
items.sort(key=lambda item: item.fit.score, reverse=True)
|
|
90
|
+
if args.json:
|
|
91
|
+
payload = [asdict(item) for item in (items if args.one_page else items[:args.limit])]
|
|
92
|
+
print(json.dumps({"items": payload, "next_cursor": cursor} if args.one_page else payload, indent=2))
|
|
93
|
+
else:
|
|
94
|
+
for item in items[:args.limit]:
|
|
95
|
+
if models:
|
|
96
|
+
fit = item.fit
|
|
97
|
+
ram = f"{fit.total_gb:.2f}" if fit.total_gb is not None else "—"
|
|
98
|
+
speed = f"{fit.tok_s:.1f}" if fit.tok_s is not None else "—"
|
|
99
|
+
print(f"{item.id:<48} {fmt_params(item.model.params):>8} {fit.quant:<10} {ram:>8} "
|
|
100
|
+
f"{speed:>8} {fit.score:>5} {fit.verdict:<10} {item.downloads:>10,} {item.task}")
|
|
101
|
+
else:
|
|
102
|
+
name = f"{item.id} ({item.name})" if item.name else item.id
|
|
103
|
+
print(f"{name:<58} {item.downloads:>10,} {item.rows_bucket or '—':<19} {item.task}")
|
|
104
|
+
if not items:
|
|
105
|
+
print("No results.")
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _pull(args: argparse.Namespace) -> None:
|
|
109
|
+
prefix, sep, _ = args.id.partition(":")
|
|
110
|
+
source = prefix if sep and prefix in providers.SOURCES[args.kind] else "hf"
|
|
111
|
+
item = SearchItem(source, args.id)
|
|
112
|
+
console = Console(stderr=True)
|
|
113
|
+
bar = Progress(
|
|
114
|
+
TextColumn("{task.description}", markup=False),
|
|
115
|
+
BarColumn(),
|
|
116
|
+
TaskProgressColumn(),
|
|
117
|
+
TextColumn("{task.fields[detail]}", markup=False),
|
|
118
|
+
console=console,
|
|
119
|
+
)
|
|
120
|
+
task = None
|
|
121
|
+
label = ""
|
|
122
|
+
terminal = console.is_terminal
|
|
123
|
+
last_report = monotonic()
|
|
124
|
+
pending_summary = ""
|
|
125
|
+
printed_summary = ""
|
|
126
|
+
|
|
127
|
+
def display(update: PullProgress) -> None:
|
|
128
|
+
nonlocal task, label, last_report, pending_summary, printed_summary
|
|
129
|
+
if update.stage != "transfer":
|
|
130
|
+
bar.stop()
|
|
131
|
+
if pending_summary and pending_summary != printed_summary:
|
|
132
|
+
console.print(pending_summary, markup=False, highlight=False)
|
|
133
|
+
console.print(update.message, markup=False, highlight=False)
|
|
134
|
+
elif terminal:
|
|
135
|
+
if task is None or label != update.message:
|
|
136
|
+
if task is not None:
|
|
137
|
+
bar.remove_task(task)
|
|
138
|
+
label = update.message
|
|
139
|
+
task = bar.add_task(label, total=update.total, detail=update.detail)
|
|
140
|
+
bar.start()
|
|
141
|
+
bar.update(task, completed=update.completed or 0, total=update.total, detail=update.detail)
|
|
142
|
+
else:
|
|
143
|
+
pending_summary = update.detail or update.message
|
|
144
|
+
now = monotonic()
|
|
145
|
+
if now - last_report >= 5 and pending_summary != printed_summary:
|
|
146
|
+
console.print(pending_summary, markup=False, highlight=False)
|
|
147
|
+
printed_summary = pending_summary
|
|
148
|
+
last_report = now
|
|
149
|
+
|
|
150
|
+
try:
|
|
151
|
+
path = providers.pull(args.kind, item, args.name or providers.default_folder(item),
|
|
152
|
+
category=getattr(args, "category", ""), notes=args.notes,
|
|
153
|
+
allow=args.allow, revision=args.revision, config=args.config,
|
|
154
|
+
progress=display, native_progress=terminal)
|
|
155
|
+
finally:
|
|
156
|
+
bar.stop()
|
|
157
|
+
print(f"Downloaded and indexed {path}")
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _tui(args: argparse.Namespace) -> None:
|
|
161
|
+
from .tui import DataHubApp
|
|
162
|
+
|
|
163
|
+
DataHubApp(memory=args.memory, max_context=args.max_context, config=args.config).run()
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _init(args: argparse.Namespace) -> None:
|
|
167
|
+
config = args.config
|
|
168
|
+
create_directories(config)
|
|
169
|
+
with catalog.database(config):
|
|
170
|
+
pass
|
|
171
|
+
print(f"Data root ready at {config.data_root}")
|
|
172
|
+
print(f"SQLite catalog at {config.db_path}")
|
|
173
|
+
if args.save_config:
|
|
174
|
+
print(f"Saved configuration to {save_config(config)}")
|
|
175
|
+
print("\nOptional shell settings")
|
|
176
|
+
print("\n".join(shell_exports(config)))
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def main(argv: list[str] | None = None) -> None:
|
|
180
|
+
parser = argparse.ArgumentParser(description="Search model and dataset registries and manage your local catalog.")
|
|
181
|
+
parser.add_argument("--version", action="version", version=f"datahub {__version__}")
|
|
182
|
+
catalog.add_root_flags(parser)
|
|
183
|
+
parser.add_argument("--memory", type=_memory, help="Simulate usable memory, e.g. 24G or 512MiB")
|
|
184
|
+
parser.add_argument("--max-context", type=_positive_int, default=8192,
|
|
185
|
+
help="Context tokens used for model estimates (default: 8192)")
|
|
186
|
+
parser.set_defaults(handler=_tui)
|
|
187
|
+
commands = parser.add_subparsers(dest="cmd")
|
|
188
|
+
tui = commands.add_parser("tui", help="Open the full-screen interface")
|
|
189
|
+
catalog.add_root_flags(tui)
|
|
190
|
+
tui.set_defaults(handler=_tui)
|
|
191
|
+
init = commands.add_parser("init", help="Create the data directory and SQLite catalog")
|
|
192
|
+
catalog.add_root_flags(init)
|
|
193
|
+
init.add_argument("--save-config", action="store_true", help="Save resolved roots to the user config file")
|
|
194
|
+
init.set_defaults(handler=_init)
|
|
195
|
+
hw = commands.add_parser("hw", help="Show detected hardware and memory budget")
|
|
196
|
+
hw.add_argument("--json", action="store_true")
|
|
197
|
+
hw.set_defaults(handler=_hw)
|
|
198
|
+
|
|
199
|
+
for kind, alias in (("models", "sm"), ("datasets", "sd")):
|
|
200
|
+
search = commands.add_parser(f"search-{kind}", aliases=[alias], help=f"Search remote {kind}")
|
|
201
|
+
search.set_defaults(handler=_search, kind=kind)
|
|
202
|
+
search.add_argument("query", nargs="?", default="")
|
|
203
|
+
presets = providers.MODEL_USE_CASES if kind == "models" else providers.DATASET_USE_CASES
|
|
204
|
+
search.add_argument("-u", "--use-case", default="", help=", ".join(presets))
|
|
205
|
+
search.add_argument("--source", choices=(*providers.SOURCES[kind], "all"), default="hf")
|
|
206
|
+
search.add_argument("--sort", choices=list(providers.SORTS) if kind == "models"
|
|
207
|
+
else [key for key in providers.SORTS if key != "score"], default="downloads")
|
|
208
|
+
search.add_argument("--ungated", action="store_true")
|
|
209
|
+
search.add_argument("--max-gb", type=_positive_float, help="Maximum download size in GiB when known")
|
|
210
|
+
search.add_argument("-n", "--limit", type=_positive_int, default=15)
|
|
211
|
+
search.add_argument("--json", action="store_true")
|
|
212
|
+
search.add_argument("--one-page", action="store_true", help="Return one provider page and cursor as JSON")
|
|
213
|
+
search.add_argument("--cursor", help="Resume a provider page using a cursor from --one-page")
|
|
214
|
+
if kind == "models":
|
|
215
|
+
search.add_argument("--fits", action="store_true")
|
|
216
|
+
search.add_argument("--max-params", type=_positive_float, help="Maximum parameters in billions")
|
|
217
|
+
search.add_argument("--format", default="", help="Hugging Face format or library filter")
|
|
218
|
+
else:
|
|
219
|
+
search.add_argument("--size", default="", help=", ".join(providers.DATASET_SIZE_MAP))
|
|
220
|
+
search.add_argument("--modality", default="")
|
|
221
|
+
search.add_argument("--license", default="")
|
|
222
|
+
|
|
223
|
+
for kind, name, alias in (("models", "model", "pm"), ("datasets", "dataset", "pd")):
|
|
224
|
+
pull = commands.add_parser(f"pull-{name}", aliases=[alias], help=f"Download and index a {name}")
|
|
225
|
+
catalog.add_root_flags(pull)
|
|
226
|
+
pull.set_defaults(handler=_pull, kind=kind)
|
|
227
|
+
pull.add_argument("id", help="Hugging Face repo ID or a provider-prefixed result ID")
|
|
228
|
+
pull.add_argument("--name", help="Local folder name")
|
|
229
|
+
pull.add_argument("--notes", default="")
|
|
230
|
+
pull.add_argument("--allow", action="append", help="Hugging Face file glob (repeatable)")
|
|
231
|
+
pull.add_argument("--revision", default="main", help="Hugging Face revision")
|
|
232
|
+
if kind == "datasets":
|
|
233
|
+
pull.add_argument("-c", "--category", required=True)
|
|
234
|
+
|
|
235
|
+
catalog.add_subcommands(commands)
|
|
236
|
+
args = parser.parse_args(argv)
|
|
237
|
+
if getattr(args, "one_page", False):
|
|
238
|
+
args.json = True
|
|
239
|
+
try:
|
|
240
|
+
if args.handler not in (_hw, _search):
|
|
241
|
+
args.config = resolve_config(data_root=getattr(args, "data_root", None),
|
|
242
|
+
projects_root=getattr(args, "projects_root", None))
|
|
243
|
+
args.handler(args)
|
|
244
|
+
except KeyboardInterrupt:
|
|
245
|
+
sys.exit(130)
|
|
246
|
+
except (OSError, ValueError, sqlite3.Error, subprocess.SubprocessError) as error:
|
|
247
|
+
parser.exit(1, f"{parser.prog}: {error}\n")
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
if __name__ == "__main__":
|
|
251
|
+
main()
|
datahub/config.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Resolve catalog paths from flags, environment, and user configuration."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import shlex
|
|
9
|
+
import tempfile
|
|
10
|
+
import tomllib
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class Config:
|
|
17
|
+
data_root: Path
|
|
18
|
+
projects_root: Path | None = None
|
|
19
|
+
|
|
20
|
+
@property
|
|
21
|
+
def db_path(self) -> Path:
|
|
22
|
+
return self.data_root / "catalog.db"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def config_path() -> Path:
|
|
26
|
+
if os.name == "nt" and os.getenv("APPDATA"):
|
|
27
|
+
base = Path(os.environ["APPDATA"])
|
|
28
|
+
else:
|
|
29
|
+
base = Path(os.getenv("XDG_CONFIG_HOME") or Path.home() / ".config")
|
|
30
|
+
return base.expanduser() / "datahub" / "config.toml"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def resolve_config(*, data_root: str | Path | None = None,
|
|
34
|
+
projects_root: str | Path | None = None) -> Config:
|
|
35
|
+
path = config_path()
|
|
36
|
+
data = data_root or os.getenv("DATA_ROOT")
|
|
37
|
+
projects = projects_root or os.getenv("PROJECTS_ROOT")
|
|
38
|
+
if not data or not projects:
|
|
39
|
+
try:
|
|
40
|
+
with path.open("rb") as stream:
|
|
41
|
+
settings = tomllib.load(stream)
|
|
42
|
+
except FileNotFoundError:
|
|
43
|
+
settings = {}
|
|
44
|
+
except tomllib.TOMLDecodeError as error:
|
|
45
|
+
raise ValueError(f"Invalid configuration in {path}: {error}") from error
|
|
46
|
+
for name, override in (("data_root", data), ("projects_root", projects)):
|
|
47
|
+
if not override and name in settings and not isinstance(settings[name], str):
|
|
48
|
+
raise ValueError(f"{name} in {path} must be a path string")
|
|
49
|
+
data = data or settings.get("data_root")
|
|
50
|
+
projects = projects or settings.get("projects_root")
|
|
51
|
+
return Config(
|
|
52
|
+
Path(data or Path.home() / "data").expanduser().absolute(),
|
|
53
|
+
Path(projects).expanduser().absolute() if projects else None,
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def create_directories(config: Config) -> None:
|
|
58
|
+
root = config.data_root
|
|
59
|
+
if root.is_symlink() and not root.is_dir():
|
|
60
|
+
raise OSError(f"Data root symlink is unavailable: {root}")
|
|
61
|
+
for name in ("datasets", "models/weights", "models/trained", "cache"):
|
|
62
|
+
(root / name).mkdir(parents=True, exist_ok=True)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def save_config(config: Config) -> Path:
|
|
66
|
+
path = config_path()
|
|
67
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
68
|
+
lines = [f"data_root = {json.dumps(str(config.data_root), ensure_ascii=False)}"]
|
|
69
|
+
if config.projects_root is not None:
|
|
70
|
+
lines.append(f"projects_root = {json.dumps(str(config.projects_root), ensure_ascii=False)}")
|
|
71
|
+
with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, encoding="utf-8", delete=False) as stream:
|
|
72
|
+
pending = Path(stream.name)
|
|
73
|
+
stream.write("\n".join(lines) + "\n")
|
|
74
|
+
try:
|
|
75
|
+
pending.replace(path)
|
|
76
|
+
finally:
|
|
77
|
+
pending.unlink(missing_ok=True)
|
|
78
|
+
return path
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def shell_exports(config: Config) -> list[str]:
|
|
82
|
+
root = config.data_root
|
|
83
|
+
mounts = {
|
|
84
|
+
"DATA_ROOT": root,
|
|
85
|
+
"HF_HOME": root / "cache" / "huggingface",
|
|
86
|
+
"TORCH_HOME": root / "cache" / "torch",
|
|
87
|
+
"OLLAMA_MODELS": root / "cache" / "ollama",
|
|
88
|
+
}
|
|
89
|
+
if os.name == "nt":
|
|
90
|
+
quoted = {key: str(value).replace("'", "''") for key, value in mounts.items()}
|
|
91
|
+
return [f"$env:{key} = '{value}'" for key, value in quoted.items()]
|
|
92
|
+
return [f"export {key}={shlex.quote(str(value))}" for key, value in mounts.items()]
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def folder_name(value: str) -> str:
|
|
96
|
+
if (not value or value.startswith(".") or value != value.strip()
|
|
97
|
+
or value.endswith(".")
|
|
98
|
+
or re.fullmatch(r"(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³])(?:\..*)?", value, re.IGNORECASE)
|
|
99
|
+
or re.search(r'[/\\:*?"<>|\x00-\x1f]', value)):
|
|
100
|
+
raise ValueError("Use a visible, single folder name without path separators")
|
|
101
|
+
return value
|
datahub/hardware.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"""Detect a local inference budget and estimate memory bandwidth."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
import os
|
|
7
|
+
import platform
|
|
8
|
+
import re
|
|
9
|
+
import subprocess
|
|
10
|
+
from dataclasses import dataclass, replace
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
GIB = 1024**3
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class HardwareProfile:
|
|
18
|
+
os_name: str
|
|
19
|
+
arch: str
|
|
20
|
+
chip: str
|
|
21
|
+
cpu_cores: int
|
|
22
|
+
ram_gb: float
|
|
23
|
+
accelerator: str
|
|
24
|
+
gpu_name: str
|
|
25
|
+
vram_gb: float
|
|
26
|
+
comfortable_gb: float
|
|
27
|
+
bandwidth_gb_s: float
|
|
28
|
+
notes: str = ""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
# Approximate peak GB/s by Apple chip family. Some bin variants differ.
|
|
32
|
+
APPLE_BANDWIDTH = {
|
|
33
|
+
1: (68, 200, 400, 800),
|
|
34
|
+
2: (100, 200, 400, 800),
|
|
35
|
+
3: (100, 150, 350, 819),
|
|
36
|
+
4: (120, 273, 546, 0),
|
|
37
|
+
5: (153, 307, 614, 0),
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
# Representative published bandwidths. Unknown cards use a conservative estimate.
|
|
41
|
+
CUDA_BANDWIDTH = {
|
|
42
|
+
"5090": 1792, "5080": 960, "5070": 672, "5060": 448,
|
|
43
|
+
"4090": 1008, "4080": 717, "4070": 504, "4060": 272,
|
|
44
|
+
"3090": 936, "3080": 760, "3070": 448, "3060": 360,
|
|
45
|
+
"A100": 1935, "H100": 3000, "H200": 4800, "L40": 864,
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def parse_memory(value: str) -> float:
|
|
50
|
+
match = re.fullmatch(r"\s*(\d+(?:\.\d+)?|\.\d+)\s*([gmt])?(?:i?b)?\s*", value, re.IGNORECASE)
|
|
51
|
+
if not match:
|
|
52
|
+
raise ValueError("memory must be a positive size such as 8G or 512MiB")
|
|
53
|
+
amount = float(match[1])
|
|
54
|
+
amount *= {"m": 1 / 1024, "t": 1024}.get((match[2] or "g").lower(), 1)
|
|
55
|
+
if not math.isfinite(amount) or amount <= 0:
|
|
56
|
+
raise ValueError("memory must be finite and greater than zero")
|
|
57
|
+
return amount
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _run(*command: str) -> str:
|
|
61
|
+
try:
|
|
62
|
+
result = subprocess.run(command, capture_output=True, text=True, timeout=3, check=False)
|
|
63
|
+
return result.stdout.strip() if result.returncode == 0 else ""
|
|
64
|
+
except (OSError, subprocess.SubprocessError):
|
|
65
|
+
return ""
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _read(path: str) -> str:
|
|
69
|
+
try:
|
|
70
|
+
return Path(path).read_text(encoding="utf-8", errors="replace")
|
|
71
|
+
except OSError:
|
|
72
|
+
return ""
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _number(text: str) -> int:
|
|
76
|
+
match = re.search(r"\d+", text)
|
|
77
|
+
return int(match[0]) if match else 0
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _apple_bandwidth(chip: str) -> float:
|
|
81
|
+
match = re.search(r"\bM(\d+)\s*(Pro|Max|Ultra)?", chip, re.IGNORECASE)
|
|
82
|
+
if not match:
|
|
83
|
+
return 68
|
|
84
|
+
tier = ("", "pro", "max", "ultra").index((match[2] or "").lower())
|
|
85
|
+
return APPLE_BANDWIDTH.get(int(match[1]), APPLE_BANDWIDTH[4])[tier] or 800
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def detect_hardware(memory: str | float | None = None) -> HardwareProfile:
|
|
89
|
+
system = platform.system()
|
|
90
|
+
arch = platform.machine().lower()
|
|
91
|
+
cores = os.cpu_count() or 1
|
|
92
|
+
chip = platform.processor() or arch
|
|
93
|
+
ram = 0.0
|
|
94
|
+
if system == "Darwin":
|
|
95
|
+
ram = _number(_run("sysctl", "-n", "hw.memsize")) / GIB
|
|
96
|
+
chip = _run("sysctl", "-n", "machdep.cpu.brand_string") or chip
|
|
97
|
+
elif system == "Linux":
|
|
98
|
+
mem = re.search(r"^MemTotal:\s+(\d+)", _read("/proc/meminfo"), re.MULTILINE)
|
|
99
|
+
ram = int(mem[1]) / 1024**2 if mem else 0.0
|
|
100
|
+
brand = re.search(r"^(?:model name|Hardware)\s*:\s*(.+)$", _read("/proc/cpuinfo"), re.MULTILINE)
|
|
101
|
+
chip = brand[1] if brand else chip
|
|
102
|
+
elif system == "Windows":
|
|
103
|
+
ram_text = _run("wmic", "ComputerSystem", "get", "TotalPhysicalMemory")
|
|
104
|
+
if not ram_text:
|
|
105
|
+
ram_text = _run("powershell", "-NoProfile", "-Command",
|
|
106
|
+
"(Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory")
|
|
107
|
+
ram = _number(ram_text) / GIB
|
|
108
|
+
brand = _run("wmic", "cpu", "get", "Name")
|
|
109
|
+
if not brand:
|
|
110
|
+
brand = _run("powershell", "-NoProfile", "-Command",
|
|
111
|
+
"(Get-CimInstance Win32_Processor | Select-Object -First 1).Name")
|
|
112
|
+
chip = next((line.strip() for line in brand.splitlines() if line.strip() not in ("", "Name")), chip)
|
|
113
|
+
|
|
114
|
+
if not ram:
|
|
115
|
+
try:
|
|
116
|
+
ram = os.sysconf("SC_PHYS_PAGES") * os.sysconf("SC_PAGE_SIZE") / GIB
|
|
117
|
+
except (AttributeError, OSError, ValueError):
|
|
118
|
+
pass
|
|
119
|
+
|
|
120
|
+
if system == "Darwin" and arch in ("arm64", "aarch64"):
|
|
121
|
+
wired = _number(_run("sysctl", "-n", "iogpu.wired_limit_mb"))
|
|
122
|
+
budget = min(ram * 0.92, wired / 1024) if wired else ram * 0.75
|
|
123
|
+
profile = HardwareProfile(system, arch, chip, cores, ram, "apple_silicon",
|
|
124
|
+
f"{chip} GPU", budget, budget * 0.85,
|
|
125
|
+
_apple_bandwidth(chip), "Unified memory")
|
|
126
|
+
else:
|
|
127
|
+
gpus = []
|
|
128
|
+
for row in _run("nvidia-smi", "--query-gpu=name,memory.total", "--format=csv,noheader,nounits").splitlines():
|
|
129
|
+
name, _, mib = row.rpartition(",")
|
|
130
|
+
if mib.strip().isdigit() and int(mib) > 0:
|
|
131
|
+
gpus.append((int(mib) / 1024, name.strip()))
|
|
132
|
+
if gpus:
|
|
133
|
+
budget, gpu = max(gpus)
|
|
134
|
+
bandwidth = next((bw for name, bw in CUDA_BANDWIDTH.items() if name in gpu), 300)
|
|
135
|
+
profile = HardwareProfile(system, arch, chip, cores, ram, "cuda", gpu, budget,
|
|
136
|
+
budget * 0.85, bandwidth, "Largest single CUDA device")
|
|
137
|
+
else:
|
|
138
|
+
budget = max(0, ram * 0.60)
|
|
139
|
+
profile = HardwareProfile(system, arch, chip, cores, ram, "cpu", "", budget,
|
|
140
|
+
budget * 0.80, min(60, 12 + 2 * cores),
|
|
141
|
+
"CPU-only inference")
|
|
142
|
+
if memory is not None:
|
|
143
|
+
budget = parse_memory(memory) if isinstance(memory, str) else float(memory)
|
|
144
|
+
if not math.isfinite(budget) or budget <= 0:
|
|
145
|
+
raise ValueError("memory must be finite and greater than zero")
|
|
146
|
+
profile = replace(profile, vram_gb=budget, comfortable_gb=budget * 0.85,
|
|
147
|
+
notes=f"{profile.notes}. Simulated memory budget.")
|
|
148
|
+
return profile
|
datahub/ollama_search.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Parse Ollama's public search cards and the next-page HTMX marker."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from html.parser import HTMLParser
|
|
8
|
+
from urllib.parse import parse_qs, urlsplit
|
|
9
|
+
|
|
10
|
+
CAPABILITIES = frozenset({"decision", "embedding", "thinking", "tools", "vision"})
|
|
11
|
+
_AMOUNT = r"\d+(?:\.\d+)?[bm]"
|
|
12
|
+
_SIZE = re.compile(rf"(?:\d+x)?{_AMOUNT}(?:-a{_AMOUNT})?", re.IGNORECASE)
|
|
13
|
+
_SLUG = re.compile(r"[\w.-]+/[\w.-]+", re.ASCII)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class OllamaCard:
|
|
18
|
+
slug: str
|
|
19
|
+
note: str = ""
|
|
20
|
+
downloads: int = 0
|
|
21
|
+
sizes: list[str] = field(default_factory=list)
|
|
22
|
+
capabilities: list[str] = field(default_factory=list)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class _SearchParser(HTMLParser):
|
|
26
|
+
def __init__(self) -> None:
|
|
27
|
+
super().__init__(convert_charrefs=True)
|
|
28
|
+
self.cards: list[OllamaCard] = []
|
|
29
|
+
self.next_page: str | None = None
|
|
30
|
+
self.recognized = False
|
|
31
|
+
self._card: OllamaCard | None = None
|
|
32
|
+
self._capture: list[tuple[str, bool, list[str]]] = []
|
|
33
|
+
|
|
34
|
+
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
|
35
|
+
values = dict(attrs)
|
|
36
|
+
if "data-result-count" in values or values.get("id") == "searchresults":
|
|
37
|
+
self.recognized = True
|
|
38
|
+
if tag == "li" and values.get("hx-trigger") == "revealed":
|
|
39
|
+
endpoint = urlsplit(values.get("hx-get") or "")
|
|
40
|
+
if not endpoint.netloc and endpoint.path == "/search":
|
|
41
|
+
query = parse_qs(endpoint.query)
|
|
42
|
+
number = (query.get("page") or query.get("p") or [""])[0]
|
|
43
|
+
if number.isascii() and number.isdecimal():
|
|
44
|
+
self.next_page = number
|
|
45
|
+
self.recognized = True
|
|
46
|
+
|
|
47
|
+
if tag == "a":
|
|
48
|
+
endpoint = urlsplit(values.get("href") or "")
|
|
49
|
+
slug = endpoint.path.removeprefix("/")
|
|
50
|
+
classes = (values.get("class") or "").split()
|
|
51
|
+
if (not endpoint.scheme and not endpoint.netloc and _SLUG.fullmatch(slug)
|
|
52
|
+
and (slug.startswith("library/") or {"group", "grid"}.issubset(classes))):
|
|
53
|
+
self._card = OllamaCard(slug.removeprefix("library/"))
|
|
54
|
+
return
|
|
55
|
+
if self._card is None:
|
|
56
|
+
return
|
|
57
|
+
if tag in {"span", "p"}:
|
|
58
|
+
badge = "rounded-md" in (values.get("class") or "").split()
|
|
59
|
+
self._capture.append((tag, badge, []))
|
|
60
|
+
if tag == "span":
|
|
61
|
+
count = re.fullmatch(r"([\d,]+)\s+(?:downloads?|pulls?)", values.get("title") or "", re.IGNORECASE)
|
|
62
|
+
if count:
|
|
63
|
+
self._card.downloads = int(count[1].replace(",", ""))
|
|
64
|
+
|
|
65
|
+
def handle_data(self, data: str) -> None:
|
|
66
|
+
if self._capture:
|
|
67
|
+
self._capture[-1][2].append(data)
|
|
68
|
+
|
|
69
|
+
def handle_endtag(self, tag: str) -> None:
|
|
70
|
+
card = self._card
|
|
71
|
+
if card is None:
|
|
72
|
+
return
|
|
73
|
+
if tag == "a":
|
|
74
|
+
self.cards.append(card)
|
|
75
|
+
self.recognized = True
|
|
76
|
+
self._capture.clear()
|
|
77
|
+
self._card = None
|
|
78
|
+
elif self._capture and self._capture[-1][0] == tag:
|
|
79
|
+
_, badge, chunks = self._capture.pop()
|
|
80
|
+
text = " ".join("".join(chunks).split())
|
|
81
|
+
if self._capture:
|
|
82
|
+
self._capture[-1][2].extend(chunks)
|
|
83
|
+
if tag == "p":
|
|
84
|
+
card.note = text
|
|
85
|
+
elif text.lower() in CAPABILITIES and text.lower() not in card.capabilities:
|
|
86
|
+
card.capabilities.append(text.lower())
|
|
87
|
+
elif badge and _SIZE.fullmatch(text) and text.lower() not in card.sizes:
|
|
88
|
+
card.sizes.append(text.lower())
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def parse_search_html(html: str, *, allow_empty_fragment: bool = False) -> tuple[list[OllamaCard], str | None]:
|
|
92
|
+
parser = _SearchParser()
|
|
93
|
+
parser.feed(html)
|
|
94
|
+
parser.close()
|
|
95
|
+
if not parser.recognized and "No models found" not in html and not (allow_empty_fragment and not html.strip()):
|
|
96
|
+
raise ValueError("Ollama returned an unrecognized search page")
|
|
97
|
+
return parser.cards, parser.next_page
|
datahub/progress.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Progress events shared by the command line and full-screen app."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
|
|
8
|
+
from .catalog import fmt_size
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True)
|
|
12
|
+
class PullProgress:
|
|
13
|
+
message: str
|
|
14
|
+
completed: float | None = None
|
|
15
|
+
total: float | None = None
|
|
16
|
+
unit: str = ""
|
|
17
|
+
elapsed: float = 0
|
|
18
|
+
stage: str = "transfer"
|
|
19
|
+
|
|
20
|
+
@property
|
|
21
|
+
def detail(self) -> str:
|
|
22
|
+
if self.completed is None or self.unit == "%":
|
|
23
|
+
return ""
|
|
24
|
+
if self.unit == "B":
|
|
25
|
+
transferred = fmt_size(int(self.completed))
|
|
26
|
+
if self.total is not None:
|
|
27
|
+
transferred += f" / {fmt_size(int(self.total))}"
|
|
28
|
+
rate = self.completed / self.elapsed if self.elapsed > 0 else 0
|
|
29
|
+
if rate:
|
|
30
|
+
transferred += f" · {fmt_size(int(rate))}/s"
|
|
31
|
+
if self.total is not None and self.completed < self.total:
|
|
32
|
+
seconds = round((self.total - self.completed) / rate)
|
|
33
|
+
minutes, seconds = divmod(seconds, 60)
|
|
34
|
+
hours, minutes = divmod(minutes, 60)
|
|
35
|
+
eta = f"{hours:d}:{minutes:02d}:{seconds:02d}" if hours else f"{minutes:d}:{seconds:02d}"
|
|
36
|
+
transferred += f" · ETA {eta}"
|
|
37
|
+
return transferred
|
|
38
|
+
count = f"{int(self.completed)}"
|
|
39
|
+
if self.total is not None:
|
|
40
|
+
count += f" / {int(self.total)}"
|
|
41
|
+
return f"{count} {self.unit}".rstrip()
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
ProgressCallback = Callable[[PullProgress], None]
|