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/providers.py
ADDED
|
@@ -0,0 +1,702 @@
|
|
|
1
|
+
"""Paginated registries and downloads with a shared result format."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import csv
|
|
7
|
+
import fnmatch
|
|
8
|
+
import io
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import re
|
|
12
|
+
import shutil
|
|
13
|
+
import sqlite3
|
|
14
|
+
import subprocess
|
|
15
|
+
import sysconfig
|
|
16
|
+
import tempfile
|
|
17
|
+
import threading
|
|
18
|
+
from dataclasses import dataclass, replace
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from time import monotonic
|
|
21
|
+
from typing import Any
|
|
22
|
+
from urllib.error import HTTPError
|
|
23
|
+
from urllib.parse import quote, urlencode, urljoin, urlsplit
|
|
24
|
+
from urllib.request import Request, urlopen
|
|
25
|
+
|
|
26
|
+
from . import catalog
|
|
27
|
+
from .config import Config, folder_name, resolve_config
|
|
28
|
+
from .hardware import GIB, HardwareProfile
|
|
29
|
+
from .ollama_search import OllamaCard, parse_search_html
|
|
30
|
+
from .progress import ProgressCallback, PullProgress
|
|
31
|
+
from .scoring import FITS, ModelSpec, QuantTier, parse_parameters, score_model
|
|
32
|
+
|
|
33
|
+
HF = "https://huggingface.co"
|
|
34
|
+
OLLAMA_SEARCH = "https://ollama.com/search"
|
|
35
|
+
OLLAMA_API = "https://ollamadb.dev/api/v1/models"
|
|
36
|
+
OPENML = "https://www.openml.org/api/v1/json"
|
|
37
|
+
SOURCES = {"models": ("hf", "ollama"), "datasets": ("hf", "openml", "kaggle")}
|
|
38
|
+
SORTS = {"downloads": "Downloads", "likes": "Likes", "trendingScore": "Trending", "score": "Fit score", "newest": "Newest"}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
MODEL_USE_CASES: dict[str, dict[str, Any]] = {
|
|
42
|
+
"depth": {"pipeline_tag": "depth-estimation", "filters": [], "search": ""},
|
|
43
|
+
"image-text": {"pipeline_tag": "zero-shot-image-classification", "filters": [], "search": ""},
|
|
44
|
+
"clip": {"pipeline_tag": "zero-shot-image-classification", "filters": [], "search": "clip"},
|
|
45
|
+
"vision": {"pipeline_tag": "image-feature-extraction", "filters": [], "search": ""},
|
|
46
|
+
"detection": {"pipeline_tag": "object-detection", "filters": [], "search": ""},
|
|
47
|
+
"segmentation": {"pipeline_tag": "image-segmentation", "filters": [], "search": ""},
|
|
48
|
+
"vlm": {"pipeline_tag": "image-text-to-text", "filters": [], "search": ""},
|
|
49
|
+
"ocr": {"pipeline_tag": "image-text-to-text", "filters": [], "search": "ocr"},
|
|
50
|
+
"3d": {"pipeline_tag": "image-to-3d", "filters": [], "search": ""},
|
|
51
|
+
"embeddings": {"pipeline_tag": "feature-extraction", "filters": [], "search": "embed"},
|
|
52
|
+
"rerank": {"pipeline_tag": "text-ranking", "filters": [], "search": ""},
|
|
53
|
+
"llm": {"pipeline_tag": "text-generation", "filters": [], "search": ""},
|
|
54
|
+
"chat": {"pipeline_tag": "text-generation", "filters": [], "search": "instruct"},
|
|
55
|
+
"thinking": {"pipeline_tag": "text-generation", "filters": [], "search": "reasoning"},
|
|
56
|
+
"tools": {"pipeline_tag": "text-generation", "filters": [], "search": "tool"},
|
|
57
|
+
"code": {"pipeline_tag": "text-generation", "filters": [], "search": "coder"},
|
|
58
|
+
"ner": {"pipeline_tag": "token-classification", "filters": [], "search": "ner"},
|
|
59
|
+
"sentiment": {"pipeline_tag": "text-classification", "filters": [], "search": "sentiment"},
|
|
60
|
+
"asr": {"pipeline_tag": "automatic-speech-recognition", "filters": [], "search": ""},
|
|
61
|
+
"speech": {"pipeline_tag": "automatic-speech-recognition", "filters": [], "search": ""},
|
|
62
|
+
"audio": {"pipeline_tag": "audio-classification", "filters": [], "search": ""},
|
|
63
|
+
"music": {"pipeline_tag": "", "filters": [], "search": "music"},
|
|
64
|
+
"tabular": {"pipeline_tag": "tabular-classification", "filters": [], "search": ""},
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
# Dataset use-case aliases -> HF task_categories / modality filters
|
|
68
|
+
DATASET_USE_CASES: dict[str, dict[str, Any]] = {
|
|
69
|
+
"depth": {"filters": [], "search": "depth"},
|
|
70
|
+
"vision": {"filters": ["modality:image"], "search": ""},
|
|
71
|
+
"detection": {"filters": ["task_categories:object-detection"], "search": ""},
|
|
72
|
+
"segmentation": {"filters": ["task_categories:image-segmentation"], "search": ""},
|
|
73
|
+
"geospatial": {"filters": [], "search": "geospatial"},
|
|
74
|
+
"finance": {"filters": [], "search": "finance"},
|
|
75
|
+
"tabular": {"filters": ["modality:tabular"], "search": ""},
|
|
76
|
+
"cybersecurity": {"filters": [], "search": "cybersecurity"},
|
|
77
|
+
"llm": {"filters": ["task_categories:text-generation"], "search": ""},
|
|
78
|
+
"code": {"filters": ["task_categories:text-generation"], "search": "code"},
|
|
79
|
+
"qa": {"filters": ["task_categories:question-answering"], "search": ""},
|
|
80
|
+
"ner": {"filters": ["task_categories:token-classification"], "search": ""},
|
|
81
|
+
"audio": {"filters": ["modality:audio"], "search": ""},
|
|
82
|
+
"music": {"filters": ["modality:audio"], "search": "music"},
|
|
83
|
+
"video": {"filters": ["modality:video"], "search": ""},
|
|
84
|
+
"3d": {"filters": ["modality:3d"], "search": ""},
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
DATASET_SIZE_MAP: dict[str, str] = {
|
|
88
|
+
"tiny": "size_categories:n<1K",
|
|
89
|
+
"small": "size_categories:1K<n<10K",
|
|
90
|
+
"medium": "size_categories:10K<n<100K",
|
|
91
|
+
"large": "size_categories:100K<n<1M",
|
|
92
|
+
"xlarge": "size_categories:1M<n<10M",
|
|
93
|
+
"huge": "size_categories:10M<n<100M",
|
|
94
|
+
"massive": "size_categories:100M<n<1B",
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@dataclass(frozen=True)
|
|
99
|
+
class SearchOptions:
|
|
100
|
+
query: str = ""
|
|
101
|
+
use_case: str = ""
|
|
102
|
+
source: str = "hf"
|
|
103
|
+
sort: str = "downloads"
|
|
104
|
+
max_gb: float | None = None
|
|
105
|
+
max_params: float | None = None # Billions
|
|
106
|
+
fits: bool = False
|
|
107
|
+
ungated: bool = False
|
|
108
|
+
size: str = ""
|
|
109
|
+
format: str = ""
|
|
110
|
+
modality: str = ""
|
|
111
|
+
license: str = ""
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@dataclass(frozen=True)
|
|
115
|
+
class SearchItem:
|
|
116
|
+
source: str
|
|
117
|
+
id: str
|
|
118
|
+
task: str = ""
|
|
119
|
+
disk_bytes: int | None = None
|
|
120
|
+
downloads: int = 0
|
|
121
|
+
likes: int = 0
|
|
122
|
+
gated: bool = False
|
|
123
|
+
rows_bucket: str = ""
|
|
124
|
+
name: str = ""
|
|
125
|
+
model: ModelSpec | None = None
|
|
126
|
+
fit: QuantTier | None = None
|
|
127
|
+
note: str = ""
|
|
128
|
+
size_tags: tuple[str, ...] = ()
|
|
129
|
+
pull_ref: str = ""
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
@dataclass(frozen=True)
|
|
133
|
+
class SearchPage:
|
|
134
|
+
items: list[SearchItem]
|
|
135
|
+
next_cursor: str | None
|
|
136
|
+
errors: tuple[str, ...] = ()
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _hf_token() -> str | None:
|
|
140
|
+
token = os.getenv("HF_TOKEN") or os.getenv("HUGGING_FACE_HUB_TOKEN")
|
|
141
|
+
if token:
|
|
142
|
+
return token
|
|
143
|
+
try:
|
|
144
|
+
from huggingface_hub import get_token
|
|
145
|
+
except ImportError:
|
|
146
|
+
home = Path(os.getenv("HF_HOME", Path.home() / ".cache/huggingface"))
|
|
147
|
+
try:
|
|
148
|
+
return Path(os.getenv("HF_TOKEN_PATH", home / "token")).read_text(encoding="utf-8").strip()
|
|
149
|
+
except OSError:
|
|
150
|
+
return None
|
|
151
|
+
return get_token()
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _request(url: str, token: str | None = None) -> Request:
|
|
155
|
+
request = Request(url, headers={"User-Agent": "datahub-cli/0.1"})
|
|
156
|
+
if token:
|
|
157
|
+
request.add_unredirected_header("Authorization", f"Bearer {token}")
|
|
158
|
+
return request
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _json(url: str, token: str | None = None) -> tuple[Any, str]:
|
|
162
|
+
with urlopen(_request(url, token), timeout=18) as response:
|
|
163
|
+
return json.load(response), ", ".join(response.headers.get_all("Link", ()))
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _next_link(link: str, base: str) -> str | None:
|
|
167
|
+
for match in re.finditer(r"<([^>]+)>\s*((?:;\s*[^,;]+)*)", link):
|
|
168
|
+
if re.search(r';\s*rel\s*=\s*(?:"[^"]*\bnext\b[^"]*"|next\b)', match[2], re.IGNORECASE):
|
|
169
|
+
url = urljoin(base, match[1])
|
|
170
|
+
if urlsplit(url).netloc == urlsplit(base).netloc and urlsplit(url).scheme == "https":
|
|
171
|
+
return url
|
|
172
|
+
return None
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _int(value: Any) -> int:
|
|
176
|
+
try:
|
|
177
|
+
return int(float(value))
|
|
178
|
+
except (ValueError, TypeError, OverflowError):
|
|
179
|
+
return 0
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def safetensors_bytes(metadata: dict) -> int | None:
|
|
183
|
+
dtype_bytes = {
|
|
184
|
+
"F64": 8, "I64": 8, "U64": 8, "F32": 4, "I32": 4, "U32": 4,
|
|
185
|
+
"F16": 2, "BF16": 2, "I16": 2, "U16": 2, "I8": 1, "U8": 1,
|
|
186
|
+
"BOOL": 1, "I4": 0.5, "U4": 0.5,
|
|
187
|
+
}
|
|
188
|
+
counts = metadata.get("parameters") or {}
|
|
189
|
+
total = 0.0
|
|
190
|
+
for dtype, count in counts.items():
|
|
191
|
+
dtype = dtype.upper()
|
|
192
|
+
total += max(0, _int(count)) * (1 if dtype.startswith("F8_") else dtype_bytes.get(dtype, 2))
|
|
193
|
+
return int(total) or None
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _model_item(source, ident, task, tags, disk, params, active, downloads, likes, gated,
|
|
197
|
+
options, hw, context, quant="") -> SearchItem | None:
|
|
198
|
+
if options.max_params is not None and (params is None or params > options.max_params * 1e9):
|
|
199
|
+
return None
|
|
200
|
+
spec = ModelSpec(ident, params, active, task, tuple(tags), disk, quant)
|
|
201
|
+
fit = score_model(spec, hw, context)
|
|
202
|
+
if options.fits and fit.verdict not in FITS:
|
|
203
|
+
return None
|
|
204
|
+
if options.max_gb is not None:
|
|
205
|
+
size = disk / GIB if disk is not None else fit.weights_gb
|
|
206
|
+
if size is None or size > options.max_gb:
|
|
207
|
+
return None
|
|
208
|
+
return SearchItem(source, ident, task, disk, downloads, likes, gated, model=spec, fit=fit)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _first_card_value(card, tags, key):
|
|
212
|
+
values = card.get(key) or [tag.split(":", 1)[1] for tag in tags if tag.startswith(f"{key}:")]
|
|
213
|
+
return values if isinstance(values, str) else (values[0] if values else "")
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _hf_page(kind, options, hw, context, cursor, page_size):
|
|
217
|
+
models = kind == "models"
|
|
218
|
+
fields = ("safetensors", "tags", "pipeline_tag", "downloads", "likes", "gated") if models else (
|
|
219
|
+
"cardData", "tags", "downloads", "likes", "gated")
|
|
220
|
+
params = [("expand", field) for field in fields]
|
|
221
|
+
params.extend((("limit", str(page_size)), ("direction", "-1"),
|
|
222
|
+
("sort", {"score": "downloads", "newest": "createdAt"}.get(options.sort, options.sort))))
|
|
223
|
+
case = options.use_case.lower()
|
|
224
|
+
presets = MODEL_USE_CASES if models else DATASET_USE_CASES
|
|
225
|
+
preset = presets.get(case, {})
|
|
226
|
+
query = options.query or preset.get("search", "") or (case if not models and case not in presets else "")
|
|
227
|
+
if query:
|
|
228
|
+
params.append(("search", query))
|
|
229
|
+
filters = list(preset.get("filters", ()))
|
|
230
|
+
if models:
|
|
231
|
+
pipeline = preset.get("pipeline_tag", case)
|
|
232
|
+
if pipeline:
|
|
233
|
+
params.append(("pipeline_tag", pipeline))
|
|
234
|
+
if options.format:
|
|
235
|
+
filters.append(options.format)
|
|
236
|
+
else:
|
|
237
|
+
if options.size:
|
|
238
|
+
filters.append(DATASET_SIZE_MAP.get(options.size, f"size_categories:{options.size}"))
|
|
239
|
+
for key in ("modality", "license"):
|
|
240
|
+
if value := getattr(options, key):
|
|
241
|
+
filters.append(f"{key}:{value}")
|
|
242
|
+
params.extend(("filter", value) for value in filters)
|
|
243
|
+
endpoint = f"{HF}/api/{kind}"
|
|
244
|
+
url = cursor or f"{endpoint}?{urlencode(params)}"
|
|
245
|
+
if not isinstance(url, str) or urlsplit(url)[:3] != urlsplit(endpoint)[:3]:
|
|
246
|
+
raise ValueError("Invalid Hugging Face cursor")
|
|
247
|
+
rows, link = _json(url, _hf_token())
|
|
248
|
+
items = []
|
|
249
|
+
for row in rows:
|
|
250
|
+
ident, gated = row.get("id", ""), bool(row.get("gated"))
|
|
251
|
+
if not ident or options.ungated and gated:
|
|
252
|
+
continue
|
|
253
|
+
tags = row.get("tags") or []
|
|
254
|
+
downloads, likes = _int(row.get("downloads")), _int(row.get("likes"))
|
|
255
|
+
if models:
|
|
256
|
+
metadata = row.get("safetensors") or {}
|
|
257
|
+
total, active = parse_parameters(ident, metadata)
|
|
258
|
+
item = _model_item("hf", ident, row.get("pipeline_tag") or "", tags, safetensors_bytes(metadata),
|
|
259
|
+
total, active, downloads, likes, gated, options, hw, context)
|
|
260
|
+
if item:
|
|
261
|
+
items.append(item)
|
|
262
|
+
else:
|
|
263
|
+
card = row.get("cardData") or {}
|
|
264
|
+
items.append(SearchItem("hf", ident, _first_card_value(card, tags, "task_categories"),
|
|
265
|
+
downloads=downloads, likes=likes, gated=gated,
|
|
266
|
+
rows_bucket=_first_card_value(card, tags, "size_categories")))
|
|
267
|
+
return items, _next_link(link, endpoint)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _ollama_item(card: OllamaCard, options: SearchOptions, hw: HardwareProfile,
|
|
271
|
+
context: int) -> SearchItem | None:
|
|
272
|
+
ident = f"ollama:{card.slug}"
|
|
273
|
+
task = "feature-extraction" if "embedding" in card.capabilities else (
|
|
274
|
+
"image-text-to-text" if "vision" in card.capabilities else "text-generation")
|
|
275
|
+
variants = [(tag, *parse_parameters(tag)) for tag in card.sizes]
|
|
276
|
+
if not variants:
|
|
277
|
+
variants = [("", *parse_parameters(card.slug))]
|
|
278
|
+
variants.sort(key=lambda variant: variant[1] or 0, reverse=True)
|
|
279
|
+
candidates = []
|
|
280
|
+
for tag, total, active in variants:
|
|
281
|
+
result = _model_item("ollama", ident, task, card.capabilities, None, total, active,
|
|
282
|
+
card.downloads, 0, False, replace(options, fits=False), hw, context,
|
|
283
|
+
quant="FP16" if task == "feature-extraction" else "Q4_K_M")
|
|
284
|
+
if result is not None:
|
|
285
|
+
candidates.append(replace(
|
|
286
|
+
result, task=", ".join(card.capabilities) or task, note=card.note,
|
|
287
|
+
size_tags=tuple(card.sizes), pull_ref=f"{card.slug}:{tag}" if tag else card.slug,
|
|
288
|
+
))
|
|
289
|
+
if options.fits:
|
|
290
|
+
candidates = [item for item in candidates if item.fit is not None and item.fit.verdict in FITS]
|
|
291
|
+
if not candidates:
|
|
292
|
+
return None
|
|
293
|
+
budget = hw.comfortable_gb or hw.vram_gb
|
|
294
|
+
return next((item for item in candidates if item.fit is not None and
|
|
295
|
+
item.fit.total_gb is not None and item.fit.total_gb <= budget), candidates[-1])
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _ollama_page(options: SearchOptions, hw: HardwareProfile, context: int,
|
|
299
|
+
cursor: str | None, page_size: int) -> tuple[list[SearchItem], str | None, str | None]:
|
|
300
|
+
if cursor and cursor.startswith("db:"):
|
|
301
|
+
items, next_offset = _ollamadb_page(options, hw, context, cursor[3:], page_size)
|
|
302
|
+
return items, f"db:{next_offset}" if next_offset else None, None
|
|
303
|
+
|
|
304
|
+
page = int(cursor or 1)
|
|
305
|
+
if page < 1:
|
|
306
|
+
raise ValueError("Ollama page numbers start at 1")
|
|
307
|
+
case = options.use_case.lower()
|
|
308
|
+
capability = {"vision": "vision", "vlm": "vision", "embeddings": "embedding",
|
|
309
|
+
"embedding": "embedding", "thinking": "thinking", "tools": "tools"}.get(case)
|
|
310
|
+
query = options.query or (case if case not in {"llm", "chat"} and not capability else "")
|
|
311
|
+
params = {"q": query, "o": "newest" if options.sort in {"newest", "trendingScore"} else "popular", "p": page}
|
|
312
|
+
if capability:
|
|
313
|
+
params["c"] = capability
|
|
314
|
+
if page > 1:
|
|
315
|
+
# The website's infinite-scroll endpoint currently uses the long page parameter.
|
|
316
|
+
params["page"] = page
|
|
317
|
+
request = _request(f"{OLLAMA_SEARCH}?{urlencode(params)}")
|
|
318
|
+
if page > 1:
|
|
319
|
+
request.add_header("HX-Request", "true")
|
|
320
|
+
|
|
321
|
+
try:
|
|
322
|
+
with urlopen(request, timeout=18) as response:
|
|
323
|
+
html = response.read().decode("utf-8", errors="replace")
|
|
324
|
+
cards, next_page = parse_search_html(html, allow_empty_fragment=page > 1)
|
|
325
|
+
except (OSError, ValueError) as error:
|
|
326
|
+
if page == 1 and os.getenv("OLLAMADB_API_KEY"):
|
|
327
|
+
try:
|
|
328
|
+
items, next_offset = _ollamadb_page(options, hw, context, None, page_size)
|
|
329
|
+
except (OSError, ValueError) as fallback_error:
|
|
330
|
+
raise ValueError(f"Ollama search failed: {error}; OllamaDB fallback failed: {fallback_error}") from fallback_error
|
|
331
|
+
return items, f"db:{next_offset}" if next_offset else None, f"Ollama search failed: {error}; using OllamaDB"
|
|
332
|
+
raise ValueError(f"Ollama search failed: {error}") from error
|
|
333
|
+
|
|
334
|
+
items = [item for card in cards if (item := _ollama_item(card, options, hw, context)) is not None]
|
|
335
|
+
return items, next_page, None
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def _ollamadb_page(options, hw, context, cursor, page_size):
|
|
339
|
+
token = os.getenv("OLLAMADB_API_KEY")
|
|
340
|
+
if not token:
|
|
341
|
+
raise ValueError("OllamaDB requires OLLAMADB_API_KEY")
|
|
342
|
+
offset = int(cursor or 0)
|
|
343
|
+
params = {"limit": page_size, "skip": offset, "sort_by": "pulls", "order": "desc"}
|
|
344
|
+
case = options.use_case.lower()
|
|
345
|
+
if options.query:
|
|
346
|
+
params["search"] = options.query
|
|
347
|
+
elif case not in {"", "llm", "chat", "vision", "vlm", "embeddings"}:
|
|
348
|
+
params["search"] = case
|
|
349
|
+
if case in {"vision", "vlm", "embeddings"}:
|
|
350
|
+
params["capability"] = "embedding" if case == "embeddings" else "vision"
|
|
351
|
+
if options.max_params is not None:
|
|
352
|
+
params["params_max"] = int(options.max_params * 1e9)
|
|
353
|
+
if options.max_gb is not None:
|
|
354
|
+
params["size_max"] = int(options.max_gb * GIB)
|
|
355
|
+
data, _ = _json(f"{OLLAMA_API}?{urlencode(params)}", token)
|
|
356
|
+
rows = data.get("data", data.get("models", []))
|
|
357
|
+
items = []
|
|
358
|
+
for row in rows:
|
|
359
|
+
ident = row.get("model_identifier") or row.get("model_name") or row.get("name")
|
|
360
|
+
family = row.get("family") or row.get("family_name")
|
|
361
|
+
tag = row.get("tag") or row.get("tag_name")
|
|
362
|
+
if tag and not ident and family:
|
|
363
|
+
ident = f"{family}:{tag}"
|
|
364
|
+
elif tag and ident and ":" not in ident and ident != tag:
|
|
365
|
+
ident = f"{ident}:{tag}"
|
|
366
|
+
if not ident:
|
|
367
|
+
continue
|
|
368
|
+
reported = _int(row.get("params") or row.get("parameters") or row.get("parameter_count"))
|
|
369
|
+
total, active = parse_parameters(ident, {"total": reported})
|
|
370
|
+
capabilities = row.get("capabilities") or row.get("capability") or ()
|
|
371
|
+
if isinstance(capabilities, str):
|
|
372
|
+
capabilities = capabilities.split(",")
|
|
373
|
+
task = "feature-extraction" if "embedding" in capabilities else (
|
|
374
|
+
"image-text-to-text" if "vision" in capabilities else "text-generation")
|
|
375
|
+
tags = ["mlx"] if row.get("is_mlx") else []
|
|
376
|
+
disk = _int(row.get("size_bytes") or row.get("size") or row.get("download_size_bytes")) or None
|
|
377
|
+
# Ollama tags describe a published artifact; use its actual size for fit when available.
|
|
378
|
+
quant = row.get("quantization") or ("Q4_K_M" if disk and total and disk / total < 0.7 else "")
|
|
379
|
+
item = _model_item("ollama", f"ollama:{ident}", task, tags, disk, total, active,
|
|
380
|
+
_int(row.get("pulls")), 0, False, options, hw, context, quant)
|
|
381
|
+
if item:
|
|
382
|
+
items.append(item)
|
|
383
|
+
end = offset + len(rows)
|
|
384
|
+
more = end < _int(data.get("total_count")) if "total_count" in data else len(rows) >= page_size
|
|
385
|
+
return items, str(end) if rows and more else None
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def _openml_page(options, cursor, page_size):
|
|
389
|
+
offset = int(cursor or 0)
|
|
390
|
+
url = f"{OPENML}/data/list/status/active/limit/{page_size}/offset/{offset}"
|
|
391
|
+
if options.query:
|
|
392
|
+
url += f"/data_name/{quote(options.query.lower(), safe='')}"
|
|
393
|
+
size_ranges = {"tiny": (0, 999), "small": (1000, 9999), "medium": (10000, 99999),
|
|
394
|
+
"large": (100000, 999999), "xlarge": (1000000, 9999999),
|
|
395
|
+
"huge": (10000000, 99999999), "massive": (100000000, 999999999)}
|
|
396
|
+
if options.size in size_ranges:
|
|
397
|
+
low, high = size_ranges[options.size]
|
|
398
|
+
url += f"/number_instances/{low}..{high}"
|
|
399
|
+
try:
|
|
400
|
+
payload, _ = _json(url)
|
|
401
|
+
except HTTPError as error:
|
|
402
|
+
if error.code == 412:
|
|
403
|
+
return [], None
|
|
404
|
+
raise
|
|
405
|
+
rows = payload.get("data", {}).get("dataset", [])
|
|
406
|
+
items = []
|
|
407
|
+
term = options.use_case.lower()
|
|
408
|
+
for row in rows:
|
|
409
|
+
if term not in {"", "tabular"} and term not in row.get("name", "").lower():
|
|
410
|
+
continue
|
|
411
|
+
metrics = {entry["name"]: _int(entry["value"]) for entry in row.get("quality", [])}
|
|
412
|
+
count = metrics.get("NumberOfInstances")
|
|
413
|
+
columns = metrics.get("NumberOfFeatures")
|
|
414
|
+
items.append(SearchItem("openml", f"openml:{row['did']}",
|
|
415
|
+
f"tabular ({columns} cols)" if columns else "tabular",
|
|
416
|
+
rows_bucket=f"{count:,} rows" if count else "",
|
|
417
|
+
name=row.get("name", "")))
|
|
418
|
+
return items, str(offset + len(rows)) if len(rows) >= page_size else None
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def _executable(name: str) -> str:
|
|
422
|
+
scripts = Path(sysconfig.get_path("scripts"))
|
|
423
|
+
candidate = scripts / (f"{name}.exe" if os.name == "nt" else name)
|
|
424
|
+
executable = str(candidate) if candidate.is_file() else shutil.which(name)
|
|
425
|
+
if not executable:
|
|
426
|
+
raise ValueError(f"{name} CLI is required")
|
|
427
|
+
return executable
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def _command(name: str, *arguments: str, timeout: int | None = None) -> str:
|
|
431
|
+
result = subprocess.run([_executable(name), *arguments], capture_output=True, text=True, timeout=timeout, check=False)
|
|
432
|
+
if result.returncode:
|
|
433
|
+
message = result.stderr.strip() or result.stdout.strip()
|
|
434
|
+
raise ValueError(f"{name} failed: {message or result.returncode}")
|
|
435
|
+
return result.stdout
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def _kaggle_page(options, cursor):
|
|
439
|
+
number = int(cursor or 1)
|
|
440
|
+
sort = "votes" if options.sort == "likes" else "hottest"
|
|
441
|
+
args = ["datasets", "list", "--csv", "-p", str(number), "--sort-by", sort]
|
|
442
|
+
if term := options.query or options.use_case:
|
|
443
|
+
args.extend(["-s", term])
|
|
444
|
+
if options.max_gb is not None:
|
|
445
|
+
args.extend(["--max-size", str(int(options.max_gb * GIB))])
|
|
446
|
+
rows = [row for row in csv.DictReader(io.StringIO(_command("kaggle", *args, timeout=25))) if row.get("ref")]
|
|
447
|
+
items = []
|
|
448
|
+
for row in rows:
|
|
449
|
+
disk = _int(row.get("totalBytes")) or None
|
|
450
|
+
if options.max_gb is not None and (disk is None or disk > options.max_gb * GIB):
|
|
451
|
+
continue
|
|
452
|
+
items.append(SearchItem("kaggle", f"kaggle:{row['ref']}", row.get("title") or "",
|
|
453
|
+
disk, _int(row.get("downloadCount")), _int(row.get("voteCount"))))
|
|
454
|
+
return items, str(number + 1) if rows else None
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def search(kind: str, options: SearchOptions, hw: HardwareProfile | None = None,
|
|
458
|
+
max_context: int = 8192, *, cursor: str | None = None, page_size: int = 50) -> SearchPage:
|
|
459
|
+
"""Fetch one page per selected provider. Keep the cursor opaque to callers."""
|
|
460
|
+
sources = SOURCES[kind] if options.source == "all" else (options.source,)
|
|
461
|
+
if any(source not in SOURCES[kind] for source in sources) or (kind == "models" and hw is None):
|
|
462
|
+
raise ValueError("Invalid source or missing hardware profile")
|
|
463
|
+
keyless_cursor = sources == ("ollama",)
|
|
464
|
+
if cursor and keyless_cursor:
|
|
465
|
+
current = {"ollama": cursor}
|
|
466
|
+
else:
|
|
467
|
+
current = json.loads(cursor) if cursor else dict.fromkeys(sources)
|
|
468
|
+
if not isinstance(current, dict) or any(key not in sources for key in current):
|
|
469
|
+
raise ValueError("Cursor does not match the selected providers")
|
|
470
|
+
next_pages = {}
|
|
471
|
+
items = []
|
|
472
|
+
errors = []
|
|
473
|
+
for source, token in current.items():
|
|
474
|
+
try:
|
|
475
|
+
if source == "hf":
|
|
476
|
+
rows, next_token = _hf_page(kind, options, hw, max_context, token, page_size)
|
|
477
|
+
elif source == "ollama":
|
|
478
|
+
rows, next_token, warning = _ollama_page(options, hw, max_context, token, page_size)
|
|
479
|
+
if warning:
|
|
480
|
+
errors.append(warning)
|
|
481
|
+
elif source == "openml":
|
|
482
|
+
rows, next_token = _openml_page(options, token, page_size)
|
|
483
|
+
else:
|
|
484
|
+
rows, next_token = _kaggle_page(options, token)
|
|
485
|
+
except (OSError, ValueError, subprocess.SubprocessError) as error:
|
|
486
|
+
if len(sources) == 1:
|
|
487
|
+
raise
|
|
488
|
+
errors.append(f"{source}: {error}")
|
|
489
|
+
continue
|
|
490
|
+
items.extend(rows)
|
|
491
|
+
if next_token is not None and next_token != token:
|
|
492
|
+
next_pages[source] = next_token
|
|
493
|
+
if options.sort == "score":
|
|
494
|
+
items.sort(key=lambda item: item.fit.score if item.fit else 0, reverse=True)
|
|
495
|
+
elif len(sources) > 1 and options.sort in {"downloads", "likes"}:
|
|
496
|
+
items.sort(key=lambda item: getattr(item, options.sort), reverse=True)
|
|
497
|
+
cursor = next_pages.get("ollama") if keyless_cursor else (
|
|
498
|
+
json.dumps(next_pages) if next_pages else None)
|
|
499
|
+
return SearchPage(items, cursor, tuple(errors))
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
def _safe_relative(value: str) -> Path:
|
|
503
|
+
path = Path(value)
|
|
504
|
+
if not path.parts or path.is_absolute() or "\\" in value or ".." in path.parts:
|
|
505
|
+
raise ValueError(f"Invalid path: {value!r}")
|
|
506
|
+
return path
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def default_folder(item: SearchItem) -> str:
|
|
510
|
+
name = item.name or item.id.rsplit("/", 1)[-1].removeprefix(f"{item.source}:")
|
|
511
|
+
return re.sub(r"[^a-z0-9.-]+", "-", name.lower()).strip(".-") or item.source
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
_TERMINAL_ESCAPE = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]")
|
|
515
|
+
_PERCENT = re.compile(r"(?<![\d.])(\d{1,3})%")
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def _pull_command(name: str, *arguments: str, progress: ProgressCallback | None,
|
|
519
|
+
native_progress: bool) -> None:
|
|
520
|
+
if progress is None and not native_progress:
|
|
521
|
+
_command(name, *arguments)
|
|
522
|
+
return
|
|
523
|
+
command = [_executable(name), *arguments]
|
|
524
|
+
if native_progress:
|
|
525
|
+
result = subprocess.run(command, check=False)
|
|
526
|
+
if result.returncode:
|
|
527
|
+
raise ValueError(f"{name} failed (exit {result.returncode})")
|
|
528
|
+
return
|
|
529
|
+
assert progress is not None
|
|
530
|
+
with subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
|
531
|
+
text=True, errors="replace", bufsize=1) as child:
|
|
532
|
+
assert child.stdout is not None
|
|
533
|
+
last_line = ""
|
|
534
|
+
for line in child.stdout:
|
|
535
|
+
message = _TERMINAL_ESCAPE.sub("", line).strip()
|
|
536
|
+
if not message or message == last_line:
|
|
537
|
+
continue
|
|
538
|
+
last_line = message
|
|
539
|
+
match = _PERCENT.search(message)
|
|
540
|
+
completed = int(match[1]) if match else None
|
|
541
|
+
progress(PullProgress(message, completed, 100 if match else None, "%"))
|
|
542
|
+
if child.wait():
|
|
543
|
+
raise ValueError(f"{name} failed: {last_line or child.returncode}")
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
def _copy_url(url: str, path: Path, token: str | None = None,
|
|
547
|
+
progress: ProgressCallback | None = None) -> None:
|
|
548
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
549
|
+
with urlopen(_request(url, token), timeout=120) as response, path.open("wb") as stream:
|
|
550
|
+
size = _int(response.headers.get("Content-Length")) or None
|
|
551
|
+
start = last = monotonic()
|
|
552
|
+
received = 0
|
|
553
|
+
if progress:
|
|
554
|
+
progress(PullProgress(path.name, received, size, "B"))
|
|
555
|
+
while chunk := response.read(256 * 1024):
|
|
556
|
+
stream.write(chunk)
|
|
557
|
+
received += len(chunk)
|
|
558
|
+
now = monotonic()
|
|
559
|
+
if progress and now - last >= 0.15:
|
|
560
|
+
progress(PullProgress(path.name, received, size, "B", now - start))
|
|
561
|
+
last = now
|
|
562
|
+
if size is not None and received != size:
|
|
563
|
+
raise OSError(f"Incomplete download for {path.name}: received {received} of {size} bytes")
|
|
564
|
+
if progress:
|
|
565
|
+
progress(PullProgress(path.name, received, size or received, "B", monotonic() - start))
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def _hub_progress_class(progress: ProgressCallback):
|
|
569
|
+
from tqdm import tqdm
|
|
570
|
+
|
|
571
|
+
has_byte_progress = False
|
|
572
|
+
|
|
573
|
+
class HubProgress(tqdm):
|
|
574
|
+
"""Feed the SDK's aggregate byte counter and legacy file counter into the TUI."""
|
|
575
|
+
|
|
576
|
+
def __init__(self, *args, **kwargs):
|
|
577
|
+
self._started = monotonic()
|
|
578
|
+
self._name = kwargs.pop("name", "")
|
|
579
|
+
kwargs.update(file=io.StringIO(), disable=False)
|
|
580
|
+
super().__init__(*args, **kwargs)
|
|
581
|
+
|
|
582
|
+
def display(self, msg=None, pos=None):
|
|
583
|
+
nonlocal has_byte_progress
|
|
584
|
+
description = self.desc.strip()
|
|
585
|
+
# Current Hub versions also emit separate transfer counters, which can
|
|
586
|
+
# lag reconstruction when weights are deduplicated or already cached.
|
|
587
|
+
if self._name.endswith(".transfer") or description.startswith("Downloading bytes"):
|
|
588
|
+
return
|
|
589
|
+
unit = "B" if self.unit == "B" else "files"
|
|
590
|
+
if unit == "B":
|
|
591
|
+
has_byte_progress |= bool(self.total)
|
|
592
|
+
elif has_byte_progress:
|
|
593
|
+
return
|
|
594
|
+
progress(PullProgress(description or "Fetching files", self.n, self.total or None,
|
|
595
|
+
unit, monotonic() - self._started))
|
|
596
|
+
|
|
597
|
+
HubProgress.set_lock(threading.RLock())
|
|
598
|
+
return HubProgress
|
|
599
|
+
|
|
600
|
+
|
|
601
|
+
def _download_hf(kind: str, repo: str, target: Path, allow: list[str] | None, revision: str,
|
|
602
|
+
progress: ProgressCallback | None, native_progress: bool) -> None:
|
|
603
|
+
repo_type = "model" if kind == "models" else "dataset"
|
|
604
|
+
repo_id = _safe_relative(repo).as_posix()
|
|
605
|
+
repo = quote(repo_id, safe="/")
|
|
606
|
+
token = _hf_token()
|
|
607
|
+
try:
|
|
608
|
+
from huggingface_hub import snapshot_download
|
|
609
|
+
except ImportError:
|
|
610
|
+
ref = quote(revision, safe="")
|
|
611
|
+
info, _ = _json(f"{HF}/api/{kind}/{repo}/revision/{ref}", token)
|
|
612
|
+
commit = quote(info.get("sha") or revision, safe="")
|
|
613
|
+
prefix = "datasets/" if kind == "datasets" else ""
|
|
614
|
+
for entry in info.get("siblings", []):
|
|
615
|
+
name = entry["rfilename"]
|
|
616
|
+
if not allow or any(fnmatch.fnmatchcase(name, pattern) for pattern in allow):
|
|
617
|
+
path = _safe_relative(name)
|
|
618
|
+
_copy_url(f"{HF}/{prefix}{repo}/resolve/{commit}/{quote(name)}", target / path, token, progress)
|
|
619
|
+
else:
|
|
620
|
+
try:
|
|
621
|
+
kwargs = {"tqdm_class": _hub_progress_class(progress)} if progress and not native_progress else {}
|
|
622
|
+
snapshot_download(repo_id=repo_id, repo_type=repo_type, revision=revision,
|
|
623
|
+
local_dir=target, allow_patterns=allow, token=token, **kwargs)
|
|
624
|
+
except Exception as error:
|
|
625
|
+
raise ValueError(f"Hugging Face download failed for {repo_id}: {error}") from error
|
|
626
|
+
if not any(file.is_file() and ".cache" not in file.relative_to(target).parts for file in target.rglob("*")):
|
|
627
|
+
raise ValueError("No repository files matched the download selection")
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
def pull(kind: str, item: SearchItem, name: str, *, category: str = "", notes: str = "",
|
|
631
|
+
allow: list[str] | None = None, revision: str = "main",
|
|
632
|
+
config: Config | None = None, progress: ProgressCallback | None = None,
|
|
633
|
+
native_progress: bool = False) -> Path:
|
|
634
|
+
"""Stage a download beside its destination, then index the completed item."""
|
|
635
|
+
if item.source not in SOURCES[kind]:
|
|
636
|
+
raise ValueError("Source does not support this item type")
|
|
637
|
+
name = folder_name(name)
|
|
638
|
+
category = folder_name(category) if kind == "datasets" else "weights"
|
|
639
|
+
config = config or resolve_config()
|
|
640
|
+
root = config.data_root.resolve()
|
|
641
|
+
parent = root / kind / category
|
|
642
|
+
if not parent.resolve().is_relative_to(root):
|
|
643
|
+
raise ValueError("Destination must be inside the data root")
|
|
644
|
+
parent.mkdir(parents=True, exist_ok=True)
|
|
645
|
+
target = parent / name
|
|
646
|
+
# Atomic lock acquisition prevents simultaneous pulls publishing to the same path.
|
|
647
|
+
lock = parent / f".{name}.datahub-lock"
|
|
648
|
+
try:
|
|
649
|
+
lock.mkdir()
|
|
650
|
+
except FileExistsError as error:
|
|
651
|
+
raise ValueError(f"Download already in progress or interrupted for {target}") from error
|
|
652
|
+
try:
|
|
653
|
+
if target.exists() or target.is_symlink():
|
|
654
|
+
raise ValueError(f"Destination already exists: {target}")
|
|
655
|
+
with tempfile.TemporaryDirectory(prefix=".datahub-", dir=parent) as temporary:
|
|
656
|
+
stage = Path(temporary) / name
|
|
657
|
+
raw = stage / "raw" if kind == "datasets" else stage
|
|
658
|
+
raw.mkdir(parents=True)
|
|
659
|
+
ident = item.pull_ref or item.id.removeprefix(f"{item.source}:")
|
|
660
|
+
if progress:
|
|
661
|
+
progress(PullProgress(f"Fetching {item.id}", stage="preparing"))
|
|
662
|
+
if item.source == "hf":
|
|
663
|
+
_download_hf(kind, ident, raw, allow, revision, progress, native_progress)
|
|
664
|
+
source_url = f"{HF}/{'datasets/' if kind == 'datasets' else ''}{quote(ident)}"
|
|
665
|
+
elif item.source == "ollama":
|
|
666
|
+
if not re.fullmatch(r"[A-Za-z0-9_][A-Za-z0-9_./:-]*", ident):
|
|
667
|
+
raise ValueError("Invalid Ollama model name")
|
|
668
|
+
_pull_command("ollama", "pull", ident, progress=progress, native_progress=native_progress)
|
|
669
|
+
(stage / ".datahub-ollama.json").write_text(json.dumps({"model": ident}), encoding="utf-8")
|
|
670
|
+
source_url = f"https://ollama.com/library/{quote(ident)}"
|
|
671
|
+
elif item.source == "kaggle":
|
|
672
|
+
_pull_command("kaggle", "datasets", "download", "-d", ident, "-p", str(raw), "--unzip",
|
|
673
|
+
progress=progress, native_progress=native_progress)
|
|
674
|
+
source_url = f"https://www.kaggle.com/datasets/{quote(ident)}"
|
|
675
|
+
else:
|
|
676
|
+
if not ident.isdigit():
|
|
677
|
+
raise ValueError("OpenML dataset ID must be numeric")
|
|
678
|
+
data, _ = _json(f"{OPENML}/data/{ident}")
|
|
679
|
+
source_url = (data.get("data_set_description") or {}).get("url")
|
|
680
|
+
if not isinstance(source_url, str):
|
|
681
|
+
raise ValueError(f"OpenML dataset {ident} has no download URL")
|
|
682
|
+
url = urlsplit(source_url)
|
|
683
|
+
if url.scheme != "https" or url.hostname not in {"openml.org", "www.openml.org"}:
|
|
684
|
+
raise ValueError("Invalid OpenML download URL")
|
|
685
|
+
_copy_url(source_url, raw / (f"{name}" + (Path(url.path).suffix or ".arff")),
|
|
686
|
+
progress=progress)
|
|
687
|
+
metadata = json.dumps({"source_url": source_url, "notes": notes}, indent=2)
|
|
688
|
+
if kind == "datasets":
|
|
689
|
+
(stage / "meta.json").write_text(metadata, encoding="utf-8")
|
|
690
|
+
(parent / ".datahub-category").touch()
|
|
691
|
+
else:
|
|
692
|
+
(stage / ".datahub-model").write_text(metadata, encoding="utf-8")
|
|
693
|
+
stage.rename(target)
|
|
694
|
+
if progress:
|
|
695
|
+
progress(PullProgress("Indexing local catalog", stage="indexing"))
|
|
696
|
+
try:
|
|
697
|
+
catalog.cmd_scan(argparse.Namespace(deps=False, quiet=True, config=config))
|
|
698
|
+
except (OSError, sqlite3.Error) as error:
|
|
699
|
+
raise ValueError(f"Downloaded to {target}; catalog update failed: {error}. Run datahub scan to index it.") from error
|
|
700
|
+
finally:
|
|
701
|
+
lock.rmdir()
|
|
702
|
+
return target
|