408 lines
17 KiB
Python
408 lines
17 KiB
Python
"""Быстрый выбор модели из верхней панели.
|
|
|
|
Список зависит от активного движка:
|
|
- Xenith — только нативные .xnh;
|
|
- llama.cpp / LM Studio backend — локальные GGUF;
|
|
- Ollama — модели, которые отдаёт запущенный Ollama;
|
|
- OpenAI-совместимый сервер — его /v1/models.
|
|
"""
|
|
|
|
import os
|
|
import threading
|
|
|
|
import customtkinter as ctk
|
|
|
|
from ..theme import c, mono_font, ui_font
|
|
from ..core.model_library import (collapse_splits, is_auxiliary_gguf,
|
|
scan_models)
|
|
from .controls import IconButton, soft_scrollbar
|
|
from .dropdown import InlineDropdown
|
|
|
|
|
|
def _fmt_size(size) -> str:
|
|
try:
|
|
size = int(size)
|
|
except Exception:
|
|
size = 0
|
|
for suffix, divisor in (("ГБ", 1024 ** 3), ("МБ", 1024 ** 2)):
|
|
if size >= divisor:
|
|
text = f"{size / divisor:.1f}".rstrip("0").rstrip(".")
|
|
return f"{text} {suffix}"
|
|
if size >= 1024:
|
|
return f"{size / 1024:.0f} КБ"
|
|
return f"{size} Б" if size else ""
|
|
|
|
|
|
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 _summary(models) -> str:
|
|
items = [m for m in (models or []) if isinstance(m, dict)]
|
|
count = len(items)
|
|
size = sum(int(m.get("size") or 0) for m in items)
|
|
text = f"{count} {_plural_models(count)}"
|
|
if size:
|
|
text += f" · {_fmt_size(size)}"
|
|
return text
|
|
|
|
|
|
def _refresh_after_load(app):
|
|
try:
|
|
app._update_status_bar()
|
|
except Exception:
|
|
pass
|
|
try:
|
|
view = app.views.get("chat")
|
|
if view is not None:
|
|
view.render_history()
|
|
view.update_context_indicator()
|
|
except Exception:
|
|
pass
|
|
try:
|
|
err = str(getattr(app.engine, "last_error", "") or "")
|
|
if err:
|
|
app.statusbar.flash(f"Не удалось загрузить модель: {err}"[:180])
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def _display_name(model):
|
|
name = str(model.get("name") or "").strip()
|
|
if name and "/" not in name and "\\" not in name:
|
|
return name
|
|
stem = os.path.splitext(str(model.get("file") or ""))[0]
|
|
return stem.replace("_", " ").replace("-", " ") or "Модель"
|
|
|
|
|
|
class ModelPicker(InlineDropdown):
|
|
MAX_ROWS = 120
|
|
|
|
def __init__(self, app, anchor, **kwargs):
|
|
self._models = []
|
|
self._error = ""
|
|
self._busy = False
|
|
self._closed = False
|
|
super().__init__(app, anchor, width=460, height=400, **kwargs)
|
|
self._engine_id, self._engine_name, self._source = self._resolve_engine()
|
|
|
|
pad = 16
|
|
title = f"Модели · {self._engine_name}" if self._engine_name else "Модели движка"
|
|
if len(title) > 34:
|
|
title = "Модели движка"
|
|
ctk.CTkLabel(self, text=title, font=ui_font(16),
|
|
height=22, text_color=c("text")).pack(
|
|
anchor="w", padx=pad, pady=(16, 2))
|
|
self.summary = ctk.CTkLabel(self, text="Сканирование…", font=ui_font(11),
|
|
height=18, text_color=c("text_faint"), anchor="w")
|
|
self.summary.pack(anchor="w", padx=pad, pady=(0, 8))
|
|
|
|
search_row = ctk.CTkFrame(self, fg_color="transparent")
|
|
search_row.pack(fill="x", padx=pad, pady=(0, 8))
|
|
ctk.CTkLabel(search_row, text="Поиск", font=ui_font(11), height=16,
|
|
text_color=c("text_faint")).pack(side="left", padx=(0, 8))
|
|
self.search = ctk.CTkEntry(search_row, height=32, font=ui_font(11),
|
|
placeholder_text="Имя модели")
|
|
self.search.pack(side="left", fill="x", expand=True)
|
|
self.search.bind("<KeyRelease>", lambda _e: self._render())
|
|
|
|
def focus_search():
|
|
if not self._closed:
|
|
try:
|
|
self.search.focus_set()
|
|
except Exception:
|
|
pass
|
|
|
|
self.after(60, focus_search)
|
|
|
|
actions = ctk.CTkFrame(self, fg_color="transparent")
|
|
actions.pack(side="bottom", fill="x", padx=pad, pady=(0, 12))
|
|
ctk.CTkButton(actions, text="Все модели", width=124, height=30,
|
|
corner_radius=8, fg_color=c("control"),
|
|
hover_color=c("card_hover"), text_color=c("text"),
|
|
font=ui_font(11), command=self.open_models).pack(side="left")
|
|
ctk.CTkButton(actions, text="Обновить", width=92, height=30,
|
|
corner_radius=8, fg_color="transparent",
|
|
hover_color=c("card_hover"), text_color=c("text_dim"),
|
|
font=ui_font(10),
|
|
command=lambda: self._scan(force=True)).pack(side="right")
|
|
|
|
self.list_frame = ctk.CTkScrollableFrame(self, fg_color=c("bg"),
|
|
corner_radius=10, border_width=1,
|
|
border_color=c("border"))
|
|
self.list_frame.pack(fill="both", expand=True, padx=pad, pady=(0, 8))
|
|
soft_scrollbar(self.list_frame, "bg")
|
|
|
|
self._scan()
|
|
|
|
# ---------- активный движок ----------
|
|
def _resolve_engine(self):
|
|
try:
|
|
engines = self.app.engine.engines()
|
|
except Exception:
|
|
engines = []
|
|
item = next((e for e in engines if e.get("active")), None)
|
|
if item is None:
|
|
return "", "", ""
|
|
eid = str(item.get("id") or "")
|
|
name = str(item.get("name") or eid)
|
|
typ = str(item.get("type") or "")
|
|
try:
|
|
conf = dict((self.app.engine.config.get("engines") or {}).get(eid) or {})
|
|
except Exception:
|
|
conf = {}
|
|
if typ == "xenith":
|
|
source = "xenith"
|
|
elif typ == "ollama":
|
|
source = "ollama"
|
|
elif conf.get("installer_id") == "llamacpp" or conf.get("backend_path"):
|
|
source = "gguf"
|
|
else:
|
|
source = "openai"
|
|
return eid, name, source
|
|
|
|
def _empty_text(self):
|
|
if self._source == "xenith":
|
|
return "Нет моделей Xenith. Создайте модель в режиме разработчика или добавьте .xnh."
|
|
if self._source == "gguf":
|
|
return "Нет GGUF-моделей. Откройте «Все модели» → «Библиотека» и добавьте папку."
|
|
if self._source == "ollama":
|
|
return "Ollama не вернула модели. Проверьте, что сервер запущен и модели загружены."
|
|
return "Сервер не вернул модели. Проверьте адрес и состояние движка."
|
|
|
|
# ---------- скан ----------
|
|
def _scan(self, force=False):
|
|
if self._busy:
|
|
return
|
|
self._busy = True
|
|
self._error = ""
|
|
self.summary.configure(text="Сканирование…", text_color=c("text_faint"))
|
|
source = self._source
|
|
eid = self._engine_id
|
|
name = self._engine_name
|
|
|
|
def task():
|
|
data = {"models": [], "error": ""}
|
|
try:
|
|
if source == "gguf":
|
|
dirs = list((self.app.engine.config.get("models") or {}).get("dirs") or [])
|
|
scanned = scan_models(extra_dirs=dirs, use_cache=not force)
|
|
raw = [m for m in (scanned.get("models") or [])
|
|
if not is_auxiliary_gguf(m.get("file") or "")]
|
|
data["models"] = collapse_splits(raw)
|
|
else:
|
|
models = []
|
|
for item in self.app.engine.list_models(eid):
|
|
kind = str(getattr(item, "kind", "") or "").lower()
|
|
if source == "xenith" and kind != "xnh":
|
|
continue
|
|
path = str(getattr(item, "path", "") or "")
|
|
model_id = str(getattr(item, "id", "") or "")
|
|
models.append({
|
|
"name": getattr(item, "name", "") or os.path.basename(path) or model_id,
|
|
"file": os.path.basename(path) if path else model_id,
|
|
"path": path,
|
|
"model_id": model_id,
|
|
"size": getattr(item, "size", 0),
|
|
"kind": kind,
|
|
"group": ("Xenith" if source == "xenith" else name),
|
|
"engine_id": eid,
|
|
"source": source,
|
|
"native": source == "xenith",
|
|
"remote": source in ("ollama", "openai"),
|
|
})
|
|
data["models"] = models
|
|
except Exception as e:
|
|
data["error"] = str(e)
|
|
self.app.post_ui(lambda d=data: self._apply(d))
|
|
|
|
threading.Thread(target=task, daemon=True).start()
|
|
|
|
def _apply(self, data):
|
|
if self._closed:
|
|
return
|
|
self._busy = False
|
|
self._models = list(data.get("models") or [])
|
|
self._error = str(data.get("error") or "")
|
|
if self._error:
|
|
self.summary.configure(text="Движок недоступен", text_color=c("danger"))
|
|
else:
|
|
self.summary.configure(text=_summary(self._models), text_color=c("text_faint"))
|
|
self._render()
|
|
self._fit_height()
|
|
|
|
def _fit_height(self):
|
|
try:
|
|
count = len(self._models)
|
|
if self._error or count == 0:
|
|
list_height = 184
|
|
else:
|
|
list_height = min(360, max(140, count * 54 + 30))
|
|
self.list_frame.configure(height=list_height)
|
|
self.resize(min(560, 190 + list_height))
|
|
except Exception:
|
|
pass
|
|
|
|
# ---------- рендер ----------
|
|
def _render(self):
|
|
for w in self.list_frame.winfo_children():
|
|
w.destroy()
|
|
query = self.search.get().strip().lower()
|
|
items = self._models
|
|
if query:
|
|
items = [m for m in items if query in " ".join(
|
|
str(m.get(k) or "") for k in
|
|
("name", "file", "group", "quantization", "architecture",
|
|
"params_label", "path", "kind", "model_id")
|
|
).lower()]
|
|
if not items:
|
|
text = (f"Не удалось получить модели: {self._error}" if self._error
|
|
else self._empty_text())
|
|
ctk.CTkLabel(
|
|
self.list_frame, text=text, font=ui_font(10),
|
|
text_color=(c("danger") if self._error else c("text_faint")),
|
|
anchor="w", justify="left", wraplength=390,
|
|
).pack(anchor="w", padx=10, pady=10)
|
|
if self._error:
|
|
ctk.CTkButton(
|
|
self.list_frame, text="Настроить движки", width=146,
|
|
height=28, corner_radius=7, fg_color=c("control"),
|
|
hover_color=c("card_hover"), text_color=c("text"),
|
|
font=ui_font(10), command=self.open_engine_settings,
|
|
).pack(anchor="w", padx=10, pady=(0, 10))
|
|
return
|
|
shown = items[:self.MAX_ROWS]
|
|
groups = {}
|
|
for m in shown:
|
|
groups.setdefault(str(m.get("group") or "Модели"), []).append(m)
|
|
ordered = sorted(groups, key=lambda x: (0 if x == "Xenith" else 1, x.lower()))
|
|
for group in ordered:
|
|
ctk.CTkLabel(self.list_frame, text=group, font=ui_font(10),
|
|
height=16, text_color=c("text_faint"), anchor="w").pack(
|
|
anchor="w", padx=10, pady=(8, 2))
|
|
for model in groups[group]:
|
|
self._row(model)
|
|
if len(items) > len(shown):
|
|
ctk.CTkLabel(
|
|
self.list_frame,
|
|
text=f"Показаны первые {len(shown)} из {len(items)}. Уточните поиск.",
|
|
font=ui_font(10), height=16, text_color=c("text_faint"), anchor="w",
|
|
).pack(anchor="w", padx=10, pady=(6, 4))
|
|
|
|
def _is_loaded(self, model):
|
|
try:
|
|
state = self.app.app_state
|
|
if not (state and state.model_loaded):
|
|
return False
|
|
if model.get("remote"):
|
|
names = {str(model.get("model_id") or ""),
|
|
str(model.get("name") or "")}
|
|
return (str(getattr(state, "current_engine_id", "")) ==
|
|
str(model.get("engine_id") or "") and
|
|
str(getattr(state, "current_model_name", "")) in names)
|
|
return (os.path.abspath(str(state.current_model_path or "")) ==
|
|
os.path.abspath(str(model.get("path") or "")))
|
|
except Exception:
|
|
return False
|
|
|
|
def _row(self, model):
|
|
loaded = self._is_loaded(model)
|
|
row = ctk.CTkFrame(self.list_frame, fg_color="transparent", corner_radius=8)
|
|
row.pack(fill="x", padx=4, pady=1)
|
|
body = ctk.CTkFrame(row, fg_color="transparent")
|
|
body.pack(side="left", fill="x", expand=True, padx=12, pady=8)
|
|
title = _display_name(model)
|
|
if loaded:
|
|
title += " · загружена"
|
|
ctk.CTkLabel(body, text=title, font=ui_font(12), height=18,
|
|
text_color=c("text"), anchor="w",
|
|
wraplength=310).pack(anchor="w")
|
|
meta = [str(model.get(k)) for k in ("params_label", "quantization") if model.get(k)]
|
|
if model.get("context_length"):
|
|
meta.append(f"{int(model['context_length']) // 1024}K контекст")
|
|
if model.get("native"):
|
|
meta.append("XNH")
|
|
if model.get("source") == "ollama":
|
|
meta.append("Ollama")
|
|
elif model.get("source") == "openai":
|
|
meta.append("сервер")
|
|
size = _fmt_size(model.get("size"))
|
|
if size:
|
|
meta.append(size)
|
|
ctk.CTkLabel(body, text=" · ".join(meta), font=mono_font(10), height=16,
|
|
text_color=c("text_faint"), anchor="w").pack(anchor="w", pady=(1, 0))
|
|
play = IconButton(row, "play", lambda m=model: self.load(m),
|
|
size=28, icon_size=14, bg=c("bg"),
|
|
hover=c("card_hover"), icon_color=c("text_dim"))
|
|
play.pack(side="right", padx=8, pady=8)
|
|
for widget in (row, body):
|
|
widget.bind("<Button-1>", lambda _e, m=model: self.load(m))
|
|
try:
|
|
widget.configure(cursor="hand2")
|
|
except Exception:
|
|
pass
|
|
|
|
# ---------- загрузка ----------
|
|
def load(self, model):
|
|
app = self.app
|
|
source = model.get("source") or self._source
|
|
self.close()
|
|
if source == "gguf":
|
|
try:
|
|
lib = app.ensure_view("models").library
|
|
lib.select_model(model)
|
|
lib.load_model(model, open_chat=True)
|
|
app.statusbar.flash(f"Загрузка модели: {_display_name(model)}")
|
|
except Exception as e:
|
|
try:
|
|
app.statusbar.flash(f"Не удалось загрузить модель: {e}")
|
|
except Exception:
|
|
pass
|
|
return
|
|
|
|
eid = str(model.get("engine_id") or self._engine_id)
|
|
model_id = str(model.get("model_id") or model.get("name") or model.get("path") or "")
|
|
try:
|
|
if app.engine.active_id != eid:
|
|
if not app.select_engine(eid):
|
|
app.statusbar.flash("Дождитесь завершения текущей операции")
|
|
return
|
|
app.statusbar.flash(f"Загрузка модели: {_display_name(model)}")
|
|
app.switch_view("chat")
|
|
app.engine.load_model(
|
|
model_id, engine_id=eid,
|
|
on_done=lambda: app.post_ui(lambda: _refresh_after_load(app)),
|
|
)
|
|
except Exception as e:
|
|
try:
|
|
app.statusbar.flash(f"Не удалось загрузить модель: {e}"[:180])
|
|
except Exception:
|
|
pass
|
|
|
|
# ---------- навигация ----------
|
|
def open_models(self):
|
|
self.close()
|
|
try:
|
|
self.app.switch_view("models")
|
|
view = self.app.ensure_view("models")
|
|
lib = getattr(view, "library", None)
|
|
if lib is not None:
|
|
lib.on_show()
|
|
except Exception:
|
|
pass
|
|
|
|
def open_engine_settings(self):
|
|
self.close()
|
|
try:
|
|
self.app.open_settings("engines")
|
|
except Exception:
|
|
pass
|