444 lines
15 KiB
Python
444 lines
15 KiB
Python
"""Библиотека локальных GGUF-моделей: поиск каталогов, скан и кэш.
|
||
|
||
Модуль только читает локальные файлы (stdlib), без сетевых вызовов.
|
||
Метаданные каждого файла берутся из :mod:`XUI.core.gguf`, а результаты
|
||
кэшируются в ``~/.cache/xenith-studio/gguf-index.json`` по ключу
|
||
``путь + mtime + размер``.
|
||
"""
|
||
|
||
import datetime
|
||
import json
|
||
import os
|
||
import re
|
||
import threading
|
||
|
||
from . import gguf
|
||
|
||
CACHE_PATH = os.path.join(
|
||
os.path.expanduser("~"), ".cache", "xenith-studio", "gguf-index.json"
|
||
)
|
||
|
||
_MAX_CACHE_BYTES = 64 * 1024 * 1024
|
||
_CACHE_LOCK = threading.Lock()
|
||
|
||
# Ключи LM Studio, в которых может лежать путь к каталогу моделей.
|
||
_SETTINGS_PATH_KEYS = {
|
||
"downloadsfolder",
|
||
"downloadsfolders",
|
||
"modelsdirectory",
|
||
"modelsdirectories",
|
||
}
|
||
|
||
_SKIP_PARTS = (".part", ".partial", ".tmp", ".download", ".crdownload", ".aria2")
|
||
|
||
|
||
def _norm(path: str) -> str:
|
||
"""Раскрыть ~ и привести путь к абсолютному виду."""
|
||
return os.path.abspath(os.path.expanduser(str(path)))
|
||
|
||
|
||
def _dedupe(paths) -> list:
|
||
"""Убрать дубли путей, сохранив порядок появления."""
|
||
seen = set()
|
||
out = []
|
||
for path in paths:
|
||
if not path:
|
||
continue
|
||
try:
|
||
key = os.path.normcase(_norm(path))
|
||
except Exception:
|
||
continue
|
||
if key in seen:
|
||
continue
|
||
seen.add(key)
|
||
out.append(_norm(path))
|
||
return out
|
||
|
||
|
||
def _settings_path() -> str:
|
||
return os.path.join(os.path.expanduser("~"), ".lmstudio", "settings.json")
|
||
|
||
|
||
def _collect_paths_from_json(value, out: list, depth: int = 0):
|
||
"""Собрать пути из настроек LM Studio (в т.ч. вложенных)."""
|
||
if depth > 6:
|
||
return
|
||
if isinstance(value, dict):
|
||
for key, item in value.items():
|
||
if str(key).strip().lower() in _SETTINGS_PATH_KEYS:
|
||
if isinstance(item, str) and item.strip():
|
||
out.append(item)
|
||
elif isinstance(item, (list, tuple)):
|
||
for entry in item:
|
||
if isinstance(entry, str) and entry.strip():
|
||
out.append(entry)
|
||
_collect_paths_from_json(item, out, depth + 1)
|
||
elif isinstance(value, (list, tuple)):
|
||
for item in value:
|
||
_collect_paths_from_json(item, out, depth + 1)
|
||
|
||
|
||
def _lmstudio_dirs() -> list:
|
||
"""Пути моделей из настроек LM Studio (если файл читается)."""
|
||
out = []
|
||
path = _settings_path()
|
||
try:
|
||
with open(path, "r", encoding="utf-8") as fh:
|
||
data = json.load(fh)
|
||
_collect_paths_from_json(data, out)
|
||
except Exception:
|
||
pass
|
||
return out
|
||
|
||
|
||
def _repo_models_dir() -> str:
|
||
"""<repo>/models, где <repo> — корень проекта (на два уровня выше core)."""
|
||
here = os.path.dirname(os.path.abspath(__file__))
|
||
repo = os.path.dirname(os.path.dirname(here))
|
||
return os.path.join(repo, "models")
|
||
|
||
|
||
def discover_roots(extra_dirs=None) -> list:
|
||
"""Найти существующие каталоги, где могут лежать GGUF-модели.
|
||
|
||
Источники: настройки LM Studio, стандартные каталоги
|
||
(``~/.lmstudio/models``, ``~/Downloads/models``,
|
||
``~/.local/share/xenith-studio/models``, ``<repo>/models``)
|
||
и ``extra_dirs``. Возвращаются только существующие каталоги,
|
||
без дублей, в порядке приоритета.
|
||
"""
|
||
candidates = []
|
||
candidates.extend(_lmstudio_dirs())
|
||
home = os.path.expanduser("~")
|
||
candidates.extend(
|
||
[
|
||
os.path.join(home, ".lmstudio", "models"),
|
||
os.path.join(home, "Downloads", "models"),
|
||
os.path.join(home, ".local", "share", "xenith-studio", "models"),
|
||
_repo_models_dir(),
|
||
]
|
||
)
|
||
try:
|
||
from .paths import bundled_models_dirs
|
||
candidates.extend(bundled_models_dirs())
|
||
except Exception:
|
||
pass
|
||
if extra_dirs:
|
||
if isinstance(extra_dirs, (str, bytes, os.PathLike)):
|
||
extra_dirs = [extra_dirs]
|
||
candidates.extend(str(item) for item in extra_dirs if item)
|
||
|
||
roots = []
|
||
for path in _dedupe(candidates):
|
||
try:
|
||
if os.path.isdir(path):
|
||
roots.append(path)
|
||
except OSError:
|
||
continue
|
||
return roots
|
||
|
||
|
||
def _iter_gguf(root: str, max_depth: int):
|
||
"""Лениво перебрать *.gguf под root, не заходя в скрытые каталоги."""
|
||
stack = [(root, 0)]
|
||
while stack:
|
||
current, depth = stack.pop()
|
||
try:
|
||
entries = list(os.scandir(current))
|
||
except OSError:
|
||
continue
|
||
for entry in entries:
|
||
name = entry.name
|
||
try:
|
||
if entry.is_dir(follow_symlinks=False):
|
||
if name.startswith("."):
|
||
continue
|
||
if depth < max_depth:
|
||
stack.append((entry.path, depth + 1))
|
||
continue
|
||
if not entry.is_file(follow_symlinks=True):
|
||
continue
|
||
except OSError:
|
||
continue
|
||
if name.startswith("."):
|
||
continue
|
||
low = name.lower()
|
||
if not low.endswith(".gguf"):
|
||
continue
|
||
if any(part in low for part in _SKIP_PARTS) or name.endswith("~"):
|
||
continue
|
||
yield entry.path
|
||
|
||
|
||
def _load_cache() -> dict:
|
||
"""Прочитать кэш; повреждённый/отсутствующий файл — пустой кэш."""
|
||
try:
|
||
if os.path.getsize(CACHE_PATH) > _MAX_CACHE_BYTES:
|
||
return {}
|
||
with open(CACHE_PATH, "r", encoding="utf-8") as fh:
|
||
data = json.load(fh)
|
||
entries = data.get("entries") if isinstance(data, dict) else None
|
||
return entries if isinstance(entries, dict) else {}
|
||
except Exception:
|
||
return {}
|
||
|
||
|
||
def _save_cache(entries: dict):
|
||
"""Атомарно записать кэш; любые ошибки записи игнорируются."""
|
||
try:
|
||
directory = os.path.dirname(CACHE_PATH)
|
||
if directory:
|
||
os.makedirs(directory, exist_ok=True)
|
||
payload = {"version": 1, "entries": entries}
|
||
tmp = f"{CACHE_PATH}.{os.getpid()}.tmp"
|
||
with _CACHE_LOCK:
|
||
with open(tmp, "w", encoding="utf-8") as fh:
|
||
json.dump(payload, fh, ensure_ascii=False)
|
||
os.replace(tmp, CACHE_PATH)
|
||
except Exception:
|
||
try:
|
||
if "tmp" in locals() and os.path.exists(tmp):
|
||
os.remove(tmp)
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def _cache_hit(entry, mtime: float, size: int):
|
||
if not isinstance(entry, dict):
|
||
return None
|
||
meta = entry.get("meta")
|
||
if not isinstance(meta, dict):
|
||
return None
|
||
try:
|
||
cached_mtime = float(entry.get("mtime", -1))
|
||
cached_size = int(entry.get("size", -1))
|
||
except (TypeError, ValueError):
|
||
return None
|
||
if cached_size != int(size):
|
||
return None
|
||
if abs(cached_mtime - float(mtime)) > 1e-6:
|
||
return None
|
||
return dict(meta)
|
||
|
||
|
||
def _file_meta(path: str, cache: dict | None, fresh: dict | None) -> dict:
|
||
"""Метаданные файла с учётом кэша path+mtime+size."""
|
||
try:
|
||
stat = os.stat(path)
|
||
mtime = float(stat.st_mtime)
|
||
size = int(stat.st_size)
|
||
except OSError:
|
||
meta = gguf.read_gguf_metadata(path)
|
||
if fresh is not None:
|
||
fresh[path] = {"mtime": 0.0, "size": 0, "meta": meta}
|
||
return meta
|
||
|
||
if cache is not None:
|
||
meta = _cache_hit(cache.get(path), mtime, size)
|
||
if meta is not None:
|
||
meta["path"] = path
|
||
meta["file"] = os.path.basename(path)
|
||
meta["size"] = size
|
||
meta["mtime"] = mtime
|
||
if fresh is not None:
|
||
fresh[path] = {"mtime": mtime, "size": size, "meta": meta}
|
||
return meta
|
||
|
||
meta = gguf.read_gguf_metadata(path)
|
||
if fresh is not None:
|
||
fresh[path] = {"mtime": mtime, "size": size, "meta": meta}
|
||
return meta
|
||
|
||
|
||
def _group_for(path: str, root: str) -> tuple:
|
||
"""Вернуть (group, relative) для файла относительно корня."""
|
||
try:
|
||
relative = os.path.relpath(path, root)
|
||
except ValueError:
|
||
relative = os.path.basename(path)
|
||
if relative == os.pardir or relative.startswith(os.pardir + os.sep):
|
||
relative = os.path.basename(path)
|
||
parts = [part for part in relative.split(os.sep) if part not in ("", os.curdir)]
|
||
group = parts[0] if len(parts) > 1 else ""
|
||
return group, os.sep.join(parts) if parts else os.path.basename(path)
|
||
|
||
|
||
def _walk_roots(roots: list, max_depth: int):
|
||
"""Обойти корни от самых глубоких, чтобы publisher был точнее.
|
||
|
||
``~/Downloads`` и ``~/Downloads/models`` могут пересекаться: для файла
|
||
из ``~/Downloads/models/llama/...`` группой должен быть ``llama``,
|
||
а не ``models``.
|
||
"""
|
||
ordered = sorted(
|
||
roots,
|
||
key=lambda p: (len(os.path.normpath(p).split(os.sep)), len(p)),
|
||
reverse=True,
|
||
)
|
||
seen = set()
|
||
for root in ordered:
|
||
for path in _iter_gguf(root, max_depth):
|
||
key = os.path.normcase(_norm(path))
|
||
if key in seen:
|
||
continue
|
||
seen.add(key)
|
||
yield path, root
|
||
|
||
|
||
def scan_models(
|
||
roots=None,
|
||
extra_dirs=None,
|
||
max_depth: int = 6,
|
||
use_cache: bool = True,
|
||
) -> dict:
|
||
"""Просканировать каталоги и вернуть найденные GGUF-модели.
|
||
|
||
Результат: ``{"models": [...], "roots": [...], "total_size": int,
|
||
"count": int, "scanned_at": iso}``. Каждая модель — словарь из
|
||
:func:`XUI.core.gguf.read_gguf_metadata` плюс ``group``/``publisher``,
|
||
``relative`` и ``root``. Сеть не используется.
|
||
"""
|
||
if roots is None:
|
||
root_list = discover_roots(extra_dirs)
|
||
else:
|
||
if isinstance(roots, (str, bytes, os.PathLike)):
|
||
roots = [roots]
|
||
candidates = [str(item) for item in roots if item]
|
||
if extra_dirs:
|
||
if isinstance(extra_dirs, (str, bytes, os.PathLike)):
|
||
extra_dirs = [extra_dirs]
|
||
candidates.extend(str(item) for item in extra_dirs if item)
|
||
root_list = []
|
||
for path in _dedupe(candidates):
|
||
try:
|
||
if os.path.isdir(path):
|
||
root_list.append(path)
|
||
except OSError:
|
||
continue
|
||
|
||
try:
|
||
depth = max(0, int(max_depth))
|
||
except (TypeError, ValueError):
|
||
depth = 6
|
||
|
||
cache = _load_cache() if use_cache else None
|
||
fresh = {} if use_cache else None
|
||
models = []
|
||
try:
|
||
for path, root in _walk_roots(root_list, depth):
|
||
meta = _file_meta(path, cache, fresh)
|
||
group, relative = _group_for(path, root)
|
||
meta["group"] = group
|
||
meta["publisher"] = group
|
||
meta["relative"] = relative
|
||
meta["root"] = root
|
||
models.append(meta)
|
||
finally:
|
||
if use_cache and fresh is not None:
|
||
_save_cache(fresh)
|
||
|
||
models.sort(
|
||
key=lambda item: (
|
||
str(item.get("group") or "").casefold(),
|
||
str(item.get("name") or "").casefold(),
|
||
str(item.get("file") or "").casefold(),
|
||
)
|
||
)
|
||
total_size = sum(int(item.get("size") or 0) for item in models)
|
||
return {
|
||
"models": models,
|
||
"roots": root_list,
|
||
"total_size": total_size,
|
||
"count": len(models),
|
||
"scanned_at": datetime.datetime.now().astimezone().isoformat(timespec="seconds"),
|
||
}
|
||
|
||
|
||
def _format_size(size: int) -> str:
|
||
"""Размер в удобных единицах: 900 Б, 4.2 ГБ."""
|
||
try:
|
||
value = int(size)
|
||
except (TypeError, ValueError):
|
||
return "0 Б"
|
||
if value <= 0:
|
||
return "0 Б"
|
||
for suffix, divisor in (("ТБ", 1024 ** 4), ("ГБ", 1024 ** 3),
|
||
("МБ", 1024 ** 2), ("КБ", 1024)):
|
||
if value >= divisor:
|
||
text = f"{value / divisor:.1f}".rstrip("0").rstrip(".")
|
||
return f"{text} {suffix}"
|
||
return f"{value} Б"
|
||
|
||
|
||
def _plural_models(count: int) -> str:
|
||
"""Русское склонение слова «модель»."""
|
||
tail = abs(int(count)) % 100
|
||
if 11 <= tail <= 19:
|
||
return "моделей"
|
||
last = tail % 10
|
||
if last == 1:
|
||
return "модель"
|
||
if 2 <= last <= 4:
|
||
return "модели"
|
||
return "моделей"
|
||
|
||
|
||
def library_summary(models) -> dict:
|
||
"""Сводка по списку моделей: количество, размер и готовая строка."""
|
||
items = [item for item in (models or []) if isinstance(item, dict)]
|
||
total = sum(int(item.get("size") or 0) for item in items)
|
||
count = len(items)
|
||
size_label = _format_size(total)
|
||
return {
|
||
"count": count,
|
||
"size": total,
|
||
"size_label": size_label,
|
||
"summary": f"{count} {_plural_models(count)} · {size_label}",
|
||
}
|
||
|
||
|
||
_SPLIT_RE = re.compile(r"-(\d{5})-of-(\d{5})\.gguf$", re.IGNORECASE)
|
||
|
||
|
||
def is_auxiliary_gguf(filename: str) -> bool:
|
||
"""Служебные файлы (mmproj, imatrix), которые не являются моделью."""
|
||
|
||
name = os.path.basename(str(filename or "")).lower()
|
||
return name.startswith("mmproj") or "imatrix" in name
|
||
|
||
|
||
def collapse_splits(models) -> list:
|
||
"""Склеивает части одного GGUF в одну запись библиотеки.
|
||
|
||
llama.cpp умеет загружать составную модель по первому шарду, поэтому
|
||
в списке достаточно одной строки с суммарным размером.
|
||
"""
|
||
|
||
groups: dict = {}
|
||
out: list = []
|
||
for model in models or []:
|
||
name = str(model.get("file") or "")
|
||
match = _SPLIT_RE.search(name)
|
||
if not match:
|
||
out.append(dict(model))
|
||
continue
|
||
total = int(match.group(2))
|
||
base = name[:match.start()]
|
||
key = (os.path.dirname(str(model.get("path") or "")), base, total)
|
||
entry = groups.get(key)
|
||
if entry is None:
|
||
entry = dict(model)
|
||
entry["split_index"] = int(match.group(1))
|
||
entry["split_total"] = total
|
||
entry["shard_paths"] = [str(model.get("path") or "")]
|
||
entry["split"] = f"{match.group(1)}/{match.group(2)}"
|
||
groups[key] = entry
|
||
out.append(entry)
|
||
else:
|
||
try:
|
||
entry["size"] = int(entry.get("size") or 0) + int(model.get("size") or 0)
|
||
except Exception:
|
||
pass
|
||
entry.setdefault("shard_paths", []).append(str(model.get("path") or ""))
|
||
return out
|