studiolink 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- studiolink/__init__.py +5 -0
- studiolink/__main__.py +6 -0
- studiolink/cli.py +337 -0
- studiolink/config.py +55 -0
- studiolink/lmstudio_adapter.py +109 -0
- studiolink/models.py +161 -0
- studiolink/ollama_adapter.py +160 -0
- studiolink/ports.py +19 -0
- studiolink/service.py +246 -0
- studiolink/state.py +68 -0
- studiolink/syncer.py +188 -0
- studiolink-0.1.0.dist-info/METADATA +272 -0
- studiolink-0.1.0.dist-info/RECORD +17 -0
- studiolink-0.1.0.dist-info/WHEEL +5 -0
- studiolink-0.1.0.dist-info/entry_points.txt +2 -0
- studiolink-0.1.0.dist-info/licenses/LICENSE +21 -0
- studiolink-0.1.0.dist-info/top_level.txt +1 -0
studiolink/__init__.py
ADDED
studiolink/__main__.py
ADDED
studiolink/cli.py
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import logging
|
|
6
|
+
import sys
|
|
7
|
+
from datetime import timezone
|
|
8
|
+
|
|
9
|
+
from studiolink import __version__
|
|
10
|
+
from studiolink.lmstudio_adapter import LMStudioError
|
|
11
|
+
from studiolink.models import DoctorCheck, ImportMode, LinkMode, SyncResult
|
|
12
|
+
from studiolink.service import StatusEntry, StudioLinkService
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
16
|
+
parser = argparse.ArgumentParser(
|
|
17
|
+
prog="sdl",
|
|
18
|
+
usage="sdl [-v] [--version] [--help] <command> [<args>]",
|
|
19
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
20
|
+
add_help=False,
|
|
21
|
+
)
|
|
22
|
+
parser.add_argument(
|
|
23
|
+
"-v", action="store_true", help="Enable verbose output (debug logging)."
|
|
24
|
+
)
|
|
25
|
+
parser.add_argument(
|
|
26
|
+
"--version", action="store_true", help="Show version information."
|
|
27
|
+
)
|
|
28
|
+
parser.add_argument(
|
|
29
|
+
"--help", action="store_true", help="Show this help message and exit."
|
|
30
|
+
)
|
|
31
|
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
32
|
+
|
|
33
|
+
scan_parser = subparsers.add_parser(
|
|
34
|
+
"scan", help="Discover GGUF-backed Ollama models."
|
|
35
|
+
)
|
|
36
|
+
scan_parser.add_argument("--json", action="store_true", help="Emit JSON output.")
|
|
37
|
+
scan_parser.set_defaults(func=run_scan)
|
|
38
|
+
|
|
39
|
+
sync_parser = subparsers.add_parser(
|
|
40
|
+
"sync", help="Import one or more models into LM Studio."
|
|
41
|
+
)
|
|
42
|
+
sync_parser.add_argument("models", nargs="*", help="Model names from `sdl scan`.")
|
|
43
|
+
sync_parser.add_argument(
|
|
44
|
+
"--all", action="store_true", help="Sync every discovered model."
|
|
45
|
+
)
|
|
46
|
+
sync_parser.add_argument(
|
|
47
|
+
"--dry-run",
|
|
48
|
+
action="store_true",
|
|
49
|
+
help="Preview the import command without changing state.",
|
|
50
|
+
)
|
|
51
|
+
sync_parser.add_argument(
|
|
52
|
+
"--copy", action="store_true", help="Use LM Studio copy mode."
|
|
53
|
+
)
|
|
54
|
+
sync_parser.add_argument(
|
|
55
|
+
"--hard-link", action="store_true", help="Use LM Studio hard-link mode."
|
|
56
|
+
)
|
|
57
|
+
sync_parser.add_argument(
|
|
58
|
+
"--symbolic-link", action="store_true", help="Use LM Studio symbolic-link mode."
|
|
59
|
+
)
|
|
60
|
+
sync_parser.add_argument(
|
|
61
|
+
"--direct",
|
|
62
|
+
action="store_true",
|
|
63
|
+
help="Use Ollama blobs directly (skip import, no extra storage).",
|
|
64
|
+
)
|
|
65
|
+
sync_parser.add_argument("--json", action="store_true", help="Emit JSON output.")
|
|
66
|
+
sync_parser.set_defaults(func=run_sync)
|
|
67
|
+
|
|
68
|
+
status_parser = subparsers.add_parser(
|
|
69
|
+
"status", help="Show discovered models and sync state."
|
|
70
|
+
)
|
|
71
|
+
status_parser.add_argument("--json", action="store_true", help="Emit JSON output.")
|
|
72
|
+
status_parser.set_defaults(func=run_status)
|
|
73
|
+
|
|
74
|
+
doctor_parser = subparsers.add_parser(
|
|
75
|
+
"doctor", help="Check local StudioLink prerequisites."
|
|
76
|
+
)
|
|
77
|
+
doctor_parser.add_argument("--json", action="store_true", help="Emit JSON output.")
|
|
78
|
+
doctor_parser.set_defaults(func=run_doctor)
|
|
79
|
+
return parser
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _preparse_args(argv: list[str] | None) -> tuple[argparse.Namespace | None, bool]:
|
|
83
|
+
"""Pre-parse args to handle help/version before subparsers."""
|
|
84
|
+
parser = argparse.ArgumentParser(
|
|
85
|
+
prog="sdl",
|
|
86
|
+
usage="sdl [-v] [--version] [--help] <command> [<args>]",
|
|
87
|
+
add_help=False,
|
|
88
|
+
)
|
|
89
|
+
parser.add_argument("--version", action="store_true")
|
|
90
|
+
parser.add_argument("--help", action="store_true")
|
|
91
|
+
parser.add_argument("-v", action="store_true")
|
|
92
|
+
parser.add_argument("command", nargs="?", choices=["scan", "sync", "status", "doctor"])
|
|
93
|
+
|
|
94
|
+
import io
|
|
95
|
+
from contextlib import redirect_stderr
|
|
96
|
+
|
|
97
|
+
try:
|
|
98
|
+
with redirect_stderr(io.StringIO()):
|
|
99
|
+
args = parser.parse_args(argv)
|
|
100
|
+
except SystemExit:
|
|
101
|
+
return None, True
|
|
102
|
+
|
|
103
|
+
if args.help or args.version:
|
|
104
|
+
return args, False
|
|
105
|
+
|
|
106
|
+
return args, True
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def main(argv: list[str] | None = None) -> int:
|
|
110
|
+
preparsed, should_continue = _preparse_args(argv)
|
|
111
|
+
|
|
112
|
+
if preparsed is None and not should_continue:
|
|
113
|
+
build_parser().print_help()
|
|
114
|
+
return 0
|
|
115
|
+
|
|
116
|
+
if preparsed and (preparsed.help or preparsed.version):
|
|
117
|
+
parser = build_parser()
|
|
118
|
+
if preparsed.version:
|
|
119
|
+
print(f"StudioLink {__version__}")
|
|
120
|
+
return 0
|
|
121
|
+
if preparsed.help:
|
|
122
|
+
build_parser().print_help()
|
|
123
|
+
return 0
|
|
124
|
+
|
|
125
|
+
parser = build_parser()
|
|
126
|
+
|
|
127
|
+
import io
|
|
128
|
+
from contextlib import redirect_stderr
|
|
129
|
+
|
|
130
|
+
try:
|
|
131
|
+
with redirect_stderr(io.StringIO()):
|
|
132
|
+
args = parser.parse_args(argv)
|
|
133
|
+
except SystemExit:
|
|
134
|
+
print(
|
|
135
|
+
"Error: Invalid command. Use 'sdl --help' for available commands.",
|
|
136
|
+
file=sys.stderr,
|
|
137
|
+
)
|
|
138
|
+
return 1
|
|
139
|
+
|
|
140
|
+
verbose = (preparsed and getattr(preparsed, "v", False)) or (args and getattr(args, "verbose", False))
|
|
141
|
+
if verbose:
|
|
142
|
+
logging.basicConfig(level=logging.DEBUG, format="%(levelname)s: %(message)s")
|
|
143
|
+
logging.getLogger("studiolink").setLevel(logging.DEBUG)
|
|
144
|
+
else:
|
|
145
|
+
logging.basicConfig(level=logging.WARNING, format="%(levelname)s: %(message)s")
|
|
146
|
+
logging.getLogger("studiolink").setLevel(logging.WARNING)
|
|
147
|
+
service = StudioLinkService()
|
|
148
|
+
logging.debug("Configuration loaded:")
|
|
149
|
+
logging.debug(" Ollama manifests: %s", service.config.ollama_manifests_dir)
|
|
150
|
+
logging.debug(" Ollama blobs: %s", service.config.ollama_blobs_dir)
|
|
151
|
+
logging.debug(" LM Studio models: %s", service.config.lmstudio_models_dir)
|
|
152
|
+
logging.debug(" State file: %s", service.config.state_file)
|
|
153
|
+
try:
|
|
154
|
+
return int(args.func(args, service))
|
|
155
|
+
except ValueError as exc:
|
|
156
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
157
|
+
return 2
|
|
158
|
+
except LMStudioError as exc:
|
|
159
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
160
|
+
return 1
|
|
161
|
+
except Exception as exc:
|
|
162
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
163
|
+
return 1
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def run_scan(args: argparse.Namespace, service: StudioLinkService) -> int:
|
|
167
|
+
models = service.scan()
|
|
168
|
+
if args.json:
|
|
169
|
+
print(json.dumps([_model_to_json(model) for model in models], indent=2))
|
|
170
|
+
return 0
|
|
171
|
+
|
|
172
|
+
if not models:
|
|
173
|
+
print("No Ollama manifests were discovered.")
|
|
174
|
+
return 0
|
|
175
|
+
|
|
176
|
+
print(f"Discovered {len(models)} model(s):")
|
|
177
|
+
for model in models:
|
|
178
|
+
print(f"- {model.canonical_name} [{model.readiness.value}]")
|
|
179
|
+
print(f" blob: {model.blob_path or 'missing'}")
|
|
180
|
+
if model.issues:
|
|
181
|
+
print(f" issues: {'; '.join(model.issues)}")
|
|
182
|
+
return 0
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def run_sync(args: argparse.Namespace, service: StudioLinkService) -> int:
|
|
186
|
+
mode = _resolve_link_mode(args)
|
|
187
|
+
import_mode = ImportMode.DIRECT if args.direct else ImportMode.ALIAS
|
|
188
|
+
results = service.sync(
|
|
189
|
+
model_names=args.models,
|
|
190
|
+
sync_all=bool(args.all),
|
|
191
|
+
link_mode=mode,
|
|
192
|
+
import_mode=import_mode,
|
|
193
|
+
dry_run=bool(args.dry_run),
|
|
194
|
+
)
|
|
195
|
+
if args.json:
|
|
196
|
+
print(json.dumps([_sync_result_to_json(item) for item in results], indent=2))
|
|
197
|
+
return 0 if all(item.status != "error" for item in results) else 1
|
|
198
|
+
|
|
199
|
+
for item in results:
|
|
200
|
+
print(f"- {item.model.canonical_name}: {item.status}")
|
|
201
|
+
print(f" {item.message}")
|
|
202
|
+
return 0 if all(item.status != "error" for item in results) else 1
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def run_status(args: argparse.Namespace, service: StudioLinkService) -> int:
|
|
206
|
+
entries = service.status()
|
|
207
|
+
if args.json:
|
|
208
|
+
print(json.dumps([_status_entry_to_json(entry) for entry in entries], indent=2))
|
|
209
|
+
return 0
|
|
210
|
+
|
|
211
|
+
if not entries:
|
|
212
|
+
print("No Ollama manifests were discovered.")
|
|
213
|
+
return 0
|
|
214
|
+
|
|
215
|
+
synced = sum(1 for entry in entries if entry.synced)
|
|
216
|
+
print(f"Discovered {len(entries)} model(s); {synced} tracked as synced.")
|
|
217
|
+
for entry in entries:
|
|
218
|
+
print(f"- {entry.model.canonical_name}: {entry.display_status}")
|
|
219
|
+
if entry.sync_record is not None:
|
|
220
|
+
imported_at = entry.sync_record.imported_at.astimezone(
|
|
221
|
+
timezone.utc
|
|
222
|
+
).isoformat()
|
|
223
|
+
print(f" imported: {imported_at}")
|
|
224
|
+
if entry.model.issues:
|
|
225
|
+
print(f" issues: {'; '.join(entry.model.issues)}")
|
|
226
|
+
return 0
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def run_doctor(args: argparse.Namespace, service: StudioLinkService) -> int:
|
|
230
|
+
checks = service.doctor()
|
|
231
|
+
if args.json:
|
|
232
|
+
print(json.dumps([_doctor_check_to_json(check) for check in checks], indent=2))
|
|
233
|
+
return 0 if all(check.ok for check in checks) else 1
|
|
234
|
+
|
|
235
|
+
for check in checks:
|
|
236
|
+
prefix = "OK" if check.ok else "FAIL"
|
|
237
|
+
print(f"- {prefix}: {check.name} -> {check.details}")
|
|
238
|
+
return 0 if all(check.ok for check in checks) else 1
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def run_help(args: argparse.Namespace, service: StudioLinkService) -> int:
|
|
242
|
+
help_text = """StudioLink - Sync Ollama-downloaded GGUF models into LM Studio.
|
|
243
|
+
|
|
244
|
+
Available Commands:
|
|
245
|
+
|
|
246
|
+
scan Discover GGUF-backed Ollama models.
|
|
247
|
+
Usage: sdl scan [--json] [-v]
|
|
248
|
+
|
|
249
|
+
sync Import one or more models into LM Studio.
|
|
250
|
+
Usage: sdl sync <model> [<model>...] [--copy|--hard-link|--symbolic-link] [--dry-run] [-v]
|
|
251
|
+
sdl sync --all [--copy|--hard-link|--symbolic-link] [--dry-run] [-v]
|
|
252
|
+
|
|
253
|
+
status Show discovered models and sync state.
|
|
254
|
+
Usage: sdl status [--json] [-v]
|
|
255
|
+
|
|
256
|
+
doctor Check local StudioLink prerequisites.
|
|
257
|
+
Usage: sdl doctor [--json] [-v]
|
|
258
|
+
|
|
259
|
+
help Show this help message.
|
|
260
|
+
|
|
261
|
+
Global Options:
|
|
262
|
+
|
|
263
|
+
-v, --verbose Enable verbose output (debug logging).
|
|
264
|
+
--version Show version information.
|
|
265
|
+
--help Show help for a specific command.
|
|
266
|
+
|
|
267
|
+
Examples:
|
|
268
|
+
|
|
269
|
+
sdl scan # List all available models
|
|
270
|
+
sdl -v scan # Scan with debug output
|
|
271
|
+
sdl sync <modelname> # Import a specific model
|
|
272
|
+
sdl sync --all # Import all discovered models
|
|
273
|
+
sdl status # Check sync status
|
|
274
|
+
sdl doctor # Verify prerequisites
|
|
275
|
+
|
|
276
|
+
For more help on a specific command:
|
|
277
|
+
sdl <command> --help
|
|
278
|
+
"""
|
|
279
|
+
print(help_text)
|
|
280
|
+
return 0
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _resolve_link_mode(args: argparse.Namespace) -> LinkMode | None:
|
|
284
|
+
selected = [
|
|
285
|
+
mode
|
|
286
|
+
for flag, mode in (
|
|
287
|
+
(args.copy, LinkMode.COPY),
|
|
288
|
+
(args.hard_link, LinkMode.HARD_LINK),
|
|
289
|
+
(args.symbolic_link, LinkMode.SYMBOLIC_LINK),
|
|
290
|
+
)
|
|
291
|
+
if flag
|
|
292
|
+
]
|
|
293
|
+
if len(selected) > 1:
|
|
294
|
+
raise ValueError("choose only one of --copy, --hard-link, or --symbolic-link")
|
|
295
|
+
return selected[0] if selected else None
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _model_to_json(model: object) -> dict[str, object]:
|
|
299
|
+
return {
|
|
300
|
+
"canonical_name": getattr(model, "canonical_name"),
|
|
301
|
+
"fully_qualified_name": getattr(model, "fully_qualified_name"),
|
|
302
|
+
"blob_path": str(getattr(model, "blob_path"))
|
|
303
|
+
if getattr(model, "blob_path")
|
|
304
|
+
else None,
|
|
305
|
+
"readiness": getattr(model, "readiness").value,
|
|
306
|
+
"gguf_valid": getattr(model, "gguf_valid"),
|
|
307
|
+
"issues": list(getattr(model, "issues")),
|
|
308
|
+
"user_repo": getattr(model, "user_repo"),
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _sync_result_to_json(result: SyncResult) -> dict[str, object]:
|
|
313
|
+
return {
|
|
314
|
+
"model": result.model.canonical_name,
|
|
315
|
+
"status": result.status,
|
|
316
|
+
"message": result.message,
|
|
317
|
+
"record": None if result.record is None else result.record.to_json(),
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _status_entry_to_json(entry: StatusEntry) -> dict[str, object]:
|
|
322
|
+
return {
|
|
323
|
+
"model": _model_to_json(entry.model),
|
|
324
|
+
"synced": entry.synced,
|
|
325
|
+
"status": entry.display_status,
|
|
326
|
+
"sync_record": None
|
|
327
|
+
if entry.sync_record is None
|
|
328
|
+
else entry.sync_record.to_json(),
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _doctor_check_to_json(check: DoctorCheck) -> dict[str, object]:
|
|
333
|
+
return {
|
|
334
|
+
"name": check.name,
|
|
335
|
+
"ok": check.ok,
|
|
336
|
+
"details": check.details,
|
|
337
|
+
}
|
studiolink/config.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from studiolink.models import LinkMode
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _expand_path(env_name: str, default: Path) -> Path:
|
|
11
|
+
raw = os.environ.get(env_name)
|
|
12
|
+
return Path(raw).expanduser() if raw else default.expanduser()
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(slots=True, frozen=True)
|
|
16
|
+
class StudioLinkConfig:
|
|
17
|
+
ollama_exe: Path
|
|
18
|
+
lms_exe: Path
|
|
19
|
+
ollama_models_dir: Path
|
|
20
|
+
ollama_manifests_dir: Path
|
|
21
|
+
ollama_blobs_dir: Path
|
|
22
|
+
lmstudio_models_dir: Path
|
|
23
|
+
state_dir: Path
|
|
24
|
+
state_file: Path
|
|
25
|
+
import_staging_dir: Path
|
|
26
|
+
default_link_mode: LinkMode = LinkMode.HARD_LINK
|
|
27
|
+
|
|
28
|
+
@classmethod
|
|
29
|
+
def from_env(cls) -> "StudioLinkConfig":
|
|
30
|
+
home = Path.home()
|
|
31
|
+
ollama_models_dir = _expand_path(
|
|
32
|
+
"STUDIOLINK_OLLAMA_MODELS_DIR",
|
|
33
|
+
home / ".ollama" / "models",
|
|
34
|
+
)
|
|
35
|
+
state_dir = _expand_path("STUDIOLINK_STATE_DIR", home / ".studiolink")
|
|
36
|
+
return cls(
|
|
37
|
+
ollama_exe=_expand_path(
|
|
38
|
+
"STUDIOLINK_OLLAMA_EXE",
|
|
39
|
+
home / "AppData" / "Local" / "Programs" / "Ollama" / "ollama.exe",
|
|
40
|
+
),
|
|
41
|
+
lms_exe=_expand_path(
|
|
42
|
+
"STUDIOLINK_LMS_EXE",
|
|
43
|
+
home / ".lmstudio" / "bin" / "lms.exe",
|
|
44
|
+
),
|
|
45
|
+
ollama_models_dir=ollama_models_dir,
|
|
46
|
+
ollama_manifests_dir=ollama_models_dir / "manifests",
|
|
47
|
+
ollama_blobs_dir=ollama_models_dir / "blobs",
|
|
48
|
+
lmstudio_models_dir=_expand_path(
|
|
49
|
+
"STUDIOLINK_LMSTUDIO_MODELS_DIR",
|
|
50
|
+
home / ".lmstudio" / "models",
|
|
51
|
+
),
|
|
52
|
+
state_dir=state_dir,
|
|
53
|
+
state_file=state_dir / "state.json",
|
|
54
|
+
import_staging_dir=state_dir / "imports",
|
|
55
|
+
)
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import subprocess
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from studiolink.config import StudioLinkConfig
|
|
7
|
+
from studiolink.models import ImportResult, LinkMode
|
|
8
|
+
|
|
9
|
+
DEFAULT_TIMEOUT = 60
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class LMStudioError(Exception):
|
|
13
|
+
"""Raised when LM Studio CLI command fails."""
|
|
14
|
+
|
|
15
|
+
def __init__(
|
|
16
|
+
self, message: str, command: list[str], return_code: int, stderr: str
|
|
17
|
+
) -> None:
|
|
18
|
+
super().__init__(message)
|
|
19
|
+
self.command = command
|
|
20
|
+
self.return_code = return_code
|
|
21
|
+
self.stderr = stderr
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class LMStudioAdapter:
|
|
25
|
+
def __init__(self, config: StudioLinkConfig) -> None:
|
|
26
|
+
self.config = config
|
|
27
|
+
|
|
28
|
+
def get_version(self) -> str | None:
|
|
29
|
+
try:
|
|
30
|
+
result = self._run([str(self.config.lms_exe), "--version"], check=True)
|
|
31
|
+
return result.stdout.strip() or None
|
|
32
|
+
except subprocess.CalledProcessError as exc:
|
|
33
|
+
raise LMStudioError(
|
|
34
|
+
f"Failed to get LM Studio version: {exc.stderr}",
|
|
35
|
+
exc.cmd,
|
|
36
|
+
exc.returncode,
|
|
37
|
+
exc.stderr,
|
|
38
|
+
) from exc
|
|
39
|
+
|
|
40
|
+
def get_import_capabilities(self) -> set[LinkMode]:
|
|
41
|
+
try:
|
|
42
|
+
result = self._run(
|
|
43
|
+
[str(self.config.lms_exe), "import", "--help"], check=True
|
|
44
|
+
)
|
|
45
|
+
except subprocess.CalledProcessError as exc:
|
|
46
|
+
raise LMStudioError(
|
|
47
|
+
f"Failed to get LM Studio import capabilities: {exc.stderr}",
|
|
48
|
+
exc.cmd,
|
|
49
|
+
exc.returncode,
|
|
50
|
+
exc.stderr,
|
|
51
|
+
) from exc
|
|
52
|
+
help_text = "\n".join(part for part in (result.stdout, result.stderr) if part)
|
|
53
|
+
capabilities: set[LinkMode] = set()
|
|
54
|
+
if "--hard-link" in help_text:
|
|
55
|
+
capabilities.add(LinkMode.HARD_LINK)
|
|
56
|
+
if "--copy" in help_text:
|
|
57
|
+
capabilities.add(LinkMode.COPY)
|
|
58
|
+
if "--symbolic-link" in help_text:
|
|
59
|
+
capabilities.add(LinkMode.SYMBOLIC_LINK)
|
|
60
|
+
return capabilities
|
|
61
|
+
|
|
62
|
+
def import_model(
|
|
63
|
+
self,
|
|
64
|
+
source_path: str,
|
|
65
|
+
*,
|
|
66
|
+
user_repo: str,
|
|
67
|
+
link_mode: LinkMode,
|
|
68
|
+
dry_run: bool = False,
|
|
69
|
+
) -> ImportResult:
|
|
70
|
+
command = [
|
|
71
|
+
str(self.config.lms_exe),
|
|
72
|
+
"import",
|
|
73
|
+
source_path,
|
|
74
|
+
"--yes",
|
|
75
|
+
"--user-repo",
|
|
76
|
+
user_repo,
|
|
77
|
+
link_mode.lms_flag,
|
|
78
|
+
]
|
|
79
|
+
if dry_run:
|
|
80
|
+
command.append("--dry-run")
|
|
81
|
+
|
|
82
|
+
try:
|
|
83
|
+
result = self._run(command, check=True)
|
|
84
|
+
except subprocess.CalledProcessError as exc:
|
|
85
|
+
raise LMStudioError(
|
|
86
|
+
f"LM Studio import failed for {source_path}: {exc.stderr}",
|
|
87
|
+
exc.cmd,
|
|
88
|
+
exc.returncode,
|
|
89
|
+
exc.stderr,
|
|
90
|
+
) from exc
|
|
91
|
+
return ImportResult(
|
|
92
|
+
command=tuple(command),
|
|
93
|
+
stdout=result.stdout,
|
|
94
|
+
stderr=result.stderr,
|
|
95
|
+
return_code=result.returncode,
|
|
96
|
+
dry_run=dry_run,
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
@staticmethod
|
|
100
|
+
def _run(
|
|
101
|
+
command: list[str], *, check: bool, timeout: int = DEFAULT_TIMEOUT
|
|
102
|
+
) -> subprocess.CompletedProcess[str]:
|
|
103
|
+
return subprocess.run(
|
|
104
|
+
command,
|
|
105
|
+
capture_output=True,
|
|
106
|
+
text=True,
|
|
107
|
+
check=check,
|
|
108
|
+
timeout=timeout,
|
|
109
|
+
)
|
studiolink/models.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
from enum import StrEnum
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class LinkMode(StrEnum):
|
|
10
|
+
HARD_LINK = "hard-link"
|
|
11
|
+
COPY = "copy"
|
|
12
|
+
SYMBOLIC_LINK = "symbolic-link"
|
|
13
|
+
|
|
14
|
+
@property
|
|
15
|
+
def lms_flag(self) -> str:
|
|
16
|
+
return {
|
|
17
|
+
LinkMode.HARD_LINK: "--hard-link",
|
|
18
|
+
LinkMode.COPY: "--copy",
|
|
19
|
+
LinkMode.SYMBOLIC_LINK: "--symbolic-link",
|
|
20
|
+
}[self]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ImportMode(StrEnum):
|
|
24
|
+
ALIAS = "alias" # Use import aliases (hard links) - default
|
|
25
|
+
DIRECT = "direct" # Use Ollama blobs directly (no import)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class ModelReadiness(StrEnum):
|
|
29
|
+
READY = "ready"
|
|
30
|
+
STALE = "stale"
|
|
31
|
+
INVALID = "invalid"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(slots=True, frozen=True)
|
|
35
|
+
class OllamaModel:
|
|
36
|
+
canonical_name: str
|
|
37
|
+
fully_qualified_name: str
|
|
38
|
+
registry: str
|
|
39
|
+
namespace: str
|
|
40
|
+
repository: str
|
|
41
|
+
tag: str
|
|
42
|
+
manifest_path: Path
|
|
43
|
+
model_digest: str | None
|
|
44
|
+
blob_path: Path | None
|
|
45
|
+
declared_size: int | None
|
|
46
|
+
blob_size: int | None
|
|
47
|
+
gguf_valid: bool
|
|
48
|
+
issues: tuple[str, ...] = ()
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def readiness(self) -> ModelReadiness:
|
|
52
|
+
if self.gguf_valid:
|
|
53
|
+
return ModelReadiness.READY
|
|
54
|
+
if any(
|
|
55
|
+
"blob is missing from the Ollama blob store" in issue
|
|
56
|
+
for issue in self.issues
|
|
57
|
+
):
|
|
58
|
+
return ModelReadiness.STALE
|
|
59
|
+
return ModelReadiness.INVALID
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def blob_present(self) -> bool:
|
|
63
|
+
return self.blob_path is not None and self.blob_path.exists()
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def short_name(self) -> str:
|
|
67
|
+
return f"{self.repository}:{self.tag}"
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def user_repo(self) -> str:
|
|
71
|
+
repo_parts = []
|
|
72
|
+
if self.registry != "registry.ollama.ai":
|
|
73
|
+
repo_parts.append(self.registry.replace(".", "-"))
|
|
74
|
+
if self.namespace != "library":
|
|
75
|
+
repo_parts.append(self.namespace)
|
|
76
|
+
repo_parts.append(self.repository.replace("/", "--"))
|
|
77
|
+
return f"ollama/{'-'.join(repo_parts)}"
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def import_filename(self) -> str:
|
|
81
|
+
raw = f"{self.canonical_name}-{(self.model_digest or 'unknown').replace(':', '-')[:5]}"
|
|
82
|
+
safe = "".join(
|
|
83
|
+
ch if ch.isalnum() or ch in ("-", "_", ".") else "-" for ch in raw
|
|
84
|
+
)
|
|
85
|
+
while "--" in safe:
|
|
86
|
+
safe = safe.replace("--", "-")
|
|
87
|
+
return f"{safe}.gguf"
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@dataclass(slots=True, frozen=True)
|
|
91
|
+
class SyncRecord:
|
|
92
|
+
canonical_name: str
|
|
93
|
+
digest: str
|
|
94
|
+
blob_path: Path
|
|
95
|
+
import_alias_path: Path
|
|
96
|
+
user_repo: str
|
|
97
|
+
link_mode: LinkMode
|
|
98
|
+
imported_at: datetime
|
|
99
|
+
import_command: tuple[str, ...] = field(default_factory=tuple)
|
|
100
|
+
|
|
101
|
+
def to_json(self) -> dict[str, object]:
|
|
102
|
+
return {
|
|
103
|
+
"canonical_name": self.canonical_name,
|
|
104
|
+
"digest": self.digest,
|
|
105
|
+
"blob_path": str(self.blob_path),
|
|
106
|
+
"import_alias_path": str(self.import_alias_path),
|
|
107
|
+
"user_repo": self.user_repo,
|
|
108
|
+
"link_mode": self.link_mode.value,
|
|
109
|
+
"imported_at": self.imported_at.isoformat(),
|
|
110
|
+
"import_command": list(self.import_command),
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
@classmethod
|
|
114
|
+
def from_json(cls, payload: dict[str, object]) -> "SyncRecord":
|
|
115
|
+
return cls(
|
|
116
|
+
canonical_name=str(payload["canonical_name"]),
|
|
117
|
+
digest=str(payload["digest"]),
|
|
118
|
+
blob_path=Path(str(payload["blob_path"])),
|
|
119
|
+
import_alias_path=Path(str(payload["import_alias_path"])),
|
|
120
|
+
user_repo=str(payload["user_repo"]),
|
|
121
|
+
link_mode=LinkMode(str(payload["link_mode"])),
|
|
122
|
+
imported_at=datetime.fromisoformat(str(payload["imported_at"])),
|
|
123
|
+
import_command=tuple(
|
|
124
|
+
str(item) for item in payload.get("import_command", [])
|
|
125
|
+
),
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def is_synced(model: OllamaModel, record: SyncRecord | None) -> bool:
|
|
130
|
+
"""Check if the sync record matches current model state."""
|
|
131
|
+
if record is None:
|
|
132
|
+
return False
|
|
133
|
+
if record.digest != model.model_digest:
|
|
134
|
+
return False
|
|
135
|
+
if record.link_mode is None:
|
|
136
|
+
return False
|
|
137
|
+
return True
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@dataclass(slots=True, frozen=True)
|
|
141
|
+
class ImportResult:
|
|
142
|
+
command: tuple[str, ...]
|
|
143
|
+
stdout: str
|
|
144
|
+
stderr: str
|
|
145
|
+
return_code: int
|
|
146
|
+
dry_run: bool = False
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
@dataclass(slots=True, frozen=True)
|
|
150
|
+
class SyncResult:
|
|
151
|
+
model: OllamaModel
|
|
152
|
+
status: str
|
|
153
|
+
message: str
|
|
154
|
+
record: SyncRecord | None = None
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
@dataclass(slots=True, frozen=True)
|
|
158
|
+
class DoctorCheck:
|
|
159
|
+
name: str
|
|
160
|
+
ok: bool
|
|
161
|
+
details: str
|