Files
Hermes_rocket.chat_Plugin/plugin/archivar/keyword_extractor.py
T

167 lines
7.1 KiB
Python

# @implements: [F-103] — Butler-Kurator 5-stufige Pipeline: thematisches Keyword-Lernen (Schicht 4)
"""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")