193 lines
7.4 KiB
Python
193 lines
7.4 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
r"""syncWebUiFunctions.py - doprowadza funkcje (filtry) Open WebUI do stanu TioxyAi.
|
|
|
|
CO ROBI
|
|
Instaluje albo aktualizuje filtr "bionic_status" ze zrodla
|
|
abilities/functions/bionicStatus.py w bazie Open WebUI (router
|
|
/api/v1/functions) i WLACZA go globalnie: is_active + is_global.
|
|
Filtr informuje w czacie, ze silnik Bionic wczytuje model (JIT),
|
|
z licznikiem sekund - bez niego pierwsza wiadomosc do pobranego modelu
|
|
wyglada jak zawieszenie.
|
|
|
|
DLACZEGO PRZEZ API
|
|
Open WebUI laduje funkcje z wlasnej bazy. Montaz plikow do kontenera nic
|
|
nie rejestruje - jedyne wejscie to API administratora, ten sam mechanizm
|
|
co przy narzedziach (syncWebUiDocTools.py).
|
|
|
|
FILTR A NARZEDZIE
|
|
Router /functions przyjmuje Pipe/Filter/Action/Event - filtr to klasa
|
|
'Filter' z metodami inlet/outlet. W przeciwienstwie do narzedzi funkcje
|
|
MAJA przelaczniki: bez is_active filtr nie dziala, a bez is_global
|
|
dziala tylko dla modeli, ktore go wskaza. Oba ustawiamy.
|
|
|
|
WALIDACJA KSZTAKTU
|
|
Open WebUI dla nieznanej sciezki oddaje HTML z kodem 200. Lista funkcji
|
|
jest sprawdzana typowo; nieczytany stan = nie zmieniamy niczego.
|
|
|
|
PLACEHOLDER
|
|
Zrodlo ma {{BIONIC_URL}} - adres silnika widziany z kontenera webui
|
|
(host.docker.internal + BIONIC_PORT z .env). Podmienia go ten skrypt;
|
|
w zrodle nie ma portu na sztywno.
|
|
|
|
KODY WYJSCIA (konwencja repo): 0 = bez zmian, 10 = zmieniono, 1 = blad.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import pathlib
|
|
import sys
|
|
|
|
from webUiApi import opis_bledu, zaloguj_administratora, zapytaj
|
|
|
|
SCIEZKA_LISTY = "/api/v1/functions/export"
|
|
SCIEZKA_UTWORZENIA = "/api/v1/functions/create"
|
|
SCIEZKA_AKTUALIZACJI = "/api/v1/functions/id/%s/update"
|
|
SCIEZKA_PRZELACZNIKA = "/api/v1/functions/id/%s/toggle"
|
|
SCIEZKA_GLOBALNEGO = "/api/v1/functions/id/%s/toggle/global"
|
|
|
|
# (id funkcji, plik zrodlowy, tytul w UI). Id musi byc identyfikatorem Pythona.
|
|
FUNKCJE = [
|
|
("bionic_status", "bionicStatus.py", "TioxyAi: status wczytywania Bionic"),
|
|
]
|
|
|
|
OPIS = ("Informuje w czacie, gdy silnik Bionic wczytuje model (JIT), "
|
|
"z licznikiem czasu i komunikatem koncowym.")
|
|
|
|
_PLACEHOLDER = "{{BIONIC_URL}}"
|
|
|
|
|
|
def _czytaj_zrodla(katalog: str) -> dict:
|
|
tresci = {}
|
|
for id_, plik, _tytul in FUNKCJE:
|
|
sciezka = pathlib.Path(katalog) / plik
|
|
try:
|
|
tresci[id_] = sciezka.read_text(encoding="utf-8")
|
|
except OSError as blad:
|
|
raise SystemExit("[ERROR] nie moge przeczytac %s: %s" % (sciezka, blad))
|
|
return tresci
|
|
|
|
|
|
def _podmien(tresc: str, bionic_url: str) -> str:
|
|
if not bionic_url:
|
|
return tresc
|
|
return tresc.replace(_PLACEHOLDER, bionic_url.rstrip("/"))
|
|
|
|
|
|
def _czytaj_liste(url: str, token: str):
|
|
"""Lista funkcji jako ksztalt: lista slownikow z 'id' i 'content'."""
|
|
kod, odp = zapytaj(url, SCIEZKA_LISTY, token=token)
|
|
if kod != 200:
|
|
print("[ERROR] nie moge odczytac listy funkcji: %s" % opis_bledu(odp))
|
|
return None
|
|
if not isinstance(odp, list) or not all(isinstance(f, dict) and "id" in f for f in odp):
|
|
print("[ERROR] %s nie zwrocilo listy funkcji (ksztalt: %s) - nie zmieniam niczego"
|
|
% (SCIEZKA_LISTY, type(odp).__name__))
|
|
return None
|
|
return {f["id"]: f for f in odp}
|
|
|
|
|
|
def _nasze_obce(obecne: dict) -> list:
|
|
"""Kopie funkcji z id z przyrostkiem - efekt recznej edycji w UI."""
|
|
nasze = {id_ for id_, _plik, _tytul in FUNKCJE}
|
|
return [id_ for id_ in obecne
|
|
if id_ not in nasze and any(id_.startswith(n + "-") or id_.startswith(n + "_")
|
|
for n in nasze)]
|
|
|
|
|
|
def _wlacz(url: str, id_: str, token: str, stan: dict) -> bool:
|
|
"""Ustawia is_active i is_global na True. True = wszystko wlaczone."""
|
|
ok = True
|
|
if not stan.get("is_active"):
|
|
kod, odp = zapytaj(url, SCIEZKA_PRZELACZNIKA % id_, {}, token=token)
|
|
if kod != 200:
|
|
print("[ERROR] nie moge wlaczyc funkcji '%s': %s" % (id_, opis_bledu(odp)))
|
|
ok = False
|
|
if not stan.get("is_global"):
|
|
kod, odp = zapytaj(url, SCIEZKA_GLOBALNEGO % id_, {}, token=token)
|
|
if kod != 200:
|
|
print("[ERROR] nie moge ustawic funkcji '%s' jako globalnej: %s"
|
|
% (id_, opis_bledu(odp)))
|
|
ok = False
|
|
return ok
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--url", required=True, help="adres Open WebUI")
|
|
parser.add_argument("--plik", required=True, help="config/openWebUiUsers.json")
|
|
parser.add_argument("--funkcje", required=True,
|
|
help="katalog abilities/functions ze zrodlami")
|
|
parser.add_argument("--bionic-url", default="",
|
|
help="adres silnika Bionic widziany z kontenera webui")
|
|
args = parser.parse_args()
|
|
|
|
tresci = {id_: _podmien(t, args.bionic_url)
|
|
for id_, t in _czytaj_zrodla(args.funkcje).items()}
|
|
|
|
token = zaloguj_administratora(args.url, args.plik)
|
|
if not token:
|
|
return 1
|
|
|
|
obecne = _czytaj_liste(args.url, token)
|
|
if obecne is None:
|
|
return 1
|
|
|
|
for id_ in sorted(_nasze_obce(obecne)):
|
|
print("[WARN] w bazie jest zmodyfikowana kopia funkcji TioxyAi: '%s'. "
|
|
"Usun ja w UI, inaczej moze dublowac zdarzenia statusu." % id_)
|
|
|
|
zmieniono = 0
|
|
for id_, _plik, tytul in FUNKCJE:
|
|
tresc = tresci[id_]
|
|
wpis = obecne.get(id_)
|
|
stan = wpis or {}
|
|
if wpis is None:
|
|
print("[INFO] tworze funkcje: %s" % id_)
|
|
kod, odp = zapytaj(args.url, SCIEZKA_UTWORZENIA,
|
|
{"id": id_, "name": tytul, "content": tresc,
|
|
"meta": {"description": OPIS}}, token=token)
|
|
if kod != 200:
|
|
print("[ERROR] nie udalo sie utworzyc '%s': %s" % (id_, opis_bledu(odp)))
|
|
return 1
|
|
stan = odp if isinstance(odp, dict) else {}
|
|
zmieniono = 10
|
|
elif ((wpis.get("content") or "") != tresc
|
|
or (wpis.get("name") or "") != tytul):
|
|
print("[INFO] aktualizuje funkcje: %s" % id_)
|
|
kod, odp = zapytaj(args.url, SCIEZKA_AKTUALIZACJI % id_,
|
|
{"id": id_, "name": tytul, "content": tresc,
|
|
"meta": {"description": OPIS}}, token=token)
|
|
if kod != 200:
|
|
print("[ERROR] nie udalo sie zaktualizowac '%s': %s" % (id_, opis_bledu(odp)))
|
|
return 1
|
|
stan = odp if isinstance(odp, dict) else stan
|
|
zmieniono = 10
|
|
|
|
if not (stan.get("is_active") and stan.get("is_global")):
|
|
if not _wlacz(args.url, id_, token, stan):
|
|
return 1
|
|
zmieniono = 10
|
|
print("[INFO] funkcja '%s' wlaczona globalnie" % id_)
|
|
|
|
# Potwierdzenie stanu docelowego - nie ufamy samym odpowiedziom toggle.
|
|
po = _czytaj_liste(args.url, token)
|
|
if po is None:
|
|
return 1
|
|
for id_, _plik, _tytul in FUNKCJE:
|
|
wpis = po.get(id_) or {}
|
|
if not (wpis.get("is_active") and wpis.get("is_global")):
|
|
print("[ERROR] funkcja '%s' nie jest aktywna globalnie po synchronizacji "
|
|
"(is_active=%s, is_global=%s)"
|
|
% (id_, wpis.get("is_active"), wpis.get("is_global")))
|
|
return 1
|
|
|
|
if zmieniono == 0:
|
|
print("[OK] funkcje Open WebUI zgodne z TioxyAi (%d funkcji)" % len(FUNKCJE))
|
|
return 0
|
|
print("[OK] funkcje Open WebUI uzgodnione z TioxyAi")
|
|
return 10
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main()) |