523 lines
19 KiB
Python
523 lines
19 KiB
Python
# @implements: [F-041] — P-028 Split Keyword Matching (morphologisch, P-108b exakt)
|
|
"""
|
|
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)
|
|
# For multi-word keywords: ALL keyword words must find a fuzzy match
|
|
# in the text. A single matching word is not enough — otherwise
|
|
# 'hermes-gateway' would falsely match 'hermes deployment pipeline'
|
|
# just because 'hermes' == 'hermes'.
|
|
# For single-word keywords: that one word must find a fuzzy match.
|
|
# Words shorter than MIN_FUZZY_LEN are skipped here (they were already
|
|
# checked by Strategy 1/2); if we reach Strategy 3 and a keyword word
|
|
# is too short for fuzzy, the keyword as a whole does NOT match.
|
|
kw_words = kw_norm.split()
|
|
text_words = text_no_hyphen.split()
|
|
|
|
all_fuzzy_matched = True
|
|
for kw_word in kw_words:
|
|
if len(kw_word) < MIN_FUZZY_LEN:
|
|
# Short words can't be reliably fuzzy-matched.
|
|
# If we're here, Strategy 1/2 didn't match them either.
|
|
# For multi-word keywords, this means the keyword doesn't fully match.
|
|
all_fuzzy_matched = False
|
|
break
|
|
found = False
|
|
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:
|
|
found = True
|
|
break
|
|
if not found:
|
|
all_fuzzy_matched = False
|
|
break
|
|
|
|
if all_fuzzy_matched and len(kw_words) > 0:
|
|
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)
|
|
# For multi-word keywords: ALL keyword words must find a fuzzy match
|
|
# in the text. A single matching word is not enough — otherwise
|
|
# 'hermes-gateway' would falsely match 'hermes deployment pipeline'
|
|
# just because 'hermes' == 'hermes'.
|
|
# For single-word keywords: that one word must find a fuzzy match.
|
|
# Words shorter than MIN_FUZZY_LEN are skipped here (they were already
|
|
# checked by Strategy 1/2); if we reach Strategy 3 and a keyword word
|
|
# is too short for fuzzy, the keyword as a whole does NOT match.
|
|
kw_words = kw_norm.split()
|
|
text_words = text_no_hyphen.split()
|
|
|
|
all_fuzzy_matched = True
|
|
for kw_word in kw_words:
|
|
if len(kw_word) < MIN_FUZZY_LEN:
|
|
# Short words can't be reliably fuzzy-matched.
|
|
# If we're here, Strategy 1/2 didn't match them either.
|
|
# For multi-word keywords, this means the keyword doesn't fully match.
|
|
all_fuzzy_matched = False
|
|
break
|
|
found = False
|
|
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:
|
|
found = True
|
|
break
|
|
if not found:
|
|
all_fuzzy_matched = False
|
|
break
|
|
|
|
if all_fuzzy_matched and len(kw_words) > 0:
|
|
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))
|