d005eb769d
Booster-Strategie: IMMER aktiv (nicht nur bei Konflikten) - router.py: Konfliktbedingung entfernt, Booster auf alle FAISS-Treffer - booster.py: Boost +0.05→+0.10, zusätzlich +0.05 pro weiterem unique Keyword - config.py: FAISS_AUTO_ROUTE 0.85→0.70 Kombiniert semantische Breite (FAISS) mit präziser Keyword-Diskriminierung. Ziel: granulare Raum-Entscheidungen bei überlappenden Themen.
202 lines
8.2 KiB
Python
202 lines
8.2 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)
|
|
|
|
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 typing import Dict, List, Set, Tuple
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class KeywordBooster:
|
|
"""Keyword-basierter Score-Booster für RoomIndexManager.search()-Ergebnisse.
|
|
|
|
Baut aus einer geladenen RoomMap ein Mapping: keyword → set of room_ids.
|
|
Wendet dann Boosts auf FAISS-Scores an basierend auf Keyword-Eindeutigkeit.
|
|
"""
|
|
|
|
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._keyword_to_rooms: Dict[str, Set[str]] = {}
|
|
self._build_mapping()
|
|
|
|
# ── Mapping ───────────────────────────────────────────────────────
|
|
|
|
def _build_mapping(self) -> None:
|
|
"""Baut keyword → set(room_ids) aus allen keywords_100 + keywords_context."""
|
|
self._keyword_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
|
|
|
|
all_keywords: List[str] = []
|
|
all_keywords.extend(entry.keywords_100)
|
|
all_keywords.extend(entry.keywords_context)
|
|
|
|
for kw in all_keywords:
|
|
kw_lower = kw.lower().strip()
|
|
if not kw_lower:
|
|
continue
|
|
if kw_lower not in self._keyword_to_rooms:
|
|
self._keyword_to_rooms[kw_lower] = set()
|
|
self._keyword_to_rooms[kw_lower].add(room_id)
|
|
|
|
logger.debug(
|
|
"KeywordBooster mapping built: %d keywords across %d rooms",
|
|
len(self._keyword_to_rooms),
|
|
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 ───────────────────────────────
|
|
text_lower = text.lower()
|
|
matched_keywords: List[str] = [
|
|
kw for kw in self._keyword_to_rooms if kw in text_lower
|
|
]
|
|
|
|
if not matched_keywords:
|
|
# Keine Keywords → Scores unverändert zurück
|
|
return sorted(scores, key=lambda x: x[1], reverse=True)
|
|
|
|
# ── Boost-Phase: +0.10 für eindeutige Keywords ────────────
|
|
for kw in matched_keywords:
|
|
rooms = self._keyword_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 = self._keyword_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.03 ────────────────────
|
|
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_lower, top1_room)
|
|
unique_count_2 = self._count_unique_matches(text_lower, 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_lower: str, room_id: str) -> int:
|
|
"""Zählt wie viele eindeutige Keywords (nur in diesem Raum) im Text vorkommen.
|
|
|
|
Args:
|
|
text_lower: Der Text in lowercase.
|
|
room_id: Die zu prüfende Raum-ID.
|
|
|
|
Returns:
|
|
Anzahl der eindeutigen Keyword-Treffer für diesen Raum.
|
|
"""
|
|
count = 0
|
|
for kw, rooms in self._keyword_to_rooms.items():
|
|
if len(rooms) == 1 and room_id in rooms and kw in text_lower:
|
|
count += 1
|
|
return count
|
|
|
|
def reload(self) -> None:
|
|
"""Baut das Keyword-Mapping neu (nach RoomMap.reload())."""
|
|
self._build_mapping()
|