Files
Hermes_rocket.chat_Plugin/plugin/archivar/keyword_extractor.py
T
Bernd (Hermes) d37b8c24c9 feat(archivar): extract_thematic_keyword() — Schicht 4 Keyword-Extraktion (Butler-Lernkonzept V2)
Neue Funktion extract_thematic_keyword(text, room_map, llm_available, llm_ner_fn)
mit 4-Schichten-Kaskade: 4a keywords_100 exact → 4b keywords_context exact →
4c N-Gram (longest non-stopword, >=4 Zeichen) → 4d LLM-NER (nur wenn verfügbar).

KEIN room_name_to_topic-Fallback — bei leerem Ergebnis (None, 'none').
14 Unit-Tests (jede Schicht + Edge-Cases + kein Raumname).
2026-08-26 09:53:18 +02:00

191 lines
8.5 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
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.
STOPWORDS: frozenset = frozenset({
# Deutsch
"der", "die", "das", "den", "dem", "des", "ein", "eine", "einer",
"einem", "einen", "und", "oder", "aber", "auch", "nur", "noch",
"schon", "sehr", "mit", "für", "von", "auf", "aus", "bei", "nach",
"zu", "zum", "zur", "im", "in", "an", "ist", "sind", "war", "wird",
"werden", "wurde", "hat", "haben", "hatte", "kann", "können",
"muss", "müssen", "soll", "sollen", "will", "wollen", "nicht",
"kein", "keine", "ja", "nein", "doch", "mal", "bitte", "danke",
"hallo", "hi", "ok", "okay", "gut", "gerne", "gern", "also",
"dann", "denn", "weil", "wenn", "wie", "was", "wer", "wo", "wann",
"warum", "dass", "das", "dies", "diese", "dieser", "dieses",
"mein", "meine", "dein", "deine", "sein", "seine", "ihr", "ihre",
"wir", "uns", "unser", "euer", "ich", "du", "er", "sie", "es",
"man", "sich", "hier", "dort", "da", "jetzt", "heute", "morgen",
"gestern", "immer", "oft", "manchmal", "nie", "wieder", "mehr",
"weniger", "viel", "viele", "wenig", "etwas", "nichts", "alles",
"alle", "jeder", "jede", "jedes", "so", "sofort", "gleich",
"thema", "raum", "channel", "doku", "dokumentation", "file",
"datei", "log", "task", "aufgabe", "catch", "default", "fallback",
"frage", "antwort", "nachricht", "message", "text", "wort",
"begriff", "stichwort", "keyword", "sache", "ding", "problem",
"lösung", "loesung", "idee", "punkt", "aspekt", "kontext",
# Englisch
"the", "a", "an", "and", "or", "but", "of", "to", "in", "on",
"for", "with", "is", "are", "was", "were", "be", "been", "have",
"has", "had", "do", "does", "did", "will", "would", "can",
"could", "should", "this", "that", "these", "those", "it", "we",
"you", "they", "he", "she", "i", "not", "no", "yes", "ok", "okay",
"please", "thanks", "thank", "hello", "hi", "just", "now", "then",
"here", "there", "very", "much", "many", "some", "any", "all",
})
# 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")