Consolidate experiment evidence and audit backup restore readiness
This commit is contained in:
1 parent
a940b90484
commit
4d39fc8d22
107 files changed
+13691
-420
No files matched your search
@@ -82,3 +82,36 @@ Athena-Restore erhalten. Vollständiger frischer Restore nicht getestet.
|
||||
|
||||
Quellen: [Speech](https://www.librechat.ai/docs/configuration/librechat_yaml/object_structure/speech),
|
||||
[Bildwerkzeuge](https://www.librechat.ai/docs/features/image_gen).
|
||||
|
||||
## Bildanzeige und HTTP-Sitzungen korrigiert (12.10.2026)
|
||||
|
||||
Nutzer-Screenshot zeigte defektes Bildsymbol trotz abgeschlossener Generation.
|
||||
Eng begrenzte Metadatenprüfung des letzten Bilddatensatzes: lokale PNG-Datei
|
||||
vorhanden und gültig (1597755 Bytes, PNG-Magic), Bildroute unauthentifiziert401.
|
||||
Keine privaten Chats, Produktionslogs oder Bildinhalte gelesen.
|
||||
|
||||
Installationsfehler: NODE_ENV=production mit DOMAIN_SERVER=http192.168.1.2:3080
|
||||
und fehlendem SESSION_COOKIE_SECURE-Override. Offizielle shouldUseSecureCookie-
|
||||
Funktion setzt dann secure=true (nur localhost ist standardmäßig ausgenommen).
|
||||
Bildauthentifizierung verlangt refreshToken-Cookie; Secure-Cookies können über
|
||||
HTTP auf einer normalen LAN-IP nicht funktionieren. Normale Chatrequests mit
|
||||
Bearer-Access-Token können dennoch funktionieren. Der bisherige Infrastruktur-
|
||||
Test ohne Browser-Sitzung hatte dies nicht abgedeckt. Kein als bewiesener
|
||||
Upstream-Bug auszugeben.
|
||||
|
||||
Nutzer wählte ausdrücklich vorerst HTTP im LAN statt neuer HTTPS-Domain.
|
||||
SESSION_COOKIE_SECURE=false in geschützter Unraid-XML/Container-Env gesetzt.
|
||||
API-Funktion geprüft: sollteUseSecureCookie=false (tatsächlicher Export
|
||||
shouldUseSecureCookie). HttpOnly/SameSite, Anmeldung und private Bildzugriffs-
|
||||
kontrolle unverändert. Kein secureImageLinks=false und kein öffentliches
|
||||
Freigeben der Bilder. Einmal neu anmelden, damit der Browser gültiges Cookie
|
||||
erhält. Bei Umstieg auf HTTPS SESSION_COOKIE_SECURE=true plus DOMAIN_CLIENT/
|
||||
DOMAIN_SERVER auf HTTPS anpassen. Browser-Mikrofon bleibt bis HTTPS eingeschränkt.
|
||||
|
||||
Geschützte XML-Sicherung:
|
||||
librechat/install-backups/http-cookies-20261012-174421.
|
||||
Fixhelper verweigert Anwendung außerhalb der konkreten freigegebenen HTTP-LAN-
|
||||
Adresse. Sicherung/Restore müssen aktualisierte XML und diesen Override erhalten.
|
||||
Der HTTP-Betrieb überträgt Sitzungscookies unverschlüsselt und wurde vom Nutzer
|
||||
bewusst gewählt; bei LAN-fremder Nutzung HTTPS einrichten.
|
||||
Abschließende Bildanzeige mit tatsächlicher Browser-Sitzung noch zu prüfen.
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
function run($a){$p=proc_open($a,[1=>['pipe','w'],2=>['pipe','w']],$ps);$o=stream_get_contents($ps[1]);$e=stream_get_contents($ps[2]);foreach($ps as$s)fclose($s);if(proc_close($p))throw new Exception('Container operation failed; output suppressed');return $o;}
|
||||
$xp='/boot/config/plugins/dockerMan/templates-user/my-LibreChat.xml';$root='/mnt/nvme-storage/appdata/librechat';$x=simplexml_load_file($xp);$domain=null;foreach($x->Config as$c)if((string)$c['Target']==='DOMAIN_SERVER')$domain=(string)$c;if($domain!=='http://192.168.1.2:3080')throw new Exception('Expected HTTP LAN deployment only');
|
||||
$back=$root.'/install-backups/http-cookies-'.gmdate('Ymd-His');mkdir($back,0700,true);copy($xp,$back.'/my-LibreChat.xml');chmod($back.'/my-LibreChat.xml',0600);
|
||||
$found=false;foreach($x->Config as$c)if((string)$c['Target']==='SESSION_COOKIE_SECURE'){$c[0]='false';$found=true;}if(!$found){$c=$x->addChild('Config','false');foreach(['Name'=>'HTTPS-only Session Cookie','Target'=>'SESSION_COOKIE_SECURE','Type'=>'Variable','Mode'=>'','Display'=>'always','Mask'=>'false','Description'=>'false nur für freigegebenen HTTP-LAN-Betrieb; bei HTTPS wieder true setzen.']as$k=>$v)$c->addAttribute($k,$v);}$x->asXML($xp);chmod($xp,0600);
|
||||
$a=['docker','create','--name','LibreChat','--network','bridge','--restart','unless-stopped','--pids-limit','2048','-l','net.unraid.docker.managed=dockerman'];foreach(['WebUI'=>'net.unraid.docker.webui','Icon'=>'net.unraid.docker.icon']as$k=>$v)if((string)$x->$k!='')array_push($a,'-l',$v.'='.(string)$x->$k);foreach($x->Config as$c){$v=(string)$c;$target=(string)$c['Target'];$type=(string)$c['Type'];if($type==='Variable')array_push($a,'-e',$target.'='.$v);elseif($type==='Port')array_push($a,'-p',$v.':'.$target.'/'.(string)$c['Mode']);elseif($type==='Path')array_push($a,'-v',$v.':'.$target.':'.(string)$c['Mode']);else throw new Exception('Unknown config type');}$a[]=(string)$x->Repository;
|
||||
run(['docker','stop','--time','30','LibreChat']);run(['docker','rm','LibreChat']);run($a);run(['docker','start','LibreChat']);echo json_encode(['http_cookie_fix_applied'=>true,'image_authorization_preserved'=>true,'backup'=>$back])."\n";
|
||||
@@ -1,5 +1,37 @@
|
||||
# OpenCode Athena profile list — 2026-10-13
|
||||
|
||||
## Mac Desktop parity — 2026-10-14
|
||||
|
||||
Configured the installed OpenCode Desktop 2.0.28 using the current Unraid global
|
||||
provider as source. The Mac keeps provider ID `athena_deck`, zsh, and the existing
|
||||
disabled LM Studio provider. All twelve model definitions, context limits,
|
||||
capabilities, sampling options and active thinking variants match Unraid;
|
||||
IQ2 remains excluded. Strata contexts are 262144, 524288 and 262144 per request
|
||||
for the single, 512K and dual profiles respectively.
|
||||
|
||||
Desktop 2's legacy-config conversion interpreted `variants.*.disabled` as model
|
||||
settings and displayed three additional ineffective variants. Removed only those
|
||||
disabled legacy entries on the Mac; the five enabled variants are preserved.
|
||||
The official bundled CLI parses the resulting provider, and the live Desktop UI
|
||||
shows all twelve enabled models and the five intended thinking variants.
|
||||
|
||||
The old Mac Athena credential failed the metadata request with HTTP 401. Copied
|
||||
the working Unraid credential directly into the existing Mac auth entry without
|
||||
printing its value; authenticated GET /v1/models confirmed every configured ID.
|
||||
Local configuration and authentication backups have mode 0600 and are not part
|
||||
of Git. No source credentials or private chat/session contents belong here.
|
||||
|
||||
Unraid's global configuration has no MCP entries, instruction files, plugins or
|
||||
custom agents/skills in its inspected global directories to migrate. Project
|
||||
files, project-specific configuration and chat histories were not transferred.
|
||||
Native shell/file tools use the Mac when a local project is opened.
|
||||
|
||||
Enabled all twelve models through the Desktop UI and selected the dual profile
|
||||
in an empty draft; no model request was sent. No Unraid/Athena process was
|
||||
restarted, unloaded or reconfigured. The desktop watched the changed files live.
|
||||
This is client configuration, not a new Deck runtime feature. Restore requires
|
||||
the user's private OpenCode auth data separately from these public instructions.
|
||||
|
||||
Updated existing Athena providers in both configurations without changing
|
||||
provider credentials, endpoint URLs, other providers or application defaults:
|
||||
|
||||
|
||||
@@ -30,11 +30,18 @@ automatische Freigabeprüfung hatte diese Schritte bis zur ausdrücklichen
|
||||
Zustimmung blockiert. Browserdarstellung noch nicht Ende zu Ende geprüft.
|
||||
|
||||
Tokenfilter: Kostenanzeige und externe models.dev-Abfragen ausgeschaltet.
|
||||
Kontext-Prozentanzeige ebenfalls ausgeschaltet, bis die realen Athena-
|
||||
Profilgrößen verlässlich zugeordnet werden; keine geratenen Modellgrößen.
|
||||
Eigene Kontext-Prozentanzeige dieses Plugins bleibt ausgeschaltet;
|
||||
die separate globale Athena-Kontextanzeige nutzt die geprüften Profilgrößen.
|
||||
Tokenzahlen und Dauer bleiben verfügbar. API-Zahlen werden bevorzugt,
|
||||
Schätzungen können verwendet werden, wenn keine Zahlen vorliegen.
|
||||
|
||||
8. Oktober: Im installierten Token Usage Display wurde ein kleiner Adapter
|
||||
ergänzt, der seine fertige Statusbeschreibung an den nachfolgenden Kontextfilter
|
||||
übergibt. Die gemeinsame letzte Statusmeldung erhält so Dauer und Tokens/s;
|
||||
zwei getrennte Meldungen verdrängten zuvor die Statistik. Der hier vendorte
|
||||
Upstream-Code und seine Prüfsumme bleiben unverändert. Adapter, Sicherung,
|
||||
Updatehinweise und Tests: [Kontextanzeige](../openwebui-context-display/README.md).
|
||||
|
||||
## Reproduktion, Abhängigkeiten, Sicherung
|
||||
|
||||
`install.py` ist der dokumentierte Importweg für einen vorhandenen
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
"""
|
||||
title: Athena Context Display
|
||||
version: 1.2.0
|
||||
description: Displays the last request's context, separate from cumulative tool-loop usage.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import time
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def positive(value):
|
||||
if isinstance(value, bool):
|
||||
return None
|
||||
try:
|
||||
number = int(value)
|
||||
return number if number > 0 else None
|
||||
except (ValueError, TypeError, OverflowError):
|
||||
return None
|
||||
|
||||
|
||||
def last_context(usage):
|
||||
"""OWUI merge_usage sums canonical fields but preserves last-call aliases.
|
||||
|
||||
Never use input_tokens, output_tokens, total_tokens or cached-token details:
|
||||
all four may be summed over the entire native tool loop.
|
||||
"""
|
||||
if not isinstance(usage, dict):
|
||||
return None
|
||||
if positive(usage.get('prompt_tokens')):
|
||||
prompt = positive(usage['prompt_tokens'])
|
||||
completion = positive(usage.get('completion_tokens')) or 0
|
||||
elif positive(usage.get('prompt_eval_count')):
|
||||
prompt = positive(usage['prompt_eval_count'])
|
||||
completion = positive(usage.get('eval_count')) or 0
|
||||
elif positive(usage.get('prompt_n')) or positive(usage.get('cache_n')):
|
||||
prompt = (positive(usage.get('prompt_n')) or 0) + (positive(usage.get('cache_n')) or 0)
|
||||
completion = positive(usage.get('predicted_n')) or 0
|
||||
else:
|
||||
return None
|
||||
return prompt + completion
|
||||
|
||||
|
||||
def number(value):
|
||||
return f'{value:,}'.replace(',', '.')
|
||||
|
||||
|
||||
def reported_model_seconds(event):
|
||||
"""Provider timings cover prefill + generation, not queue/network/tools."""
|
||||
if not isinstance(event, dict):
|
||||
return None
|
||||
fields = {}
|
||||
for name in ('usage', 'timings'):
|
||||
if isinstance(event.get(name), dict):
|
||||
fields.update(event[name])
|
||||
if 'prompt_ms' in fields and 'predicted_ms' in fields:
|
||||
values, scale = [fields['prompt_ms'], fields['predicted_ms']], 1000
|
||||
elif 'prompt_eval_duration' in fields and 'eval_duration' in fields:
|
||||
values, scale = [fields['prompt_eval_duration'], fields['eval_duration']], 1e9
|
||||
else:
|
||||
return None
|
||||
try:
|
||||
values = [float(value) for value in values]
|
||||
if any(not math.isfinite(value) or value < 0 for value in values):
|
||||
return None
|
||||
return sum(values) / scale
|
||||
except (ValueError, TypeError, OverflowError):
|
||||
return None
|
||||
|
||||
|
||||
def phase_description(meter, now, show_rest=False):
|
||||
if not isinstance(meter, dict):
|
||||
return ''
|
||||
elapsed = max(0, now - meter['started'])
|
||||
description = f'⌛ Gesamt: {elapsed:.1f}s'
|
||||
rounds = meter.get('rounds') or []
|
||||
if not rounds or any(value is None for value in rounds):
|
||||
return description + ' · Modell: nicht vollständig messbar'
|
||||
model_seconds = sum(rounds)
|
||||
# Never hide overlapping/inconsistent provider timing with a fabricated 0.
|
||||
if model_seconds > elapsed + 0.05:
|
||||
return description + ' · Modell: Zeitwerte widersprüchlich'
|
||||
remaining = max(0, elapsed - model_seconds)
|
||||
description += f' · Modell: {model_seconds:.1f}s'
|
||||
if show_rest:
|
||||
description += f' · Rest ≈ {remaining:.1f}s (Tools/Warten/Verarbeitung)'
|
||||
return description
|
||||
|
||||
|
||||
class Filter:
|
||||
class Valves(BaseModel):
|
||||
priority: int = Field(default=100, description='Run after ordinary output filters.')
|
||||
show_rest: bool = Field(default=False, description='Show estimated tools/waiting/processing remainder.')
|
||||
show_compaction_threshold: bool = Field(default=False, description='Show the configured compaction threshold.')
|
||||
profile_windows: str = Field(default='{}', description='JSON: exact model ID -> configured profile context tokens. Refresh after changing Deck profile windows.')
|
||||
|
||||
def __init__(self):
|
||||
self.valves = self.Valves()
|
||||
|
||||
async def inlet(self, body: dict, __metadata__: dict = None) -> dict:
|
||||
if isinstance(__metadata__, dict) and not __metadata__.get('task'):
|
||||
__metadata__['_athena_phase_meter'] = {'started': time.monotonic(), 'rounds': []}
|
||||
return body
|
||||
|
||||
async def request(self, body: dict, __metadata__: dict = None) -> dict:
|
||||
meter = (__metadata__ or {}).get('_athena_phase_meter')
|
||||
if isinstance(meter, dict) and not (__metadata__ or {}).get('task'):
|
||||
meter['rounds'].append(None)
|
||||
return body
|
||||
|
||||
async def stream(self, event: dict, __metadata__: dict = None) -> dict:
|
||||
meter = (__metadata__ or {}).get('_athena_phase_meter')
|
||||
if isinstance(meter, dict) and meter.get('rounds'):
|
||||
seconds = reported_model_seconds(event)
|
||||
if seconds is not None:
|
||||
# Streaming counters are cumulative *within* each model call.
|
||||
# Replace its last value; do not sum every chunk.
|
||||
meter['rounds'][-1] = seconds
|
||||
return event
|
||||
|
||||
async def outlet(self, body: dict, __event_emitter__=None,
|
||||
__metadata__: dict = None, __model__: dict = None) -> dict:
|
||||
# No chat text changes, requests, credentials, tokenization or GPU work.
|
||||
if (__metadata__ or {}).get('task') or not __event_emitter__:
|
||||
return body
|
||||
try:
|
||||
model = __model__ if isinstance(__model__, dict) else {}
|
||||
info = model.get('info') or {}
|
||||
model_id = model.get('id') or body.get('model')
|
||||
if model_id in ('arena-model', 're_registry', 're-registry'):
|
||||
return body
|
||||
messages = body.get('messages') or []
|
||||
assistant = next((m for m in reversed(messages)
|
||||
if isinstance(m, dict) and m.get('role') == 'assistant'), None)
|
||||
if not assistant:
|
||||
return body
|
||||
usage = assistant.get('usage') or (assistant.get('info') or {}).get('usage')
|
||||
used = last_context(usage)
|
||||
try:
|
||||
windows = json.loads(self.valves.profile_windows)
|
||||
if not isinstance(windows, dict):
|
||||
windows = {}
|
||||
except (ValueError, TypeError):
|
||||
windows = {}
|
||||
# Provider metadata takes priority over the explicitly verified map.
|
||||
window = positive(model.get('context_window')) or positive((model.get('meta') or {}).get('n_ctx'))
|
||||
window = window or positive(windows.get(model_id)) or positive(windows.get(info.get('base_model_id')))
|
||||
threshold = positive((info.get('params') or {}).get('compact_token_threshold'))
|
||||
description = '🧠 Kontext: unbekannt (keine Tokenwerte der letzten Anfrage)'
|
||||
if used is not None:
|
||||
description = f'🧠 Kontext: {number(used)} Token'
|
||||
if window:
|
||||
percent = used / window * 100
|
||||
description = f'🧠 {number(used)} / {number(window)} Token ({percent:.1f} %)'
|
||||
else:
|
||||
description += ' · Profilfenster unbekannt'
|
||||
if threshold and self.valves.show_compaction_threshold:
|
||||
description += f' · Verdichtungsschwelle: {number(threshold)}'
|
||||
# Token Usage Display runs first and shares this request's metadata.
|
||||
# OWUI shows only the final status: preserve its metrics in that status.
|
||||
statistics = (__metadata__ or {}).get('_athena_token_usage_status')
|
||||
if isinstance(statistics, str) and statistics.strip():
|
||||
description = statistics + ' │ ' + description
|
||||
meter = (__metadata__ or {}).get('_athena_phase_meter')
|
||||
if isinstance(meter, dict) and meter.get('rounds') and meter['rounds'][-1] is None:
|
||||
# Non-streaming final call: only fill that call, never infer
|
||||
# earlier rounds from cumulative consumption metadata.
|
||||
meter['rounds'][-1] = reported_model_seconds({'usage': usage})
|
||||
phases = phase_description(meter, time.monotonic(), self.valves.show_rest)
|
||||
if phases:
|
||||
description += ' │ ' + phases
|
||||
await __event_emitter__({'type': 'status', 'data': {
|
||||
'description': description, 'done': True, 'hidden': False}})
|
||||
except Exception:
|
||||
# A broken display must never interrupt a model response.
|
||||
log.warning('Athena context display unavailable')
|
||||
return body
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Targeted, backed-up installation into an existing OpenWebUI SQLite DB.
|
||||
|
||||
Run in OpenWebUI's environment, with JSON {content, windows} on stdin.
|
||||
No server restart or authentication secrets. Also adapts the token-statistics
|
||||
filter to the shared, compact status line; both entries are backed up.
|
||||
"""
|
||||
import argparse
|
||||
import datetime
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
import sys
|
||||
import time
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--db', required=True)
|
||||
parser.add_argument('--backup-dir', required=True)
|
||||
args = parser.parse_args()
|
||||
payload = json.load(sys.stdin)
|
||||
content = payload['content']
|
||||
compile(content, 'athena_context_display', 'exec')
|
||||
windows = payload['windows']
|
||||
assert isinstance(windows, dict) and all(isinstance(k, str) and type(v) is int and v > 0 for k, v in windows.items())
|
||||
c = sqlite3.connect(args.db)
|
||||
c.row_factory = sqlite3.Row
|
||||
c.execute('BEGIN IMMEDIATE')
|
||||
ident = 'athena_context_display'
|
||||
old = c.execute('select * from function where id=?', (ident,)).fetchone()
|
||||
statistics = c.execute("select * from function where id='token_usage_display'").fetchone()
|
||||
assert statistics, 'Token Usage Display must be installed first'
|
||||
owner = c.execute("select user_id from function where id='token_usage_display'").fetchone()
|
||||
if not owner:
|
||||
owner = c.execute("select id as user_id from user where role='admin' limit 1").fetchone()
|
||||
assert owner, 'No existing administrator found'
|
||||
backup_dir = Path(args.backup_dir)
|
||||
backup_dir.mkdir(parents=True, exist_ok=True)
|
||||
backup = backup_dir / ('context-display-before-' + datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S%fZ') + '.json')
|
||||
fd = os.open(backup, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||
with os.fdopen(fd, 'w') as f:
|
||||
json.dump({'id': ident, 'previous': dict(old) if old else None,
|
||||
'token_usage_display': dict(statistics)}, f)
|
||||
# Keep the upstream formatter and its valves. A tiny adapter exposes only its
|
||||
# finished display text to the following filter, via request-local metadata.
|
||||
stats_content = statistics['content']
|
||||
marker = " __metadata__['_athena_token_usage_status'] = v.separator.join(stats_parts)"
|
||||
anchor = ' if stats_parts and __event_emitter__:\n'
|
||||
if marker not in stats_content:
|
||||
assert stats_content.count(anchor) == 1, 'Unknown Token Usage Display version; refusing blind patch'
|
||||
stats_content = stats_content.replace(anchor,
|
||||
" # Athena Context Display: preserve metrics in the final status.\n"
|
||||
" if stats_parts and isinstance(__metadata__, dict):\n"
|
||||
+ marker + '\n\n' + anchor, 1)
|
||||
compile(stats_content, 'token_usage_display', 'exec')
|
||||
c.execute("update function set content=?,updated_at=? where id='token_usage_display'",
|
||||
(stats_content, int(time.time())))
|
||||
stats_valves = json.loads(statistics['valves'] or '{}')
|
||||
for key in ('show_input_tokens', 'show_output_tokens', 'show_total_tokens',
|
||||
'show_cumulative_tokens', 'show_generation_time', 'show_reasoning_tokens',
|
||||
'show_cached_tokens', 'show_audio_tokens', 'show_model_name',
|
||||
'show_data_source', 'show_context_window'):
|
||||
stats_valves[key] = False
|
||||
stats_valves.update(show_tokens_per_second=True, cost_mode='off')
|
||||
c.execute("update function set valves=? where id='token_usage_display'", (json.dumps(stats_valves),))
|
||||
valves = json.loads(old['valves'] or '{}') if old else {}
|
||||
valves.update(priority=100, profile_windows=json.dumps(windows, sort_keys=True),
|
||||
show_rest=False, show_compaction_threshold=False)
|
||||
now = int(time.time())
|
||||
if old:
|
||||
assert old['type'] == 'filter', 'Existing ID is not a filter'
|
||||
c.execute('update function set name=?,content=?,valves=?,is_active=1,is_global=1,updated_at=? where id=?',
|
||||
('Athena Context Display', content, json.dumps(valves), now, ident))
|
||||
else:
|
||||
c.execute('insert into function (id,user_id,name,type,content,meta,valves,is_active,is_global,updated_at,created_at) values (?,?,?,?,?,?,?,?,?,?,?)',
|
||||
(ident, owner['user_id'], 'Athena Context Display', 'filter', content,
|
||||
json.dumps({'description': 'Kontext der letzten Modellanfrage / konfiguriertes Profilfenster'}),
|
||||
json.dumps(valves), 1, 1, now, now))
|
||||
c.commit()
|
||||
r = c.execute('select content,is_active,is_global from function where id=?', (ident,)).fetchone()
|
||||
assert r['content'] == content and r['is_active'] and r['is_global']
|
||||
print(json.dumps({'id': ident, 'active': True, 'global': True, 'profiles': len(windows),
|
||||
'sha256': hashlib.sha256(content.encode()).hexdigest(), 'backup': str(backup)}))
|
||||
@@ -0,0 +1,114 @@
|
||||
import asyncio
|
||||
import copy
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
|
||||
spec = importlib.util.spec_from_file_location('context_filter', Path(__file__).with_name('filter.py'))
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
|
||||
|
||||
class ContextTests(unittest.TestCase):
|
||||
def test_phase_meter_prefill_and_thinking_generation_included(self):
|
||||
self.assertEqual(module.reported_model_seconds({'timings': {'prompt_ms': 500, 'predicted_ms': 1900}}), 2.4)
|
||||
self.assertEqual(module.reported_model_seconds({'usage': {'prompt_eval_duration': 500000000, 'eval_duration': 1900000000}}), 2.4)
|
||||
|
||||
def test_phase_meter_missing_and_inconsistent_timings_are_explicit(self):
|
||||
self.assertIn('nicht vollständig', module.phase_description({'started': 0, 'rounds': [1, None]}, 10))
|
||||
self.assertIn('widersprüchlich', module.phase_description({'started': 0, 'rounds': [20]}, 10))
|
||||
self.assertIsNone(module.reported_model_seconds({'timings': {'prompt_ms': float('nan'), 'predicted_ms': 1}}))
|
||||
|
||||
def test_all_model_rounds_count_once_and_requests_are_unchanged(self):
|
||||
async def run():
|
||||
f = module.Filter()
|
||||
body = {'messages': []}
|
||||
metadata = {}
|
||||
self.assertIs(await f.inlet(body, metadata), body)
|
||||
self.assertIs(await f.request(body, metadata), body)
|
||||
event = {'timings': {'prompt_ms': 500, 'predicted_ms': 1000}}
|
||||
self.assertIs(await f.stream(event, metadata), event)
|
||||
await f.stream({'timings': {'prompt_ms': 500, 'predicted_ms': 1900}}, metadata)
|
||||
await f.request(body, metadata)
|
||||
await f.stream({'timings': {'prompt_ms': 100, 'predicted_ms': 900}}, metadata)
|
||||
self.assertEqual(metadata['_athena_phase_meter']['rounds'], [2.4, 1.0])
|
||||
metadata['_athena_phase_meter']['started'] = 0
|
||||
description = module.phase_description(metadata['_athena_phase_meter'], 10, show_rest=True)
|
||||
self.assertIn('Modell: 3.4s', description)
|
||||
self.assertIn('Rest ≈ 6.6s', description)
|
||||
asyncio.run(run())
|
||||
|
||||
def test_compact_times_hide_remainder(self):
|
||||
description = module.phase_description({'started': 0, 'rounds': [3.4]}, 10)
|
||||
self.assertEqual(description, '⌛ Gesamt: 10.0s · Modell: 3.4s')
|
||||
|
||||
def test_tool_loop_uses_last_request_not_sum_or_accumulated_cache(self):
|
||||
usage = {'input_tokens': 63001, 'output_tokens': 410, 'total_tokens': 63411,
|
||||
'prompt_tokens': 21181, 'completion_tokens': 129,
|
||||
'prompt_tokens_details': {'cached_tokens': 62410}}
|
||||
self.assertEqual(module.last_context(usage), 21310)
|
||||
|
||||
def test_llama_cache_included_once(self):
|
||||
self.assertEqual(module.last_context({'prompt_n': 198, 'cache_n': 20983, 'predicted_n': 129}), 21310)
|
||||
|
||||
def test_canonical_only_is_unknown_not_falsely_cumulative(self):
|
||||
self.assertIsNone(module.last_context({'input_tokens': 63001, 'output_tokens': 410}))
|
||||
|
||||
def test_ollama(self):
|
||||
self.assertEqual(module.last_context({'prompt_eval_count': 300, 'eval_count': 20}), 320)
|
||||
|
||||
def test_concurrent_responses_and_no_content_mutation(self):
|
||||
async def run():
|
||||
f = module.Filter()
|
||||
f.valves.profile_windows = '{"medium":160000,"fast":76800}'
|
||||
async def call(model_id, prompt):
|
||||
events = []
|
||||
async def emit(event):
|
||||
events.append(event)
|
||||
body = {'model': model_id, 'messages': [{'role': 'assistant', 'content': 'Hello',
|
||||
'usage': {'prompt_tokens': prompt, 'completion_tokens': 129}}]}
|
||||
original = copy.deepcopy(body)
|
||||
result = await f.outlet(body, emit, __model__={'id': model_id})
|
||||
self.assertEqual(result, original)
|
||||
return events[0]['data']['description']
|
||||
medium, fast = await asyncio.gather(call('medium', 21181), call('fast', 1000))
|
||||
self.assertIn('21.310 / 160.000', medium)
|
||||
self.assertIn('1.129 / 76.800', fast)
|
||||
asyncio.run(run())
|
||||
|
||||
def test_background_task_emits_nothing(self):
|
||||
async def run():
|
||||
async def emit(event):
|
||||
self.fail('Background task emitted context status')
|
||||
body = {'messages': [{'role': 'assistant'}]}
|
||||
self.assertIs(await module.Filter().outlet(body, emit, {'task': 'title_generation'}), body)
|
||||
asyncio.run(run())
|
||||
|
||||
def test_failed_emitter_does_not_break_answer(self):
|
||||
async def run():
|
||||
async def emit(event):
|
||||
raise RuntimeError('Disconnected client')
|
||||
body = {'messages': [{'role': 'assistant'}]}
|
||||
self.assertIs(await module.Filter().outlet(body, emit), body)
|
||||
asyncio.run(run())
|
||||
|
||||
def test_existing_throughput_and_duration_survive_final_status(self):
|
||||
async def run():
|
||||
events = []
|
||||
async def emit(event):
|
||||
events.append(event)
|
||||
body = {'model': 'medium', 'messages': [{'role': 'assistant',
|
||||
'usage': {'prompt_tokens': 21181, 'completion_tokens': 129}}]}
|
||||
f = module.Filter()
|
||||
f.valves.profile_windows = '{"medium":160000}'
|
||||
statistics = '⬆︎ 63,001 · ⬇︎ 410 · ⏱ 1.9s · ⚡ 67.8 t/s'
|
||||
metadata = {'_athena_token_usage_status': statistics}
|
||||
await f.outlet(body, emit, metadata, {'id': 'medium'})
|
||||
description = events[-1]['data']['description']
|
||||
self.assertTrue(description.startswith(statistics + ' │ '))
|
||||
self.assertIn('21.310 / 160.000', description)
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,103 @@
|
||||
# EFA-Abfragen für OpenWebUI
|
||||
|
||||
`efa_bahn.py` fragt öffentliche EFA-GET-Endpunkte ab. Kein zusätzlicher MCP,
|
||||
kein API-Key, keine Drittbibliotheken. Python **3.10 oder neuer** und die
|
||||
Zeitzonendaten für Europe/Berlin sind erforderlich.
|
||||
|
||||
## Installation
|
||||
|
||||
`efa_bahn.py` in den persistenten Benutzerbereich des Open-Terminal-Containers
|
||||
kopieren, zum Beispiel `/home/user/Skripte/efa_bahn.py`. Prüfen, dass dieser Pfad auf ein
|
||||
persistentes Volume zeigt; die Container-Schreibschicht überlebt einen Neubau
|
||||
nicht. Anschließend `SKILL.md` als **nativen OpenWebUI-Skill** speichern. Bei einem
|
||||
anderen Skriptpfad die Aufrufe im Skill entsprechend anpassen.
|
||||
|
||||
Keine Dienste neu starten. Der Workspace muss für Chat/Automatismus verfügbar
|
||||
sein. Das Skript verändert keine Konten, Notizen oder Container.
|
||||
|
||||
```sh
|
||||
python3 /home/user/Skripte/efa_bahn.py journeys --origin Rastatt --destination 'Karlsruhe Hbf' --date tomorrow --time 05:15 --regional-only
|
||||
python3 /home/user/Skripte/efa_bahn.py departures --station 'Karlsruhe Hbf' --date today --time 14:30 --limit 20
|
||||
python3 /home/user/Skripte/efa_bahn.py alerts --query Karlsruhe --date today
|
||||
python3 /home/user/Skripte/efa_bahn.py stops --query 'Hannover Hauptbahnhof'
|
||||
```
|
||||
|
||||
Standardausgabe ist weiterhin JSON. Mit `--format text` nach dem Unterbefehl
|
||||
liefert das Skript kompakte deutsche Fakten für kleine Modelle: korrekt berechneter
|
||||
Wochentag, Fahrtdauer, Umstiege, Sollzeiten, bestätigte Prognosen und Gleisänderungen.
|
||||
Es führt dafür keine zusätzlichen Netzabfragen aus. Der Skill nutzt diese Ausgabe.
|
||||
Beispiel: `python3 /home/user/Skripte/efa_bahn.py journeys --origin Rastatt --destination Karlsruhe --date tomorrow --time 05:20 --format text`.
|
||||
Keine Meldung gefunden wird ausdrücklich nicht als Entwarnung dargestellt.
|
||||
`ok=false` und Exitcode 1 bedeuten einen Fehler.
|
||||
Für eine gezielte Echtzeitprüfung bei `departures` die gefundene Zugnummer mit
|
||||
`--train 4700` übergeben; der Filter wird vor der Ausgabebegrenzung angewendet.
|
||||
Leere Ergebnislisten sind keine Garantie, dass keine Fahrten/Störungen existieren.
|
||||
Ungültige CLI-Argumente melden argparse-Fehler mit Exitcode 2.
|
||||
|
||||
## Daten und Grenzen
|
||||
|
||||
- Quelle: https://www.efa.de/efa/; dokumentierte GET-Schnittstellen:
|
||||
https://mobidata-bw.de/daten/portal/efa-json/EFA_JSON_API_Training_EN_2.9.pdf
|
||||
- Verbindungen: `XML_TRIP_REQUEST2`; Bahnhofssuche: `XML_STOPFINDER_REQUEST`;
|
||||
Abfahrten: `XML_DM_REQUEST`; Meldungen: `XML_ADDINFO_REQUEST`.
|
||||
- Bekannt getestete IDs für Rastatt und Karlsruhe Hbf sind vorbelegt. Andere
|
||||
mehrdeutige Stationen müssen explizit per ID gewählt werden.
|
||||
- Ein bloßer Städtename bedeutet bei der Bahnabfrage den Hauptbahnhof. Kommas
|
||||
im EFA-Stationsnamen werden beim Vergleich normalisiert; Zusätze wie Süd oder
|
||||
Vorplatz bleiben relevant. Bei mehreren gleichwertigen Treffern keine stille Wahl.
|
||||
- STOPFINDER kann BROKER/-8011 und dennoch gültige `locations` liefern (am
|
||||
08.10.2026 für Mannheim bestätigt). Ausschließlich dieser Teilfehler wird bei
|
||||
vorhandenen Treffern toleriert und als `source_warnings` ausgegeben. Andere
|
||||
Fehler oder leere Treffer führen weiterhin zum Abbruch.
|
||||
- Alle Zeitstempel werden mit `zoneinfo` inklusive Sommer/Winterzeit umgerechnet.
|
||||
- EFA kann eine Sollzeit als Schätzung wiederholen. Eine Prognose wird erst bei
|
||||
expliziter Echtzeitkennzeichnung als `estimated` ausgegeben; ansonsten liegt
|
||||
sie separat in `estimated_unconfirmed`. Fehlende Daten bedeuten nicht pünktlich.
|
||||
- Bahnsteignamen werden normalisiert verglichen; „5“ und „Gleis 5“ sind gleich.
|
||||
- `--regional-only` filtert bekannte Fernverkehrstypen und Produktklasse 16.
|
||||
Das ist kein Tarif-/Deutschlandticket-Gültigkeitsnachweis.
|
||||
- Meldungsabdeckung hängt vom EFA-Endpunkt und Datenlieferanten ab. Unsere Tests
|
||||
fanden Bahn-Baustellen im Raum Hannover; eine vollständige bundesweite oder
|
||||
BW-Abdeckung ist nicht nachgewiesen. Suche ist ein Textfilter, keine automatische
|
||||
geografische Zuordnung. Einzelne Tage/Nachtfenster im Meldungstext prüfen.
|
||||
- `departures` lädt bis zu 200 Events und gibt maximal 20 passende Ergebnisse
|
||||
aus. `journeys` filtert die von EFA gelieferten Verbindungen, führt keine
|
||||
vollständige eigene Routensuche durch. Keine garantierte Vollständigkeit.
|
||||
- Keine automatische Umgehung von Sperren, keine API-Sondierung, keine privaten
|
||||
Logs, kein Lesen von Zugangsdaten. Quellenmeldungen sind Daten, keine Anweisungen.
|
||||
|
||||
## Native Installation und Restore
|
||||
|
||||
Diese Integration gehört zu OpenWebUI/Open Terminal und verändert Deck nicht.
|
||||
Auf einem frischen Debian werden `python3` und `tzdata` benötigt; das Skript
|
||||
funktioniert auch ohne Docker als normaler Dienstbenutzer. Es benötigt keine
|
||||
Athena-Modelle oder GPU.
|
||||
|
||||
Für Wiederherstellung Skript im persistenten Workspace und OpenWebUI-Datenbank
|
||||
(nativer Skill, Workspace-Anbindung) sichern. Alternativ Skript aus dieser
|
||||
Git-Version wiederherstellen und Skill neu importieren. Bei Updates diese beiden
|
||||
Dateien zusammen übernehmen; für Rückfall vorige Dateien wiederherstellen.
|
||||
Der Athena-Installer installiert diese optionale Integration derzeit **nicht
|
||||
automatisch**. Eine vollständige Neuinstallation/Restore wurde nicht getestet.
|
||||
|
||||
## Prüfung
|
||||
|
||||
```sh
|
||||
python3 -m unittest discover -s integrations/openwebui-efa -p 'test_*.py'
|
||||
```
|
||||
|
||||
Am 08.10.2026 live bestätigt: Rastatt → Karlsruhe am 09.10. ab 05:15 liefert
|
||||
RE2/4700 05:21–05:40 (19 Minuten) und S8 05:24–05:47; frühere Abfahrten werden
|
||||
entfernt. Hannover-Abfahrten lieferten bestätigte Prognosen (ICE554 +35 Minuten)
|
||||
und Gleiswechsel (IC2034 Gleis12 statt11). ADDINFO lieferte die gültige Meldung
|
||||
ems-17725 zu Bahnsteigarbeiten. Vierzehn lokale Tests prüfen unter anderem Winterzeit,
|
||||
Sollzeit-Fallback, Ausfall, Gleisvergleich, Mehrdeutigkeit und Meldungsgültigkeit.
|
||||
Ein weiterer Lauf direkt im vorhandenen Unraid-Python (ohne Installation) bestätigte
|
||||
IC2048 Mannheim 19:23 als `cancelled=true` mit `DEPARTURE_CANCELLED`; dabei wurde
|
||||
auch der Filter `--train 2048` geprüft. Der konkrete Open-Terminal-Container wurde
|
||||
nicht verändert; dessen persistenter Zielpfad ist vor der Installation zu prüfen.
|
||||
Keine Tests senden E-Mails oder ändern Systeme.
|
||||
|
||||
Kompakte Textausgabe am 08.10.2026 live für Rastatt → Karlsruhe am 09.10.
|
||||
ab 05:20 geprüft: Freitag, RE2/4700 05:21–05:40 und S8 05:24–05:47
|
||||
mit erhaltenem Zielzusatz Vorplatz. Keine zusätzlichen Quellenabfragen.
|
||||
@@ -0,0 +1,46 @@
|
||||
---
|
||||
name: efa-bahn
|
||||
description: Bahnverbindungen, Abfahrten, Ausfälle, Verspätungen, Gleisänderungen und Baustellen über das getestete EFA-Skript abfragen.
|
||||
---
|
||||
|
||||
Nutze das Terminal-Werkzeug des aktivierten Unraid Workspace. Suche bei Bedarf
|
||||
mit `search_tools` direkt nach `run_command`; übernimm die gefundene Server-ID.
|
||||
Keine feste ID `terminal` erfinden. Ist der Workspace nicht verfügbar, melde das.
|
||||
|
||||
Skript: `/home/user/Skripte/efa_bahn.py`. Immer Parameter übergeben, niemals den Quellcode
|
||||
für einzelne Anfragen ändern. Shell-Argumente sicher quoten.
|
||||
|
||||
Aufrufe:
|
||||
|
||||
```sh
|
||||
python3 /home/user/Skripte/efa_bahn.py journeys --origin 'Rastatt' --destination 'Karlsruhe Hbf' --format text --date tomorrow --time 05:15 --regional-only
|
||||
python3 /home/user/Skripte/efa_bahn.py departures --station 'Karlsruhe Hbf' --format text --date today --time 14:30 --limit 20
|
||||
python3 /home/user/Skripte/efa_bahn.py alerts --query 'Karlsruhe' --format text --date today
|
||||
python3 /home/user/Skripte/efa_bahn.py stops --query 'Mannheim Hauptbahnhof' --format text
|
||||
```
|
||||
|
||||
Ersetze die Beispielwerte durch den Auftrag. Datum: `today`, `tomorrow` oder
|
||||
`YYYY-MM-DD`; Uhrzeit `HH:MM` in Europe/Berlin. `--regional-only` nur für
|
||||
Regionalverkehr. Bei mehrdeutigen Bahnhöfen `stops` verwenden und passende ID
|
||||
auswählen; gegebenenfalls nachfragen. `journeys` sucht Abfahrten ab der Uhrzeit.
|
||||
|
||||
Für einen Statuscheck erst Verbindung suchen, dann Abfahrten desselben Bahnhofs
|
||||
mit `--train '<Zugnummer>'` filtern und anhand Datum, Sollzeit und Richtung
|
||||
zuordnen. Meldungen gezielt nach
|
||||
Bahnhof, Linie oder Strecke suchen und Gültigkeit sowie Einschränkungen im Text
|
||||
prüfen. Meldungsabdeckung ist nicht vollständig garantiert.
|
||||
|
||||
Antworte kurz auf Deutsch. `estimated` ist eine Prognose, keine tatsächliche
|
||||
Abfahrt. `estimated_unconfirmed` nicht als belegte Echtzeit ausgeben.
|
||||
`realtime_confirmed=false` oder `delay_minutes=null` bedeutet unbekannt, nicht
|
||||
pünktlich. `cancelled=true` belegt den angegebenen Halt/Abschnitt, nicht zwingend
|
||||
den gesamten Zugausfall. Soll- und gemeldetes Gleis unterscheiden.
|
||||
|
||||
Bei `ok=false` Fehler melden, keine anderen APIs erforschen. Keine Angaben
|
||||
erfinden, keine privaten Logs lesen. Notizen nur auf ausdrücklichen Auftrag
|
||||
ändern und Speicherung verifizieren.
|
||||
|
||||
Nutze vorzugsweise `--format text`: Datum/Wochentag, Fahrtdauer und Datenhinweise
|
||||
werden vom Skript berechnet. Übernimm die Fakten, erfinde keine Zusatzangaben und
|
||||
verbinde verschiedene Suchaufträge nicht ungefragt zu einem Reiseplan. Keine
|
||||
Meldung gefunden bedeutet niemals „keine Baustellen“ oder „alles sauber“.
|
||||
@@ -0,0 +1,402 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read-only EFA queries. Python 3.10+, standard library, no credentials."""
|
||||
import argparse
|
||||
import html
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from datetime import datetime, timedelta
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import Request, urlopen
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
BASE = "https://www.efa.de/efa/"
|
||||
BERLIN = ZoneInfo("Europe/Berlin")
|
||||
KNOWN = {"rastatt": "de:08216:1844", "rastatt bahnhof": "de:08216:1844",
|
||||
"karlsruhe": "de:08212:90", "karlsruhe hbf": "de:08212:90", "karlsruhe hauptbahnhof": "de:08212:90"}
|
||||
REQUEST_WARNINGS = []
|
||||
|
||||
|
||||
class EfaError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def clean(value):
|
||||
return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]*>", " ", str(value or "")))).strip()
|
||||
|
||||
|
||||
def iso(value):
|
||||
if not value:
|
||||
return None
|
||||
try:
|
||||
dt = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
return dt.astimezone(BERLIN) if dt.tzinfo else None
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
def local(value):
|
||||
dt = iso(value)
|
||||
return dt.isoformat() if dt else None
|
||||
|
||||
|
||||
def request(endpoint, params):
|
||||
params = dict(params, outputFormat="rapidJSON", language="de")
|
||||
url = BASE + endpoint + "?" + urlencode(params)
|
||||
req = Request(url, headers={"Accept": "application/json", "User-Agent": "efa-bahn/1.0"})
|
||||
try:
|
||||
with urlopen(req, timeout=30) as response:
|
||||
body = response.read(8 * 1024 * 1024 + 1)
|
||||
if len(body) > 8 * 1024 * 1024:
|
||||
raise EfaError("EFA-Antwort zu gross; Anfrage eingrenzen.")
|
||||
data = json.loads(body)
|
||||
except HTTPError as exc:
|
||||
raise EfaError(f"EFA HTTP {exc.code}: {url}") from exc
|
||||
except (URLError, TimeoutError, OSError, ValueError) as exc:
|
||||
raise EfaError(f"EFA-Anfrage fehlgeschlagen: {exc}; URL: {url}") from exc
|
||||
if not isinstance(data, dict):
|
||||
raise EfaError("Unerwartetes EFA-Antwortformat.")
|
||||
errors = [m for m in data.get("systemMessages", [])
|
||||
if isinstance(m, dict) and str(m.get("type", "")).lower() in ("error", "fatal")]
|
||||
if errors:
|
||||
# A failed broker sub-provider can coexist with valid stop results.
|
||||
# Only tolerate the observed STOPFINDER/-8011 case, never general errors.
|
||||
partial = (endpoint == "XML_STOPFINDER_REQUEST" and data.get("locations")
|
||||
and all(m.get("module") == "BROKER" and str(m.get("code")) == "-8011" for m in errors))
|
||||
if partial:
|
||||
REQUEST_WARNINGS.append({"endpoint": endpoint, "messages": errors,
|
||||
"note": "Partial station-search response; usable locations returned, search may be incomplete."})
|
||||
else:
|
||||
raise EfaError("EFA systemMessages: " + json.dumps(errors, ensure_ascii=False))
|
||||
return data
|
||||
|
||||
|
||||
def stops(name):
|
||||
data = request("XML_STOPFINDER_REQUEST", {"commonMacro": "stopfinder", "type_sf": "stop", "name_sf": name})
|
||||
return [{"id": x.get("id"), "name": x.get("name"),
|
||||
"place": (x.get("parent") or {}).get("name"), "is_best": x.get("isBest", False)}
|
||||
for x in data.get("locations", []) if x.get("id")]
|
||||
|
||||
|
||||
def station(name):
|
||||
if name.lower() in KNOWN:
|
||||
return {"id": KNOWN[name.lower()], "name": name}
|
||||
if name.startswith("de:") or name.isdigit():
|
||||
return {"id": name, "name": name}
|
||||
# For a train request a bare city means its main station. Preserve explicit
|
||||
# station names; never silently pick a forecourt or a different station.
|
||||
query = name if re.search(r"\b(hbf|hauptbahnhof|bahnhof|bf)\b", name, re.I) else name + " Hauptbahnhof"
|
||||
query = re.sub(r"\bhbf\b", "Hauptbahnhof", query, flags=re.I)
|
||||
options = stops(query)
|
||||
if not options:
|
||||
raise EfaError(f"Bahnhof nicht gefunden: {name}")
|
||||
normalize = lambda s: re.sub(r"\s+", " ", re.sub(r"[,()]", " ", str(s))).strip().casefold()
|
||||
exact = [x for x in options if normalize(x["name"]) == normalize(query)]
|
||||
if len(exact) == 1:
|
||||
return exact[0]
|
||||
if len(options) == 1:
|
||||
return options[0]
|
||||
# Do not silently choose a forecourt, underground station or another locality.
|
||||
raise EfaError("Bahnhof mehrdeutig; passende ID mit 'stops' ermitteln: "
|
||||
+ json.dumps(options[:10], ensure_ascii=False))
|
||||
|
||||
|
||||
def messages(items):
|
||||
result = []
|
||||
for item in items or []:
|
||||
links = item.get("infoLinks") or []
|
||||
if not links:
|
||||
links = [{"title": item.get("title"), "content": item.get("content")}]
|
||||
for link in links:
|
||||
result.append({"id": item.get("id"), "title": clean(link.get("title") or link.get("urlText")),
|
||||
"text": clean(link.get("content")), "url": link.get("url"),
|
||||
"validity": (item.get("timestamps") or {}).get("validity", []),
|
||||
"additional_links": link.get("additionalLinks", [])})
|
||||
return result
|
||||
|
||||
|
||||
def normalized_platform(value):
|
||||
return re.sub(r"^(gleis|bstg\.?|bahnsteig|platform|track)\s*", "", str(value or "").strip(), flags=re.I).casefold()
|
||||
|
||||
|
||||
def status(raw, point, prefix):
|
||||
props = point.get("properties") or {}
|
||||
statuses = list(raw.get("realtimeStatus") or []) + list(props.get("realtimeStatus") or [])
|
||||
cancelled = raw.get("isCancelled")
|
||||
point_cancel = "DEPARTURE_CANCELLED" if prefix == "departure" else "ARRIVAL_CANCELLED"
|
||||
if point_cancel in statuses or point.get("isCancelled") is True:
|
||||
cancelled = True
|
||||
planned = point.get(prefix + "TimePlanned")
|
||||
estimated = point.get(prefix + "TimeEstimated")
|
||||
p, e = iso(planned), iso(estimated)
|
||||
monitored = raw.get("isRealtimeControlled", point.get("isRealtimeControlled"))
|
||||
realtime_confirmed = monitored is True or "MONITORED" in statuses
|
||||
# EFA may copy tomorrow's scheduled time into the estimated field. Do not
|
||||
# turn that fallback into an assertion of punctuality.
|
||||
delay = round((e - p).total_seconds() / 60) if p and e and realtime_confirmed else None
|
||||
reported = props.get("platformName")
|
||||
scheduled = props.get("plannedPlatformName")
|
||||
different = bool(reported and scheduled and normalized_platform(reported) != normalized_platform(scheduled))
|
||||
flag = (raw.get("properties") or {}).get("platformChange") == "changed"
|
||||
return {"planned": local(planned), "estimated": local(estimated) if realtime_confirmed else None,
|
||||
"estimated_unconfirmed": local(estimated) if not realtime_confirmed else None,
|
||||
"delay_minutes": delay, "realtime_confirmed": realtime_confirmed,
|
||||
"is_realtime_controlled": monitored,
|
||||
"cancelled": cancelled if isinstance(cancelled, bool) else None,
|
||||
"cancellation_scope": "this_stop_or_departure" if cancelled is True else None,
|
||||
"platform_planned": scheduled, "platform_reported": reported,
|
||||
"platform_changed": True if different or flag else (False if reported and scheduled else None),
|
||||
"realtime_status": statuses}
|
||||
|
||||
|
||||
def transport(raw):
|
||||
t = raw.get("transportation") or {}
|
||||
props = t.get("properties") or {}
|
||||
return {"name": t.get("name"), "line": t.get("number"),
|
||||
"train_type": props.get("trainType"), "train_number": props.get("trainNumber"),
|
||||
"direction": (t.get("destination") or {}).get("name"),
|
||||
"product": (t.get("product") or {}).get("name")}
|
||||
|
||||
|
||||
def board(stop, when, limit=10, train=None):
|
||||
data = request("XML_DM_REQUEST", {"commonMacro": "dm", "type_dm": "any", "name_dm": stop["id"],
|
||||
"mode": "direct", "useRealtime": 1, "limit": 200,
|
||||
"itdDate": when.strftime("%Y%m%d"), "itdTime": when.strftime("%H%M")})
|
||||
result = []
|
||||
for event in data.get("stopEvents", []):
|
||||
info = transport(event)
|
||||
if train and re.sub(r"\s+", "", train).casefold() not in {
|
||||
re.sub(r"\s+", "", str(info.get(k) or "")).casefold()
|
||||
for k in ("train_number", "line", "name")}:
|
||||
continue
|
||||
planned = iso(event.get("departureTimePlanned"))
|
||||
if not planned or planned < when:
|
||||
continue
|
||||
point = dict(event.get("location") or {})
|
||||
point.update({k: v for k, v in event.items() if k.startswith("departureTime")})
|
||||
result.append(dict(info, station=point.get("name"),
|
||||
departure=status(event, point, "departure"),
|
||||
hints=[clean(h.get("content")) for h in event.get("hints", [])],
|
||||
messages=messages(event.get("infos"))))
|
||||
result.sort(key=lambda x: x["departure"]["planned"])
|
||||
return result[:limit]
|
||||
|
||||
|
||||
def journeys(origin, destination, when, limit, regional):
|
||||
data = request("XML_TRIP_REQUEST2", {"commonMacro": "trip", "type_origin": "any", "name_origin": origin["id"],
|
||||
"type_destination": "any", "name_destination": destination["id"],
|
||||
"itdDate": when.strftime("%Y%m%d"), "itdTime": when.strftime("%H%M"),
|
||||
"itdTripDateTimeDepArr": "dep", "useRealtime": 1})
|
||||
result = []
|
||||
for journey in data.get("journeys", []):
|
||||
raw_legs = journey.get("legs") or []
|
||||
if not raw_legs:
|
||||
continue
|
||||
legs = []
|
||||
for leg in raw_legs:
|
||||
start, end = leg.get("origin") or {}, leg.get("destination") or {}
|
||||
legs.append(dict(transport(leg), origin=start.get("name"), destination=end.get("name"),
|
||||
departure=status(leg, start, "departure"), arrival=status(leg, end, "arrival"),
|
||||
hints=[clean(h.get("content")) for h in leg.get("hints", [])],
|
||||
messages=messages(leg.get("infos"))))
|
||||
# Walking legs may have no train type. Inspect every motorised leg.
|
||||
if regional and any(((x["train_type"] or "").upper() in {"ICE", "IC", "EC", "ECE", "TGV", "RJ", "RJX", "NJ", "EN", "FLX"}
|
||||
and not re.match(r"^(RE|RB|S)\s*\d", str(x["line"] or ""), re.I))
|
||||
or (r.get("transportation") or {}).get("product", {}).get("class") == 16
|
||||
for x, r in zip(legs, raw_legs)):
|
||||
continue
|
||||
dep = iso(legs[0]["departure"]["planned"])
|
||||
arr = iso(legs[-1]["arrival"]["planned"])
|
||||
if not dep or dep < when or not arr or arr < dep:
|
||||
continue
|
||||
result.append({"departure_planned": dep.isoformat(), "arrival_planned": arr.isoformat(),
|
||||
"duration_minutes": round((arr - dep).total_seconds() / 60),
|
||||
"interchanges": journey.get("interchanges"), "legs": legs,
|
||||
"messages": messages(journey.get("infos"))})
|
||||
result.sort(key=lambda x: x["departure_planned"])
|
||||
return result[:limit]
|
||||
|
||||
|
||||
def alerts(query, when, limit):
|
||||
data = request("XML_ADDINFO_REQUEST", {"commonMacro": "addinfo", "filterPublicationStatus": "current"})
|
||||
info = data.get("infos") or {}
|
||||
if not isinstance(info, dict):
|
||||
raise EfaError("Unerwartetes EFA-Meldungsformat.")
|
||||
result = []
|
||||
for item in info.get("current", []):
|
||||
affected = item.get("affected") or {}
|
||||
# Exclude metadata and IDs from free-text matching.
|
||||
searchable = " ".join([clean(x.get("title")) + " " + clean(x.get("content")) for x in item.get("infoLinks", [])]
|
||||
+ [clean(x.get("name")) for x in affected.get("lines", []) + affected.get("stops", [])])
|
||||
if query.casefold() not in searchable.casefold():
|
||||
continue
|
||||
periods = (item.get("timestamps") or {}).get("validity") or []
|
||||
relevant = not periods or any((not iso(p.get("from")) or iso(p.get("from")) <= when)
|
||||
and (not iso(p.get("to")) or iso(p.get("to")) >= when) for p in periods)
|
||||
if not relevant:
|
||||
continue
|
||||
result.append({"id": item.get("id"), "messages": messages([item]),
|
||||
"affected_lines": [{"name": x.get("name"), "id": x.get("id")} for x in affected.get("lines", [])],
|
||||
"affected_stops": [{"name": x.get("name"), "id": x.get("id")} for x in affected.get("stops", [])]})
|
||||
return {"matches": result[:limit], "matching_count": len(result),
|
||||
"coverage": "Only messages published by this EFA endpoint. Text may specify additional dates/times."}
|
||||
|
||||
|
||||
def when_from(args):
|
||||
now = datetime.now(BERLIN)
|
||||
day = now.date() if args.date == "today" else ((now + timedelta(days=1)).date() if args.date == "tomorrow"
|
||||
else datetime.strptime(args.date, "%Y-%m-%d").date())
|
||||
clock = datetime.strptime(args.time or now.strftime("%H:%M"), "%H:%M").time()
|
||||
return datetime.combine(day, clock, BERLIN)
|
||||
|
||||
|
||||
WEEKDAYS = ("Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sonntag")
|
||||
|
||||
|
||||
def date_label(value):
|
||||
dt = iso(value)
|
||||
return f"{WEEKDAYS[dt.weekday()]}, {dt:%d.%m.%Y}" if dt else "Datum unbekannt"
|
||||
|
||||
|
||||
def time_label(value):
|
||||
dt = iso(value)
|
||||
return dt.strftime("%H:%M") if dt else "unbekannt"
|
||||
|
||||
|
||||
def status_text(value):
|
||||
parts = []
|
||||
if value.get("cancelled") is True:
|
||||
parts.append("AUSFALL an diesem Halt/Abschnitt")
|
||||
if value.get("estimated"):
|
||||
parts.append("Prognose " + time_label(value["estimated"]))
|
||||
if value.get("delay_minutes") is not None:
|
||||
parts.append(f"Verspätung {value['delay_minutes']:+d} Min.")
|
||||
if value.get("platform_changed"):
|
||||
parts.append(f"Gleisänderung: gemeldet {value.get('platform_reported') or 'unbekannt'}, "
|
||||
f"geplant {value.get('platform_planned') or 'unbekannt'}")
|
||||
else:
|
||||
platform = value.get("platform_planned") or value.get("platform_reported")
|
||||
if platform:
|
||||
label = str(platform) if re.match(r"^gleis\b", str(platform), re.I) else f"Gleis {platform}"
|
||||
parts.append(f"{label} ({'geplant' if value.get('platform_planned') else 'gemeldet'})")
|
||||
if not value.get("realtime_confirmed"):
|
||||
parts.append("keine bestätigten Echtzeitdaten")
|
||||
return "; ".join(parts)
|
||||
|
||||
|
||||
def message_lines(items):
|
||||
return ["Meldung: " + ": ".join(str(m[k]) for k in ("title", "text") if m.get(k))
|
||||
for m in items or []]
|
||||
|
||||
|
||||
def render_text(output):
|
||||
"""Deterministic facts for small models; no additional network calls."""
|
||||
if not output["ok"]:
|
||||
return "EFA-Abfrage fehlgeschlagen: " + output["error"]
|
||||
lines = ["Quelle: EFA | Abfrage: " + str(output["queried_at"])]
|
||||
if output.get("requested_from"):
|
||||
lines.append("Gesucht ab: " + date_label(output["requested_from"]) + " "
|
||||
+ time_label(output["requested_from"]) + " (Europe/Berlin)")
|
||||
if "journeys" in output:
|
||||
if not output["journeys"]:
|
||||
lines.append("Keine passende Verbindung in den gelieferten Ergebnissen gefunden.")
|
||||
for i, journey in enumerate(output["journeys"], 1):
|
||||
transfers = journey.get("interchanges")
|
||||
lines.append(f"Verbindung {i}: {time_label(journey['departure_planned'])} → "
|
||||
f"{time_label(journey['arrival_planned'])}, {journey['duration_minutes']} Min., "
|
||||
+ (f"{transfers} Umstiege" if transfers is not None else "Umstiege unbekannt"))
|
||||
for leg in journey["legs"]:
|
||||
name = leg.get("name") or leg.get("line") or leg.get("product") or "Abschnitt"
|
||||
number = leg.get("train_number")
|
||||
lines.append(f" {name}" + (f" (Zug {number})" if number else "")
|
||||
+ (f", Richtung {leg['direction']}" if leg.get("direction") else ""))
|
||||
lines.append(f" {leg['origin']} {time_label(leg['departure']['planned'])} → "
|
||||
f"{leg['destination']} {time_label(leg['arrival']['planned'])} (Fahrplan)")
|
||||
lines.append(" Abfahrt: " + status_text(leg["departure"]))
|
||||
lines.append(" Ankunft: " + status_text(leg["arrival"]))
|
||||
lines.extend(" " + line for line in message_lines(leg.get("messages")))
|
||||
lines.extend(" Hinweis: " + h for h in leg.get("hints", []) if h)
|
||||
lines.extend(message_lines(journey.get("messages")))
|
||||
if "departures" in output:
|
||||
if not output["departures"]:
|
||||
lines.append("Keine passende Abfahrt in den gelieferten Ergebnissen gefunden.")
|
||||
for event in output["departures"]:
|
||||
lines.append(f"{event.get('name') or event.get('line') or 'Zug'} "
|
||||
f"(Zug {event.get('train_number') or 'unbekannt'}), "
|
||||
f"Richtung {event.get('direction') or 'unbekannt'}: "
|
||||
f"{time_label(event['departure']['planned'])} (Fahrplan); "
|
||||
+ status_text(event["departure"]))
|
||||
lines.extend(message_lines(event.get("messages")))
|
||||
lines.extend("Hinweis: " + h for h in event.get("hints", []) if h)
|
||||
if "stops" in output:
|
||||
lines.extend(f"{x['id']}: {x['name']}" for x in output["stops"])
|
||||
if not output["stops"]:
|
||||
lines.append("Keine Bahnhofstreffer gefunden.")
|
||||
if "alerts" in output:
|
||||
found = output["alerts"]
|
||||
lines.append(f"Passende Meldungen: {found['matching_count']} (angezeigt: {len(found['matches'])})")
|
||||
for item in found["matches"]:
|
||||
lines.extend(message_lines(item["messages"]))
|
||||
for m in item["messages"]:
|
||||
if m.get("validity"):
|
||||
lines.append("Gültigkeitszeiträume: " + json.dumps(m["validity"], ensure_ascii=False))
|
||||
if m.get("url"):
|
||||
lines.append("Link: " + m["url"])
|
||||
lines.append("Meldungsabdeckung unvollständig/unbestätigt. Keine Treffer schließen Baustellen oder Störungen NICHT aus. Zeitfenster im Meldungstext prüfen.")
|
||||
if output.get("source_warnings"):
|
||||
lines.append("Quellenhinweis: Stationssuche lieferte gültige Treffer mit Teilfehler; Trefferliste möglicherweise unvollständig.")
|
||||
lines.append("Fehlende Echtzeitdaten bedeuten nicht pünktlich, verkehrend oder störungsfrei. Keine zusätzlichen Angaben zu Tickets oder Fahrradmitnahme ableiten.")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
p = sub.add_parser("stops", help="Resolve station names; choose an ID if ambiguous")
|
||||
p.add_argument("--query", required=True)
|
||||
p.add_argument("--format", choices=("json", "text"), default="json")
|
||||
for name in ("departures", "journeys", "alerts"):
|
||||
p = sub.add_parser(name)
|
||||
p.add_argument("--format", choices=("json", "text"), default="json")
|
||||
p.add_argument("--date", default="today", help="today, tomorrow, YYYY-MM-DD")
|
||||
p.add_argument("--time", help="Europe/Berlin HH:MM; default current local time")
|
||||
p.add_argument("--limit", type=int, choices=range(1, 21), default=5, metavar="1..20")
|
||||
if name == "departures":
|
||||
p.add_argument("--station", required=True)
|
||||
p.add_argument("--train", help="Optional exact train number or line, e.g. 4700 or RE2")
|
||||
elif name == "journeys":
|
||||
p.add_argument("--origin", required=True)
|
||||
p.add_argument("--destination", required=True)
|
||||
p.add_argument("--regional-only", action="store_true")
|
||||
else:
|
||||
p.add_argument("--query", required=True, help="Station, line or route fragment")
|
||||
args = parser.parse_args()
|
||||
output = {"ok": True, "source": BASE, "queried_at": datetime.now(BERLIN).isoformat(),
|
||||
"warning": "Missing realtime data does not mean punctual, operating or disruption-free."}
|
||||
try:
|
||||
if args.command == "stops":
|
||||
output["stops"] = stops(args.query)
|
||||
else:
|
||||
when = when_from(args)
|
||||
output["requested_from"] = when.isoformat()
|
||||
output["requested_date_label"] = date_label(when.isoformat())
|
||||
if args.command == "departures":
|
||||
stop = station(args.station)
|
||||
output.update(station=stop, departures=board(stop, when, args.limit, args.train))
|
||||
elif args.command == "journeys":
|
||||
origin, dest = station(args.origin), station(args.destination)
|
||||
output.update(origin=origin, destination=dest,
|
||||
journeys=journeys(origin, dest, when, args.limit, args.regional_only))
|
||||
else:
|
||||
output["alerts"] = alerts(args.query, when, args.limit)
|
||||
except (EfaError, ValueError) as exc:
|
||||
output.update(ok=False, error=str(exc))
|
||||
if REQUEST_WARNINGS:
|
||||
output["source_warnings"] = REQUEST_WARNINGS
|
||||
print(render_text(output) if args.format == "text" else json.dumps(output, ensure_ascii=False, indent=2))
|
||||
return 0 if output["ok"] else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,107 @@
|
||||
import unittest
|
||||
import io
|
||||
import json
|
||||
from datetime import datetime
|
||||
from unittest.mock import patch
|
||||
import efa_bahn as efa
|
||||
|
||||
|
||||
class EfaTests(unittest.TestCase):
|
||||
def test_summer_and_winter(self):
|
||||
self.assertEqual(efa.local('2026-10-08T15:00:00Z'), '2026-10-08T17:00:00+02:00')
|
||||
self.assertEqual(efa.local('2026-12-08T15:00:00Z'), '2026-12-08T16:00:00+01:00')
|
||||
|
||||
def test_schedule_fallback_not_live(self):
|
||||
point = {'departureTimePlanned': '2026-10-09T03:21:00Z',
|
||||
'departureTimeEstimated': '2026-10-09T03:21:00Z'}
|
||||
result = efa.status({}, point, 'departure')
|
||||
self.assertIsNone(result['estimated'])
|
||||
self.assertIsNone(result['delay_minutes'])
|
||||
self.assertIsNotNone(result['estimated_unconfirmed'])
|
||||
|
||||
def test_delay_and_platform_change(self):
|
||||
point = {'departureTimePlanned': '2026-10-08T15:22:00Z',
|
||||
'departureTimeEstimated': '2026-10-08T15:39:00Z',
|
||||
'properties': {'plannedPlatformName': '9', 'platformName': '10'}}
|
||||
result = efa.status({'isRealtimeControlled': True}, point, 'departure')
|
||||
self.assertEqual(result['delay_minutes'], 17)
|
||||
self.assertTrue(result['platform_changed'])
|
||||
|
||||
def test_platform_label_not_change(self):
|
||||
point = {'properties': {'platformName': 'Gleis 5', 'plannedPlatformName': '5'}}
|
||||
self.assertFalse(efa.status({}, point, 'departure')['platform_changed'])
|
||||
|
||||
def test_stop_cancellation_and_unknown(self):
|
||||
point = {'properties': {'realtimeStatus': ['DEPARTURE_CANCELLED']}}
|
||||
self.assertTrue(efa.status({}, point, 'departure')['cancelled'])
|
||||
self.assertIsNone(efa.status({}, {}, 'departure')['cancelled'])
|
||||
|
||||
def test_no_silent_ambiguous_station(self):
|
||||
with patch.object(efa, 'stops', return_value=[{'name': 'Hbf Vorplatz', 'id': '1'}, {'name': 'Hbf tief', 'id': '2'}]):
|
||||
with self.assertRaises(efa.EfaError):
|
||||
efa.station('Hbf')
|
||||
|
||||
def test_departure_cutoff_and_overnight_duration(self):
|
||||
def leg(dep, arr):
|
||||
return {'origin': {'departureTimePlanned': dep}, 'destination': {'arrivalTimePlanned': arr},
|
||||
'transportation': {'name': 'RE 2'}}
|
||||
data = {'journeys': [
|
||||
{'legs': [leg('2026-10-08T21:00:00Z', '2026-10-08T21:30:00Z')]},
|
||||
{'legs': [leg('2026-10-08T21:55:00Z', '2026-10-08T22:15:00Z')]},
|
||||
]}
|
||||
with patch.object(efa, 'request', return_value=data):
|
||||
result = efa.journeys({'id': '1'}, {'id': '2'}, datetime(2026, 10, 8, 23, 30, tzinfo=efa.BERLIN), 5, False)
|
||||
self.assertEqual(len(result), 1)
|
||||
self.assertEqual(result[0]['duration_minutes'], 20)
|
||||
|
||||
def test_alert_validity(self):
|
||||
future = {'infoLinks': [{'title': 'Bauarbeiten Hannover'}],
|
||||
'timestamps': {'validity': [{'from': '2026-10-10T03:00:00Z'}]}}
|
||||
current = {'infoLinks': [{'title': 'Bauarbeiten Hannover'}],
|
||||
'timestamps': {'validity': [{'from': '2026-10-01T03:00:00Z', 'to': '2026-10-12T03:00:00Z'}]}}
|
||||
with patch.object(efa, 'request', return_value={'infos': {'current': [future, current]}}):
|
||||
result = efa.alerts('Hannover', datetime(2026, 10, 8, 18, 0, tzinfo=efa.BERLIN), 5)
|
||||
self.assertEqual(result['matching_count'], 1)
|
||||
|
||||
def test_partial_broker_error_with_stations(self):
|
||||
data = {'systemMessages': [{'type': 'error', 'module': 'BROKER', 'code': -8011}],
|
||||
'locations': [{'id': 'de:08222:2417', 'name': 'Mannheim, Hauptbahnhof'}]}
|
||||
with patch.object(efa, 'urlopen', return_value=io.BytesIO(json.dumps(data).encode())):
|
||||
self.assertEqual(efa.request('XML_STOPFINDER_REQUEST', {})['locations'][0]['id'], 'de:08222:2417')
|
||||
data['locations'] = []
|
||||
with patch.object(efa, 'urlopen', return_value=io.BytesIO(json.dumps(data).encode())):
|
||||
with self.assertRaises(efa.EfaError):
|
||||
efa.request('XML_STOPFINDER_REQUEST', {})
|
||||
efa.REQUEST_WARNINGS.clear()
|
||||
|
||||
def test_city_main_station_without_forecourt(self):
|
||||
options = [{'name': 'Mannheim, Hauptbahnhof', 'id': '1'}, {'name': 'Mannheim, Lindenhof, MA Hauptbahnhof Süd', 'id': '2'}]
|
||||
with patch.object(efa, 'stops', return_value=options) as mock:
|
||||
self.assertEqual(efa.station('Mannheim')['id'], '1')
|
||||
mock.assert_called_once_with('Mannheim Hauptbahnhof')
|
||||
|
||||
def test_correct_weekday(self):
|
||||
self.assertEqual(efa.date_label('2026-10-09T05:21:00+02:00'), 'Freitag, 09.10.2026')
|
||||
|
||||
def test_empty_alerts_not_all_clear(self):
|
||||
text = efa.render_text({'ok': True, 'queried_at': 'now',
|
||||
'alerts': {'matching_count': 0, 'matches': []}})
|
||||
self.assertIn('NICHT aus', text)
|
||||
self.assertIn('unvollständig', text)
|
||||
|
||||
def test_text_keeps_unknown_realtime_and_platform_change(self):
|
||||
unknown = efa.status({}, {'departureTimePlanned': '2026-10-09T03:21:00Z',
|
||||
'departureTimeEstimated': '2026-10-09T03:21:00Z'}, 'departure')
|
||||
self.assertNotIn('Prognose', efa.status_text(unknown))
|
||||
self.assertIn('keine bestätigten Echtzeitdaten', efa.status_text(unknown))
|
||||
changed = efa.status({'isRealtimeControlled': True},
|
||||
{'properties': {'platformName': '10', 'plannedPlatformName': '9'}}, 'departure')
|
||||
self.assertIn('gemeldet 10, geplant 9', efa.status_text(changed))
|
||||
|
||||
def test_text_reports_error(self):
|
||||
self.assertEqual(efa.render_text({'ok': False, 'error': 'test'}),
|
||||
'EFA-Abfrage fehlgeschlagen: test')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,25 @@
|
||||
# Proper-People-Skill: kompakte Inventarprüfung
|
||||
|
||||
Am 11. Oktober 2026 wurde Abschnitt 7 des vorhandenen nativen OpenWebUI-Skills
|
||||
`proper-people` über `POST /api/v1/skills/id/proper-people/update` geändert und
|
||||
durch anschließendes `GET` bytegenau bestätigt. Name, Beschreibung, Metadaten
|
||||
und Aktivierungsstatus bleiben erhalten. Andere Abschnitte wurden nicht ersetzt.
|
||||
|
||||
Der korrigierte Abschnitt steht in [inventory-section.md](inventory-section.md).
|
||||
Die vollständige vorherige Skillfassung ist ausschließlich privat gesichert.
|
||||
Aktuelle vollständige Skillfassung SHA-256:
|
||||
`e0ba49aa06435a8bbd8b234f573366cbf1f1db9f76ed65e2fe85297857ad9d44`.
|
||||
|
||||
Inventare vor Ausgabe auf die Vergleichsfelder reduzieren; `detail=compact`
|
||||
nur verwenden, wenn das tatsächlich installierte MCP-Schema es unterstützt.
|
||||
Alternativ im Tool-Script filtern. Pagination und Bestandsrevision erhalten.
|
||||
Die automatische Übergabe beider Datenquellen in eine gemeinsame Ausführung
|
||||
vorher prüfen. Ohne diesen Weg unvollständigen Abgleich melden; keine Suche
|
||||
nach Zugangsdaten in Logs und keine Rekonstruktion großer Listen aus dem
|
||||
Modellgedächtnis. Kompakte Ausgabe löst nicht automatisch den Dateiübergang.
|
||||
|
||||
Keine MCP-Implementierung verändert, keine Medienaktion ausgeführt. Das
|
||||
Speichern ist geprüft; eine erneute vollständige Bestandsprüfung ist noch offen.
|
||||
Bei Restore den vollständigen nativen Skill über OpenWebUIs Datenbackup
|
||||
wiederherstellen. Dieses Dokument enthält nur die öffentliche Abschnittsänderung
|
||||
und ersetzt kein vollständiges OpenWebUI-Backup.
|
||||
@@ -0,0 +1,59 @@
|
||||
### 7. Bestandsprüfung („Was fehlt in Emby?") — Emby ist maßgeblich
|
||||
|
||||
Diese Prüfung ist **lesend**; keine Downloads, keine Löschungen, keine Bibliotheksänderungen ohne
|
||||
Auftrag des Nutzers.
|
||||
|
||||
1. **Maßgeblich ist die Emby-Episodenliste** der jeweiligen **Jahresstaffel** (`Staffel {JJJJ}`,
|
||||
`IndexNumber = JJJJ`). Der **Dateisystembestand ist eine separate Prüfung** und darf nicht
|
||||
stillschweigend mit dem Emby-Bestand gleichgesetzt werden — Emby kann Dateien kennen, die das
|
||||
Dateisystem nicht zeigt, und umgekehrt (Emby-Sicht ≠ Terminal-Container-Dateisystem ≠ Unraid-Host).
|
||||
Immer beide getrennt ausweisen und angeben, aus welcher Ebene die Zahl stammt.
|
||||
2. **Alle Videoformate zählen**, unabhängig von Groß-/Kleinschreibung: MKV, MP4, WEBM, AVI, MOV
|
||||
(und m4v/ts). **Keine ausschließlich auf `*.mp4` beschränkte Abfrage** — MKV-Bestände würden sonst
|
||||
als „fehlend" erscheinen. Verifizierter Anker: **Season 2022 = 18 Episoden, Season 2023 = 17
|
||||
Episoden, beide vollständig als MKV.** Diese dürfen bei einer Format- oder Inventarprüfung **nicht**
|
||||
als fehlend gemeldet werden.
|
||||
3. **Jahresstaffeln und echte Episodennummern benutzen** — keine fortlaufenden Staffelnummern.
|
||||
Zuordnung bevorzuge über **Serien-/TVDB-IDs** (TVDB 389212, Emby-Series-/Season-IDs). **Dateinamen
|
||||
sind nur geprüfter Rückfall**, nie Primärquelle: ein Dateiname kann eine falsche Nummer tragen
|
||||
(Nummer-Drift durch Shorts) oder einen umformulierten Titel.
|
||||
4. **Fehlende Folgen erst nach vollständigem Abgleich benennen.** Wenn eine Inventarliste
|
||||
unvollständig ist (Pagination nicht vollständig durchlaufen, TVDB-Seite leer, Staffelliste
|
||||
abgeschnitten, Emby-Timeout), gibt es **keine abschließende Fehlmenge** — dann ausdrücklich sagen,
|
||||
dass die Prüfung unvollständig ist und welche Staffel noch fehlt. Nie eine Zahl wie „es fehlen X"
|
||||
aus einer Teilmenge ableiten.
|
||||
5. **Abgleichrichtung klar machen:** TVDB/YouTube-Referenzliste (Soll) gegen Emby-Bestand (Ist).
|
||||
Lücken durch Shorts sind erwartet und keine „fehlenden" Folgen — aber nur, wenn der Short per
|
||||
Shorts-Tab-Video-ID bestätigt ist. Unklare Fälle kennzeichnen, nicht in die Fehlmenge rechnen.
|
||||
6. **Kontext sparsam halten:** Aktuelles Schema von `emby_series_inventory` prüfen.
|
||||
`detail="compact"` nur übergeben, wenn dieser Parameter tatsächlich verfügbar ist.
|
||||
Ansonsten innerhalb von `run_tool_script` abrufen und vor `print` auf
|
||||
`id`, `title`, `seasonNumber`, `episodeNumber`, `episodeNumberEnd`,
|
||||
`runtimeSeconds` reduzieren. Keine vollständigen Inventare mit Pfaden oder
|
||||
`mediaSources` ungefiltert in den Chat ausgeben. Gesamtzahl, `returned`,
|
||||
`hasMore`, `nextStart`, Serienidentität und `inventoryRevision` erhalten.
|
||||
Jede weitere Seite mit `expectedRevision` abrufen; bei Bestandsänderung neu beginnen.
|
||||
Seitenlimit und Sandbox-Aufruflimit aus dem aktuellen Schema beachten.
|
||||
Mehr kleine Seiten allein sparen keinen Kontext, wenn alle Rohdaten ausgegeben werden.
|
||||
7. **Datenfluss vor dem Abruf planen:** YouTube-Liste mit yt-dlp als Datei im
|
||||
Terminal erfassen; zusätzlich eine kompakte Liste aus ID, Titel und Laufzeit
|
||||
bilden. Beide Bestände müssen für einen programmatischen Vergleich in derselben
|
||||
Ausführungsumgebung verfügbar sein. Ein MCP-Ergebnis ist keine Terminal-Datei.
|
||||
Vorhandene geprüfte Export-/Dateiübergabe-Werkzeuge verwenden. Alternativ die
|
||||
kompakten Listen in der Werkzeug-Sandbox vergleichen, sofern sie dort tatsächlich
|
||||
verfügbar sind. Keine 278 Datensätze aus dem Gedächtnis rekonstruieren.
|
||||
Fehlt eine automatische Übergabe, den konkreten fehlenden Exportweg benennen
|
||||
und den Abgleich als unvollständig melden, statt Rohdaten erneut abzurufen.
|
||||
8. **Vergleich:** Identische bestätigte Video-/Provider-IDs bevorzugen; sonst
|
||||
normalisierte Titel vergleichen. Ähnliche Titel und Laufzeit nur als Kandidaten
|
||||
verwenden, nicht als eindeutigen Nachweis. Mehrdeutige Zuordnungen, doppelte
|
||||
Einträge und Referenzvideos ohne Episodencharakter getrennt ausweisen.
|
||||
Die Differenz zweier Gesamtzahlen beweist keine fehlende Folge.
|
||||
Nur Zusammenfassung, tatsächlich fehlende Videos und ungeklärte Kandidaten
|
||||
ausgeben; den vollständigen Vergleich intern programmgesteuert durchführen.
|
||||
9. **Keine Schlüsselsuche:** Für die Bestandsprüfung den funktionierenden
|
||||
Emby-MCP nutzen. Keine Zugangsdaten aus Logs, Chatverläufen oder beliebigen
|
||||
Dateien suchen oder ausgeben. Eine HTTP-API nur mit bereits eingerichtetem,
|
||||
autorisiertem Zugang verwenden; fehlender Datei-Export rechtfertigt keinen
|
||||
Wechsel zur Credential-Suche. Kein Refresh, Download oder Bibliotheksumbau
|
||||
während einer ausschließlich lesenden Bestandsprüfung.
|
||||
@@ -100,3 +100,27 @@ Verifiziert: 32 Zuordnungen im unveränderten Selector, 32 Provider-Payloads
|
||||
Diese Prüfung benötigt keine Inferenz und belegt die Parameterweitergabe,
|
||||
keine feste Denkzeit oder Tokenzahl. Ein neuer Live-A/B-Modelllauf wurde wegen
|
||||
der laufenden Benutzeranfrage bewusst nicht ausgeführt.
|
||||
|
||||
## Read-only-Prüfung am 12. Oktober 2026
|
||||
|
||||
Aktuelle Registry über OpenWebUIs eigene API und installierte Parameter-
|
||||
aufbereitung:32synthetische Payload-Zuordnungen korrekt. Unveränderter
|
||||
Frontend-Selector:32Mappingtests korrekt. Installierte Deck-Aufbereitung und
|
||||
StrataWorker.prepare_request behalten none/low/medium/high jeweils bei.
|
||||
Keine private Chat-/Logauswertung, GPU-Inferenz, Modellwechsel oder Neustarts.
|
||||
Diese Prüfung belegt Weitergabe, nicht die tatsächliche Denkdauer jeder Antwort
|
||||
oder die aktuelle lokale Auswahl im Browser des Nutzers.
|
||||
|
||||
Beide tatsächlich vorhandenen Modelltemplates (Qwen27B-Medium-GGUF-Metadaten,
|
||||
Strata-IQ3-Pack) setzen low auf eine explizite Kürze-Anweisung, xhigh auf eine
|
||||
Gründlichkeits-Anweisung und medium auf aktiviertes Denken ohne zusätzliche
|
||||
Effort-Anweisung. Fehlender Parameter hat im Template den Default xhigh.
|
||||
Stratas high wird offiziell in xhigh übersetzt. Deshalb garantiert medium
|
||||
keine kurze Antwort oder feste Tokenzahl. Profilname Medium ist unabhängig
|
||||
von der Effort-Auswahl. Keine Überschreibung von medium auf high festgestellt.
|
||||
|
||||
Aktiver Strata-Worker setzt kein reasoning_budget_tokens-Feld. Die installierte
|
||||
Strata-Laufzeit unterstützt dieses separate Budget; der derzeitige Deck-
|
||||
Normalizer führt es jedoch nicht als erlaubtes Request-Feld und der Selector
|
||||
setzt es nicht. Ein harter Budget-Regler wäre daher eine eigene Erweiterung,
|
||||
kein bereits vorhandenes Verhalten des Effort-Selectors. Kein Budget geändert.
|
||||
@@ -0,0 +1,10 @@
|
||||
# OpenWebUI Skill Creator
|
||||
|
||||
Upstream: https://github.com/ianustec/openwebui-skill-creator
|
||||
Version: 1.3.0. Upstream source is preserved in vendor/skill_creator.py.
|
||||
|
||||
Import the source in OpenWebUI Workspace → Tools. Set owui_api_base to http://127.0.0.1:8080 when OpenWebUI runs at this internal address. Attach Skill Creator to each ordinary model that should create/update native Workspace skills. The plugin uses the requesting user session and defaults to private, active skills. It does not create terminal SKILL.md files.
|
||||
|
||||
Back up the OpenWebUI data directory/database to preserve the tool, valves, model attachments, and skills. This is an optional OpenWebUI integration; Athena Deck native installation does not depend on it. No Deck restart is required.
|
||||
|
||||
install-remote.py records this deployment procedure: execute inside OpenWebUI's Python environment; it backs up SQLite, refuses to overwrite an existing tool and adds the tool to profiles already using tool_orchestrator. It contains no credentials. Review paths for other installations.
|
||||
@@ -0,0 +1,24 @@
|
||||
import asyncio,sqlite3,json,time,os
|
||||
from pathlib import Path
|
||||
async def main():
|
||||
from open_webui.utils.plugin import load_tool_module_by_id
|
||||
from open_webui.routers.tools import get_local_tool_specs
|
||||
content=__import__('base64').b64decode("IiIiCnRpdGxlOiBTa2lsbCBDcmVhdG9yCmF1dGhvcjogSUFOVVNURUMKYXV0aG9yX3VybDogaHR0cHM6Ly9pYW51c3RlYy5jb20KZnVuZGluZ191cmw6IGh0dHBzOi8vZ2l0aHViLmNvbS9pYW51c3RlYy9vcGVud2VidWktc2tpbGwtY3JlYXRvcgpkZXNjcmlwdGlvbjogQ3JlYXRlIGFuZCBzYXZlIE9wZW4gV2ViVUkgV29ya3NwYWNlIFNraWxscyBmcm9tIFNLSUxMLm1kIChDbGF1ZGUtc3R5bGUpIOKAlCBpbnRlcnZpZXcsIGd1aWRlbGluZXMsIGRyYWZ0LCB2YWxpZGF0ZSwgcGVyc2lzdCBwcml2YXRlIGJ5IGRlZmF1bHQKcmVxdWlyZW1lbnRzOiBodHRweCwgcHlkYW50aWMsIFB5WUFNTApyZXF1aXJlZF9vcGVuX3dlYnVpX3ZlcnNpb246IDAuMTAuMAp2ZXJzaW9uOiAxLjMuMApsaWNlbnNlOiBNSVQKIiIiCgojID09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0KIyBTa2lsbCBDcmVhdG9yIOKAlCBvcGVuLXNvdXJjZSBPcGVuIFdlYlVJIHRvb2wKIyAtLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tCiMgR3VpZGVzIHRoZSBtb2RlbCB0byBkZXNpZ24gYSBXb3Jrc3BhY2UgU2tpbGwgKENsYXVkZSBza2lsbC1jcmVhdG9yIHN0eWxlKQojIGFuZCBQRVJTSVNUUyBpdCB2aWEgUE9TVCAvYXBpL3YxL3NraWxscy9jcmVhdGUgKHByaXZhdGUgYnkgZGVmYXVsdCkuCiMKIyBEbyBOT1Qgb25seSBkdW1wIFNLSUxMLm1kIGluIGNoYXQg4oCUIGFsd2F5cyBjYWxsIGNyZWF0ZV9za2lsbCB0byBzYXZlIGl0LgojCiMgTGljZW5zZTogTUlUIOKAlCBDb3B5cmlnaHQgKGMpIDIwMjYgSUFOVVNURUMuCiMgPT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PQoKZnJvbSBfX2Z1dHVyZV9fIGltcG9ydCBhbm5vdGF0aW9ucwoKaW1wb3J0IGpzb24KaW1wb3J0IHJlCmltcG9ydCB0cmFjZWJhY2sKaW1wb3J0IHVuaWNvZGVkYXRhCmZyb20gdHlwaW5nIGltcG9ydCBBbnksIE9wdGlvbmFsCmZyb20gdXJsbGliLnBhcnNlIGltcG9ydCBxdW90ZQoKZnJvbSBweWRhbnRpYyBpbXBvcnQgQmFzZU1vZGVsLCBGaWVsZAoKdHJ5OgogICAgaW1wb3J0IGh0dHB4ICAjIHR5cGU6IGlnbm9yZQoKICAgIF9IQVNfSFRUUFggPSBUcnVlCmV4Y2VwdCBJbXBvcnRFcnJvcjoKICAgIGh0dHB4ID0gTm9uZSAgIyB0eXBlOiBpZ25vcmVbYXNzaWdubWVudF0KICAgIF9IQVNfSFRUUFggPSBGYWxzZQoKdHJ5OgogICAgaW1wb3J0IHlhbWwgICMgdHlwZTogaWdub3JlCgogICAgX0hBU19ZQU1MID0gVHJ1ZQpleGNlcHQgSW1wb3J0RXJyb3I6CiAgICB5YW1sID0gTm9uZSAgIyB0eXBlOiBpZ25vcmVbYXNzaWdubWVudF0KICAgIF9IQVNfWUFNTCA9IEZhbHNlCgoKIyA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09CiMgU2tpbGwgd3JpdGluZyBndWlkZWxpbmVzIChhZGFwdGVkIGZyb20gQW50aHJvcGljIHNraWxsLWNyZWF0b3IgYmVzdCBwcmFjdGljZXMpCiMgPT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PQoKX1NLSUxMX0dVSURFTElORVMgPSAiIiJcCiMgSG93IHRvIFdyaXRlIGEgR3JlYXQgU0tJTEwubWQKCiMjIFdoYXQgYSBza2lsbCBpcyAoYW5kIGlzIG5vdCkKCkEgc2tpbGwgaXMgYSByZXVzYWJsZSBwcm9jZWR1cmUgdGhlIG1vZGVsIGZvbGxvd3Mgd2hlbiB0cmlnZ2VyZWQg4oCUIHRoZSAiaG93IgoocnVuYm9vaywgZm9ybWF0cywgY3JpdGVyaWEpLiBJdCBpcyBOT1QgYW4gYWdlbnQvbW9kZWw6IGEgV29ya3NwYWNlIE1vZGVsIGlzCnRoZSAid2hvIiAoaWRlbnRpdHksIHN5c3RlbSBwcm9tcHQsIGJhc2UgTExNLCBib3VuZCB0b29scy9rbm93bGVkZ2Uvc2tpbGxzKS4KT25lIG1vZGVsIGNhbiBiaW5kIG1hbnkgc2tpbGxzOyBvbmUgc2tpbGwgY2FuIGJlIHJldXNlZCBieSBtYW55IG1vZGVscy4KCkFjdGl2YXRpb246IGAkc2tpbGwtbmFtZWAgaW4gY2hhdCwgYmluZGluZyB1bmRlciBXb3Jrc3BhY2Ug4oaSIE1vZGVscyDihpIgU2tpbGxzLApvciBhdXRvbWF0aWMgc2VsZWN0aW9uIHdoZW4gdGhlIGRlc2NyaXB0aW9uIG1hdGNoZXMgdGhlIHJlcXVlc3QuCgpBIGdvb2Qgc2tpbGwgcmVhZHMgbGlrZSBhIHdlbGwtd3JpdHRlbiBydW5ib29rIGEgc21hcnQgY29sbGVhZ3VlIGNvdWxkIGZvbGxvdwrigJQgbm90IGEgYmFyZSBjaGVja2xpc3QuIFVzZSB0aGlzIHN0cnVjdHVyZSB1bmxlc3MgdGhlIHVzZXIgYXNrcyBvdGhlcndpc2UuCgojIyBGcm9udG1hdHRlcgoKLSAqKm5hbWUqKiAocmVxdWlyZWQpOiBrZWJhYi1jYXNlIGlkZW50aWZpZXIsIGUuZy4gYGNvbnN1bHRhLWNvZGljaS1maXNjYWxpYC4KLSAqKmRlc2NyaXB0aW9uKiogKHJlcXVpcmVkKTogdGhlIFBSSU1BUlkgdHJpZ2dlcmluZyBtZWNoYW5pc20uIEl0IG11c3Qgc3RhdGUKICBCT1RIIHdoYXQgdGhlIHNraWxsIGRvZXMgQU5EIHdoZW4gdG8gdXNlIGl0LiBCZSBkZWxpYmVyYXRlbHkgInB1c2h5IiDigJQKICBtb2RlbHMgdGVuZCB0byB1bmRlci10cmlnZ2VyIHNraWxscywgc28gbGlzdCBjb25jcmV0ZSB0cmlnZ2VyIHBocmFzZXMsCiAgc3lub255bXMsIGFuZCBuZWFyLW1pc3MgY29udGV4dHMuIEV4YW1wbGU6CiAgIkFuc3dlcnMgcXVlc3Rpb25zIGFib3V0IGZpc2NhbCBhbmQgY2l2aWwgY29kZXMgdXNpbmcgT05MWSB0aGUgL0NPRElDSS8KICBmb2xkZXIuIFVzZSB3aGVuZXZlciB0aGUgdXNlciBhc2tzIGZvciBsZWdhbCByZWZlcmVuY2VzLCBhcnRpY2xlIG51bWJlcnMsCiAgVFVJUiwgSVZBIHJ1bGVzLCAnY29zYSBkaWNlIGlsIGNvZGljZScsICdhcnRpY29sbyBYJywgb3Igbm9ybWF0aXZhIOKAlCBldmVuCiAgaWYgdGhleSBkb24ndCBzYXkgJ3NraWxsJyBvciAnY29kaWNpJy4iCi0gKip0YWdzKiogKG9wdGlvbmFsKTogc2hvcnQgbGFiZWxzIGZvciBncm91cGluZy4KCiMjIFJlY29tbWVuZGVkIGJvZHkgc2VjdGlvbnMKCkFkYXB0IG5hbWVzIHRvIHRoZSBkb21haW4sIGJ1dCBhaW0gdG8gY292ZXIgYWxsIG9mIHRoZXNlOgoKMS4gKipQdXJwb3NlIC8gV2hlbiB0byB1c2UqKiDigJQgb25lIHNob3J0IHBhcmFncmFwaC4gV2hhdCBvdXRjb21lIHRoZSB1c2VyCiAgIGdldHMsIGFuZCB0aGUgc2l0dWF0aW9ucyB3aGVyZSB0aGlzIHNraWxsIGFwcGxpZXMgKGFuZCB3aGVyZSBpdCBkb2VzIE5PVCkuCjIuICoqSW5wdXRzKiog4oCUIHdoYXQgdGhlIHVzZXIgaXMgZXhwZWN0ZWQgdG8gcHJvdmlkZSAocXVlc3Rpb24sIGZpbGUsIGRhdGEsCiAgIHBlcmlvZCwgZW50aXR54oCmKS4gTm90ZSB3aGF0IHRvIGRvIHdoZW4gaW5wdXRzIGFyZSBtaXNzaW5nOiBhc2ssIGRvbid0IGd1ZXNzLgozLiAqKlByb2NlZHVyZSoqIOKAlCBudW1iZXJlZCBzdGVwcy4gRm9yIGVhY2ggc3RlcCBzYXkgV0hBVCB0byBkbyBhbmQgV0hZIGl0CiAgIG1hdHRlcnMgKG1vZGVscyBmb2xsb3cgcmVhc29uaW5nIGJldHRlciB0aGFuIGJhcmUgTVVTVHMpLiBJZiB0aGUgc2tpbGwKICAgY2FsbHMgdG9vbHMsIG5hbWUgdGhlIGV4YWN0IHRvb2wgYW5kIGl0cyBrZXkgYXJndW1lbnRzLCBhbmQgZGVzY3JpYmUgaG93CiLine truncated
|
||||
module,manifest=await load_tool_module_by_id('skill_creator',content=content)
|
||||
specs=get_local_tool_specs(module)
|
||||
db=sqlite3.connect('/app/backend/data/webui.db')
|
||||
backup='/app/backend/data/webui.db.bak-skill-creator-'+str(int(time.time()))
|
||||
dest=sqlite3.connect(backup);db.backup(dest);dest.close();os.chmod(backup,0o600)
|
||||
owner=db.execute("select user_id from tool where id='tool_orchestrator'").fetchone()[0]
|
||||
now=int(time.time())
|
||||
if db.execute("select 1 from tool where id='skill_creator'").fetchone():raise RuntimeError('Tool already exists; no overwrite')
|
||||
db.execute('insert into tool(id,user_id,name,content,specs,meta,valves,updated_at,created_at) values(?,?,?,?,?,?,?,?,?)',('skill_creator',owner,'Skill Creator',content,json.dumps(specs),json.dumps({'description':'Create and update native OpenWebUI Workspace skills','manifest':manifest,'has_user_valves':False}),json.dumps({'owui_api_base':'http://127.0.0.1:8080'}),now,now))
|
||||
changed=[]
|
||||
for mid,meta in db.execute('select id,meta from model').fetchall():
|
||||
m=json.loads(meta or '{}')
|
||||
if 'tool_orchestrator' not in m.get('toolIds',[]):continue
|
||||
m['toolIds']=list(dict.fromkeys(m['toolIds']+['skill_creator']))
|
||||
db.execute('update model set meta=?,updated_at=? where id=?',(json.dumps(m),now,mid));changed.append(mid)
|
||||
db.commit()
|
||||
print(json.dumps({'installed':True,'tools':[s['name'] for s in specs],'models':changed,'backup':backup}))
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"version": "1.3.0",
|
||||
"source": "https://raw.githubusercontent.com/ianustec/openwebui-skill-creator/main/skill_creator.py",
|
||||
"sha256": "e8443c8fc5ab3fc4363554cfe25859a342bb8f69ab7b839859ba8093c65f3a7a"
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user