Files
Hermes_rocket.chat_Plugin/plugin/archivar/keyword_extractor.py
T
Bernd (Hermes) 6cbea1bf91 feat(blocklist): Stopword-Blocklist 4-Ebenen-Kaskade (B13/B14-Fix)
Erweitert is_invalid_learn_keyword um die 4-Ebenen-Kaskade (Konzept
Analysen/Stopword-Blocklist-Architektur_Rainer.md §3):

1. E1 Stopword — DE ∪ EN Funktionswoerter (stopwords-iso, statisch als
   stopwords_de.json 620 + stopwords_en.json 1298 Woerter, MIT-Lizenz)
   plus plugin-spezifische Add-Ons (A6: thema/raum/channel/doku/...).
2. E2 Raumname — P-112 (identisch/Substring, unveraendert).
3. E3 Domaenenwort — room_map.blocked_keywords (Modellnamen, CLI-Flags,
   Technik-Begriffe; konfigurierbar pro Instanz).
4. E4 Struktur — Proton-UID (25-32 alphanumerisch mit Ziffer), reine
   Zahlen, reine Sonderzeichen.

Rueckgabe Optional[str] mit Begruendungs-String (Telemetrie).

- blocklist.py: Kaskade + Lazy-Load-Cache (FM1) + get_stopwords().
- keyword_extractor.py: lokale STOPWORDS-Liste ersetzt durch Loader
  (single source of truth, FM5). Schichten 4a/4b/4c/4d rufen zentrale
  Blocklist.
- room_map.py: blocked_keywords Property + _from_dict/save/reload.
- room-map.schema.json: blocked_keywords (list[str], default []).
- templates/room-map.json: Initial-Befuellung (17 Woerter).
- adapter.py-Aufrufstellen UNVERAENDERT (additiv, A5).

Spike verifiziert: A1 (620/1298 Woerter), A4 (Proton-UID-Regex korrigiert
auf alphanumerisch+Ziffer — Konzept-Regex ^[a-z]{25,32}$ war falsch),
A7 (10000 Aufrufe 3.4ms < 100ms).

Tests: +23 (test_blocklist 25, test_keyword_extractor 18, test_room_map
+3). 1997 passed, 1 vorbestehender flaky Test (test_user_visible, auch
auf HEAD rot — geteilte /tmp/test_map.json).
2026-09-03 06:47:16 +02:00

166 lines
7.0 KiB
Python

