374e2e7700
TEIL 1 — booster.py: - Split _keyword_to_rooms into _kw100_to_rooms + _kwctx_to_rooms - keywords_100 matched via match_keyword_exact (no fuzzy/stemming, hyphen-insensitive) - keywords_context matched via match_keyword (fuzzy/stemming preserved) - _build_mapping() builds both mappings separately - boost() uses separate matchers per keyword type - _count_unique_matches() checks both mappings with respective matchers - _record_matches() now takes only matched_kw100 (context keywords never tracked) - cleanup_orphaned_rooms() rebuilds both mappings TEIL 2 — room-map.json (data, not in git): - Removed 39 space-variant dual keywords (e.g. 'presence engine' removed, 'presence-engine' kept). No longer needed since match_keyword_exact is hyphen-insensitive. - Backup: .bak-pre-curation-20260805 Tests: 35/35 passed (pytest -k booster)
321 lines
13 KiB
Python
321 lines
13 KiB
Python
"""
|
|
Keyword-Booster für Archivar v5.
|
|
|
|
Verfeinert FAISS-Suchergebnisse durch Keyword-Analyse:
|
|
- Eindeutige Keywords (nur in einem Raum) geben +0.10 Boost
|
|
- Mehrere eindeutige Keywords geben zusätzlichen Boost (+0.05 pro weiterem Keyword)
|
|
- Mehrdeutige Keywords sind neutral
|
|
- Bei knappen Top-2 entscheidet die Anzahl eindeutiger Keywords (+0.05 Boost)
|
|
|
|
P-028 Mitigation (2026-08-05):
|
|
- keywords_100 werden mit match_keyword_exact gematcht (kein Fuzzy/Stemming,
|
|
nur hyphen-insensitiv) → verhindert False Positives wie 'homelab' ↔ 'homelabor'
|
|
- keywords_context werden mit match_keyword gematcht (mit Fuzzy/Stemming,
|
|
da Context-Keywords weniger präzise sein sollen)
|
|
|
|
Usage::
|
|
|
|
from .room_map import RoomMap
|
|
from .booster import KeywordBooster
|
|
|
|
room_map = RoomMap.load()
|
|
booster = KeywordBooster(room_map)
|
|
|
|
scores = [("room_a", 0.87), ("room_b", 0.85), ("room_c", 0.62)]
|
|
text = "Das Plugin hat einen Bug im Router"
|
|
boosted = booster.boost(text, scores)
|
|
# → [("room_a", 0.97), ("room_b", 0.85), ("room_c", 0.62)]
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
from datetime import datetime, timedelta
|
|
from typing import Dict, List, Set, Tuple
|
|
|
|
from .keyword_matcher import match_keyword, match_keyword_exact
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class KeywordBooster:
|
|
"""Keyword-basierter Score-Booster für RoomIndexManager.search()-Ergebnisse.
|
|
|
|
Baut aus einer geladenen RoomMap zwei Mappings:
|
|
- _kw100_to_rooms: keyword → set of room_ids (aus keywords_100)
|
|
- _kwctx_to_rooms: keyword → set of room_ids (aus keywords_context)
|
|
|
|
keywords_100 werden mit match_keyword_exact gematcht (P-028),
|
|
keywords_context mit match_keyword (Fuzzy/Stemming).
|
|
"""
|
|
|
|
def __init__(self, room_map) -> None:
|
|
"""Initialisiere den Booster mit einer geladenen RoomMap.
|
|
|
|
Args:
|
|
room_map: Eine ``RoomMap``-Instanz (aus ``room_map.py``).
|
|
"""
|
|
self._room_map = room_map
|
|
self._kw100_to_rooms: Dict[str, Set[str]] = {}
|
|
self._kwctx_to_rooms: Dict[str, Set[str]] = {}
|
|
self._build_mapping()
|
|
|
|
# ── Mapping ───────────────────────────────────────────────────────
|
|
|
|
def _build_mapping(self) -> None:
|
|
"""Baut kw100 → set(room_ids) und kwctx → set(room_ids) getrennt auf."""
|
|
self._kw100_to_rooms.clear()
|
|
self._kwctx_to_rooms.clear()
|
|
|
|
for room_id, entry in self._room_map.rooms.items():
|
|
if entry.catch_all:
|
|
continue # Catch-All nimmt nicht an Keyword-Boosts teil
|
|
|
|
# keywords_100 → _kw100_to_rooms
|
|
for kw in entry.keywords_100:
|
|
kw_lower = kw.lower().strip()
|
|
if not kw_lower:
|
|
continue
|
|
if kw_lower not in self._kw100_to_rooms:
|
|
self._kw100_to_rooms[kw_lower] = set()
|
|
self._kw100_to_rooms[kw_lower].add(room_id)
|
|
|
|
# keywords_context → _kwctx_to_rooms
|
|
for kw in entry.keywords_context:
|
|
kw_lower = kw.lower().strip()
|
|
if not kw_lower:
|
|
continue
|
|
if kw_lower not in self._kwctx_to_rooms:
|
|
self._kwctx_to_rooms[kw_lower] = set()
|
|
self._kwctx_to_rooms[kw_lower].add(room_id)
|
|
|
|
total_kw = len(self._kw100_to_rooms) + len(self._kwctx_to_rooms)
|
|
logger.debug(
|
|
"KeywordBooster mapping built: %d kw100 + %d kwctx = %d total across %d rooms",
|
|
len(self._kw100_to_rooms),
|
|
len(self._kwctx_to_rooms),
|
|
total_kw,
|
|
len(self._room_map.rooms),
|
|
)
|
|
|
|
# ── Public API ─────────────────────────────────────────────────────
|
|
|
|
def boost(
|
|
self,
|
|
text: str,
|
|
scores: List[Tuple[str, float]],
|
|
) -> List[Tuple[str, float]]:
|
|
"""Wendet Keyword-Boosts auf FAISS-Scores an.
|
|
|
|
Args:
|
|
text: Der Nachrichtentext (für Keyword-Extraktion).
|
|
scores: Liste von ``(room_id, score)``-Tupeln aus
|
|
``RoomIndexManager.search()``, absteigend nach Score sortiert.
|
|
|
|
Returns:
|
|
Neue Liste von ``(room_id, adjusted_score)``-Tupeln,
|
|
absteigend nach adjusted_score sortiert.
|
|
"""
|
|
if not scores:
|
|
return []
|
|
|
|
# ── Score-Dict aufbauen ──────────────────────────────────
|
|
score_dict: Dict[str, float] = {room_id: score for room_id, score in scores}
|
|
|
|
# ── Keywords im Text finden (P-028: getrennte Matcher) ────
|
|
# keywords_100: match_keyword_exact (kein Fuzzy, hyphen-insensitiv)
|
|
matched_kw100: List[str] = [
|
|
kw for kw in self._kw100_to_rooms if match_keyword_exact(kw, text)
|
|
]
|
|
# keywords_context: match_keyword (mit Fuzzy/Stemming)
|
|
matched_kwctx: List[str] = [
|
|
kw for kw in self._kwctx_to_rooms if match_keyword(kw, text)
|
|
]
|
|
|
|
matched_keywords = matched_kw100 + matched_kwctx
|
|
|
|
if not matched_keywords:
|
|
# Keine Keywords → Scores unverändert zurück
|
|
return sorted(scores, key=lambda x: x[1], reverse=True)
|
|
|
|
# ── V8.2 A3: Matches für Demotion-Tracking aufzeichnen ──────
|
|
self._record_matches(text, matched_kw100)
|
|
|
|
# ── Boost-Phase: +0.10 für eindeutige Keywords ────────────
|
|
# Vereinigtes Mapping für Boost-Lookup
|
|
all_kw_to_rooms: Dict[str, Set[str]] = {}
|
|
all_kw_to_rooms.update(self._kw100_to_rooms)
|
|
all_kw_to_rooms.update(self._kwctx_to_rooms)
|
|
|
|
for kw in matched_keywords:
|
|
rooms = all_kw_to_rooms[kw]
|
|
if len(rooms) == 1:
|
|
unique_room = next(iter(rooms))
|
|
if unique_room in score_dict:
|
|
score_dict[unique_room] += 0.10
|
|
logger.debug(
|
|
"Boost +0.10: keyword='%s' → room='%s' (unique)",
|
|
kw,
|
|
unique_room[:8],
|
|
)
|
|
|
|
# ── Zusätzlicher Boost für mehrere eindeutige Keywords ────
|
|
# Zähle eindeutige Keywords pro Raum und gib Bonus für hohe Anzahl
|
|
unique_counts_per_room: Dict[str, int] = {}
|
|
for kw in matched_keywords:
|
|
rooms = all_kw_to_rooms[kw]
|
|
if len(rooms) == 1:
|
|
unique_room = next(iter(rooms))
|
|
if unique_room in score_dict:
|
|
unique_counts_per_room[unique_room] = unique_counts_per_room.get(unique_room, 0) + 1
|
|
|
|
# Bonus: +0.05 für jeden weiteren unique Match über dem ersten
|
|
for room_id, count in unique_counts_per_room.items():
|
|
if count > 1:
|
|
additional_boost = (count - 1) * 0.05
|
|
score_dict[room_id] += additional_boost
|
|
logger.debug(
|
|
"Additional boost +%s: room='%s' has %d unique keywords",
|
|
additional_boost,
|
|
room_id[:8],
|
|
count,
|
|
)
|
|
|
|
# ── Nach Boost sortieren ──────────────────────────────────
|
|
boosted = sorted(score_dict.items(), key=lambda x: x[1], reverse=True)
|
|
|
|
# ── Konfliktlösung: Top-2 Diff < 0.05 ────────────────────
|
|
if len(boosted) >= 2:
|
|
top1_room, top1_score = boosted[0]
|
|
top2_room, top2_score = boosted[1]
|
|
diff = top1_score - top2_score
|
|
|
|
if diff < 0.05:
|
|
# Zähle eindeutige Keyword-Treffer für beide Räume
|
|
unique_count_1 = self._count_unique_matches(text, top1_room)
|
|
unique_count_2 = self._count_unique_matches(text, top2_room)
|
|
|
|
if unique_count_1 > unique_count_2:
|
|
score_dict[top1_room] += 0.05
|
|
logger.debug(
|
|
"Conflict resolution: +0.05 for '%s' (%d unique vs %d)",
|
|
top1_room[:8],
|
|
unique_count_1,
|
|
unique_count_2,
|
|
)
|
|
elif unique_count_2 > unique_count_1:
|
|
score_dict[top2_room] += 0.05
|
|
logger.debug(
|
|
"Conflict resolution: +0.05 for '%s' (%d unique vs %d)",
|
|
top2_room[:8],
|
|
unique_count_2,
|
|
unique_count_1,
|
|
)
|
|
# Bei Gleichstand: kein zusätzlicher Boost
|
|
|
|
# ── Finale Sortierung ─────────────────────────────────────
|
|
return sorted(score_dict.items(), key=lambda x: x[1], reverse=True)
|
|
|
|
# ── Helpers ────────────────────────────────────────────────────────
|
|
|
|
def _count_unique_matches(self, text: str, room_id: str) -> int:
|
|
"""Zählt wie viele eindeutige Keywords (nur in diesem Raum) im Text vorkommen.
|
|
|
|
Prüft beide Mappings (kw100 + kwctx) mit den jeweiligen Matchern.
|
|
|
|
Args:
|
|
text: Der Nachrichtentext (RAW, Normalisierung passiert intern).
|
|
room_id: Die zu prüfende Raum-ID.
|
|
|
|
Returns:
|
|
Anzahl der eindeutigen Keyword-Treffer für diesen Raum.
|
|
"""
|
|
count = 0
|
|
|
|
# keywords_100: match_keyword_exact
|
|
for kw, rooms in self._kw100_to_rooms.items():
|
|
if len(rooms) == 1 and room_id in rooms and match_keyword_exact(kw, text):
|
|
count += 1
|
|
|
|
# keywords_context: match_keyword
|
|
for kw, rooms in self._kwctx_to_rooms.items():
|
|
if len(rooms) == 1 and room_id in rooms and match_keyword(kw, text):
|
|
count += 1
|
|
|
|
return count
|
|
|
|
# ── V8.2 A3: 90-Tage-Demotion ─────────────────────────────────────
|
|
|
|
def _record_matches(self, text: str, matched_kw100: List[str]) -> None:
|
|
"""Zeichnet last_matched-Timestamps für alle getroffenen kw100-Keywords.
|
|
|
|
Wird nach jedem boost()-Aufruf aufgerufen, um die RoomMap-Tracking-Felder
|
|
aktuell zu halten. Nur Keywords in keywords_100 werden getrackt
|
|
(Demotion betrifft nur 100%-Keywords).
|
|
|
|
Args:
|
|
text: Der Nachrichtentext (RAW, Normalisierung passiert intern).
|
|
matched_kw100: Liste der via match_keyword_exact gefundenen kw100-Keywords.
|
|
"""
|
|
now = datetime.now().isoformat()
|
|
for kw in matched_kw100:
|
|
rooms = self._kw100_to_rooms.get(kw, set())
|
|
for room_id in rooms:
|
|
entry = self._room_map.get_room_by_id(room_id)
|
|
if entry is None:
|
|
continue
|
|
if kw in (k.lower() for k in entry.keywords_100):
|
|
self._room_map.set_keyword_last_matched(room_id, kw, now)
|
|
|
|
def demote_stale_keywords(self, max_age_days: int = 90) -> int:
|
|
"""Führt die 90-Tage-Demotion für ungenutzte keywords_100 durch.
|
|
|
|
Delegiert an RoomMap.demote_stale_keywords() und baut danach
|
|
das interne Keyword-Mapping neu auf.
|
|
|
|
Args:
|
|
max_age_days: Maximale Tage ohne Match bevor Demotion.
|
|
|
|
Returns:
|
|
Anzahl der demoted Keywords.
|
|
"""
|
|
demoted = self._room_map.demote_stale_keywords(max_age_days)
|
|
if demoted > 0:
|
|
# Mapping neu bauen, da sich keywords_100/keywords_context geändert haben
|
|
self._build_mapping()
|
|
logger.info(
|
|
"KeywordBooster: %d stale keywords demoted, mapping rebuilt",
|
|
demoted,
|
|
)
|
|
return demoted
|
|
|
|
def reload(self) -> None:
|
|
"""Baut das Keyword-Mapping neu (nach RoomMap.reload())."""
|
|
self._build_mapping()
|
|
|
|
def cleanup_orphaned_rooms(self, valid_room_ids: set) -> int:
|
|
"""M13: Bereinigt das Keyword-Mapping für gelöschte Räume.
|
|
|
|
Baut die internen ``_kw100_to_rooms``- und ``_kwctx_to_rooms``-Mappings
|
|
komplett neu aus der aktuellen RoomMap. Da die RoomMap bereits durch M13
|
|
bereinigt wurde, enthalten die neuen Mappings nur noch gültige Räume.
|
|
|
|
Args:
|
|
valid_room_ids: Set von Raum-IDs, die behalten werden sollen
|
|
(wird für Konsistenz-Logging verwendet, die eigentliche
|
|
Bereinigung erfolgt durch Neuaufbau aus der RoomMap).
|
|
|
|
Returns:
|
|
Anzahl der Keywords im neuen Mapping (0 wenn keine Räume übrig).
|
|
"""
|
|
before = len(self._kw100_to_rooms) + len(self._kwctx_to_rooms)
|
|
self._build_mapping()
|
|
after = len(self._kw100_to_rooms) + len(self._kwctx_to_rooms)
|
|
if before != after:
|
|
logger.info(
|
|
"KeywordBooster GC: mapping rebuilt — %d → %d keywords "
|
|
"(%d orphaned keyword entries removed)",
|
|
before, after, before - after,
|
|
)
|
|
return after
|