295 lines
12 KiB
Python
295 lines
12 KiB
Python
"""Быстрый выбор локальной модели из верхней панели.
|
|
|
|
Показывает и GGUF-модели из библиотеки, и нативные .xnh-модели Xenith.
|
|
"""
|
|
|
|
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,
|
|
library_summary, 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} Б"
|
|
|
|
|
|
def _refresh_after_native_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):
|
|
super().__init__(app, anchor, width=460, height=400, **kwargs)
|
|
self._models = []
|
|
self._busy = False
|
|
self._closed = False
|
|
|
|
pad = 16
|
|
ctk.CTkLabel(self, text="Локальные модели", 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=140, 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_library).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 _scan(self, force=False):
|
|
if self._busy:
|
|
return
|
|
self._busy = True
|
|
self.summary.configure(text="Сканирование…")
|
|
|
|
def task():
|
|
try:
|
|
dirs = list((self.app.engine.config.get("models") or {}).get("dirs") or [])
|
|
data = scan_models(extra_dirs=dirs, use_cache=not force)
|
|
except Exception as e:
|
|
data = {"models": [], "error": str(e)}
|
|
native = []
|
|
try:
|
|
for item in self.app.engine.list_models("xenith"):
|
|
kind = str(getattr(item, "kind", "") or "").lower()
|
|
if kind != "xnh":
|
|
continue
|
|
native.append({
|
|
"name": getattr(item, "name", "") or os.path.basename(item.path),
|
|
"file": os.path.basename(item.path),
|
|
"path": item.path,
|
|
"size": getattr(item, "size", 0),
|
|
"kind": "xnh",
|
|
"group": "Xenith",
|
|
"engine_id": "xenith",
|
|
"native": True,
|
|
})
|
|
except Exception:
|
|
native = []
|
|
data["native"] = native
|
|
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
|
|
raw = [m for m in (data.get("models") or [])
|
|
if not is_auxiliary_gguf(m.get("file") or "")]
|
|
gguf = collapse_splits(raw)
|
|
native = list(data.get("native") or [])
|
|
seen = {os.path.abspath(str(m.get("path") or "")) for m in native}
|
|
merged = native + [m for m in gguf
|
|
if os.path.abspath(str(m.get("path") or "")) not in seen]
|
|
self._models = merged
|
|
summary = library_summary(self._models)
|
|
self.summary.configure(text=str(summary.get("summary") or ""),
|
|
text_color=c("text_faint"))
|
|
if data.get("error"):
|
|
self.summary.configure(text=f"Ошибка: {data['error']}", text_color=c("danger"))
|
|
self._render()
|
|
self._fit_height()
|
|
|
|
def _fit_height(self):
|
|
try:
|
|
count = len(self._models)
|
|
list_height = min(400, max(184, count * 72 + 36))
|
|
self.list_frame.configure(height=list_height)
|
|
self.resize(min(560, 246 + 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")
|
|
).lower()]
|
|
if not items:
|
|
ctk.CTkLabel(
|
|
self.list_frame,
|
|
text="Модели не найдены. Откройте библиотеку и добавьте GGUF или .xnh.",
|
|
font=ui_font(10), text_color=c("text_faint"), anchor="w",
|
|
justify="left", wraplength=390,
|
|
).pack(anchor="w", padx=10, pady=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 m in groups[group]:
|
|
self._row(m)
|
|
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 _row(self, model):
|
|
loaded = False
|
|
try:
|
|
state = self.app.app_state
|
|
loaded = bool(state and state.model_loaded and os.path.abspath(
|
|
str(state.current_model_path or "")) == os.path.abspath(str(model.get("path") or "")))
|
|
except Exception:
|
|
loaded = False
|
|
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")
|
|
meta.append(_fmt_size(model.get("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
|
|
native = bool(model.get("native")) or str(model.get("kind") or "").lower() == "xnh"
|
|
self.close()
|
|
if native:
|
|
path = str(model.get("path") or "")
|
|
try:
|
|
if not app.select_engine("xenith"):
|
|
app.statusbar.flash("Дождитесь завершения текущей операции")
|
|
return
|
|
app.statusbar.flash(f"Загрузка модели: {_display_name(model)}")
|
|
app.switch_view("chat")
|
|
app.engine.load_model(
|
|
path, engine_id="xenith",
|
|
on_done=lambda: app.post_ui(lambda: _refresh_after_native_load(app)),
|
|
)
|
|
except Exception as e:
|
|
try:
|
|
app.statusbar.flash(f"Не удалось загрузить модель: {e}"[:180])
|
|
except Exception:
|
|
pass
|
|
return
|
|
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
|
|
|
|
def open_library(self):
|
|
self.close()
|
|
try:
|
|
self.app.switch_view("models")
|
|
view = self.app.ensure_view("models")
|
|
view.mode_switch.set("Библиотека")
|
|
view._set_mode("Библиотека")
|
|
except Exception:
|
|
pass
|