BUGFIX: FAISS Phase-1 TypeError float+str in adapter_integration.py:292
Root cause: RoomIndexManager.stats() returns a dict with mixed types (bool, int, float, str). sum() iterated over all values and crashed when hitting built_at_iso (str) after built_at (float). Fix: Replace stats() call with direct .size and .room_ids properties. Also commit FAISS Phase-1 files (booster.py, room_index.py, seed_data.py) that were deployed to Gateway but not yet in repo. Tests: 58 passed (0 failures)
This commit is contained in:
@@ -0,0 +1,178 @@
|
||||
"""
|
||||
Keyword-Booster für Archivar v5.
|
||||
|
||||
Verfeinert FAISS-Suchergebnisse durch Keyword-Analyse:
|
||||
- Eindeutige Keywords (nur in einem Raum) geben +0.05 Boost
|
||||
- Mehrdeutige Keywords sind neutral
|
||||
- Bei knappen Top-2 entscheidet die Anzahl eindeutiger Keywords
|
||||
|
||||
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.92), ("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.05 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.05
|
||||
logger.debug(
|
||||
"Boost +0.05: keyword='%s' → room='%s' (unique)",
|
||||
kw,
|
||||
unique_room[:8],
|
||||
)
|
||||
|
||||
# ── 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.03:
|
||||
# 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.02
|
||||
logger.debug(
|
||||
"Conflict resolution: +0.02 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.02
|
||||
logger.debug(
|
||||
"Conflict resolution: +0.02 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()
|
||||
Reference in New Issue
Block a user