Files
Xenith-Studio/XUI/views/models.py
T

301 lines
12 KiB
Python

import os
import threading
import customtkinter as ctk
from tkinter import filedialog
from .base import ViewBase
from ..theme import c, mono_font, ui_font
def _fmt_size(size: int) -> str:
try:
size = int(size)
except Exception:
size = 0
if size >= 1024 ** 3:
return f"{size / (1024 ** 3):.2f} ГБ"
if size >= 1024 ** 2:
return f"{size / (1024 ** 2):.1f} МБ"
if size >= 1024:
return f"{size / 1024:.0f} КБ"
return f"{size} Б"
class ModelsView(ViewBase):
def __init__(self, master, **kwargs):
super().__init__(master, **kwargs)
self.title_text = "Модели"
self.configure(fg_color="transparent")
# Пути, добавленные вручную (переживают смену темы).
if self.app_state is not None:
self.extra_model_paths = self.app_state.extra_model_paths
else:
self.extra_model_paths = []
self._loading = False
self._scanned = False
self._load_buttons = []
self.current_label = ctk.CTkLabel(
self, text="Модель —", anchor="w",
font=ctk.CTkFont(size=11), text_color=c("text_dim"),
)
self.current_label.pack(anchor="w", padx=24, pady=(18, 8))
self.status_label = ctk.CTkLabel(self, text="", anchor="w", font=ui_font(11),
text_color=c("text_faint"))
self.status_label.pack(anchor="w", padx=24, pady=(0, 8))
btns = ctk.CTkFrame(self, fg_color="transparent")
btns.pack(anchor="w", padx=24, pady=6)
self.btn_scan = ctk.CTkButton(btns, text="Сканировать", command=self.scan, height=34)
self.btn_scan.pack(side="left")
self.btn_add_file = ctk.CTkButton(btns, text="Добавить файл", command=self.add_file, height=34)
self.btn_add_file.pack(side="left", padx=8)
self.btn_add_folder = ctk.CTkButton(btns, text="Добавить папку", command=self.add_folder, height=34)
self.btn_add_folder.pack(side="left", padx=8)
self.list_frame = ctk.CTkScrollableFrame(self)
self.list_frame.pack(fill="both", expand=True, padx=24, pady=(10, 20))
self._update_current_label()
self._render_placeholder("Нажмите «Сканировать», чтобы увидеть модели движков")
# ---------- заголовок ----------
def _update_current_label(self):
if not self.app_state:
self.current_label.configure(text="Модель —")
return
if self.app_state.model_loaded:
name = self.app_state.current_model_name or "загружена"
engine = getattr(self.app_state, "current_engine_name", "") or ""
path = self.app_state.current_model_path
text = f"Модель — {name}"
if engine:
text += f" · {engine}"
if path:
text += f" ({path})"
self.current_label.configure(text=text)
else:
self.current_label.configure(text="Модель не загружена")
# ---------- сканирование ----------
def on_show(self):
self._update_current_label()
if not self._scanned and not self._loading:
self.scan()
def scan(self):
if self._loading or not self.engine:
return
self._set_loading(True, "Сканирование движков…")
def task():
groups = {}
errors = {}
try:
engines = self.engine.engines()
except Exception as e:
engines = []
errors[""] = str(e)
for item in engines:
eid = item.get("id")
if not item.get("enabled", True):
continue
try:
groups[eid] = self.engine.list_models(eid)
except Exception as e:
groups[eid] = []
errors[eid] = str(e)
self.ui(lambda: self._render_groups(groups, errors))
threading.Thread(target=task, daemon=True).start()
def _clear_list(self):
for w in self.list_frame.winfo_children():
w.destroy()
self._load_buttons = []
def _render_placeholder(self, text):
self._clear_list()
ctk.CTkLabel(
self.list_frame, text=text, anchor="w", justify="left",
font=ui_font(12), text_color=c("text_dim"),
).pack(anchor="w", pady=(4, 2))
def _render_groups(self, groups, errors):
self._clear_list()
self._scanned = True
self._set_loading(False)
if not groups:
self._render_placeholder("Нет доступных движков. Добавьте движок в настройках")
return
try:
engine_meta = {e["id"]: e for e in self.engine.engines()}
except Exception:
engine_meta = {}
current_name = self.app_state.current_model_name if self.app_state else ""
current_path = self.app_state.current_model_path if self.app_state else ""
current_engine = getattr(self.app_state, "current_engine_id", None) if self.app_state else None
active_id = getattr(self.engine, "active_id", "")
total = 0
for eid, models in groups.items():
meta = engine_meta.get(eid, {})
title = meta.get("name") or eid
if eid == active_id:
title += " · активный"
header = ctk.CTkFrame(self.list_frame, fg_color="transparent")
header.pack(fill="x", pady=(10, 4))
ctk.CTkLabel(header, text=title, font=ui_font(12),
text_color=c("text")).pack(side="left", padx=2)
if errors.get(eid):
ctk.CTkLabel(header, text="недоступен", font=ui_font(10),
text_color=c("danger")).pack(side="left", padx=8)
if not models:
msg = errors.get(eid) or "нет моделей"
ctk.CTkLabel(self.list_frame, text=msg, font=ui_font(11),
text_color=c("text_faint"), anchor="w",
wraplength=760, justify="left").pack(anchor="w", padx=14, pady=(0, 6))
continue
for model in models:
total += 1
is_current = bool(
(model.id == current_name or (current_path and model.path == current_path))
and (current_engine in (None, eid))
)
self._add_model_row(eid, model, is_current)
if total == 0:
ctk.CTkLabel(
self.list_frame,
text="Модели не найдены. Проверьте, запущен ли движок, или добавьте файл/папку",
font=ui_font(12), text_color=c("text_dim"), anchor="w",
wraplength=760, justify="left",
).pack(anchor="w", padx=2, pady=(8, 2))
def _add_model_row(self, engine_id, model, is_current):
row = ctk.CTkFrame(self.list_frame, fg_color="transparent", corner_radius=0)
row.pack(fill="x", pady=0)
content = ctk.CTkFrame(row, fg_color="transparent", corner_radius=0)
content.pack(fill="x")
label_text = model.name or model.id
meta = []
if model.size:
meta.append(_fmt_size(model.size))
if model.path:
meta.append(model.path)
if meta:
label_text += " " + " · ".join(meta)
ctk.CTkLabel(content, text=label_text, anchor="w", wraplength=860, justify="left",
font=ui_font(12), text_color=c("text_dim")).pack(side="left", padx=14, pady=12)
if is_current:
ctk.CTkLabel(content, text="текущая", font=ui_font(10),
text_color=c("text_faint")).pack(side="left", padx=(4, 8))
btn_text = "Открыть в чате" if is_current else "Загрузить"
btn = ctk.CTkButton(
content,
text=btn_text,
width=136,
height=32,
command=lambda e=engine_id, m=model, cur=is_current: self._on_model_action(e, m, cur),
state=("disabled" if self._loading and not is_current else "normal"),
fg_color=(c("action_bg") if is_current else c("control")),
hover_color=(c("action_hover") if is_current else c("card_hover")),
text_color=(c("action_fg") if is_current else c("text")),
font=ui_font(12),
)
btn.pack(side="right", padx=14, pady=8)
self._load_buttons.append(btn)
ctk.CTkFrame(row, fg_color=c("border"), height=1, corner_radius=0).pack(fill="x")
def _on_model_action(self, engine_id, model, is_current):
if is_current and self.app:
self.app.switch_view("chat")
return
self.load(engine_id, model.id)
def load(self, engine_id, model_id):
if not self.engine:
return
try:
if self.app is not None and self.app.any_busy(exclude=self):
self.status_label.configure(text="Дождитесь завершения текущей операции")
return
except Exception:
pass
self._set_loading(True, f"Загрузка: {model_id}")
if self.app_state:
self.app_state.log(f"[UI] Загрузка модели: {model_id} ({engine_id})")
try:
self.engine.set_active_engine(engine_id)
except Exception as e:
self.status_label.configure(text=f"Ошибка выбора движка: {e}")
self._set_loading(False)
return
self.engine.load_model(model_id, on_done=self._after_load_threadsafe, engine_id=engine_id)
def _after_load_threadsafe(self):
self.ui(self.after_load)
def after_load(self):
if self.app and self.app_state:
self.app.sidebar.update_status(self.app_state, self.engine.is_ready() if self.engine else False)
self._loading = False
self.status_label.configure(text="")
self._update_current_label()
self.scan()
try:
still_here = self.app is None or self.app.current_view is self
except Exception:
still_here = False
if self.app_state and self.app_state.model_loaded and self.app and still_here:
self.app.switch_view("chat")
# ---------- добавление путей ----------
def add_file(self):
f = filedialog.askopenfilename(title="Выбрать файл модели")
if not f:
return
ap = os.path.abspath(f)
if ap not in self.extra_model_paths:
self.extra_model_paths.append(ap)
self.scan()
def add_folder(self):
d = filedialog.askdirectory(title="Выбрать папку с моделями")
if not d:
return
ap = os.path.abspath(d)
if ap not in self.extra_model_paths:
self.extra_model_paths.append(ap)
self.scan()
def _set_loading(self, loading: bool, msg: str = ""):
self._loading = loading
if msg:
self.status_label.configure(text=msg)
elif not loading:
self.status_label.configure(text="")
state = "disabled" if loading else "normal"
try:
self.btn_scan.configure(state=state)
self.btn_add_file.configure(state=state)
self.btn_add_folder.configure(state=state)
except Exception:
pass