Files

583 lines
23 KiB
Python

import os
import threading
import customtkinter as ctk
from tkinter import filedialog
from .base import ViewBase
from .library import LibraryPane
from ..theme import c, ui_font
from ..components.controls import Segmented, soft_scrollbar
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} Б"
def _short_error(message) -> str:
text = str(message or "").strip()
for marker in (" [Errno", ": [Errno"):
if marker in text:
text = text.split(marker, 1)[0].rstrip(" :")
break
return text
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.mode = "library"
self.mode_switch = Segmented(
self, ["Библиотека", "Модели движков"], command=self._set_mode,
height=32, font_size=11, width=236,
)
self.mode_switch.pack(anchor="w", padx=24, pady=(16, 12))
self.mode_switch.set("Библиотека")
body = ctk.CTkFrame(self, fg_color="transparent")
body.pack(fill="both", expand=True, padx=16, pady=(0, 10))
body.grid_rowconfigure(0, weight=1)
body.grid_columnconfigure(0, weight=1)
self._body = body
self.library = LibraryPane(
body, self.app, self.engine, self.app_state,
on_open_chat=(lambda: self.app.switch_view("chat")) if self.app else None,
)
self.library.grid(row=0, column=0, sticky="nsew")
self.engines_pane = ctk.CTkFrame(body, fg_color="transparent")
self.engines_pane.grid(row=0, column=0, sticky="nsew")
self.engines_pane.grid_remove()
# Модель и движок уже показаны в верхней панели — здесь не дублируем.
self.current_label = ctk.CTkLabel(
self.engines_pane, text="Модель —", anchor="w",
font=ui_font(11), text_color=c("text_dim"),
)
self.status_label = ctk.CTkLabel(self.engines_pane, text="", anchor="w",
font=ui_font(11), height=16,
text_color=c("text_faint"))
btns = ctk.CTkFrame(self.engines_pane, fg_color="transparent")
btns.pack(anchor="w", padx=8, pady=(4, 10))
self.btn_scan = ctk.CTkButton(btns, text="Сканировать", width=112,
command=self.scan, height=32, font=ui_font(11))
self.btn_scan.pack(side="left")
for text, command, ghost in (
("Добавить файл", self.add_file, True),
("Добавить папку", self.add_folder, True),
):
ctk.CTkButton(
btns, text=text, height=32, corner_radius=8,
fg_color=("transparent" if ghost else c("control")),
hover_color=c("card_hover"), text_color=c("text_dim"),
font=ui_font(11), command=command,
).pack(side="left", padx=(6, 0))
self.btn_pull = ctk.CTkButton(btns, text="Скачать модель", width=132,
height=32, font=ui_font(11),
command=self.pull_model_dialog)
self.btn_pull.pack(side="left", padx=(12, 0))
self.status_label.pack(anchor="w", padx=8, pady=(0, 6))
self.list_frame = ctk.CTkScrollableFrame(self.engines_pane)
self.list_frame.pack(fill="both", expand=True, padx=8, pady=(0, 20))
soft_scrollbar(self.list_frame, "card")
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 _set_mode(self, label):
self.mode = "library" if label == "Библиотека" else "engines"
if self.mode == "library":
self.engines_pane.grid_remove()
self.library.grid()
self.library.on_show()
else:
self.library.grid_remove()
self.engines_pane.grid()
self._update_current_label()
if not self._loading:
self.scan()
def reload_library(self):
if hasattr(self, "library") and self.library is not None:
self.library.reload_library()
def shutdown(self):
try:
self.library.shutdown()
except Exception:
pass
# ---------- сканирование ----------
def on_show(self):
if self.mode == "library":
self.library.on_show()
return
self._update_current_label()
if 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 = _short_error(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")
info = ctk.CTkFrame(content, fg_color="transparent")
info.pack(side="left", fill="x", expand=True, padx=14, pady=9)
ctk.CTkLabel(info, text=(model.name or model.id), anchor="w",
justify="left", height=18, font=ui_font(12),
text_color=c("text")).pack(anchor="w")
meta = []
if model.size:
meta.append(_fmt_size(model.size))
if model.kind:
meta.append(str(model.kind).upper())
if meta:
ctk.CTkLabel(info, text=" · ".join(meta), anchor="w", height=16,
font=ui_font(10), text_color=c("text_faint")).pack(anchor="w")
if is_current:
ctk.CTkLabel(content, text="текущая", font=ui_font(10), height=16,
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=(124 if is_current else 104),
height=30,
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(11),
)
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")
# ---------- загрузка моделей Ollama ----------
def _ollama_engines(self):
out = []
try:
items = self.engine.engines() if self.engine else []
except Exception:
items = []
for item in items:
if item.get("type") != "ollama" or not item.get("enabled", True):
continue
out.append((item.get("id"), item.get("name") or item.get("id")))
return out
def pull_model_dialog(self):
engines = self._ollama_engines()
if not engines:
self.status_label.configure(
text="Нет доступного движка Ollama. Добавьте его в «Настройки → Движки»")
return
try:
ModelPullDialog(self, engines)
except Exception as e:
self.status_label.configure(text=f"Не удалось открыть загрузку: {e}")
# ---------- добавление путей ----------
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)
self.btn_pull.configure(state=state)
except Exception:
pass
class ModelPullDialog(ctk.CTkToplevel):
"""Загрузка модели Ollama по имени (``llama3.2:3b`` и т. п.)."""
def __init__(self, host, engines, **kwargs):
super().__init__(host, **kwargs)
self.host = host
self.app = host.app
self.engines = list(engines)
self._closed = False
self._pulling = False
self._last_status = ""
self.title("Скачать модель Ollama")
self.geometry("500x310")
self.minsize(460, 280)
self.configure(fg_color=c("bg"))
self.transient(host)
try:
self.attributes("-type", "dialog")
except Exception:
pass
self._center(host, 500, 310)
self.after(80, self._raise)
self.protocol("WM_DELETE_WINDOW", self.close)
pad = 20
ctk.CTkLabel(self, text="Скачать модель Ollama", font=ui_font(18),
text_color=c("text")).pack(anchor="w", padx=pad, pady=(18, 2))
ctk.CTkLabel(self, text="Модель загрузится в хранилище выбранного движка",
font=ui_font(11), text_color=c("text_faint")).pack(
anchor="w", padx=pad, pady=(0, 12))
names = [str(name) for _eid, name in self.engines]
self._eid_by_name = {str(name): eid for eid, name in self.engines}
self.engine_menu = ctk.CTkOptionMenu(
self, values=names, width=440, height=32, dynamic_resizing=False,
font=ui_font(12), dropdown_font=ui_font(12),
)
self.engine_menu.pack(anchor="w", padx=pad, pady=(0, 10))
self.engine_menu.set(names[0])
self.name_entry = ctk.CTkEntry(self, height=34, font=ui_font(12),
placeholder_text="например, llama3.2:3b")
self.name_entry.pack(fill="x", padx=pad, pady=(0, 4))
self.name_entry.insert(0, "llama3.2:3b")
ctk.CTkLabel(self, text="Можно указать тег: qwen2.5:7b, gemma3:4b, mistral:7b",
font=ui_font(10), text_color=c("text_faint"), anchor="w").pack(
anchor="w", padx=pad, pady=(0, 10))
self.progress = ctk.CTkProgressBar(self, height=8, mode="determinate")
self.progress.pack(fill="x", padx=pad, pady=(0, 4))
self.progress.set(0)
self.status = ctk.CTkLabel(self, text="", font=ui_font(10),
text_color=c("text_faint"), anchor="w",
justify="left", wraplength=450)
self.status.pack(fill="x", padx=pad, pady=(0, 8))
actions = ctk.CTkFrame(self, fg_color="transparent")
actions.pack(fill="x", padx=pad, pady=(4, 16))
self.cancel_btn = ctk.CTkButton(actions, text="Отмена", width=100, height=34,
command=self.close)
self.cancel_btn.pack(side="right")
self.pull_btn = ctk.CTkButton(actions, text="Скачать", width=130, height=34,
fg_color=c("action_bg"), hover_color=c("action_hover"),
text_color=c("action_fg"), font=ui_font(12),
command=self.start)
self.pull_btn.pack(side="right", padx=8)
self.name_entry.bind("<Return>", lambda _e: self.start())
def _center(self, host, w, h):
try:
host.update_idletasks()
x = host.winfo_rootx() + max(0, (host.winfo_width() - w) // 2)
y = host.winfo_rooty() + max(0, (host.winfo_height() - h) // 2)
self.geometry(f"{w}x{h}+{x}+{y}")
except Exception:
pass
def _raise(self):
try:
self.lift()
self.focus_force()
self.name_entry.focus_set()
except Exception:
pass
def start(self):
if self._pulling:
return
name = self.name_entry.get().strip()
if not name:
self.status.configure(text="Укажите имя модели", text_color=c("danger"))
return
eid = self._eid_by_name.get(self.engine_menu.get())
adapter = self.host.engine.get_engine(eid) if self.host.engine else None
if adapter is None:
self.status.configure(text="Движок Ollama недоступен", text_color=c("danger"))
return
self._pulling = True
self._last_status = ""
self.pull_btn.configure(state="disabled")
self.cancel_btn.configure(state="disabled")
self.progress.set(0)
self.status.configure(text="Подключение к Ollama…", text_color=c("text_faint"))
def progress(done, total):
try:
frac = (float(done) / float(total)) if total else 0.0
text = f"{self._last_status or 'Загрузка'} · {frac * 100:.0f}%"
text += f" · {_fmt_size(done)} из {_fmt_size(total)}"
except Exception:
frac, text = 0.0, self._last_status or "Загрузка"
self.app.post_ui(lambda f=frac, t=text: self._progress(f, t))
def on_status(text):
self._last_status = str(text)
self.app.post_ui(lambda t=str(text): self._status(t))
def task():
try:
result = adapter.pull_model(name, on_progress=progress, on_status=on_status)
self.app.post_ui(lambda r=result: self._finish(True, r))
except Exception as e:
self.app.post_ui(lambda msg=str(e): self._finish(False, {"error": msg}))
threading.Thread(target=task, daemon=True).start()
def _progress(self, value, text):
if self._closed:
return
try:
self.progress.set(max(0.0, min(1.0, float(value))))
self.status.configure(text=text, text_color=c("text_faint"))
except Exception:
pass
def _status(self, text):
if self._closed:
return
try:
self.status.configure(text=text, text_color=c("text_faint"))
except Exception:
pass
def _finish(self, ok, result):
if self._closed:
return
self._pulling = False
try:
self.pull_btn.configure(state="normal")
self.cancel_btn.configure(state="normal")
except Exception:
pass
if not ok:
err = result.get("error", "неизвестная ошибка") if isinstance(result, dict) else "ошибка"
self.status.configure(text=f"Ошибка: {err}"[:300], text_color=c("danger"))
return
try:
self.progress.set(1)
except Exception:
pass
self.status.configure(text="Модель скачана", text_color=c("success"))
try:
self.host.scan()
except Exception:
pass
self.app.after(650, self.close)
def close(self):
if self._pulling:
return
self._closed = True
try:
self.destroy()
except Exception:
pass