llmctl-cli 0.4.1__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.
llmctl/hf.py ADDED
@@ -0,0 +1,580 @@
1
+ """Hugging Face live search, capability profiling, and model addition."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import concurrent.futures
6
+ import re
7
+ import urllib.parse
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from llmctl.config import AppConfig
13
+ from llmctl.hardware import (
14
+ HardwareInfo,
15
+ detect_hardware,
16
+ recommended_cpu_ctx_size,
17
+ recommended_cpu_threads,
18
+ )
19
+ from llmctl.http_client import HttpError, request_json
20
+ from llmctl.presets import add_preset
21
+ from llmctl.service import select_backend
22
+ from llmctl.ui import Console
23
+
24
+ GIB = 1024**3
25
+
26
+ TRUSTED_ORGS = {
27
+ "unsloth",
28
+ "qwen",
29
+ "ggml-org",
30
+ "bartowski",
31
+ "lmstudio-community",
32
+ "google",
33
+ "mistralai",
34
+ "deepseek-ai",
35
+ }
36
+
37
+ NOISE_PREFIXES = (
38
+ "arxiv:",
39
+ "license:",
40
+ "region:",
41
+ "base_model:",
42
+ "dataset:",
43
+ "doi:",
44
+ "eval_results",
45
+ "autotrain",
46
+ "endpoints_",
47
+ )
48
+
49
+ NOISE_TAGS = {
50
+ "gguf",
51
+ "transformers",
52
+ "safetensors",
53
+ "pytorch",
54
+ "text-generation",
55
+ "text-generation-inference",
56
+ "conversational",
57
+ "custom_code",
58
+ "en",
59
+ "zh",
60
+ "multilingual",
61
+ "llama-cpp",
62
+ "imatrix",
63
+ "quantized",
64
+ }
65
+
66
+
67
+ @dataclass
68
+ class GgufCandidate:
69
+ """A compatible GGUF file in a Hugging Face repository."""
70
+
71
+ path: str
72
+ size_gb: float
73
+ fit_tag: str
74
+
75
+
76
+ def default_alias_for_repo(repo_spec: str) -> str:
77
+ """Derive a clean preset alias from a repo ID like 'org/Qwen2.5-Coder-7B-Instruct-GGUF:Q4'."""
78
+ base = repo_spec.split(":", 1)[0].split("/")[-1].lower()
79
+ alias = re.sub(r"(-gguf|-instruct|\.gguf)$", "", base)
80
+ return alias or base
81
+
82
+
83
+ def pick_best_mmproj(mmproj_files: list[str]) -> str | None:
84
+ """Choose the best default multimodal projector file (BF16/F16/Q8_0 preferred)."""
85
+ if not mmproj_files:
86
+ return None
87
+ for preferred in ("bf16", "f16", "q8_0", "f32"):
88
+ for path in mmproj_files:
89
+ if preferred in path.lower():
90
+ return path
91
+ return mmproj_files[0]
92
+
93
+
94
+ def mmproj_hf_url(repo_id: str, mmproj_file: str) -> str:
95
+ """Build the direct Hugging Face resolve URL for an mmproj GGUF file."""
96
+ clean_repo = repo_id.split(":", 1)[0].strip()
97
+ return f"https://huggingface.co/{clean_repo}/resolve/main/{mmproj_file}"
98
+
99
+
100
+ def get_repo_ggufs(
101
+ repo_id: str,
102
+ vram_safe_gb: float,
103
+ ram_max_gb: float,
104
+ *,
105
+ token: str | None = None,
106
+ ) -> tuple[list[GgufCandidate], list[str]]:
107
+ """Fetch compatible GGUF files and any mmproj filenames from a Hugging Face repo."""
108
+ try:
109
+ tree = request_json(
110
+ f"https://huggingface.co/api/models/{repo_id}/tree/main",
111
+ token=token,
112
+ timeout=15.0,
113
+ )
114
+ except HttpError:
115
+ return [], []
116
+
117
+ if not isinstance(tree, list):
118
+ return [], []
119
+
120
+ mmproj_files: list[str] = []
121
+ valid: list[GgufCandidate] = []
122
+ max_limit = ram_max_gb if ram_max_gb > 0 else float("inf")
123
+
124
+ for entry in tree:
125
+ if not isinstance(entry, dict):
126
+ continue
127
+ path = str(entry.get("path", ""))
128
+ if not path.endswith(".gguf"):
129
+ continue
130
+ if "mmproj" in path.lower():
131
+ mmproj_files.append(path)
132
+ continue
133
+ size_bytes = entry.get("size", 0)
134
+ if not isinstance(size_bytes, (int, float)) or size_bytes <= 0:
135
+ continue
136
+ size_gb = size_bytes / GIB
137
+ if size_gb <= max_limit:
138
+ if vram_safe_gb > 0 and size_gb <= vram_safe_gb:
139
+ tag = "100% GPU"
140
+ elif vram_safe_gb > 0:
141
+ tag = "GPU + RAM"
142
+ else:
143
+ tag = "CPU / RAM"
144
+ valid.append(GgufCandidate(path=path, size_gb=size_gb, fit_tag=tag))
145
+
146
+ valid.sort(key=lambda item: item.size_gb)
147
+ mmproj_files.sort()
148
+ return valid, mmproj_files
149
+
150
+
151
+ def extract_profile(model_meta: dict[str, Any], has_mmproj: bool) -> tuple[str, str]:
152
+ """Infer human-readable capabilities and cleaned tags from Hugging Face metadata."""
153
+ repo_id = str(model_meta.get("id", "")).lower()
154
+ pipeline = str(model_meta.get("pipeline_tag") or "").lower()
155
+ raw_tags = [str(t).lower() for t in model_meta.get("tags", [])]
156
+ blob = " ".join([*raw_tags, pipeline, repo_id])
157
+
158
+ caps: list[str] = []
159
+ if (
160
+ has_mmproj
161
+ or pipeline == "image-text-to-text"
162
+ or any(k in blob for k in ("vision", "multimodal", "-vl-", "vlm"))
163
+ ):
164
+ caps.append("Visión")
165
+ if any(k in blob for k in ("thinking", "reasoning", "deepseek-r1", "qwq")):
166
+ caps.append("Thinking")
167
+ if any(k in blob for k in ("tool", "function-calling", "function_calling", "agent")):
168
+ caps.append("Tools")
169
+ if any(k in blob for k in ("coder", "coding", "code-generation", "programming")):
170
+ caps.append("Código")
171
+ if "math" in raw_tags or "-math" in repo_id:
172
+ caps.append("Mates")
173
+ if "moe" in raw_tags or re.search(r"a\d+b", repo_id):
174
+ caps.append("MoE")
175
+
176
+ useful_tags = [
177
+ t
178
+ for t in raw_tags
179
+ if t not in NOISE_TAGS and not t.startswith(NOISE_PREFIXES) and len(t) <= 24
180
+ ][:6]
181
+
182
+ caps_str = " ".join(f"[{c}]" for c in caps) if caps else "[Chat / General]"
183
+ tags_str = ", ".join(useful_tags) if useful_tags else (pipeline or "sin etiquetas")
184
+ return caps_str, tags_str
185
+
186
+
187
+ def default_alias_for_local_file(model_file: Path) -> str:
188
+ """Derive a clean preset alias from a local GGUF filename."""
189
+ stem = model_file.stem.lower()
190
+ cleaned = re.sub(r"(-q\d+[\w.-]*|-f16|-bf16|-instruct|-gguf)$", "", stem)
191
+ return cleaned or stem
192
+
193
+
194
+ def add_local_model_preset(
195
+ config: AppConfig,
196
+ console: Console,
197
+ *,
198
+ model_file: Path,
199
+ name: str | None = None,
200
+ mmproj_file: Path | None = None,
201
+ auto_mmproj: bool = False,
202
+ cpu_moe: bool = False,
203
+ n_cpu_moe: int | None = None,
204
+ cpu_optimize: bool = False,
205
+ no_restart: bool = False,
206
+ ) -> int:
207
+ """Register a local .gguf file directly in models.ini without Hugging Face."""
208
+ resolved_model = model_file.expanduser().resolve()
209
+ if not resolved_model.is_file():
210
+ console.error(f"No se encontró el archivo GGUF local: {resolved_model}")
211
+ return 1
212
+
213
+ extra_options: dict[str, str] = {}
214
+ resolved_mmproj: Path | None = None
215
+ if mmproj_file is not None:
216
+ resolved_mmproj = mmproj_file.expanduser().resolve()
217
+ if not resolved_mmproj.is_file():
218
+ console.error(f"No se encontró el archivo mmproj local: {resolved_mmproj}")
219
+ return 1
220
+ elif auto_mmproj:
221
+ siblings = sorted(
222
+ p.name
223
+ for p in resolved_model.parent.iterdir()
224
+ if p.is_file() and p.suffix.lower() == ".gguf" and "mmproj" in p.name.lower()
225
+ )
226
+ best = pick_best_mmproj(siblings)
227
+ if best:
228
+ resolved_mmproj = resolved_model.parent / best
229
+
230
+ if resolved_mmproj is not None:
231
+ extra_options["mmproj"] = str(resolved_mmproj)
232
+
233
+ if cpu_optimize:
234
+ hw = detect_hardware(sys_platform=config.sys_platform)
235
+ extra_options["threads"] = str(recommended_cpu_threads(hw))
236
+ extra_options["ctx-size"] = str(recommended_cpu_ctx_size(hw))
237
+
238
+ alias = (name or default_alias_for_local_file(resolved_model)).strip()
239
+ try:
240
+ preset = add_preset(
241
+ config.models_ini,
242
+ alias,
243
+ model_path=str(resolved_model),
244
+ cpu_moe=cpu_moe,
245
+ n_cpu_moe=n_cpu_moe,
246
+ extra_options=extra_options or None,
247
+ )
248
+ except ValueError as exc:
249
+ console.error(str(exc))
250
+ return 1
251
+
252
+ restarted = False
253
+ restart_note = ""
254
+ if not no_restart:
255
+ backend = select_backend(config)
256
+ if backend.name == "remote":
257
+ restart_note = (
258
+ f"Backend remoto ({config.api_root}): recuerda copiar el GGUF y reiniciar "
259
+ "el router en el host remoto."
260
+ )
261
+ else:
262
+ res = backend.restart()
263
+ restarted = res.ok
264
+ restart_note = res.message
265
+
266
+ if console.json_mode:
267
+ console.emit_json(
268
+ {
269
+ "added": preset.to_dict(),
270
+ "local_file": str(resolved_model),
271
+ "models_ini": str(config.models_ini),
272
+ "restarted": restarted,
273
+ "note": restart_note,
274
+ }
275
+ )
276
+ return 0
277
+
278
+ console.ok(f"Preset local [{preset.name}] -> {resolved_model} añadido a {config.models_ini}.")
279
+ if restart_note:
280
+ if restarted:
281
+ console.ok(restart_note)
282
+ else:
283
+ console.warn(restart_note)
284
+ return 0
285
+
286
+
287
+ def add_model_preset(
288
+ config: AppConfig,
289
+ console: Console,
290
+ *,
291
+ repo: str,
292
+ name: str | None = None,
293
+ hf_file: str | None = None,
294
+ cpu_moe: bool = False,
295
+ n_cpu_moe: int | None = None,
296
+ mmproj_url: str | None = None,
297
+ auto_mmproj: bool = False,
298
+ cpu_optimize: bool = False,
299
+ no_restart: bool = False,
300
+ ) -> int:
301
+ """Add a model preset to models.ini and optionally restart the local router."""
302
+ alias = (name or default_alias_for_repo(repo)).strip()
303
+ extra_options: dict[str, str] = {}
304
+
305
+ resolved_mmproj = mmproj_url
306
+ if not resolved_mmproj and auto_mmproj:
307
+ repo_id = repo.split(":", 1)[0].strip()
308
+ _, mmproj_files = get_repo_ggufs(repo_id, 0.0, 0.0, token=config.hf_token)
309
+ best = pick_best_mmproj(mmproj_files)
310
+ if best:
311
+ resolved_mmproj = mmproj_hf_url(repo_id, best)
312
+
313
+ if resolved_mmproj:
314
+ extra_options["mmproj-url"] = resolved_mmproj
315
+
316
+ if cpu_optimize:
317
+ hw = detect_hardware(sys_platform=config.sys_platform)
318
+ extra_options["threads"] = str(recommended_cpu_threads(hw))
319
+ extra_options["ctx-size"] = str(recommended_cpu_ctx_size(hw))
320
+
321
+ try:
322
+ preset = add_preset(
323
+ config.models_ini,
324
+ alias,
325
+ repo,
326
+ hf_file=hf_file,
327
+ cpu_moe=cpu_moe,
328
+ n_cpu_moe=n_cpu_moe,
329
+ extra_options=extra_options or None,
330
+ )
331
+ except ValueError as exc:
332
+ console.error(str(exc))
333
+ return 1
334
+
335
+ restarted = False
336
+ restart_note = ""
337
+ if not no_restart:
338
+ backend = select_backend(config)
339
+ if backend.name == "remote":
340
+ restart_note = (
341
+ f"Backend remoto ({config.api_root}): reinicia el router en el host remoto "
342
+ "para cargar el nuevo preset."
343
+ )
344
+ else:
345
+ res = backend.restart()
346
+ restarted = res.ok
347
+ restart_note = res.message
348
+
349
+ if console.json_mode:
350
+ console.emit_json(
351
+ {
352
+ "added": preset.to_dict(),
353
+ "models_ini": str(config.models_ini),
354
+ "restarted": restarted,
355
+ "note": restart_note,
356
+ }
357
+ )
358
+ return 0
359
+
360
+ console.ok(f"Preset [{preset.name}] añadido a {config.models_ini}.")
361
+ if restart_note:
362
+ if restarted:
363
+ console.ok(restart_note)
364
+ else:
365
+ console.warn(restart_note)
366
+ console.info("Recarga la lista de modelos en tu cliente OpenAI-compatible para usarlo.")
367
+ return 0
368
+
369
+
370
+ def query_hf_live(
371
+ config: AppConfig,
372
+ console: Console,
373
+ hw: HardwareInfo,
374
+ *,
375
+ search: str | None = None,
376
+ sort: str = "trendingScore",
377
+ pipeline_tag: str | None = None,
378
+ only_trusted: bool = True,
379
+ no_restart: bool = False,
380
+ ) -> int:
381
+ """Query Hugging Face Hub interactively and add the selected GGUF preset."""
382
+ params: dict[str, str] = {
383
+ "filter": "gguf",
384
+ "sort": sort,
385
+ "direction": "-1",
386
+ "limit": "40",
387
+ }
388
+ if search:
389
+ params["search"] = search
390
+ if pipeline_tag:
391
+ params["pipeline_tag"] = pipeline_tag
392
+
393
+ url = "https://huggingface.co/api/models?" + urllib.parse.urlencode(params)
394
+ console.line("\nConsultando Hugging Face en vivo...")
395
+ try:
396
+ models = request_json(url, token=config.hf_token, timeout=15.0)
397
+ except HttpError as exc:
398
+ console.error(f"Error consultando Hugging Face: {exc}")
399
+ return 1
400
+
401
+ if not isinstance(models, list):
402
+ console.error("Respuesta inesperada de la API de Hugging Face.")
403
+ return 1
404
+
405
+ if only_trusted:
406
+ models = [
407
+ m
408
+ for m in models
409
+ if isinstance(m, dict) and str(m.get("id", "")).split("/")[0].lower() in TRUSTED_ORGS
410
+ ]
411
+
412
+ if not models:
413
+ console.warn("0 resultados en Hugging Face con los filtros aplicados.")
414
+ return 0
415
+
416
+ candidates = [m for m in models[:20] if isinstance(m, dict) and m.get("id")]
417
+ compatible: list[tuple[dict[str, Any], list[GgufCandidate], list[str]]] = []
418
+
419
+ with concurrent.futures.ThreadPoolExecutor(max_workers=6) as executor:
420
+ futures = {
421
+ executor.submit(
422
+ get_repo_ggufs,
423
+ str(m["id"]),
424
+ hw.vram_safe_gb,
425
+ hw.ram_usable_gb,
426
+ token=config.hf_token,
427
+ ): m
428
+ for m in candidates
429
+ }
430
+ for fut in concurrent.futures.as_completed(futures):
431
+ ggufs, mmproj_files = fut.result()
432
+ if ggufs:
433
+ compatible.append((futures[fut], ggufs, mmproj_files))
434
+
435
+ if not compatible:
436
+ limit = f"{hw.ram_usable_gb:.1f}"
437
+ console.warn(
438
+ f"Ninguno de los {len(candidates)} modelos devueltos tiene un GGUF <= {limit} GB."
439
+ )
440
+ return 0
441
+
442
+ order = {str(m["id"]): idx for idx, m in enumerate(candidates)}
443
+ compatible.sort(key=lambda item: order[str(item[0]["id"])])
444
+ compatible = compatible[:12]
445
+
446
+ is_cpu_only = hw.vram_total_gb <= 0
447
+ console.line(
448
+ f"\n--- {len(compatible)} modelos compatibles en vivo (<= {hw.ram_usable_gb:.1f} GB) ---"
449
+ )
450
+ for i, (meta, ggufs, mmproj_files) in enumerate(compatible, 1):
451
+ repo_id = str(meta["id"])
452
+ org = repo_id.split("/")[0].lower()
453
+ badge = "★" if org in TRUSTED_ORGS else " "
454
+ min_gb, max_gb = ggufs[0].size_gb, ggufs[-1].size_gb
455
+ caps_str, tags_str = extract_profile(meta, bool(mmproj_files))
456
+ if is_cpu_only and ("[MoE]" in caps_str or min_gb <= 6.0):
457
+ caps_str = f"{caps_str} [CPU-friendly]"
458
+ dl_count = meta.get("downloads", 0)
459
+ console.line(f" [{i:2d}] {badge} {repo_id} ({min_gb:.1f}-{max_gb:.1f} GB | ↓ {dl_count})")
460
+ console.line(f" Capacidades: {caps_str} | HF tags: {tags_str}")
461
+
462
+ try:
463
+ idx = int(console.prompt("\nElige un repositorio (número)")) - 1
464
+ meta, ggufs, mmproj_files = compatible[idx]
465
+ except (ValueError, IndexError, KeyboardInterrupt):
466
+ console.line("Cancelado.")
467
+ return 0
468
+
469
+ repo_id = str(meta["id"])
470
+ console.line(f"\n--- Archivos GGUF compatibles en {repo_id} ---")
471
+ for i, item in enumerate(ggufs, 1):
472
+ console.line(f" [{i:2d}] {item.path} — {item.size_gb:.1f} GB [{item.fit_tag}]")
473
+
474
+ try:
475
+ f_idx = int(console.prompt("\nElige el archivo a añadir (número)")) - 1
476
+ chosen = ggufs[f_idx]
477
+ except (ValueError, IndexError, KeyboardInterrupt):
478
+ console.line("Cancelado.")
479
+ return 0
480
+
481
+ suggested = default_alias_for_repo(repo_id)
482
+ alias = console.prompt("\nAlias/ID del modelo", default=suggested)
483
+ use_cpu_moe = (
484
+ (hw.vram_safe_gb > 0) and (chosen.size_gb > hw.vram_safe_gb) and (not hw.unified_memory)
485
+ )
486
+ best_mmproj = pick_best_mmproj(mmproj_files)
487
+ mmproj_url = mmproj_hf_url(repo_id, best_mmproj) if best_mmproj else None
488
+ if best_mmproj:
489
+ console.info(f"Proyector multimodal detectado: {best_mmproj} (se añadirá mmproj-url).")
490
+ if is_cpu_only:
491
+ t_rec = recommended_cpu_threads(hw)
492
+ c_rec = recommended_cpu_ctx_size(hw)
493
+ console.info(f"Modo CPU-only: se configurará threads={t_rec} y ctx-size={c_rec}.")
494
+
495
+ return add_model_preset(
496
+ config,
497
+ console,
498
+ repo=repo_id,
499
+ name=alias,
500
+ hf_file=chosen.path,
501
+ cpu_moe=use_cpu_moe,
502
+ mmproj_url=mmproj_url,
503
+ cpu_optimize=is_cpu_only,
504
+ no_restart=no_restart,
505
+ )
506
+
507
+
508
+ def run_interactive_add(
509
+ config: AppConfig,
510
+ console: Console,
511
+ *,
512
+ no_restart: bool = False,
513
+ ) -> int:
514
+ """Interactive Hugging Face search wizard."""
515
+ hw = detect_hardware(sys_platform=config.sys_platform)
516
+ vram_label = "Memoria unificada" if hw.unified_memory else "VRAM"
517
+ console.line(
518
+ f"Hardware: {hw.vram_total_gb:.1f} GB {vram_label} (útil ~{hw.vram_safe_gb:.1f} GB) | "
519
+ f"{hw.ram_total_gb:.1f} GB RAM (útil ~{hw.ram_usable_gb:.1f} GB)"
520
+ )
521
+ console.line("\n=== Búsqueda en vivo en Hugging Face ===")
522
+ console.line(" [1] Trending ahora (sort=trendingScore)")
523
+ console.line(" [2] Más descargados (sort=downloads)")
524
+ console.line(" [3] Más recientes (sort=lastModified)")
525
+ console.line(" [4] Visión / Multimodal (pipeline_tag=image-text-to-text)")
526
+ console.line(" [5] Búsqueda libre (en vivo)")
527
+
528
+ opt = console.prompt("\nOpción")
529
+ if opt not in {"1", "2", "3", "4", "5"}:
530
+ console.line("Cancelado.")
531
+ return 0
532
+
533
+ only_trusted = console.confirm("¿Filtrar estrictamente por repos fiables ★?", default=True)
534
+
535
+ if opt == "1":
536
+ return query_hf_live(
537
+ config,
538
+ console,
539
+ hw,
540
+ sort="trendingScore",
541
+ only_trusted=only_trusted,
542
+ no_restart=no_restart,
543
+ )
544
+ if opt == "2":
545
+ return query_hf_live(
546
+ config, console, hw, sort="downloads", only_trusted=only_trusted, no_restart=no_restart
547
+ )
548
+ if opt == "3":
549
+ return query_hf_live(
550
+ config,
551
+ console,
552
+ hw,
553
+ sort="lastModified",
554
+ only_trusted=only_trusted,
555
+ no_restart=no_restart,
556
+ )
557
+ if opt == "4":
558
+ return query_hf_live(
559
+ config,
560
+ console,
561
+ hw,
562
+ sort="trendingScore",
563
+ pipeline_tag="image-text-to-text",
564
+ only_trusted=only_trusted,
565
+ no_restart=no_restart,
566
+ )
567
+
568
+ query = console.prompt("Término de búsqueda")
569
+ if not query:
570
+ console.line("Cancelado.")
571
+ return 0
572
+ return query_hf_live(
573
+ config,
574
+ console,
575
+ hw,
576
+ search=query,
577
+ sort="downloads",
578
+ only_trusted=only_trusted,
579
+ no_restart=no_restart,
580
+ )