feat: V8.5+ — Morphologisches Keyword-Matching (Snowball GermanStemmer + Levenshtein Fuzzy + Pre-Compute-Cache)

This commit is contained in:
Bernd (Hermes)
2026-07-19 17:13:46 +02:00
parent 7ba62bd7e4
commit 6eb34e11e3
11 changed files with 1151 additions and 74 deletions
+23 -49
View File
@@ -46,55 +46,29 @@ from .routing_telemetry import routing_telemetry
# Constants
ROOM_MAP_PATH = "~/.hermes/hermes-agent/data/room-map.json"
# Use absolute imports instead of relative imports
try:
from classifier import (
ClassificationResult,
EmbeddingClient,
IntentClassifier,
LLMClient,
OllamaLLMClient,
)
from config import (
CONFIDENCE_THRESHOLDS,
OLLAMA_CONFIG,
LLM_CONFIG,
BUTTON_TEMPLATES,
MOVE_REQUEST_TEMPLATE,
ARCHIVAR_STUFE_LOG,
ARCHIVAR_STATE_PATH
)
from doc_store import DocumentationStore
from room_map import RoomMap, RoomMapValidationError
from router import BidirectionalRouter, RoutingDecision
from archivar_state import ArchivarState
from feedback_detector import RoutingWiderspruchDetector, ContradictionResult
except ImportError:
# Fallback for testing or different import structure
from .classifier import (
ClassificationResult,
EmbeddingClient,
IntentClassifier,
LLMClient,
OllamaLLMClient,
)
from .config import (
CONFIDENCE_THRESHOLDS,
OLLAMA_CONFIG,
LLM_CONFIG,
BUTTON_TEMPLATES,
MOVE_REQUEST_TEMPLATE,
ARCHIVAR_STUFE_LOG,
ARCHIVAR_STATE_PATH
)
from .doc_store import DocumentationStore
from .room_map import RoomMap, RoomMapValidationError
from .router import BidirectionalRouter, RoutingDecision
from .archivar_state import ArchivarState
from .room_index import RoomIndexManager
from .booster import KeywordBooster
from .seed_data import SEED_DATA
from .feedback_detector import RoutingWiderspruchDetector, ContradictionResult
from .classifier import (
ClassificationResult,
EmbeddingClient,
IntentClassifier,
LLMClient,
OllamaLLMClient,
)
from .config import (
CONFIDENCE_THRESHOLDS,
OLLAMA_CONFIG,
LLM_CONFIG,
BUTTON_TEMPLATES,
MOVE_REQUEST_TEMPLATE,
ARCHIVAR_STUFE_LOG,
ARCHIVAR_STATE_PATH
)
from .doc_store import DocumentationStore
from .room_map import RoomMap, RoomMapValidationError
from .router import BidirectionalRouter, RoutingDecision
from .archivar_state import ArchivarState
from .room_index import RoomIndexManager
from .booster import KeywordBooster
from .feedback_detector import RoutingWiderspruchDetector, ContradictionResult
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
+481
View File
@@ -0,0 +1,481 @@
"""
Keyword-Matcher mit morphologischer Varianten-Erkennung für Deutsch.
Bietet Stemming (snowballstemmer German), Fuzzy-Matching (Levenshtein)
und Case-Insensitive-Matching für 100%-Keywords in der Raum-Map.
Löst den Bug: 'Homelabs' (Plural) matcht jetzt 'homelab' (Singular),
'Dokumentationen' matcht 'dokumentation', etc.
Dependencies: snowballstemmer (pip install snowballstemmer)
"""
from __future__ import annotations
import re
from functools import lru_cache
from typing import List, Optional
import snowballstemmer
# ═══════════════════════════════════════════════════════════════════════════
# Constants (E1, E3)
# ═══════════════════════════════════════════════════════════════════════════
# E1: Word-boundary pattern as module constant
_WORD_BOUNDARY_START = r'(?:^|\s|[-_.,;:!?()\[\]{}"\'])'
_WORD_BOUNDARY_END = r'(?:$|\s|[-_.,;:!?()\[\]{}"\'])'
# E3: Extracted constants
SHORT_KEYWORD_LEN = 3
"""Keywords ≤ this length require word-boundary matching to avoid false positives."""
MIN_FUZZY_LEN = 5
"""Minimum word length for fuzzy matching (shorter words are too prone to false positives)."""
FUZZY_MAX_DIST_SHORT = 1
"""Max Levenshtein distance for words of length 5-7."""
FUZZY_MAX_DIST_LONG = 2
"""Max Levenshtein distance for words of length 8+."""
# ═══════════════════════════════════════════════════════════════════════════
# German Stemmer (snowballstemmer)
# ═══════════════════════════════════════════════════════════════════════════
# Singleton snowballstemmer instance
_stemmer = None # type: ignore[var-annotated]
def _get_stemmer():
"""Get or create the singleton snowballstemmer GermanStemmer instance."""
global _stemmer
if _stemmer is None:
_stemmer = snowballstemmer.stemmer('german')
return _stemmer
class GermanStemmer:
"""Thin compatibility wrapper around snowballstemmer.
Delegates to the snowballstemmer library's German stemmer.
This class exists for backward compatibility with code that
instantiates GermanStemmer() directly.
"""
def stem(self, word: str) -> str:
"""Stem a German word to its root form.
Args:
word: The word to stem (lowercase).
Returns:
The stemmed form.
"""
if len(word) <= 2:
return word
return _get_stemmer().stemWord(word)
@lru_cache(maxsize=4096)
def stem_word(word: str) -> str:
"""Stem a single German word using snowballstemmer.
Results are cached via lru_cache for performance (R2).
Args:
word: The word to stem (should be lowercase).
Returns:
Stemmed form.
"""
return _get_stemmer().stemWord(word)
def stem_phrase(phrase: str) -> str:
"""Stem each word in a phrase and return the stemmed phrase.
Args:
phrase: A multi-word phrase.
Returns:
Stemmed phrase with words joined by space.
"""
words = phrase.split()
stemmed = [stem_word(w) for w in words]
return ' '.join(stemmed)
def precompute_keyword_stems(keywords: List[str]) -> List[str]:
"""Pre-compute stemmed forms of keywords for caching (R2).
Call this once when loading the room map, then use the pre-computed
stems for matching instead of stemming keywords on every message.
Args:
keywords: List of raw keywords from room-map.
Returns:
List of stemmed keyword forms.
"""
return [stem_phrase(normalize_keyword(kw)) for kw in keywords]
# ═══════════════════════════════════════════════════════════════════════════
# Levenshtein Distance (stdlib-only)
# ═══════════════════════════════════════════════════════════════════════════
def levenshtein_distance(s1: str, s2: str) -> int:
"""Compute Levenshtein edit distance between two strings.
Uses O(min(m,n)) space with two-row optimization.
Args:
s1: First string.
s2: Second string.
Returns:
Edit distance (0 = identical).
"""
if len(s1) < len(s2):
return levenshtein_distance(s2, s1)
if len(s2) == 0:
return len(s1)
# Two-row optimization
prev_row = list(range(len(s2) + 1))
for i, c1 in enumerate(s1):
curr_row = [i + 1]
for j, c2 in enumerate(s2):
# Insertion, deletion, substitution
insertions = prev_row[j + 1] + 1
deletions = curr_row[j] + 1
substitutions = prev_row[j] + (0 if c1 == c2 else 1)
curr_row.append(min(insertions, deletions, substitutions))
prev_row = curr_row
return prev_row[-1]
# ═══════════════════════════════════════════════════════════════════════════
# Text Normalization
# ═══════════════════════════════════════════════════════════════════════════
def normalize_text(text: str) -> str:
"""Normalize text for matching: lowercase, collapse whitespace, strip.
Also normalizes common German characters:
- ß → ss
- Ü/ü → ue (for matching purposes)
- Ö/ö → oe
- Ä/ä → ae
Args:
text: Raw text.
Returns:
Normalized text.
"""
text = text.lower().strip()
# Collapse multiple whitespace
text = re.sub(r'\s+', ' ', text)
# Normalize German special chars
text = text.replace('ß', 'ss')
text = text.replace('ä', 'ae')
text = text.replace('ö', 'oe')
text = text.replace('ü', 'ue')
return text
def normalize_keyword(keyword: str) -> str:
"""Normalize a keyword for matching.
Same as normalize_text but also removes hyphens and special chars
that users might omit or add.
Args:
keyword: Raw keyword from room-map.
Returns:
Normalized keyword.
"""
kw = normalize_text(keyword)
# Remove hyphens for fuzzy matching (users might write
# 'hardware übersicht' instead of 'hardware-übersicht')
kw_no_hyphen = kw.replace('-', ' ').replace('_', ' ')
# Collapse again after hyphen removal
kw_no_hyphen = re.sub(r'\s+', ' ', kw_no_hyphen).strip()
return kw_no_hyphen
# ═══════════════════════════════════════════════════════════════════════════
# Keyword Matching
# ═══════════════════════════════════════════════════════════════════════════
def _make_word_boundary_pattern(word: str) -> str:
"""Build a regex pattern that matches `word` at word boundaries."""
return _WORD_BOUNDARY_START + re.escape(word) + _WORD_BOUNDARY_END
def match_keyword(keyword: str, text: str) -> bool:
"""Check if a keyword matches text using multi-strategy matching.
Strategies (tried in order, first match wins):
1. Exact match (case-insensitive, normalized)
2. Stemming match (snowballstemmer German)
3. Fuzzy match (Levenshtein ≤ 2 for words > 4 chars)
Args:
keyword: The keyword to match (from room-map keywords_100).
text: The user's message text.
Returns:
True if the keyword matches the text.
"""
if not keyword or not text:
return False
kw_norm = normalize_keyword(keyword)
text_norm = normalize_text(text)
# Strategy 1: Exact substring match (case-insensitive, normalized)
# For short keywords (≤SHORT_KEYWORD_LEN chars): require word-boundary match
# to avoid false positives like 'bat' matching 'batterie'.
if len(kw_norm) <= SHORT_KEYWORD_LEN:
pattern = _make_word_boundary_pattern(kw_norm)
if re.search(pattern, text_norm):
return True
elif kw_norm in text_norm:
return True
# Strategy 1b: Hyphen-insensitive match
# 'hardware-übersicht' should match 'hardware übersicht'
text_no_hyphen = text_norm.replace('-', ' ').replace('_', ' ')
text_no_hyphen = re.sub(r'\s+', ' ', text_no_hyphen).strip()
if len(kw_norm) <= SHORT_KEYWORD_LEN:
pattern = _make_word_boundary_pattern(kw_norm)
if re.search(pattern, text_no_hyphen):
return True
elif kw_norm in text_no_hyphen:
return True
# Strategy 2: Stemming match
# Stem both the keyword and each word in the text,
# then check if the stemmed keyword appears in the stemmed text.
# For short keywords (≤SHORT_KEYWORD_LEN chars): require word-boundary match
# to avoid false positives like 'bat' matching 'batteri' (stem of 'batterie').
kw_stemmed = stem_phrase(kw_norm)
text_stemmed = stem_phrase(text_no_hyphen)
if len(kw_norm) <= SHORT_KEYWORD_LEN:
pattern = _make_word_boundary_pattern(kw_stemmed)
if re.search(pattern, text_stemmed):
return True
elif kw_stemmed in text_stemmed:
return True
# Also try: stem each word of the keyword and check if ALL stemmed
# keyword words appear somewhere in the stemmed text.
# For short keyword words (≤SHORT_KEYWORD_LEN chars): require word-boundary match.
kw_words_stemmed = kw_stemmed.split()
if kw_words_stemmed:
all_found = True
for kw_word in kw_words_stemmed:
if len(kw_word) <= SHORT_KEYWORD_LEN:
pattern = _make_word_boundary_pattern(kw_word)
if not re.search(pattern, text_stemmed):
all_found = False
break
elif kw_word not in text_stemmed:
all_found = False
break
if all_found:
return True
# Strategy 3: Fuzzy match (Levenshtein)
# Only for words > MIN_FUZZY_LEN-1 characters to avoid false positives
# Check each word of the keyword against each word of the text
kw_words = kw_norm.split()
text_words = text_no_hyphen.split()
for kw_word in kw_words:
if len(kw_word) < MIN_FUZZY_LEN:
continue
for text_word in text_words:
if len(text_word) < MIN_FUZZY_LEN:
continue
# Scale: distance 1 for 5-7 chars, distance 2 for 8+ chars
max_dist = FUZZY_MAX_DIST_SHORT if len(kw_word) <= 7 else FUZZY_MAX_DIST_LONG
if levenshtein_distance(kw_word, text_word) <= max_dist:
return True
# Strategy 3b: Phrase-level fuzzy match (concatenated, no spaces)
# Catches 'raum-map' vs 'Raummap' where individual words are too short
# but the concatenated form is close.
kw_cat = kw_norm.replace(' ', '')
text_cat = text_no_hyphen.replace(' ', '')
if len(kw_cat) >= MIN_FUZZY_LEN and len(text_cat) >= MIN_FUZZY_LEN:
max_dist = FUZZY_MAX_DIST_SHORT if len(kw_cat) <= 7 else FUZZY_MAX_DIST_LONG
if levenshtein_distance(kw_cat, text_cat) <= max_dist:
return True
return False
def match_keyword_with_stems(
keyword: str,
text: str,
kw_stemmed_pre: str,
kw_words_stemmed_pre: List[str],
) -> bool:
"""Check if a keyword matches text using pre-computed stems (R2).
This is the performance-optimized variant: keyword stems are pre-computed
once when the room map is loaded, so only the text needs stemming at
message time.
Args:
keyword: The raw keyword (for exact/fuzzy matching).
text: The user's message text.
kw_stemmed_pre: Pre-computed stemmed form of the keyword.
kw_words_stemmed_pre: Pre-computed stemmed individual words.
Returns:
True if the keyword matches the text.
"""
if not keyword or not text:
return False
kw_norm = normalize_keyword(keyword)
text_norm = normalize_text(text)
# Strategy 1: Exact substring match
if len(kw_norm) <= SHORT_KEYWORD_LEN:
pattern = _make_word_boundary_pattern(kw_norm)
if re.search(pattern, text_norm):
return True
elif kw_norm in text_norm:
return True
# Strategy 1b: Hyphen-insensitive match
text_no_hyphen = text_norm.replace('-', ' ').replace('_', ' ')
text_no_hyphen = re.sub(r'\s+', ' ', text_no_hyphen).strip()
if len(kw_norm) <= SHORT_KEYWORD_LEN:
pattern = _make_word_boundary_pattern(kw_norm)
if re.search(pattern, text_no_hyphen):
return True
elif kw_norm in text_no_hyphen:
return True
# Strategy 2: Stemming match (text only — keyword stems are pre-computed)
text_stemmed = stem_phrase(text_no_hyphen)
if len(kw_norm) <= SHORT_KEYWORD_LEN:
pattern = _make_word_boundary_pattern(kw_stemmed_pre)
if re.search(pattern, text_stemmed):
return True
elif kw_stemmed_pre in text_stemmed:
return True
# Check if ALL pre-computed stemmed keyword words appear in stemmed text
if kw_words_stemmed_pre:
all_found = True
for kw_word in kw_words_stemmed_pre:
if len(kw_word) <= SHORT_KEYWORD_LEN:
pattern = _make_word_boundary_pattern(kw_word)
if not re.search(pattern, text_stemmed):
all_found = False
break
elif kw_word not in text_stemmed:
all_found = False
break
if all_found:
return True
# Strategy 3: Fuzzy match (Levenshtein)
kw_words = kw_norm.split()
text_words = text_no_hyphen.split()
for kw_word in kw_words:
if len(kw_word) < MIN_FUZZY_LEN:
continue
for text_word in text_words:
if len(text_word) < MIN_FUZZY_LEN:
continue
max_dist = FUZZY_MAX_DIST_SHORT if len(kw_word) <= 7 else FUZZY_MAX_DIST_LONG
if levenshtein_distance(kw_word, text_word) <= max_dist:
return True
# Strategy 3b: Phrase-level fuzzy match
kw_cat = kw_norm.replace(' ', '')
text_cat = text_no_hyphen.replace(' ', '')
if len(kw_cat) >= MIN_FUZZY_LEN and len(text_cat) >= MIN_FUZZY_LEN:
max_dist = FUZZY_MAX_DIST_SHORT if len(kw_cat) <= 7 else FUZZY_MAX_DIST_LONG
if levenshtein_distance(kw_cat, text_cat) <= max_dist:
return True
return False
def match_any_keyword(keywords: List[str], text: str) -> bool:
"""Check if ANY of the keywords match the text.
Args:
keywords: List of keywords (from keywords_100 or keywords_context).
text: The user's message text.
Returns:
True if at least one keyword matches.
"""
return any(match_keyword(kw, text) for kw in keywords)
def find_matching_keywords(keywords: List[str], text: str) -> List[str]:
"""Find all keywords that match the text.
Args:
keywords: List of keywords to check.
text: The user's message text.
Returns:
List of matching keywords.
"""
return [kw for kw in keywords if match_keyword(kw, text)]
def match_keyword_exact(keyword: str, text: str) -> bool:
"""Simple exact match (case-insensitive, normalized) — no stemming/fuzzy.
Uses word-boundary matching to avoid false positives like
'container' matching 'Containern'.
Used for context keywords where we want precise matching only.
Args:
keyword: The keyword to match.
text: The user's message text.
Returns:
True if the keyword appears in the text (case-insensitive).
"""
if not keyword or not text:
return False
kw_norm = normalize_keyword(keyword)
text_norm = normalize_text(text)
# Word-boundary match: keyword must appear as a whole word or
# be delimited by common separators (hyphen, underscore, etc.)
pattern = _make_word_boundary_pattern(kw_norm)
if re.search(pattern, text_norm):
return True
# Also try hyphen-insensitive version
text_no_hyphen = text_norm.replace('-', ' ').replace('_', ' ')
text_no_hyphen = re.sub(r'\s+', ' ', text_no_hyphen).strip()
pattern2 = _make_word_boundary_pattern(kw_norm)
return bool(re.search(pattern2, text_no_hyphen))
+23 -14
View File
@@ -31,6 +31,8 @@ from datetime import datetime, timedelta
from pathlib import Path
from typing import Optional, Dict, List
from .keyword_matcher import match_keyword, match_keyword_exact, find_matching_keywords
logger = logging.getLogger(__name__)
# Use absolute import instead of relative import
@@ -87,16 +89,19 @@ class RoomEntry:
def match_score(self, text: str) -> int:
"""Return number of keyword matches in *text* (case-insensitive).
Uses morphological matching (stemming, fuzzy) for keywords_100
and exact matching for keywords_context.
Args:
text: The message text to match against.
Returns:
Number of matching keywords (0 if none match).
"""
# Prüfe beide Listen: keywords_100 und keywords_context
text_lower = text.lower()
score_100 = sum(1 for kw in self.keywords_100 if kw.lower() in text_lower)
score_context = sum(1 for kw in self.keywords_context if kw.lower() in text_lower)
# 100%-Keywords: morphological matching (stemming, fuzzy)
score_100 = sum(1 for kw in self.keywords_100 if match_keyword(kw, text))
# Context-Keywords: exact matching only (case-insensitive)
score_context = sum(1 for kw in self.keywords_context if match_keyword_exact(kw, text))
return score_100 + score_context
@@ -219,6 +224,9 @@ class RoomMap:
def find_room_by_keywords(self, text: str, min_score: int = 1, origin_room_id: Optional[str] = None) -> Optional[RoomEntry]:
"""Find the room with the most keyword matches for *text*.
Uses morphological matching (stemming, fuzzy) for 100%-keywords
and exact matching for context keywords.
Args:
text: The message text to classify.
min_score: Minimum score required to return a room (default: 1).
@@ -231,8 +239,6 @@ class RoomMap:
if no room has any matching keywords or if the best score
is below the minimum threshold.
"""
text_lower = text.lower()
# Stufe 1: Prüfe 100% Evidenz Keywords zuerst
# Bei mehreren Räumen mit 100%-Matches: den mit den MEISTEN Treffern nehmen
# Catch-All-Räume werden in Stufe 1 NICHT berücksichtigt
@@ -244,8 +250,8 @@ class RoomMap:
if room.catch_all:
continue
# Zähle 100%-Keyword-Treffer
score_100 = sum(1 for kw in room.keywords_100 if kw.lower() in text_lower)
# Zähle 100%-Keyword-Treffer (morphologisches Matching)
score_100 = sum(1 for kw in room.keywords_100 if match_keyword(kw, text))
if score_100 > best_100_score:
best_100_score = score_100
best_100_room = room
@@ -261,7 +267,8 @@ class RoomMap:
origin_room = self._rooms[origin_room_id]
# Prüfe kontextabhängige Keywords im Ursprungsraum
# (auch Catch-All-Räume — sie können Kontext-Keywords haben)
context_score = sum(1 for kw in origin_room.keywords_context if kw.lower() in text_lower)
# Context-Keywords: exaktes Matching (kein Stemming/Fuzzy)
context_score = sum(1 for kw in origin_room.keywords_context if match_keyword_exact(kw, text))
if context_score >= min_score:
return origin_room
@@ -273,8 +280,8 @@ class RoomMap:
best_score: int = 0
for room in self._rooms.values():
# Prüfe kontextabhängige Keywords
context_score = sum(1 for kw in room.keywords_context if kw.lower() in text_lower)
# Prüfe kontextabhängige Keywords (exaktes Matching)
context_score = sum(1 for kw in room.keywords_context if match_keyword_exact(kw, text))
if context_score > best_score:
best_score = context_score
best_room = room
@@ -286,12 +293,14 @@ class RoomMap:
def is_100_percent_match(self, text: str, room: RoomEntry) -> bool:
"""Check if *text* contains any 100%-evidence keywords for *room*.
Returns True if at least one keywords_100 entry matches (case-insensitive).
Uses morphological matching (stemming, fuzzy) for robust matching
against plural forms, case declensions, and minor typos.
Returns True if at least one keywords_100 entry matches.
Used by the router to distinguish 100% keyword matches (auto-route, no Butler)
from context keyword matches (Butler asks, learning opportunity).
"""
text_lower = text.lower()
return any(kw.lower() in text_lower for kw in room.keywords_100)
return any(match_keyword(kw, text) for kw in room.keywords_100)
def calculate_weighted_score(self, text: str, room: RoomEntry) -> float:
"""
+9 -5
View File
@@ -36,6 +36,8 @@ from .booster import KeywordBooster
from .archivar_state import ArchivarState
from .routing_counter import routing_counter
from .routing_telemetry import routing_telemetry
from .keyword_matcher import match_keyword, match_keyword_exact, find_matching_keywords
from .sentence_markers import (
detect_sentence_marker,
SentenceMarkerResult,
@@ -1710,6 +1712,9 @@ class BidirectionalRouter:
def _extract_matched_keywords(self, text: str, room: RoomEntry) -> List[str]:
"""Extrahiere die Keywords, die zum Match führten.
Uses morphological matching for 100%-keywords and exact matching
for context keywords.
Args:
text: Der Nachrichtentext
room: Der gematchte Raum
@@ -1717,17 +1722,16 @@ class BidirectionalRouter:
Returns:
Liste der gematchten Keywords
"""
text_lower = text.lower()
matched_keywords = []
# Prüfe 100% Evidenz Keywords
# Prüfe 100% Evidenz Keywords (morphologisches Matching)
for kw in room.keywords_100:
if kw.lower() in text_lower and kw not in matched_keywords:
if match_keyword(kw, text) and kw not in matched_keywords:
matched_keywords.append(kw)
# Prüfe kontextabhängige Keywords
# Prüfe kontextabhängige Keywords (exaktes Matching)
for kw in room.keywords_context:
if kw.lower() in text_lower and kw not in matched_keywords:
if match_keyword_exact(kw, text) and kw not in matched_keywords:
matched_keywords.append(kw)
return matched_keywords
+2 -2
View File
@@ -18,7 +18,7 @@ from pathlib import Path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
from room_map import RoomMap, RoomEntry
from plugin.archivar.room_map import RoomMap, RoomEntry
class TestButlerModeRoomMap(unittest.TestCase):
@@ -147,7 +147,7 @@ class TestButlerModeRouter(unittest.TestCase):
"""Fix C v7: Router._resolve_move_request() Tests."""
def setUp(self):
from room_map import RoomMap, RoomEntry
from plugin.archivar.room_map import RoomMap, RoomEntry
self.room_map = RoomMap(
rooms={
"r1": RoomEntry(
@@ -0,0 +1,607 @@
"""
Tests für den Keyword-Matcher mit morphologischer Varianten-Erkennung.
Testet:
- GermanStemmer (Snowball German)
- Levenshtein-Distanz
- match_keyword() mit allen Strategien
- Integration in RoomMap.find_room_by_keywords()
- Integration in RoomMap.is_100_percent_match()
- False-Positive-Vermeidung (kurze Keywords, semantisch verschieden)
"""
from __future__ import annotations
import json
import sys
import tempfile
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
from plugin.archivar.keyword_matcher import (
GermanStemmer,
levenshtein_distance,
match_keyword,
match_keyword_exact,
match_any_keyword,
find_matching_keywords,
normalize_text,
normalize_keyword,
stem_word,
stem_phrase,
match_keyword_with_stems,
precompute_keyword_stems,
)
from plugin.archivar.room_map import RoomMap, RoomEntry
# ═══════════════════════════════════════════════════════════════════════════
# GermanStemmer Tests
# ═══════════════════════════════════════════════════════════════════════════
class TestGermanStemmer:
"""Snowball German stemmer tests."""
def setup_method(self):
self.stemmer = GermanStemmer()
def test_plural_nouns(self):
"""Pluralformen werden auf Singular reduziert."""
assert self.stemmer.stem("homelabs") == "homelab"
assert self.stemmer.stem("dokumentationen") == "dokumentation"
assert self.stemmer.stem("netzwerke") == "netzwerk"
assert self.stemmer.stem("subnetze") == "subnetz"
assert self.stemmer.stem("firewalls") == "firewall"
def test_case_declensions(self):
"""Deklinationsformen werden auf Grundform reduziert."""
# Genitiv
assert self.stemmer.stem("homelabes") == "homelab"
# Dativ Plural
assert self.stemmer.stem("homelaben") == "homelab"
def test_verb_forms(self):
"""Verbformen werden gestemmt (vereinfachter Stemmer — ein Pass)."""
# Der vereinfachte Stemmer macht nur einen Pass pro Step.
# 'laufenden' → Step1 entfernt 'en' → 'laufend'
# Das reicht für unseren Use Case (Plural/Deklination).
assert self.stemmer.stem("laufenden") == "laufend"
assert self.stemmer.stem("gehenden") == "gehend"
def test_short_words_unchanged(self):
"""Sehr kurze Wörter bleiben unverändert."""
assert self.stemmer.stem("bat") == "bat"
assert self.stemmer.stem("rc") == "rc"
assert self.stemmer.stem("ddp") == "ddp"
def test_compound_words(self):
"""Komposita werden korrekt gestemmt (kein Overstemming)."""
# 'routerkonfiguration' → sollte nicht zu 'routerkonfigura' werden
# Der Stemmer entfernt 'tion' nicht (aus Suffix-Liste entfernt).
assert self.stemmer.stem("routerkonfiguration") == "routerkonfiguration"
assert self.stemmer.stem("netzwerkdokumentation") == "netzwerkdokumentation"
# ═══════════════════════════════════════════════════════════════════════════
# Levenshtein Distance Tests
# ═══════════════════════════════════════════════════════════════════════════
class TestLevenshtein:
"""Levenshtein edit distance tests."""
def test_identical(self):
assert levenshtein_distance("homelab", "homelab") == 0
def test_one_edit(self):
assert levenshtein_distance("homelab", "homelabs") == 1
assert levenshtein_distance("raummap", "raum-map") == 1
assert levenshtein_distance("dokumentation", "dokumentationen") == 2
def test_two_edits(self):
assert levenshtein_distance("homelab", "homelap") == 1
assert levenshtein_distance("abc", "xyz") == 3
def test_empty(self):
assert levenshtein_distance("", "") == 0
assert levenshtein_distance("abc", "") == 3
assert levenshtein_distance("", "abc") == 3
# ═══════════════════════════════════════════════════════════════════════════
# Normalization Tests
# ═══════════════════════════════════════════════════════════════════════════
class TestNormalization:
"""Text normalization tests."""
def test_lowercase(self):
assert normalize_text("Homelab") == "homelab"
def test_german_special_chars(self):
assert normalize_text("Übersicht") == "uebersicht"
assert normalize_text("Öffnen") == "oeffnen"
assert normalize_text("Ändern") == "aendern"
assert normalize_text("Straße") == "strasse"
def test_keyword_hyphen_removal(self):
assert normalize_keyword("raum-map") == "raum map"
assert normalize_keyword("hardware-übersicht") == "hardware uebersicht"
# ═══════════════════════════════════════════════════════════════════════════
# match_keyword() — Core Bug-Report Test Cases
# ═══════════════════════════════════════════════════════════════════════════
class TestMatchKeyword:
"""Core match_keyword() tests from the bug report."""
# ── Morphological variants (Plural, Deklination) ─────────────────
def test_plural_homelabs(self):
"""'homelab' vs 'Homelabs' → MATCH"""
assert match_keyword("homelab", "Homelabs") is True
def test_dativ_homelab(self):
"""'homelab' vs 'dem Homelab' → MATCH"""
assert match_keyword("homelab", "dem Homelab") is True
def test_genitiv_homelab(self):
"""'homelab' vs 'Homelabes' → MATCH"""
assert match_keyword("homelab", "Homelabes") is True
def test_dativ_plural_homelab(self):
"""'homelab' vs 'Homelaben' → MATCH"""
assert match_keyword("homelab", "Homelaben") is True
def test_plural_dokumentation(self):
"""'dokumentation' vs 'Dokumentationen' → MATCH"""
assert match_keyword("dokumentation", "Dokumentationen") is True
def test_plural_netzwerk(self):
"""'netzwerk' vs 'Netzwerke' → MATCH"""
assert match_keyword("netzwerk", "Netzwerke") is True
def test_plural_subnetz(self):
"""'subnetz' vs 'Subnetze' → MATCH"""
assert match_keyword("subnetz", "Subnetze") is True
def test_plural_firewall(self):
"""'firewall' vs 'Firewalls' → MATCH"""
assert match_keyword("firewall", "Firewalls") is True
# ── Hyphen and punctuation ───────────────────────────────────────
def test_hyphen_lan_doku(self):
"""'lan dokumentation' vs 'LAN-Dokumentation' → MATCH"""
assert match_keyword("lan dokumentation", "LAN-Dokumentation") is True
def test_hyphen_umlaut(self):
"""'hardware übersicht' vs 'Hardware-Übersicht' → MATCH"""
assert match_keyword("hardware übersicht", "Hardware-Übersicht") is True
def test_punctuation_rocketchat(self):
"""'rocketchat plugin' vs 'Rocket.Chat Plugins' → MATCH"""
assert match_keyword("rocketchat plugin", "Rocket.Chat Plugins") is True
# ── Case-insensitive ─────────────────────────────────────────────
def test_case_insensitive_pfsense(self):
"""'pfsense' vs 'pfSense' → MATCH"""
assert match_keyword("pfsense", "pfSense") is True
# ── Compounds ────────────────────────────────────────────────────
def test_compound_ddp(self):
"""'ddp' vs 'DDP-WebSocket' → MATCH"""
assert match_keyword("ddp", "DDP-WebSocket") is True
def test_compound_websocket(self):
"""'websocket' vs 'WebSocket-Verbindung' → MATCH"""
assert match_keyword("websocket", "WebSocket-Verbindung") is True
def test_compound_router(self):
"""'router' vs 'Routerkonfiguration' → MATCH"""
assert match_keyword("router", "Routerkonfiguration") is True
def test_compound_proxmox(self):
"""'proxmox' vs 'Proxmox-Server' → MATCH"""
assert match_keyword("proxmox", "Proxmox-Server") is True
# ── Fuzzy matching ────────────────────────────────────────────────
def test_fuzzy_raum_map(self):
"""'raum-map' vs 'Raummap' → MATCH (Fuzzy)"""
assert match_keyword("raum-map", "Raummap") is True
# ── Semantic negatives (should NOT match) ────────────────────────
def test_semantic_different_lan_vs_netzwerk(self):
"""'lan dokumentation' vs 'Netzwerkdokumentation' → KEIN MATCH"""
assert match_keyword("lan dokumentation", "Netzwerkdokumentation") is False
def test_semantic_different_heimnetz_vs_heimarbeit(self):
"""'heimnetz' vs 'Heimarbeitsplatz' → KEIN MATCH"""
assert match_keyword("heimnetz", "Heimarbeitsplatz") is False
def test_semantic_different_homelab_vs_homeoffice(self):
"""'homelab' vs 'Homeoffice' → KEIN MATCH"""
assert match_keyword("homelab", "Homeoffice") is False
def test_semantic_different_trading_vs_tradition(self):
"""'trading' vs 'Tradition' → KEIN MATCH"""
assert match_keyword("trading", "Tradition") is False
# ── Short keyword false-positive prevention ──────────────────────
def test_short_keyword_bat_vs_batterie(self):
"""'bat' vs 'Batterie' → KEIN MATCH (Wortgrenze)"""
assert match_keyword("bat", "Batterie") is False
def test_short_keyword_bat_vs_bat_team(self):
"""'bat' vs 'BAT-Team' → MATCH (Wortgrenze)"""
assert match_keyword("bat", "BAT-Team") is True
def test_short_keyword_rc_vs_archivar(self):
"""'rc' vs 'Archivar' → KEIN MATCH (Wortgrenze)"""
assert match_keyword("rc", "Archivar") is False
def test_short_keyword_rc_vs_rc_plugin(self):
"""'rc' vs 'RC-Plugin' → MATCH (Wortgrenze)"""
assert match_keyword("rc", "RC-Plugin") is True
def test_short_keyword_ddp_vs_ddp_client(self):
"""'ddp' vs 'DDP-Client' → MATCH"""
assert match_keyword("ddp", "DDP-Client") is True
# ═══════════════════════════════════════════════════════════════════════════
# match_keyword_exact() Tests
# ═══════════════════════════════════════════════════════════════════════════
class TestMatchKeywordExact:
"""Exact matching (no stemming/fuzzy) for context keywords."""
def test_exact_match(self):
assert match_keyword_exact("docker", "Docker container") is True
def test_exact_no_stemming(self):
"""Exact match should NOT use stemming."""
# 'container' should NOT match 'Containern' (plural) in exact mode
assert match_keyword_exact("container", "Containern") is False
def test_exact_case_insensitive(self):
assert match_keyword_exact("DOCKER", "docker") is True
# ═══════════════════════════════════════════════════════════════════════════
# match_any_keyword / find_matching_keywords Tests
# ═══════════════════════════════════════════════════════════════════════════
class TestBulkMatching:
"""Bulk matching helper tests."""
def test_match_any(self):
keywords = ["homelab", "netzwerk", "dokumentation"]
assert match_any_keyword(keywords, "Homelabs sind wichtig") is True
assert match_any_keyword(keywords, "Kein Treffer hier") is False
def test_find_matching(self):
keywords = ["homelab", "netzwerk", "dokumentation"]
matched = find_matching_keywords(keywords, "Homelabs und Netzwerke")
assert "homelab" in matched
assert "netzwerk" in matched
assert "dokumentation" not in matched
# ═══════════════════════════════════════════════════════════════════════════
# RoomMap Integration Tests
# ═══════════════════════════════════════════════════════════════════════════
def _make_room_map(rooms_data: list[dict]) -> RoomMap:
"""Helper: create a RoomMap from room data dicts."""
rooms = {}
for r in rooms_data:
rooms[r["room_id"]] = RoomEntry(
room_id=r["room_id"],
name=r.get("name", ""),
theme=r.get("theme", ""),
keywords_100=r.get("keywords_100", []),
keywords_context=r.get("keywords_context", []),
catch_all=r.get("catch_all", False),
)
return RoomMap(
rooms=rooms,
excluded_room_ids=set(),
fact_store_path=Path("/tmp/test"),
)
class TestRoomMapMorphologicalMatching:
"""RoomMap integration with morphological keyword matching."""
@pytest.fixture
def room_map(self):
return _make_room_map([
{
"room_id": "r_lan",
"name": "#LAN-Dokumentation",
"theme": "LAN docs",
"keywords_100": ["homelab", "dokumentation", "netzwerk", "lan"],
"keywords_context": ["docker", "infrastruktur"],
},
{
"room_id": "r_rc",
"name": "#RC-Plugin",
"theme": "RC plugin",
"keywords_100": ["rocketchat", "ddp", "websocket"],
"keywords_context": ["plugin", "gateway"],
},
{
"room_id": "r_admin",
"name": "DM Admin",
"theme": "admin",
"keywords_100": [],
"keywords_context": [],
"catch_all": True,
},
])
def test_find_room_plural_keyword(self, room_map):
"""'Homelabs' should match #LAN-Dokumentation via 'homelab' keyword."""
result = room_map.find_room_by_keywords("Homelabs konfigurieren")
assert result is not None
assert result.room_id == "r_lan"
def test_find_room_dativ_keyword(self, room_map):
"""'dem Homelab' should match via 'homelab' keyword."""
result = room_map.find_room_by_keywords("dem Homelab fehlt RAM")
assert result is not None
assert result.room_id == "r_lan"
def test_find_room_plural_dokumentation(self, room_map):
"""'Dokumentationen' should match via 'dokumentation' keyword."""
result = room_map.find_room_by_keywords("Dokumentationen aktualisieren")
assert result is not None
assert result.room_id == "r_lan"
def test_find_room_compound_ddp(self, room_map):
"""'DDP-WebSocket' should match #RC-Plugin via 'ddp' keyword."""
result = room_map.find_room_by_keywords("DDP-WebSocket Verbindung prüfen")
assert result is not None
assert result.room_id == "r_rc"
def test_is_100_percent_match_plural(self, room_map):
"""is_100_percent_match should use morphological matching."""
lan_room = room_map.get_room_by_id("r_lan")
assert lan_room is not None
assert room_map.is_100_percent_match("Homelabs", lan_room) is True
assert room_map.is_100_percent_match("Dokumentationen", lan_room) is True
assert room_map.is_100_percent_match("Netzwerke", lan_room) is True
def test_is_100_percent_match_false_positive_prevention(self, room_map):
"""is_100_percent_match should NOT match semantically different words."""
lan_room = room_map.get_room_by_id("r_lan")
assert lan_room is not None
# 'homelab' should NOT match 'Homeoffice'
assert room_map.is_100_percent_match("Homeoffice", lan_room) is False
def test_context_keywords_exact_only(self, room_map):
"""Context keywords should use exact matching (no stemming)."""
# 'docker' is a context keyword for #LAN-Dokumentation
# 'Docker-Container' should match (exact substring)
result = room_map.find_room_by_keywords("Docker-Container prüfen")
assert result is not None
assert result.room_id == "r_lan"
def test_100_percent_overrides_context(self, room_map):
"""100% keyword match should override context keyword match."""
# 'rocketchat' is 100% for #RC-Plugin, 'docker' is context for #LAN
# 'rocketchat docker' should go to #RC-Plugin (100% wins)
result = room_map.find_room_by_keywords("rocketchat docker problem")
assert result is not None
assert result.room_id == "r_rc"
def test_no_match_semantically_different(self, room_map):
"""Semantically different words should NOT match."""
result = room_map.find_room_by_keywords("Homeoffice einrichten")
assert result is None # No room matches 'Homeoffice'
# ═══════════════════════════════════════════════════════════════════════════
# RoomEntry.match_score() Integration Tests
# ═══════════════════════════════════════════════════════════════════════════
class TestRoomEntryMatchScore:
"""RoomEntry.match_score() with morphological matching."""
def test_match_score_plural(self):
entry = RoomEntry(
room_id="r1", name="#Test", theme="test",
keywords_100=["homelab", "dokumentation"],
keywords_context=["docker"],
)
# 'Homelabs' → match 'homelab' (1), 'Dokumentationen' → match 'dokumentation' (1)
# 'Docker' → match 'docker' (1) = total 3
score = entry.match_score("Homelabs und Dokumentationen mit Docker")
assert score == 3
def test_match_score_no_false_positive(self):
entry = RoomEntry(
room_id="r1", name="#Test", theme="test",
keywords_100=["bat"],
keywords_context=[],
)
# 'Batterie' should NOT match 'bat' (word boundary)
score = entry.match_score("Batterie wechseln")
assert score == 0
def test_match_score_context_exact(self):
entry = RoomEntry(
room_id="r1", name="#Test", theme="test",
keywords_100=[],
keywords_context=["container"],
)
# 'Containern' should NOT match 'container' in exact mode
score = entry.match_score("Containern verwalten")
assert score == 0
# 'Container' should match
score = entry.match_score("Container verwalten")
assert score == 1
# ═══════════════════════════════════════════════════════════════════════════
# N1: Additional False-Positive Tests
# ═══════════════════════════════════════════════════════════════════════════
class TestFalsePositivePrevention:
"""Additional false-positive tests (N1 from F6 review)."""
def test_lan_in_ulan_bator(self):
"""'lan' should NOT match 'Ulan Bator' (word boundary)."""
assert match_keyword("lan", "Ulan Bator") is False
def test_lan_in_ulan_bator_hyphen(self):
"""'lan' should NOT match 'Ulan-Bator' (word boundary)."""
assert match_keyword("lan", "Ulan-Bator") is False
def test_bat_in_batterie(self):
"""'bat' should NOT match 'Batterie' (word boundary)."""
assert match_keyword("bat", "Batterie") is False
def test_bat_in_batterie_compound(self):
"""'bat' should NOT match 'Batteriewechsel' (word boundary)."""
assert match_keyword("bat", "Batteriewechsel") is False
def test_lan_standalone_matches(self):
"""'lan' should match 'LAN' as standalone word."""
assert match_keyword("lan", "LAN") is True
def test_lan_in_lan_doku_matches(self):
"""'lan' should match 'LAN-Dokumentation' (word boundary)."""
assert match_keyword("lan", "LAN-Dokumentation") is True
def test_bat_standalone_matches(self):
"""'bat' should match 'BAT' as standalone word."""
assert match_keyword("bat", "BAT") is True
# ═══════════════════════════════════════════════════════════════════════════
# R2: Performance Benchmark Tests
# ═══════════════════════════════════════════════════════════════════════════
class TestPerformanceKeywordMatching:
"""Performance benchmark tests (R2 from F6 review).
Verifies that keyword matching with pre-computed stems completes
in <50ms for 100 matches.
"""
def test_performance_keyword_matching(self):
"""Benchmark: 100 keyword matches should complete in <50ms."""
import time
# Simulate a realistic room map with 5 rooms, each with 3-5 keywords
keywords_list = [
["homelab", "dokumentation", "netzwerk", "lan"],
["rocketchat", "ddp", "websocket", "plugin"],
["proxmox", "virtualisierung", "container", "lxc"],
["firewall", "pfsense", "opnsense", "vlan"],
["monitoring", "grafana", "prometheus", "alerting"],
]
# Pre-compute stems for all keywords (R2: once at load time)
precomputed = []
for kws in keywords_list:
precomputed.append([
(kw, precompute_keyword_stems([kw])[0],
precompute_keyword_stems([kw])[0].split())
for kw in kws
])
# Test messages (realistic user inputs)
messages = [
"Homelabs konfigurieren mit VLAN",
"Dokumentationen für das Netzwerk",
"DDP-WebSocket Verbindung prüfen",
"Proxmox Container migrieren",
"Firewalls und pfSense Regeln",
"Grafana Dashboard für Monitoring",
"Plugin für Rocket.Chat entwickeln",
"LXC Container Backup Strategie",
"OPNsense VLAN Routing Problem",
"Prometheus Alerting konfigurieren",
]
# Warm-up: run once to fill caches
for kws in precomputed:
for kw, stemmed, stemmed_words in kws:
for msg in messages:
match_keyword_with_stems(kw, msg, stemmed, stemmed_words)
# Benchmark: 100 matches (10 messages × 10 rounds)
start = time.perf_counter()
iterations = 10
for _ in range(iterations):
for kws in precomputed:
for kw, stemmed, stemmed_words in kws:
for msg in messages:
match_keyword_with_stems(kw, msg, stemmed, stemmed_words)
elapsed_ms = (time.perf_counter() - start) * 1000
total_matches = iterations * sum(len(kws) for kws in precomputed) * len(messages)
# R2 requirement: <50ms for 100 matches
# We're doing ~2000 matches here, so scale accordingly
per_100_ms = (elapsed_ms / total_matches) * 100
assert elapsed_ms < 200, (
f"Performance too slow: {elapsed_ms:.1f}ms for {total_matches} matches "
f"(~{per_100_ms:.1f}ms per 100 matches, limit is <50ms per 100)"
)
def test_precompute_keyword_stems(self):
"""Pre-computed stems should match the same as on-the-fly stemming."""
keywords = ["homelab", "dokumentation", "netzwerk", "lan dokumentation"]
precomputed = precompute_keyword_stems(keywords)
for kw, pre in zip(keywords, precomputed):
on_the_fly = stem_phrase(normalize_keyword(kw))
assert pre == on_the_fly, (
f"Pre-computed stem mismatch for '{kw}': "
f"pre={pre!r}, on_the_fly={on_the_fly!r}"
)
def test_match_keyword_with_stems_equivalent(self):
"""match_keyword_with_stems should produce same results as match_keyword."""
test_cases = [
("homelab", "Homelabs konfigurieren", True),
("dokumentation", "Dokumentationen aktualisieren", True),
("netzwerk", "Netzwerke einrichten", True),
("homelab", "Homeoffice einrichten", False),
("bat", "Batterie wechseln", False),
("lan", "Ulan Bator", False),
("ddp", "DDP-WebSocket", True),
("raum-map", "Raummap", True),
]
for kw, text, expected in test_cases:
stemmed = precompute_keyword_stems([kw])[0]
stemmed_words = stemmed.split()
result = match_keyword_with_stems(kw, text, stemmed, stemmed_words)
assert result is expected, (
f"match_keyword_with_stems({kw!r}, {text!r}) = {result}, "
f"expected {expected}"
)
+1 -1
View File
@@ -19,7 +19,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
# Add the parent directory to the path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
from room_map import RoomMap, RoomEntry
from plugin.archivar.room_map import RoomMap, RoomEntry
class TestR1SessionStickyCatchAllGuard(unittest.TestCase):
@@ -11,7 +11,7 @@ import os
# Add the parent directory to the path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
from room_map import RoomMap, RoomEntry
from plugin.archivar.room_map import RoomMap, RoomEntry
class TestRoomMapWeightedScoring(unittest.TestCase):
@@ -32,7 +32,7 @@ from plugin.archivar.router import BidirectionalRouter
def _make_mock_room_map():
from room_map import RoomMap, RoomEntry
from plugin.archivar.room_map import RoomMap, RoomEntry
rooms = {
"r_lan": RoomEntry(
+1 -1
View File
@@ -40,7 +40,7 @@ from plugin.archivar.router import (
def _make_mock_room_map():
"""Erstelle eine Mock-RoomMap mit Test-Räumen."""
from room_map import RoomMap, RoomEntry
from plugin.archivar.room_map import RoomMap, RoomEntry
rooms = {
"r_lan": RoomEntry(