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/catalog.py
ADDED
|
@@ -0,0 +1,1152 @@
|
|
|
1
|
+
"""Lightweight CLI to index, inspect schemas, and track project usages for ~/data."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import csv
|
|
7
|
+
import json
|
|
8
|
+
import logging
|
|
9
|
+
import math
|
|
10
|
+
import os
|
|
11
|
+
import re
|
|
12
|
+
import sqlite3
|
|
13
|
+
import struct
|
|
14
|
+
import sys
|
|
15
|
+
from collections import Counter
|
|
16
|
+
from contextlib import contextmanager
|
|
17
|
+
from datetime import UTC, datetime
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
from .config import Config, create_directories, folder_name, resolve_config
|
|
22
|
+
|
|
23
|
+
SF_DATALESS = 0x40000000
|
|
24
|
+
logger = logging.getLogger(__name__)
|
|
25
|
+
|
|
26
|
+
IGNORED_NAMES = {
|
|
27
|
+
".DS_Store",
|
|
28
|
+
".Spotlight-V100",
|
|
29
|
+
".Trashes",
|
|
30
|
+
".fseventsd",
|
|
31
|
+
"__pycache__",
|
|
32
|
+
"Thumbs.db",
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
DATASET_MARKER_FILES = {
|
|
36
|
+
"meta.json",
|
|
37
|
+
"dataset_info.json",
|
|
38
|
+
"dataset_dict.json",
|
|
39
|
+
"data.yaml",
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
DATASET_MARKER_DIRS = {
|
|
43
|
+
"raw",
|
|
44
|
+
"processed",
|
|
45
|
+
"train",
|
|
46
|
+
"test",
|
|
47
|
+
"val",
|
|
48
|
+
"valid",
|
|
49
|
+
"validation",
|
|
50
|
+
"images",
|
|
51
|
+
"labels",
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
MODEL_BUNDLE_MARKERS = {
|
|
55
|
+
"config.json",
|
|
56
|
+
"adapter_config.json",
|
|
57
|
+
"params.json",
|
|
58
|
+
"model.safetensors.index.json",
|
|
59
|
+
"pytorch_model.bin.index.json",
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
MODEL_BUNDLE_SUFFIXES = {".mlpackage", ".mlmodelc"}
|
|
63
|
+
IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".tif", ".tiff", ".webp", ".bmp"}
|
|
64
|
+
VIDEO_EXTS = {".mp4", ".mov", ".avi", ".mkv", ".webm"}
|
|
65
|
+
AUDIO_EXTS = {".wav", ".mp3", ".flac", ".m4a", ".ogg"}
|
|
66
|
+
CODE_EXTS = {
|
|
67
|
+
".py", ".ts", ".tsx", ".js", ".jsx", ".json", ".yaml", ".yml",
|
|
68
|
+
".toml", ".sh", ".bash", ".zsh", ".cpp", ".cc", ".h", ".hpp",
|
|
69
|
+
".swift", ".java", ".rs", ".go", ".ipynb", ".env",
|
|
70
|
+
}
|
|
71
|
+
SKIP_PROJECT_DIRS = {
|
|
72
|
+
".git", "node_modules", ".venv", "venv", ".conda", "__pycache__",
|
|
73
|
+
"dist", "build", "target", ".next", ".pytest_cache", ".mypy_cache",
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def is_ignored(name: str) -> bool:
|
|
78
|
+
return name.startswith(".") or name in IGNORED_NAMES
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def get_db(config: Config | None = None) -> sqlite3.Connection:
|
|
82
|
+
config = config or resolve_config()
|
|
83
|
+
if not config.db_path.is_file():
|
|
84
|
+
create_directories(config)
|
|
85
|
+
conn = sqlite3.connect(config.db_path, timeout=30)
|
|
86
|
+
conn.row_factory = sqlite3.Row
|
|
87
|
+
conn.executescript(
|
|
88
|
+
"""
|
|
89
|
+
CREATE TABLE IF NOT EXISTS datasets (
|
|
90
|
+
id TEXT PRIMARY KEY,
|
|
91
|
+
category TEXT NOT NULL,
|
|
92
|
+
name TEXT NOT NULL,
|
|
93
|
+
rel_path TEXT NOT NULL,
|
|
94
|
+
size_bytes INTEGER NOT NULL,
|
|
95
|
+
file_count INTEGER NOT NULL,
|
|
96
|
+
source_url TEXT DEFAULT '',
|
|
97
|
+
notes TEXT DEFAULT '',
|
|
98
|
+
schema_json TEXT DEFAULT '',
|
|
99
|
+
updated_at TEXT NOT NULL
|
|
100
|
+
);
|
|
101
|
+
CREATE TABLE IF NOT EXISTS models (
|
|
102
|
+
id TEXT PRIMARY KEY,
|
|
103
|
+
kind TEXT NOT NULL,
|
|
104
|
+
name TEXT NOT NULL,
|
|
105
|
+
rel_path TEXT NOT NULL,
|
|
106
|
+
size_bytes INTEGER NOT NULL,
|
|
107
|
+
notes TEXT DEFAULT '',
|
|
108
|
+
schema_json TEXT DEFAULT '',
|
|
109
|
+
updated_at TEXT NOT NULL
|
|
110
|
+
);
|
|
111
|
+
CREATE TABLE IF NOT EXISTS usages (
|
|
112
|
+
item_type TEXT NOT NULL,
|
|
113
|
+
item_id TEXT NOT NULL,
|
|
114
|
+
project TEXT NOT NULL,
|
|
115
|
+
file_path TEXT NOT NULL,
|
|
116
|
+
line_no INTEGER NOT NULL,
|
|
117
|
+
updated_at TEXT NOT NULL,
|
|
118
|
+
PRIMARY KEY (item_type, item_id, file_path, line_no)
|
|
119
|
+
);
|
|
120
|
+
CREATE INDEX IF NOT EXISTS idx_usages_item ON usages(item_id);
|
|
121
|
+
"""
|
|
122
|
+
)
|
|
123
|
+
# Auto-migrate older catalog.db tables in place
|
|
124
|
+
for table in ("datasets", "models"):
|
|
125
|
+
cols = {r["name"] for r in conn.execute(f"PRAGMA table_info({table})")}
|
|
126
|
+
if "schema_json" not in cols:
|
|
127
|
+
conn.execute(f"ALTER TABLE {table} ADD COLUMN schema_json TEXT DEFAULT ''")
|
|
128
|
+
return conn
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
@contextmanager
|
|
132
|
+
def database(config: Config | None = None):
|
|
133
|
+
conn = get_db(config)
|
|
134
|
+
try:
|
|
135
|
+
with conn:
|
|
136
|
+
yield conn
|
|
137
|
+
finally:
|
|
138
|
+
conn.close()
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def visible_children(path: Path) -> list[Path]:
|
|
142
|
+
try:
|
|
143
|
+
return sorted(
|
|
144
|
+
(p for p in path.iterdir() if not is_ignored(p.name)),
|
|
145
|
+
key=lambda p: p.name.lower(),
|
|
146
|
+
)
|
|
147
|
+
except OSError:
|
|
148
|
+
return []
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def collect_files(path: Path) -> tuple[int, int, list[Path]]:
|
|
152
|
+
"""Return (total_bytes, file_count, file_paths) skipping hidden files and inner symlinks."""
|
|
153
|
+
try:
|
|
154
|
+
resolved = path.resolve(strict=True)
|
|
155
|
+
except OSError:
|
|
156
|
+
return 0, 0, []
|
|
157
|
+
|
|
158
|
+
if resolved.is_file():
|
|
159
|
+
try:
|
|
160
|
+
return resolved.stat().st_size, 1, [resolved]
|
|
161
|
+
except OSError:
|
|
162
|
+
return 0, 0, []
|
|
163
|
+
|
|
164
|
+
total_bytes = 0
|
|
165
|
+
file_count = 0
|
|
166
|
+
files: list[Path] = []
|
|
167
|
+
stack = [resolved]
|
|
168
|
+
|
|
169
|
+
while stack:
|
|
170
|
+
current = stack.pop()
|
|
171
|
+
try:
|
|
172
|
+
with os.scandir(current) as it:
|
|
173
|
+
for entry in it:
|
|
174
|
+
if is_ignored(entry.name):
|
|
175
|
+
continue
|
|
176
|
+
try:
|
|
177
|
+
if entry.is_symlink():
|
|
178
|
+
continue
|
|
179
|
+
if entry.is_dir(follow_symlinks=False):
|
|
180
|
+
stack.append(Path(entry.path))
|
|
181
|
+
elif entry.is_file(follow_symlinks=False):
|
|
182
|
+
total_bytes += entry.stat(follow_symlinks=False).st_size
|
|
183
|
+
file_count += 1
|
|
184
|
+
files.append(Path(entry.path))
|
|
185
|
+
except OSError:
|
|
186
|
+
continue
|
|
187
|
+
except OSError:
|
|
188
|
+
continue
|
|
189
|
+
|
|
190
|
+
files.sort(key=lambda p: str(p))
|
|
191
|
+
return total_bytes, file_count, files
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def fmt_size(num_bytes: int) -> str:
|
|
195
|
+
size = float(num_bytes)
|
|
196
|
+
for unit in ("B", "KB", "MB", "GB", "TB"):
|
|
197
|
+
if size < 1024.0:
|
|
198
|
+
return f"{size:.1f} {unit}"
|
|
199
|
+
size /= 1024.0
|
|
200
|
+
return f"{size:.1f} PB"
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def read_meta(path: Path, filename: str = "meta.json") -> tuple[str, str]:
|
|
204
|
+
if not path.is_dir():
|
|
205
|
+
return "", ""
|
|
206
|
+
meta_path = path / filename
|
|
207
|
+
if not meta_path.is_file():
|
|
208
|
+
return "", ""
|
|
209
|
+
try:
|
|
210
|
+
data = json.loads(meta_path.read_text(encoding="utf-8"))
|
|
211
|
+
if not isinstance(data, dict):
|
|
212
|
+
return "", ""
|
|
213
|
+
return str(data.get("source_url", "") or ""), str(data.get("notes", "") or "")
|
|
214
|
+
except (OSError, json.JSONDecodeError):
|
|
215
|
+
return "", ""
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
# ---------------------------------------------------------------------------
|
|
219
|
+
# Header-only schema introspection (fast, zero heavy dependencies required)
|
|
220
|
+
# ---------------------------------------------------------------------------
|
|
221
|
+
|
|
222
|
+
def _infer_scalar_type(val: str) -> str:
|
|
223
|
+
s = val.strip()
|
|
224
|
+
if not s:
|
|
225
|
+
return "null"
|
|
226
|
+
if s.lower() in ("true", "false"):
|
|
227
|
+
return "bool"
|
|
228
|
+
try:
|
|
229
|
+
int(s)
|
|
230
|
+
return "int"
|
|
231
|
+
except ValueError:
|
|
232
|
+
pass
|
|
233
|
+
try:
|
|
234
|
+
float(s)
|
|
235
|
+
return "float"
|
|
236
|
+
except ValueError:
|
|
237
|
+
return "str"
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _inspect_csv(fp: Path, delimiter: str = ",") -> dict[str, Any]:
|
|
241
|
+
info: dict[str, Any] = {"format": "tsv" if delimiter == "\t" else "csv"}
|
|
242
|
+
try:
|
|
243
|
+
size = fp.stat().st_size
|
|
244
|
+
with fp.open("r", encoding="utf-8", errors="replace", newline="") as f:
|
|
245
|
+
reader = csv.reader(f, delimiter=delimiter)
|
|
246
|
+
header = next(reader, None)
|
|
247
|
+
if not header:
|
|
248
|
+
return info
|
|
249
|
+
samples = [row for _, row in zip(range(5), reader)]
|
|
250
|
+
cols: dict[str, str] = {}
|
|
251
|
+
for i, col_name in enumerate(header[:60]):
|
|
252
|
+
types = {_infer_scalar_type(r[i]) for r in samples if i < len(r)} - {"null"}
|
|
253
|
+
if not types:
|
|
254
|
+
cols[col_name] = "unknown"
|
|
255
|
+
elif types == {"int"}:
|
|
256
|
+
cols[col_name] = "int"
|
|
257
|
+
elif types <= {"int", "float"}:
|
|
258
|
+
cols[col_name] = "float"
|
|
259
|
+
elif types == {"bool"}:
|
|
260
|
+
cols[col_name] = "bool"
|
|
261
|
+
else:
|
|
262
|
+
cols[col_name] = "str"
|
|
263
|
+
info["columns"] = cols
|
|
264
|
+
if len(header) > 60:
|
|
265
|
+
info["total_columns"] = len(header)
|
|
266
|
+
# Fast line count for files <= 80 MB
|
|
267
|
+
if size <= 80 * 1024 * 1024:
|
|
268
|
+
with fp.open("rb") as fb:
|
|
269
|
+
lines = sum(chunk.count(b"\n") for chunk in iter(lambda: fb.read(1 << 20), b""))
|
|
270
|
+
info["rows"] = max(0, lines - 1)
|
|
271
|
+
except OSError:
|
|
272
|
+
pass
|
|
273
|
+
return info
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _inspect_parquet(fp: Path) -> dict[str, Any]:
|
|
277
|
+
info: dict[str, Any] = {"format": "parquet"}
|
|
278
|
+
try:
|
|
279
|
+
import pyarrow.parquet as pq # type: ignore
|
|
280
|
+
|
|
281
|
+
pf = pq.ParquetFile(fp)
|
|
282
|
+
schema = pf.schema_arrow
|
|
283
|
+
info["rows"] = pf.metadata.num_rows
|
|
284
|
+
info["columns"] = {field.name: str(field.type) for field in list(schema)[:60]}
|
|
285
|
+
if len(schema) > 60:
|
|
286
|
+
info["total_columns"] = len(schema)
|
|
287
|
+
except (ImportError, OSError, ValueError) as error:
|
|
288
|
+
logger.debug("Parquet schema unavailable for %s: %s", fp, error)
|
|
289
|
+
return info
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _inspect_jsonl(fp: Path) -> dict[str, Any]:
|
|
293
|
+
info: dict[str, Any] = {"format": "jsonl"}
|
|
294
|
+
try:
|
|
295
|
+
with fp.open("r", encoding="utf-8", errors="replace") as f:
|
|
296
|
+
for line in f:
|
|
297
|
+
line = line.strip()
|
|
298
|
+
if not line:
|
|
299
|
+
continue
|
|
300
|
+
obj = json.loads(line)
|
|
301
|
+
if isinstance(obj, dict):
|
|
302
|
+
info["fields"] = {k: type(v).__name__ for k, v in list(obj.items())[:40]}
|
|
303
|
+
break
|
|
304
|
+
except (OSError, json.JSONDecodeError):
|
|
305
|
+
pass
|
|
306
|
+
return info
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _image_dims(fp: Path) -> tuple[int, int] | None:
|
|
310
|
+
try:
|
|
311
|
+
with fp.open("rb") as f:
|
|
312
|
+
head = f.read(24)
|
|
313
|
+
if len(head) >= 24 and head.startswith(b"\x89PNG\r\n\x1a\n") and head[12:16] == b"IHDR":
|
|
314
|
+
return struct.unpack(">II", head[16:24])
|
|
315
|
+
if head.startswith(b"\xff\xd8"):
|
|
316
|
+
f.seek(2)
|
|
317
|
+
while True:
|
|
318
|
+
marker_start = f.read(1)
|
|
319
|
+
if not marker_start:
|
|
320
|
+
break
|
|
321
|
+
if marker_start != b"\xff":
|
|
322
|
+
continue
|
|
323
|
+
marker = f.read(1)
|
|
324
|
+
while marker == b"\xff":
|
|
325
|
+
marker = f.read(1)
|
|
326
|
+
if not marker or marker in (b"\xd8", b"\xd9"):
|
|
327
|
+
break
|
|
328
|
+
if marker[0] in (0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF):
|
|
329
|
+
block = f.read(7)
|
|
330
|
+
if len(block) == 7:
|
|
331
|
+
h, w = struct.unpack(">HH", block[3:7])
|
|
332
|
+
return (w, h)
|
|
333
|
+
break
|
|
334
|
+
seg_len_bytes = f.read(2)
|
|
335
|
+
if len(seg_len_bytes) < 2:
|
|
336
|
+
break
|
|
337
|
+
seg_len = struct.unpack(">H", seg_len_bytes)[0]
|
|
338
|
+
if seg_len < 2:
|
|
339
|
+
break
|
|
340
|
+
f.seek(seg_len - 2, os.SEEK_CUR)
|
|
341
|
+
except OSError:
|
|
342
|
+
return None
|
|
343
|
+
return None
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def inspect_dataset_schema(root_path: Path, files: list[Path]) -> dict[str, Any]:
|
|
347
|
+
root_path = root_path.resolve()
|
|
348
|
+
ext_counts: Counter[str] = Counter()
|
|
349
|
+
tabular_tables: dict[str, Any] = {}
|
|
350
|
+
seen_parquet_dirs: set[Path] = set()
|
|
351
|
+
images: list[Path] = []
|
|
352
|
+
videos = 0
|
|
353
|
+
audios = 0
|
|
354
|
+
yolo_yaml: Path | None = None
|
|
355
|
+
|
|
356
|
+
for fp in files:
|
|
357
|
+
if fp.name == "meta.json":
|
|
358
|
+
continue
|
|
359
|
+
ext = fp.suffix.lower() or "<no_ext>"
|
|
360
|
+
ext_counts[ext] += 1
|
|
361
|
+
|
|
362
|
+
if fp.name == "data.yaml":
|
|
363
|
+
yolo_yaml = fp
|
|
364
|
+
elif ext in IMAGE_EXTS:
|
|
365
|
+
images.append(fp)
|
|
366
|
+
elif ext in VIDEO_EXTS:
|
|
367
|
+
videos += 1
|
|
368
|
+
elif ext in AUDIO_EXTS:
|
|
369
|
+
audios += 1
|
|
370
|
+
elif len(tabular_tables) < 12:
|
|
371
|
+
rel = str(fp.relative_to(root_path)) if root_path.is_dir() else fp.name
|
|
372
|
+
if ext == ".csv":
|
|
373
|
+
tabular_tables[rel] = _inspect_csv(fp, ",")
|
|
374
|
+
elif ext == ".tsv":
|
|
375
|
+
tabular_tables[rel] = _inspect_csv(fp, "\t")
|
|
376
|
+
elif ext == ".jsonl":
|
|
377
|
+
tabular_tables[rel] = _inspect_jsonl(fp)
|
|
378
|
+
elif ext == ".parquet" and fp.parent not in seen_parquet_dirs:
|
|
379
|
+
# Sample one representative file per partitioned parquet folder
|
|
380
|
+
seen_parquet_dirs.add(fp.parent)
|
|
381
|
+
part_count = sum(1 for p in files if p.parent == fp.parent and p.suffix.lower() == ".parquet")
|
|
382
|
+
meta = _inspect_parquet(fp)
|
|
383
|
+
if part_count > 1:
|
|
384
|
+
meta["partitions"] = part_count
|
|
385
|
+
rel_dir = str(fp.parent.relative_to(root_path)) if root_path.is_dir() else fp.parent.name
|
|
386
|
+
tabular_tables[f"{rel_dir}/*.parquet"] = meta
|
|
387
|
+
else:
|
|
388
|
+
tabular_tables[rel] = meta
|
|
389
|
+
|
|
390
|
+
schema: dict[str, Any] = {
|
|
391
|
+
"extensions": dict(ext_counts.most_common(10)),
|
|
392
|
+
}
|
|
393
|
+
if tabular_tables:
|
|
394
|
+
schema["tables"] = tabular_tables
|
|
395
|
+
if images:
|
|
396
|
+
sample_dims: Counter[str] = Counter()
|
|
397
|
+
for img in images[:8]:
|
|
398
|
+
dims = _image_dims(img)
|
|
399
|
+
if dims:
|
|
400
|
+
sample_dims[f"{dims[0]}x{dims[1]}"] += 1
|
|
401
|
+
img_info: dict[str, Any] = {"count": len(images)}
|
|
402
|
+
if sample_dims:
|
|
403
|
+
img_info["sample_resolutions"] = dict(sample_dims.most_common(5))
|
|
404
|
+
schema["images"] = img_info
|
|
405
|
+
if videos:
|
|
406
|
+
schema["videos"] = {"count": videos}
|
|
407
|
+
if audios:
|
|
408
|
+
schema["audio"] = {"count": audios}
|
|
409
|
+
if yolo_yaml:
|
|
410
|
+
try:
|
|
411
|
+
text = yolo_yaml.read_text(encoding="utf-8", errors="replace")
|
|
412
|
+
nc_match = re.search(r"^\s*nc\s*:\s*(\d+)", text, re.MULTILINE)
|
|
413
|
+
if nc_match:
|
|
414
|
+
schema["yolo_nc"] = int(nc_match.group(1))
|
|
415
|
+
except OSError:
|
|
416
|
+
pass
|
|
417
|
+
|
|
418
|
+
return schema
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def _safetensors_header(path: Path) -> tuple[Counter[str], Counter[str]]:
|
|
422
|
+
tensors: Counter[str] = Counter()
|
|
423
|
+
params: Counter[str] = Counter()
|
|
424
|
+
try:
|
|
425
|
+
if getattr(path.stat(), "st_flags", 0) & SF_DATALESS:
|
|
426
|
+
return tensors, params
|
|
427
|
+
with path.open("rb") as stream:
|
|
428
|
+
length = struct.unpack("<Q", stream.read(8))[0]
|
|
429
|
+
if not 0 < length <= 50 * 1024 * 1024:
|
|
430
|
+
return tensors, params
|
|
431
|
+
header = json.loads(stream.read(length))
|
|
432
|
+
if not isinstance(header, dict):
|
|
433
|
+
return tensors, params
|
|
434
|
+
for name, tensor in header.items():
|
|
435
|
+
if name == "__metadata__" or not isinstance(tensor, dict):
|
|
436
|
+
continue
|
|
437
|
+
shape = tensor.get("shape")
|
|
438
|
+
if not isinstance(shape, list) or any(type(n) is not int or n < 0 for n in shape):
|
|
439
|
+
continue
|
|
440
|
+
dtype = str(tensor.get("dtype", "unknown"))
|
|
441
|
+
tensors[dtype] += 1
|
|
442
|
+
params[dtype] += math.prod(shape)
|
|
443
|
+
except (OSError, struct.error, ValueError):
|
|
444
|
+
pass
|
|
445
|
+
return tensors, params
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def _safetensors_schema(files: list[Path]) -> dict[str, Any]:
|
|
449
|
+
tensors: Counter[str] = Counter()
|
|
450
|
+
params: Counter[str] = Counter()
|
|
451
|
+
shards = 0
|
|
452
|
+
for file in files:
|
|
453
|
+
counts, weights = _safetensors_header(file)
|
|
454
|
+
if counts:
|
|
455
|
+
shards += 1
|
|
456
|
+
tensors.update(counts)
|
|
457
|
+
params.update(weights)
|
|
458
|
+
if not shards:
|
|
459
|
+
return {}
|
|
460
|
+
return {
|
|
461
|
+
"tensors": sum(tensors.values()),
|
|
462
|
+
"params": sum(params.values()),
|
|
463
|
+
"dtypes": dict(tensors),
|
|
464
|
+
"parameters_by_dtype": dict(params),
|
|
465
|
+
"safetensors_files": shards,
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def inspect_model_schema(path: Path, files: list[Path] | None = None) -> dict[str, Any]:
|
|
470
|
+
info: dict[str, Any] = {}
|
|
471
|
+
if path.is_file():
|
|
472
|
+
ext = path.suffix.lower()
|
|
473
|
+
info["format"] = ext.lstrip(".") or "file"
|
|
474
|
+
if ext == ".safetensors":
|
|
475
|
+
info.update(_safetensors_schema([path]))
|
|
476
|
+
elif ext == ".gguf":
|
|
477
|
+
try:
|
|
478
|
+
with path.open("rb") as f:
|
|
479
|
+
magic, version, tensor_count, kv_count = struct.unpack("<4sIQQ", f.read(24))
|
|
480
|
+
if magic == b"GGUF":
|
|
481
|
+
info["gguf_version"] = version
|
|
482
|
+
info["tensors"] = tensor_count
|
|
483
|
+
info["metadata_kv"] = kv_count
|
|
484
|
+
except (OSError, struct.error):
|
|
485
|
+
pass
|
|
486
|
+
elif ext == ".onnx":
|
|
487
|
+
try:
|
|
488
|
+
import onnxruntime as ort # type: ignore
|
|
489
|
+
|
|
490
|
+
sess = ort.InferenceSession(str(path), providers=["CPUExecutionProvider"])
|
|
491
|
+
info["inputs"] = {i.name: {"shape": i.shape, "type": i.type} for i in sess.get_inputs()}
|
|
492
|
+
info["outputs"] = {o.name: {"shape": o.shape, "type": o.type} for o in sess.get_outputs()}
|
|
493
|
+
except Exception as error: # noqa: BLE001 - ONNX Runtime reports native failures with several exception types.
|
|
494
|
+
logger.debug("ONNX schema unavailable for %s: %s", path, error)
|
|
495
|
+
elif path.is_dir():
|
|
496
|
+
files = collect_files(path)[2] if files is None else files
|
|
497
|
+
shards = [file for file in files if file.suffix.lower() == ".safetensors"]
|
|
498
|
+
cfg_path = path / "config.json"
|
|
499
|
+
if cfg_path.is_file():
|
|
500
|
+
info["format"] = "hf_bundle"
|
|
501
|
+
try:
|
|
502
|
+
cfg = json.loads(cfg_path.read_text(encoding="utf-8"))
|
|
503
|
+
for key in ("model_type", "architectures", "hidden_size", "num_hidden_layers", "vocab_size", "quantization"):
|
|
504
|
+
if key in cfg:
|
|
505
|
+
info[key] = cfg[key]
|
|
506
|
+
except (OSError, json.JSONDecodeError):
|
|
507
|
+
pass
|
|
508
|
+
elif (path / ".datahub-ollama.json").is_file():
|
|
509
|
+
info["format"] = "ollama_reference"
|
|
510
|
+
try:
|
|
511
|
+
info["ollama_model"] = json.loads((path / ".datahub-ollama.json").read_text(encoding="utf-8"))["model"]
|
|
512
|
+
except (OSError, ValueError, KeyError, TypeError):
|
|
513
|
+
pass
|
|
514
|
+
elif shards:
|
|
515
|
+
info["format"] = "hf_bundle"
|
|
516
|
+
elif (path / "blobs").is_dir() and (path / "manifests").is_dir():
|
|
517
|
+
info["format"] = "ollama_store"
|
|
518
|
+
elif path.suffix.lower() in MODEL_BUNDLE_SUFFIXES:
|
|
519
|
+
info["format"] = path.suffix.lower().lstrip(".")
|
|
520
|
+
else:
|
|
521
|
+
info["format"] = "directory"
|
|
522
|
+
info.update(_safetensors_schema(shards))
|
|
523
|
+
return info
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
# ---------------------------------------------------------------------------
|
|
527
|
+
# Dataset / model layout detection
|
|
528
|
+
# ---------------------------------------------------------------------------
|
|
529
|
+
|
|
530
|
+
def is_single_dataset_dir(entry: Path, children: list[Path]) -> bool:
|
|
531
|
+
if (entry / ".datahub-category").is_file():
|
|
532
|
+
return False
|
|
533
|
+
child_names = {c.name for c in children}
|
|
534
|
+
if child_names & DATASET_MARKER_FILES:
|
|
535
|
+
return True
|
|
536
|
+
if any(c.is_dir() and c.name in DATASET_MARKER_DIRS for c in children):
|
|
537
|
+
return True
|
|
538
|
+
return all(c.is_file() for c in children)
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
def is_single_model_dir(entry: Path, children: list[Path]) -> bool:
|
|
542
|
+
if entry.suffix.lower() in MODEL_BUNDLE_SUFFIXES or (entry / ".datahub-model").is_file():
|
|
543
|
+
return True
|
|
544
|
+
child_names = {c.name for c in children}
|
|
545
|
+
if "blobs" in child_names and "manifests" in child_names:
|
|
546
|
+
return True
|
|
547
|
+
return bool(child_names & MODEL_BUNDLE_MARKERS) or any(
|
|
548
|
+
re.search(r"-\d+-of-\d+\.safetensors$", child.name, re.IGNORECASE) for child in children
|
|
549
|
+
)
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
# ---------------------------------------------------------------------------
|
|
553
|
+
# Reverse dependency scanning across PROJECTS_ROOT
|
|
554
|
+
# ---------------------------------------------------------------------------
|
|
555
|
+
|
|
556
|
+
def _infer_project_name(file_path: Path, root: Path, cache: dict[Path, str]) -> str:
|
|
557
|
+
parent = file_path.parent
|
|
558
|
+
if parent in cache:
|
|
559
|
+
return cache[parent]
|
|
560
|
+
|
|
561
|
+
cur = parent
|
|
562
|
+
found: Path | None = None
|
|
563
|
+
while cur != root and root in cur.parents:
|
|
564
|
+
if any((cur / marker).exists() for marker in (".git", "pyproject.toml", "package.json", "Cargo.toml")):
|
|
565
|
+
found = cur
|
|
566
|
+
break
|
|
567
|
+
cur = cur.parent
|
|
568
|
+
|
|
569
|
+
if found is not None:
|
|
570
|
+
name = str(found.relative_to(root))
|
|
571
|
+
else:
|
|
572
|
+
rel_parts = file_path.relative_to(root).parts
|
|
573
|
+
name = rel_parts[0] if rel_parts else root.name
|
|
574
|
+
|
|
575
|
+
cache[parent] = name
|
|
576
|
+
return name
|
|
577
|
+
|
|
578
|
+
|
|
579
|
+
def _matches_boundary(line: str, needle: str) -> bool:
|
|
580
|
+
start = 0
|
|
581
|
+
boundary_chars = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-")
|
|
582
|
+
while True:
|
|
583
|
+
idx = line.find(needle, start)
|
|
584
|
+
if idx == -1:
|
|
585
|
+
return False
|
|
586
|
+
after_idx = idx + len(needle)
|
|
587
|
+
after_ok = after_idx == len(line) or line[after_idx] not in boundary_chars
|
|
588
|
+
if after_ok:
|
|
589
|
+
return True
|
|
590
|
+
start = idx + 1
|
|
591
|
+
|
|
592
|
+
def refresh_usages(conn: sqlite3.Connection, config: Config | None = None) -> int:
|
|
593
|
+
projects_root = (config or resolve_config()).projects_root
|
|
594
|
+
if projects_root is None:
|
|
595
|
+
print("Dependency scan disabled. Set PROJECTS_ROOT or use --projects-root.", file=sys.stderr)
|
|
596
|
+
return 0
|
|
597
|
+
try:
|
|
598
|
+
flags = getattr(projects_root.stat(), "st_flags", 0)
|
|
599
|
+
except OSError:
|
|
600
|
+
flags = 0
|
|
601
|
+
if not projects_root.is_dir() or flags & SF_DATALESS:
|
|
602
|
+
print(f"Skipping dependency scan: PROJECTS_ROOT unavailable at {projects_root}", file=sys.stderr)
|
|
603
|
+
return 0
|
|
604
|
+
if not conn.in_transaction:
|
|
605
|
+
conn.execute("BEGIN IMMEDIATE")
|
|
606
|
+
|
|
607
|
+
now = datetime.now(UTC).isoformat(timespec="seconds")
|
|
608
|
+
items: list[tuple[str, str]] = []
|
|
609
|
+
for r in conn.execute("SELECT id FROM datasets"):
|
|
610
|
+
items.append(("dataset", r["id"]))
|
|
611
|
+
for r in conn.execute("SELECT id FROM models"):
|
|
612
|
+
items.append(("model", r["id"]))
|
|
613
|
+
|
|
614
|
+
if not items:
|
|
615
|
+
conn.execute("DELETE FROM usages")
|
|
616
|
+
return 0
|
|
617
|
+
|
|
618
|
+
id_to_types: dict[str, list[str]] = {}
|
|
619
|
+
for item_type, item_id in items:
|
|
620
|
+
id_to_types.setdefault(item_id, []).append(item_type)
|
|
621
|
+
all_ids = sorted(id_to_types, key=len, reverse=True)
|
|
622
|
+
pattern = re.compile("|".join(re.escape(i) for i in all_ids))
|
|
623
|
+
|
|
624
|
+
proj_cache: dict[Path, str] = {}
|
|
625
|
+
references = []
|
|
626
|
+
skipped_cloud = 0
|
|
627
|
+
stack = [projects_root]
|
|
628
|
+
|
|
629
|
+
while stack:
|
|
630
|
+
current = stack.pop()
|
|
631
|
+
try:
|
|
632
|
+
with os.scandir(current) as it:
|
|
633
|
+
for entry in it:
|
|
634
|
+
name = entry.name
|
|
635
|
+
if name.startswith(".") or name in SKIP_PROJECT_DIRS:
|
|
636
|
+
continue
|
|
637
|
+
try:
|
|
638
|
+
if entry.is_symlink():
|
|
639
|
+
continue
|
|
640
|
+
st = entry.stat(follow_symlinks=False)
|
|
641
|
+
if getattr(st, "st_flags", 0) & SF_DATALESS:
|
|
642
|
+
skipped_cloud += 1
|
|
643
|
+
continue
|
|
644
|
+
if entry.is_dir(follow_symlinks=False):
|
|
645
|
+
if name.endswith((".app", ".framework", ".xcodeproj", ".xcworkspace")):
|
|
646
|
+
continue
|
|
647
|
+
stack.append(Path(entry.path))
|
|
648
|
+
elif entry.is_file(follow_symlinks=False):
|
|
649
|
+
if name == "package-lock.json" or Path(name).suffix.lower() not in CODE_EXTS:
|
|
650
|
+
continue
|
|
651
|
+
if st.st_size == 0 or st.st_size > 512 * 1024:
|
|
652
|
+
continue
|
|
653
|
+
fpath = Path(entry.path)
|
|
654
|
+
text = fpath.read_text(encoding="utf-8", errors="ignore")
|
|
655
|
+
if not pattern.search(text):
|
|
656
|
+
continue
|
|
657
|
+
rel_file = str(fpath.relative_to(projects_root))
|
|
658
|
+
project = _infer_project_name(fpath, projects_root, proj_cache)
|
|
659
|
+
for line_no, content in enumerate(text.splitlines(), 1):
|
|
660
|
+
if not pattern.search(content):
|
|
661
|
+
continue
|
|
662
|
+
for item_id in all_ids:
|
|
663
|
+
if _matches_boundary(content, item_id):
|
|
664
|
+
references.extend(
|
|
665
|
+
(kind, item_id, project, rel_file, line_no, now)
|
|
666
|
+
for kind in id_to_types[item_id]
|
|
667
|
+
)
|
|
668
|
+
except OSError:
|
|
669
|
+
continue
|
|
670
|
+
except OSError:
|
|
671
|
+
continue
|
|
672
|
+
|
|
673
|
+
if skipped_cloud:
|
|
674
|
+
print(f"Skipped {skipped_cloud} iCloud-only (dataless) files/dirs during dependency scan.", file=sys.stderr)
|
|
675
|
+
conn.execute("DELETE FROM usages")
|
|
676
|
+
conn.executemany(
|
|
677
|
+
"""INSERT OR REPLACE INTO usages
|
|
678
|
+
(item_type, item_id, project, file_path, line_no, updated_at) VALUES (?, ?, ?, ?, ?, ?)""",
|
|
679
|
+
references,
|
|
680
|
+
)
|
|
681
|
+
return len(references)
|
|
682
|
+
|
|
683
|
+
|
|
684
|
+
# ---------------------------------------------------------------------------
|
|
685
|
+
# CLI subcommands
|
|
686
|
+
# ---------------------------------------------------------------------------
|
|
687
|
+
|
|
688
|
+
def cmd_scan(args: argparse.Namespace) -> None:
|
|
689
|
+
now = datetime.now(UTC).isoformat(timespec="seconds")
|
|
690
|
+
seen_datasets: set[str] = set()
|
|
691
|
+
seen_models: set[str] = set()
|
|
692
|
+
|
|
693
|
+
config = args.config
|
|
694
|
+
with database(config) as conn:
|
|
695
|
+
conn.execute("BEGIN IMMEDIATE")
|
|
696
|
+
datasets_dir = config.data_root / "datasets"
|
|
697
|
+
if datasets_dir.is_dir():
|
|
698
|
+
for entry in visible_children(datasets_dir):
|
|
699
|
+
if not entry.exists():
|
|
700
|
+
continue
|
|
701
|
+
if entry.is_file():
|
|
702
|
+
targets = [("uncategorized", entry)]
|
|
703
|
+
elif entry.is_dir():
|
|
704
|
+
children = visible_children(entry)
|
|
705
|
+
if not children:
|
|
706
|
+
continue
|
|
707
|
+
if is_single_dataset_dir(entry, children):
|
|
708
|
+
targets = [("uncategorized", entry)]
|
|
709
|
+
else:
|
|
710
|
+
targets = [(entry.name, c) for c in children if c.exists()]
|
|
711
|
+
else:
|
|
712
|
+
continue
|
|
713
|
+
|
|
714
|
+
for category, ds_path in targets:
|
|
715
|
+
ds_id = f"{category}/{ds_path.name}" if category != "uncategorized" else ds_path.name
|
|
716
|
+
seen_datasets.add(ds_id)
|
|
717
|
+
size_bytes, file_count, files = collect_files(ds_path)
|
|
718
|
+
source_url, notes = read_meta(ds_path)
|
|
719
|
+
schema_str = json.dumps(inspect_dataset_schema(ds_path, files))
|
|
720
|
+
rel_path = str(ds_path.relative_to(config.data_root))
|
|
721
|
+
|
|
722
|
+
conn.execute(
|
|
723
|
+
"""
|
|
724
|
+
INSERT INTO datasets (id, category, name, rel_path, size_bytes, file_count, source_url, notes, schema_json, updated_at)
|
|
725
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
726
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
727
|
+
category = excluded.category,
|
|
728
|
+
name = excluded.name,
|
|
729
|
+
rel_path = excluded.rel_path,
|
|
730
|
+
size_bytes = excluded.size_bytes,
|
|
731
|
+
file_count = excluded.file_count,
|
|
732
|
+
source_url = COALESCE(NULLIF(excluded.source_url, ''), datasets.source_url),
|
|
733
|
+
notes = COALESCE(NULLIF(excluded.notes, ''), datasets.notes),
|
|
734
|
+
schema_json = excluded.schema_json,
|
|
735
|
+
updated_at = excluded.updated_at
|
|
736
|
+
""",
|
|
737
|
+
(ds_id, category, ds_path.name, rel_path, size_bytes, file_count, source_url, notes, schema_str, now),
|
|
738
|
+
)
|
|
739
|
+
|
|
740
|
+
existing_ds = {r["id"] for r in conn.execute("SELECT id FROM datasets")}
|
|
741
|
+
for stale in existing_ds - seen_datasets:
|
|
742
|
+
conn.execute("DELETE FROM datasets WHERE id = ?", (stale,))
|
|
743
|
+
conn.execute("DELETE FROM usages WHERE item_type = 'dataset' AND item_id = ?", (stale,))
|
|
744
|
+
|
|
745
|
+
models_dir = config.data_root / "models"
|
|
746
|
+
if models_dir.is_dir():
|
|
747
|
+
for entry in visible_children(models_dir):
|
|
748
|
+
if not entry.exists():
|
|
749
|
+
continue
|
|
750
|
+
if entry.is_file():
|
|
751
|
+
targets = [("root", entry)]
|
|
752
|
+
elif entry.is_dir():
|
|
753
|
+
children = visible_children(entry)
|
|
754
|
+
if not children and not (entry / ".datahub-model").is_file():
|
|
755
|
+
continue
|
|
756
|
+
if is_single_model_dir(entry, children):
|
|
757
|
+
targets = [("root", entry)]
|
|
758
|
+
else:
|
|
759
|
+
targets = [(entry.name, c) for c in children if c.exists()]
|
|
760
|
+
else:
|
|
761
|
+
continue
|
|
762
|
+
|
|
763
|
+
for kind, item in targets:
|
|
764
|
+
m_id = f"{kind}/{item.name}" if kind != "root" else item.name
|
|
765
|
+
seen_models.add(m_id)
|
|
766
|
+
size_bytes, _, files = collect_files(item)
|
|
767
|
+
schema_str = json.dumps(inspect_model_schema(item, files))
|
|
768
|
+
_, notes = read_meta(item, ".datahub-model")
|
|
769
|
+
rel_path = str(item.relative_to(config.data_root))
|
|
770
|
+
|
|
771
|
+
conn.execute(
|
|
772
|
+
"""
|
|
773
|
+
INSERT INTO models (id, kind, name, rel_path, size_bytes, notes, schema_json, updated_at)
|
|
774
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
775
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
776
|
+
kind = excluded.kind,
|
|
777
|
+
name = excluded.name,
|
|
778
|
+
rel_path = excluded.rel_path,
|
|
779
|
+
size_bytes = excluded.size_bytes,
|
|
780
|
+
schema_json = excluded.schema_json,
|
|
781
|
+
updated_at = excluded.updated_at
|
|
782
|
+
""",
|
|
783
|
+
(m_id, kind, item.name, rel_path, size_bytes, notes, schema_str, now),
|
|
784
|
+
)
|
|
785
|
+
|
|
786
|
+
existing_m = {r["id"] for r in conn.execute("SELECT id FROM models")}
|
|
787
|
+
for stale in existing_m - seen_models:
|
|
788
|
+
conn.execute("DELETE FROM models WHERE id = ?", (stale,))
|
|
789
|
+
conn.execute("DELETE FROM usages WHERE item_type = 'model' AND item_id = ?", (stale,))
|
|
790
|
+
|
|
791
|
+
ref_msg = ""
|
|
792
|
+
if getattr(args, "deps", False):
|
|
793
|
+
ref_count = refresh_usages(conn, config)
|
|
794
|
+
ref_msg = f" and {ref_count} project references"
|
|
795
|
+
|
|
796
|
+
if not getattr(args, "quiet", False):
|
|
797
|
+
print(f"Indexed {len(seen_datasets)} datasets, {len(seen_models)} models{ref_msg} into {config.db_path}")
|
|
798
|
+
|
|
799
|
+
|
|
800
|
+
def _resolve_item(conn: sqlite3.Connection, item_id: str) -> tuple[str, sqlite3.Row]:
|
|
801
|
+
matches: list[tuple[str, sqlite3.Row]] = []
|
|
802
|
+
for table, kind in (("datasets", "dataset"), ("models", "model")):
|
|
803
|
+
row = conn.execute(f"SELECT * FROM {table} WHERE id = ?", (item_id,)).fetchone()
|
|
804
|
+
if row:
|
|
805
|
+
matches.append((kind, row))
|
|
806
|
+
if not matches:
|
|
807
|
+
for table, kind in (("datasets", "dataset"), ("models", "model")):
|
|
808
|
+
for row in conn.execute(f"SELECT * FROM {table} WHERE name = ?", (item_id,)).fetchall():
|
|
809
|
+
matches.append((kind, row))
|
|
810
|
+
if not matches:
|
|
811
|
+
raise SystemExit(f"Not found in catalog: {item_id}")
|
|
812
|
+
if len(matches) > 1:
|
|
813
|
+
ids = ", ".join(r["id"] for _, r in matches)
|
|
814
|
+
raise SystemExit(f"Ambiguous ID '{item_id}'. Matches: {ids}")
|
|
815
|
+
return matches[0]
|
|
816
|
+
|
|
817
|
+
|
|
818
|
+
def catalog_path(table: str, item_id: str, config: Config) -> Path:
|
|
819
|
+
if table not in {"datasets", "models"}:
|
|
820
|
+
raise ValueError("Invalid catalog table")
|
|
821
|
+
with database(config) as conn:
|
|
822
|
+
row = conn.execute(f"SELECT rel_path FROM {table} WHERE id = ?", (item_id,)).fetchone()
|
|
823
|
+
if row is None:
|
|
824
|
+
matches = conn.execute(f"SELECT rel_path FROM {table} WHERE name = ?", (item_id,)).fetchall()
|
|
825
|
+
if len(matches) != 1:
|
|
826
|
+
raise KeyError(f"Expected a unique catalog item for {item_id!r}")
|
|
827
|
+
row = matches[0]
|
|
828
|
+
return config.data_root / row["rel_path"]
|
|
829
|
+
|
|
830
|
+
|
|
831
|
+
def cmd_info(args: argparse.Namespace) -> None:
|
|
832
|
+
config = args.config
|
|
833
|
+
with database(config) as conn:
|
|
834
|
+
kind, row = _resolve_item(conn, args.id)
|
|
835
|
+
usages = conn.execute(
|
|
836
|
+
"SELECT project, file_path, line_no FROM usages WHERE item_type = ? AND item_id = ? ORDER BY project, file_path, line_no",
|
|
837
|
+
(kind, row["id"]),
|
|
838
|
+
).fetchall()
|
|
839
|
+
|
|
840
|
+
schema = json.loads(row["schema_json"]) if row["schema_json"] else {}
|
|
841
|
+
abs_path = str(config.data_root / row["rel_path"])
|
|
842
|
+
|
|
843
|
+
if args.json:
|
|
844
|
+
payload: dict[str, Any] = {
|
|
845
|
+
"type": kind,
|
|
846
|
+
"id": row["id"],
|
|
847
|
+
"path": abs_path,
|
|
848
|
+
"size_bytes": row["size_bytes"],
|
|
849
|
+
"size": fmt_size(row["size_bytes"]),
|
|
850
|
+
"notes": row["notes"],
|
|
851
|
+
"schema": schema,
|
|
852
|
+
"used_by": [{"project": u["project"], "file": u["file_path"], "line": u["line_no"]} for u in usages],
|
|
853
|
+
}
|
|
854
|
+
if kind == "dataset":
|
|
855
|
+
payload["file_count"] = row["file_count"]
|
|
856
|
+
payload["source_url"] = row["source_url"]
|
|
857
|
+
print(json.dumps(payload, indent=2))
|
|
858
|
+
return
|
|
859
|
+
|
|
860
|
+
print(f"{kind.upper()}: {row['id']}")
|
|
861
|
+
print(f" Path: {abs_path}")
|
|
862
|
+
if kind == "dataset":
|
|
863
|
+
print(f" Size: {fmt_size(row['size_bytes'])} ({row['file_count']} files)")
|
|
864
|
+
if row["source_url"]:
|
|
865
|
+
print(f" Src: {row['source_url']}")
|
|
866
|
+
else:
|
|
867
|
+
print(f" Size: {fmt_size(row['size_bytes'])}")
|
|
868
|
+
if row["notes"]:
|
|
869
|
+
print(f" Notes: {row['notes']}")
|
|
870
|
+
|
|
871
|
+
if schema:
|
|
872
|
+
print(" Schema:")
|
|
873
|
+
if "extensions" in schema:
|
|
874
|
+
ext_str = ", ".join(f"{k}:{v}" for k, v in schema["extensions"].items())
|
|
875
|
+
print(f" Files: {ext_str}")
|
|
876
|
+
if "images" in schema:
|
|
877
|
+
img = schema["images"]
|
|
878
|
+
res = f" ({img['sample_resolutions']})" if "sample_resolutions" in img else ""
|
|
879
|
+
print(f" Images: {img['count']}{res}")
|
|
880
|
+
if "videos" in schema:
|
|
881
|
+
print(f" Videos: {schema['videos']['count']}")
|
|
882
|
+
if "audio" in schema:
|
|
883
|
+
print(f" Audio: {schema['audio']['count']}")
|
|
884
|
+
if "tables" in schema:
|
|
885
|
+
for tname, tmeta in schema["tables"].items():
|
|
886
|
+
rows_str = f", {tmeta['rows']:,} rows" if "rows" in tmeta else ""
|
|
887
|
+
parts_str = f", {tmeta['partitions']} parts" if "partitions" in tmeta else ""
|
|
888
|
+
print(f" Table: {tname} [{tmeta.get('format', '?')}{rows_str}{parts_str}]")
|
|
889
|
+
cols = tmeta.get("columns") or tmeta.get("fields") or {}
|
|
890
|
+
if cols:
|
|
891
|
+
col_list = ", ".join(f"{c}:{t}" for c, t in list(cols.items())[:12])
|
|
892
|
+
suffix = f" ... (+{len(cols) - 12} more)" if len(cols) > 12 else ""
|
|
893
|
+
print(f" {col_list}{suffix}")
|
|
894
|
+
if kind == "model":
|
|
895
|
+
for k, v in schema.items():
|
|
896
|
+
val = f"{v:,}" if k == "params" and isinstance(v, int) else v
|
|
897
|
+
print(f" {k}: {val}")
|
|
898
|
+
|
|
899
|
+
if usages:
|
|
900
|
+
by_proj: dict[str, list[str]] = {}
|
|
901
|
+
for u in usages:
|
|
902
|
+
by_proj.setdefault(u["project"], []).append(f"{u['file_path']}:{u['line_no']}")
|
|
903
|
+
print(f" Used by ({len(by_proj)} project{'s' if len(by_proj) != 1 else ''}):")
|
|
904
|
+
for proj, locs in by_proj.items():
|
|
905
|
+
preview = ", ".join(locs[:3])
|
|
906
|
+
more = f" (+{len(locs) - 3} more)" if len(locs) > 3 else ""
|
|
907
|
+
print(f" - {proj}: {preview}{more}")
|
|
908
|
+
else:
|
|
909
|
+
print(" Used by: (none indexed — run `datahub used --refresh` to scan projects)")
|
|
910
|
+
|
|
911
|
+
|
|
912
|
+
def cmd_used(args: argparse.Namespace) -> None:
|
|
913
|
+
config = args.config
|
|
914
|
+
with database(config) as conn:
|
|
915
|
+
if args.refresh:
|
|
916
|
+
count = refresh_usages(conn, config)
|
|
917
|
+
if config.projects_root is not None and config.projects_root.is_dir():
|
|
918
|
+
print(f"Scanned {config.projects_root}: found {count} references.\n")
|
|
919
|
+
|
|
920
|
+
if args.id:
|
|
921
|
+
kind, row = _resolve_item(conn, args.id)
|
|
922
|
+
rows = conn.execute(
|
|
923
|
+
"SELECT project, file_path, line_no FROM usages WHERE item_type = ? AND item_id = ? ORDER BY project, file_path, line_no",
|
|
924
|
+
(kind, row["id"]),
|
|
925
|
+
).fetchall()
|
|
926
|
+
if not rows:
|
|
927
|
+
print(f"No project references found for {row['id']}")
|
|
928
|
+
return
|
|
929
|
+
print(f"REFERENCES FOR {row['id']} ({len(rows)})")
|
|
930
|
+
for r in rows:
|
|
931
|
+
print(f" [{r['project']}] {r['file_path']}:{r['line_no']}")
|
|
932
|
+
else:
|
|
933
|
+
rows = conn.execute(
|
|
934
|
+
"""
|
|
935
|
+
SELECT item_type, item_id, COUNT(DISTINCT project) AS proj_cnt, COUNT(*) AS ref_cnt,
|
|
936
|
+
GROUP_CONCAT(DISTINCT project) AS projects
|
|
937
|
+
FROM usages
|
|
938
|
+
GROUP BY item_type, item_id
|
|
939
|
+
ORDER BY proj_cnt DESC, item_id ASC
|
|
940
|
+
"""
|
|
941
|
+
).fetchall()
|
|
942
|
+
if not rows:
|
|
943
|
+
print("No references indexed yet. Run datahub used --refresh.")
|
|
944
|
+
return
|
|
945
|
+
print(f"{'ID':<38} {'REFS':>5} PROJECTS")
|
|
946
|
+
print("-" * 78)
|
|
947
|
+
for r in rows:
|
|
948
|
+
print(f"{r['item_id']:<38} {r['ref_cnt']:>5} {r['projects']}")
|
|
949
|
+
|
|
950
|
+
|
|
951
|
+
def cmd_orphans(args: argparse.Namespace) -> None:
|
|
952
|
+
config = args.config
|
|
953
|
+
with database(config) as conn:
|
|
954
|
+
if args.refresh:
|
|
955
|
+
refresh_usages(conn, config)
|
|
956
|
+
|
|
957
|
+
ds_rows = conn.execute(
|
|
958
|
+
"""
|
|
959
|
+
SELECT id, size_bytes FROM datasets
|
|
960
|
+
WHERE id NOT IN (SELECT item_id FROM usages WHERE item_type = 'dataset')
|
|
961
|
+
ORDER BY size_bytes DESC
|
|
962
|
+
"""
|
|
963
|
+
).fetchall()
|
|
964
|
+
m_rows = conn.execute(
|
|
965
|
+
"""
|
|
966
|
+
SELECT id, size_bytes FROM models
|
|
967
|
+
WHERE id NOT IN (SELECT item_id FROM usages WHERE item_type = 'model')
|
|
968
|
+
ORDER BY size_bytes DESC
|
|
969
|
+
"""
|
|
970
|
+
).fetchall()
|
|
971
|
+
|
|
972
|
+
total_bytes = sum(r["size_bytes"] for r in ds_rows) + sum(r["size_bytes"] for r in m_rows)
|
|
973
|
+
print(f"UNREFERENCED ITEMS ({len(ds_rows)} datasets, {len(m_rows)} models — {fmt_size(total_bytes)})")
|
|
974
|
+
if ds_rows:
|
|
975
|
+
print("\nDatasets:")
|
|
976
|
+
for r in ds_rows:
|
|
977
|
+
print(f" {r['id']:<40} {fmt_size(r['size_bytes']):>10}")
|
|
978
|
+
if m_rows:
|
|
979
|
+
print("\nModels:")
|
|
980
|
+
for r in m_rows:
|
|
981
|
+
print(f" {r['id']:<40} {fmt_size(r['size_bytes']):>10}")
|
|
982
|
+
|
|
983
|
+
|
|
984
|
+
def cmd_ls(args: argparse.Namespace) -> None:
|
|
985
|
+
order_map = {
|
|
986
|
+
"name": "id ASC",
|
|
987
|
+
"size": "size_bytes DESC, id ASC",
|
|
988
|
+
"updated": "updated_at DESC, id ASC",
|
|
989
|
+
}
|
|
990
|
+
order_sql = order_map[args.sort]
|
|
991
|
+
|
|
992
|
+
config = args.config
|
|
993
|
+
with database(config) as conn:
|
|
994
|
+
if args.type in ("all", "datasets"):
|
|
995
|
+
query = "SELECT id, size_bytes, file_count, notes FROM datasets"
|
|
996
|
+
params: list[str] = []
|
|
997
|
+
if args.category:
|
|
998
|
+
query += " WHERE category = ?"
|
|
999
|
+
params.append(args.category)
|
|
1000
|
+
query += f" ORDER BY {order_sql}"
|
|
1001
|
+
rows = conn.execute(query, params).fetchall()
|
|
1002
|
+
total_ds = sum(r["size_bytes"] for r in rows)
|
|
1003
|
+
|
|
1004
|
+
print(f"\nDATASETS ({len(rows)} — {fmt_size(total_ds)})")
|
|
1005
|
+
print(f"{'ID':<38} {'SIZE':>10} {'FILES':>8} NOTES")
|
|
1006
|
+
print("-" * 78)
|
|
1007
|
+
for r in rows:
|
|
1008
|
+
note = (r["notes"] or "").replace("\n", " ")[:30]
|
|
1009
|
+
print(f"{r['id']:<38} {fmt_size(r['size_bytes']):>10} {r['file_count']:>8} {note}")
|
|
1010
|
+
|
|
1011
|
+
if args.type in ("all", "models"):
|
|
1012
|
+
query = "SELECT id, size_bytes, notes FROM models"
|
|
1013
|
+
params = []
|
|
1014
|
+
if args.category:
|
|
1015
|
+
query += " WHERE kind = ?"
|
|
1016
|
+
params.append(args.category)
|
|
1017
|
+
query += f" ORDER BY {order_sql}"
|
|
1018
|
+
rows = conn.execute(query, params).fetchall()
|
|
1019
|
+
total_m = sum(r["size_bytes"] for r in rows)
|
|
1020
|
+
|
|
1021
|
+
print(f"\nMODELS ({len(rows)} — {fmt_size(total_m)})")
|
|
1022
|
+
print(f"{'ID':<38} {'SIZE':>10} NOTES")
|
|
1023
|
+
print("-" * 78)
|
|
1024
|
+
for r in rows:
|
|
1025
|
+
note = (r["notes"] or "").replace("\n", " ")[:36]
|
|
1026
|
+
print(f"{r['id']:<38} {fmt_size(r['size_bytes']):>10} {note}")
|
|
1027
|
+
|
|
1028
|
+
|
|
1029
|
+
def cmd_add(args: argparse.Namespace) -> None:
|
|
1030
|
+
config = args.config
|
|
1031
|
+
parts = [p for p in args.dataset_id.strip("/").split("/") if p]
|
|
1032
|
+
if len(parts) != 2 or any(p in (".", "..") for p in parts):
|
|
1033
|
+
raise SystemExit("Use format: <category>/<name> (e.g. finance/prices)")
|
|
1034
|
+
|
|
1035
|
+
category, name = map(folder_name, parts)
|
|
1036
|
+
create_directories(config)
|
|
1037
|
+
ds_dir = config.data_root / "datasets" / category / name
|
|
1038
|
+
(ds_dir / "raw").mkdir(parents=True, exist_ok=True)
|
|
1039
|
+
(ds_dir / "processed").mkdir(parents=True, exist_ok=True)
|
|
1040
|
+
(ds_dir.parent / ".datahub-category").touch()
|
|
1041
|
+
|
|
1042
|
+
meta_path = ds_dir / "meta.json"
|
|
1043
|
+
existing_meta = {}
|
|
1044
|
+
if meta_path.is_file():
|
|
1045
|
+
try:
|
|
1046
|
+
stored = json.loads(meta_path.read_text(encoding="utf-8"))
|
|
1047
|
+
if isinstance(stored, dict):
|
|
1048
|
+
existing_meta = stored
|
|
1049
|
+
except (OSError, json.JSONDecodeError):
|
|
1050
|
+
pass
|
|
1051
|
+
|
|
1052
|
+
meta = {
|
|
1053
|
+
"id": f"{category}/{name}",
|
|
1054
|
+
"source_url": args.source or existing_meta.get("source_url", ""),
|
|
1055
|
+
"notes": args.notes or existing_meta.get("notes", ""),
|
|
1056
|
+
"created_at": existing_meta.get("created_at", datetime.now(UTC).isoformat(timespec="seconds")),
|
|
1057
|
+
}
|
|
1058
|
+
meta_path.write_text(json.dumps(meta, indent=2) + "\n", encoding="utf-8")
|
|
1059
|
+
print(f"Ready: {ds_dir}")
|
|
1060
|
+
cmd_scan(argparse.Namespace(deps=False, config=config))
|
|
1061
|
+
|
|
1062
|
+
|
|
1063
|
+
def cmd_note(args: argparse.Namespace) -> None:
|
|
1064
|
+
config = args.config
|
|
1065
|
+
with database(config) as conn:
|
|
1066
|
+
cur_ds = conn.execute("UPDATE datasets SET notes = ? WHERE id = ?", (args.note, args.id))
|
|
1067
|
+
cur_m = conn.execute("UPDATE models SET notes = ? WHERE id = ?", (args.note, args.id))
|
|
1068
|
+
if cur_ds.rowcount + cur_m.rowcount == 0:
|
|
1069
|
+
raise SystemExit(f"Not found in catalog: {args.id} (run datahub scan first)")
|
|
1070
|
+
print(f"Updated note for {args.id}")
|
|
1071
|
+
|
|
1072
|
+
|
|
1073
|
+
def cmd_path(args: argparse.Namespace) -> None:
|
|
1074
|
+
config = args.config
|
|
1075
|
+
with database(config) as conn:
|
|
1076
|
+
_, row = _resolve_item(conn, args.id)
|
|
1077
|
+
print(config.data_root / row["rel_path"])
|
|
1078
|
+
|
|
1079
|
+
|
|
1080
|
+
def add_subcommands(sub: argparse._SubParsersAction) -> None:
|
|
1081
|
+
|
|
1082
|
+
p_scan = sub.add_parser("scan", help="Scan datasets/ and models/, extract schemas, update catalog.db")
|
|
1083
|
+
p_scan.add_argument("--deps", action="store_true", help="Also scan PROJECTS_ROOT for dataset/model references")
|
|
1084
|
+
|
|
1085
|
+
p_ls = sub.add_parser("ls", help="List indexed datasets and models")
|
|
1086
|
+
p_ls.add_argument("type", nargs="?", default="all", choices=["all", "datasets", "models"])
|
|
1087
|
+
p_ls.add_argument("-c", "--category", help="Filter by category (datasets) or kind (models)")
|
|
1088
|
+
p_ls.add_argument("--sort", default="name", choices=["name", "size", "updated"], help="Sort order")
|
|
1089
|
+
|
|
1090
|
+
p_info = sub.add_parser("info", help="Show cached schema, metadata, and project usages for an item")
|
|
1091
|
+
p_info.add_argument("id", help="Catalog ID or unique short name")
|
|
1092
|
+
p_info.add_argument("--json", action="store_true", help="Output compact JSON (ideal for agents)")
|
|
1093
|
+
|
|
1094
|
+
p_used = sub.add_parser("used", help="Show which projects reference a dataset/model (or all)")
|
|
1095
|
+
p_used.add_argument("id", nargs="?", help="Optional catalog ID or unique short name")
|
|
1096
|
+
p_used.add_argument("--refresh", action="store_true", help="Re-scan PROJECTS_ROOT before printing")
|
|
1097
|
+
|
|
1098
|
+
p_orphans = sub.add_parser("orphans", help="List datasets and models not referenced by any project")
|
|
1099
|
+
p_orphans.add_argument("--refresh", action="store_true", help="Re-scan PROJECTS_ROOT before printing")
|
|
1100
|
+
|
|
1101
|
+
p_add = sub.add_parser("add", help="Scaffold a new dataset folder and register it")
|
|
1102
|
+
p_add.add_argument("dataset_id", help="Format: <category>/<name>")
|
|
1103
|
+
p_add.add_argument("--source", default="", help="Source URL")
|
|
1104
|
+
p_add.add_argument("--notes", default="", help="Short description")
|
|
1105
|
+
|
|
1106
|
+
p_note = sub.add_parser("note", help="Attach or update a note on any dataset or model")
|
|
1107
|
+
p_note.add_argument("id", help="Exact catalog ID")
|
|
1108
|
+
p_note.add_argument("note", help="Note text")
|
|
1109
|
+
|
|
1110
|
+
p_path = sub.add_parser("path", help="Print absolute path for a dataset or model ID")
|
|
1111
|
+
p_path.add_argument("id", help="Catalog ID or unique name")
|
|
1112
|
+
|
|
1113
|
+
handlers = {
|
|
1114
|
+
"scan": cmd_scan,
|
|
1115
|
+
"ls": cmd_ls,
|
|
1116
|
+
"info": cmd_info,
|
|
1117
|
+
"used": cmd_used,
|
|
1118
|
+
"orphans": cmd_orphans,
|
|
1119
|
+
"add": cmd_add,
|
|
1120
|
+
"note": cmd_note,
|
|
1121
|
+
"path": cmd_path,
|
|
1122
|
+
}
|
|
1123
|
+
for subparser in (p_scan, p_ls, p_info, p_used, p_orphans, p_add, p_note, p_path):
|
|
1124
|
+
name = subparser.prog.rsplit(" ", 1)[-1]
|
|
1125
|
+
subparser.set_defaults(handler=handlers[name])
|
|
1126
|
+
add_root_flags(subparser)
|
|
1127
|
+
|
|
1128
|
+
|
|
1129
|
+
def add_root_flags(parser: argparse.ArgumentParser) -> None:
|
|
1130
|
+
parser.add_argument("--data-root", type=Path, default=argparse.SUPPRESS,
|
|
1131
|
+
help="Catalog and download directory")
|
|
1132
|
+
parser.add_argument("--projects-root", type=Path, default=argparse.SUPPRESS,
|
|
1133
|
+
help="Directory to scan for project references")
|
|
1134
|
+
|
|
1135
|
+
|
|
1136
|
+
def main() -> None:
|
|
1137
|
+
parser = argparse.ArgumentParser(prog="catalog", description="Manage ~/data catalog.db")
|
|
1138
|
+
add_root_flags(parser)
|
|
1139
|
+
add_subcommands(parser.add_subparsers(dest="cmd", required=True))
|
|
1140
|
+
args = parser.parse_args()
|
|
1141
|
+
try:
|
|
1142
|
+
args.config = resolve_config(data_root=getattr(args, "data_root", None),
|
|
1143
|
+
projects_root=getattr(args, "projects_root", None))
|
|
1144
|
+
args.handler(args)
|
|
1145
|
+
except KeyboardInterrupt:
|
|
1146
|
+
sys.exit(130)
|
|
1147
|
+
except (OSError, ValueError, sqlite3.Error) as error:
|
|
1148
|
+
parser.exit(1, f"{parser.prog}: {error}\n")
|
|
1149
|
+
|
|
1150
|
+
|
|
1151
|
+
if __name__ == "__main__":
|
|
1152
|
+
main()
|