"""Thematische Keyword-Extraktion (Schicht 4) — Butler-Lernkonzept V2.
Extrahiert ein thematisches Lern-Keyword aus dem NACHRICHTENTEXT des Users
(statt aus dem Raum-Namen). Dies ist die Vorschlags-Logik für die
Butler-Rückfrage ``ask_routing_learning_choice``.
Kaskade (in dieser Reihenfolge):
1. **4a** — Direkter Keyword-Match auf ``keywords_100`` aller Räume
(``match_keyword_exact``, P-108b: exakt, nicht fuzzy).
2. **4b** — Direkter Keyword-Match auf ``keywords_context`` aller Räume.
3. **4c** — N-Gram-Extraktion aus dem Text (longest non-stopword,
1-3 Wörter, mind. 4 Zeichen, gegen Blocklist).
4. **4d** — LLM-NER (nur wenn ``llm_available`` UND ein ``llm_ner_fn``
injiziert wurde, mit 2s-Timeout-Guard).
**WICHTIG:** ``room_name_to_topic`` ist KEINE Quelle. Wenn alle vier
Quellen nichts liefern, wird ``(None, "none")`` zurückgegeben — der Butler
fragt dann mit Option 4 („Anderes Stichwort") als Hauptempfehlung.
Siehe: ``Analysen/Butler_Lernkonzept_V2_Rainer.md`` (§3.5).
"""
from __future__ import annotations
from typing import Callable, Optional, Tuple
from .blocklist import is_invalid_learn_keyword, get_stopwords
from .keyword_matcher import match_keyword_exact
# ── Stoppwörter (Deutsch + Englisch) ──────────────────────────────────────
# Generische Füllwörter, die niemals ein thematisches Keyword sind.
# Wird bei der N-Gram-Extraktion (Schicht 4c) herausgefiltert.
#
# EINZIGE Wahrheitsquelle (FM5): die Stopwords kommen aus blocklist.py
# (stopwords-iso DE+EN JSON + plugin-spezifische Add-Ons A6). Die frühere
# lokale hardcodierte Liste (~85 Wörter) ist ersetzt — die plugin-
# spezifischen Wörter (thema, raum, channel, doku, ...) sind als Add-On
# in blocklist.py übernommen (Konzept §6.1 A6).
STOPWORDS: frozenset = get_stopwords()
# Mindestlänge eines N-Gram-Kandidaten (Zeichen, nach Normalisierung).
NGRAM_MIN_LEN = 4
# Maximale Wortanzahl eines N-Gram-Kandidaten.
NGRAM_MAX_WORDS = 3
def _normalize_candidate(word: str) -> str:
"""Normalisiert einen N-Gram-Kandidaten (lowercase, strip, Bindestrich)."""
return word.strip().lstrip("#").lower().replace(" ", "-").strip()
def _is_stopword_token(token: str) -> bool:
"""True wenn *token* ein Stoppwort ist (case-insensitive)."""
return token.lower() in STOPWORDS
def _extract_ngrams(text: str, max_n: int = NGRAM_MAX_WORDS) -> list[str]:
"""Extrahiert N-Gram-Kandidaten (1..max_n Wörter) aus *text*.
Prioritäts-Reihenfolge: zuerst Einzel-Token (n=1, längste zuerst —
erfasst Komposita wie ``Firewall-Konfiguration`` als ein Token), dann
2-Wort-Gramme, dann 3-Wort-Gramme. So wird ein sauberes thematisches
Keyword bevorzugt statt einer ganzen Phrase.
Args:
text: Der Nachrichtentext.
max_n: Maximale Wortanzahl pro N-Gram.
Returns:
Liste von N-Gram-Strings in Prioritäts-Reihenfolge (Einzel-Token
zuerst, innerhalb einer Stufe längste zuerst), ohne Stoppwort-Filterung.
"""
import re
# Tokenisiere: nur Wort-Zeichen und Bindestriche, alles andere als Trenner.
# Bindestriche bleiben im Token → Komposita ('Firewall-Konfiguration')
# sind EIN Token, kein 2-Wort-Gram.
tokens = re.findall(r"[A-Za-zÄÖÜäöüß0-9\-]+", text)
if not tokens:
return []
candidates: list[str] = []
for n in range(1, max_n + 1):
level: list[str] = []
for i in range(len(tokens) - n + 1):
gram = tokens[i:i + n]
# Überspringe N-Gramme, die mit einem Stoppwort beginnen oder enden.
if _is_stopword_token(gram[0]) or _is_stopword_token(gram[-1]):
continue
level.append(" ".join(gram))
# Innerhalb einer Stufe: längste zuerst (stabil).
level.sort(key=len, reverse=True)
candidates.extend(level)
return candidates
def extract_thematic_keyword(
text: str,
room_map,
llm_available: bool = False,
llm_ner_fn: Optional[Callable[[str], Optional[str]]] = None,
) -> Tuple[Optional[str], str]:
"""Extrahiert ein thematisches Lern-Keyword aus dem Nachrichtentext.
Kaskade: 4a (keywords_100 exact) → 4b (keywords_context exact) →
4c (N-Gram) → 4d (LLM-NER). KEIN ``room_name_to_topic``-Fallback.
Args:
text: Der Nachrichtentext des Users.
room_map: Die RoomMap-Instanz (mit ``.rooms`` → ``dict[room_id, RoomEntry]``).
llm_available: Wenn True, wird Schicht 4d (LLM-NER) versucht.
llm_ner_fn: Optionaler Callable ``(text) -> Optional[str]`` für die
LLM-NER-Extraktion. Nur relevant wenn ``llm_available=True``.
Ohne Callable wird 4d übersprungen (kein LLM injiziert).
Returns:
Tupel ``(keyword, source_tag)``. ``keyword`` ist ``None`` wenn keine
Quelle ein gültiges Keyword lieferte; ``source_tag`` ist dann ``"none"``.
Mögliche ``source_tag``-Werte: ``"keywords_100"``, ``"keywords_context"``,
``"ngram"``, ``"llm_ner"``, ``"none"``.
"""
if not text or not text.strip():
return (None, "none")
rooms = getattr(room_map, "rooms", None) if room_map is not None else None
rooms = rooms or {}
# ── Schicht 4a: keywords_100 (exakt) ──────────────────────────────
for room in rooms.values():
for kw in getattr(room, "keywords_100", []) or []:
if match_keyword_exact(kw, text):
if is_invalid_learn_keyword(kw, room_map) is None:
return (kw, "keywords_100")
# ── Schicht 4b: keywords_context (exakt) ──────────────────────────
for room in rooms.values():
for kw in getattr(room, "keywords_context", []) or []:
if match_keyword_exact(kw, text):
if is_invalid_learn_keyword(kw, room_map) is None:
return (kw, "keywords_context")
# ── Schicht 4c: N-Gram-Extraktion (longest first) ─────────────────
for candidate in _extract_ngrams(text):
norm = _normalize_candidate(candidate)
if len(norm) < NGRAM_MIN_LEN:
continue
if is_invalid_learn_keyword(norm, room_map) is not None:
continue
return (norm, "ngram")
# ── Schicht 4d: LLM-NER (nur wenn verfügbar + Callable injiziert) ─
if llm_available and llm_ner_fn is not None:
try:
result = llm_ner_fn(text)
if result:
norm = _normalize_candidate(result)
if len(norm) >= NGRAM_MIN_LEN:
if is_invalid_learn_keyword(norm, room_map) is None:
return (norm, "llm_ner")
except Exception:
# LLM-Fehler/Timeout: still ignorieren, kein Keyword.
pass
# ── Nichts gefunden — kein Vorschlag ──────────────────────────────
return (None, "none")