| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241 |
- # -*- coding: utf-8 -*-
- """
- Proximity-Strategie für Arbitration.
- Berücksichtigt zusätzlich zum Audio-Level auch Raum-Relevanz
- und Kontext-Informationen (z.B. letzter aktiver Raum).
- """
- from dataclasses import dataclass, field
- from typing import Any
- from trixy_core.arbitration.candidate import ArbitrationCandidate
- from trixy_core.arbitration.strategies.base import ArbitrationStrategy
- @dataclass
- class ProximityWeights:
- """Gewichtungen für die Proximity-Strategie."""
- audio_level: float = 0.5 # Audio-Level
- confidence: float = 0.2 # Confidence
- room_relevance: float = 0.2 # Raum-Relevanz
- history_bonus: float = 0.1 # Bonus für kürzliche Aktivität
- @dataclass
- class RoomRelevance:
- """Raum-Relevanz-Konfiguration."""
- # Räume die für bestimmte Aktionen bevorzugt werden
- room_priorities: dict[str, list[str]] = field(default_factory=dict)
- # Letzter aktiver Raum bekommt Bonus
- last_active_bonus: float = 0.15
- # Räume in der Nähe bekommen Bonus
- adjacent_rooms: dict[str, list[str]] = field(default_factory=dict)
- adjacent_bonus: float = 0.1
- class ProximityStrategy(ArbitrationStrategy):
- """
- Strategie: Berücksichtigt Raum-Relevanz und Kontext.
- Diese Strategie kombiniert Audio-Level mit Kontext-Informationen:
- - Welcher Raum war zuletzt aktiv?
- - Welche Räume sind für bestimmte Aktionen relevant?
- - Welche Räume sind benachbart?
- Beispiel:
- ```python
- strategy = ProximityStrategy()
- # Kontext mit letztem aktiven Raum
- context = {
- "last_active_room": "living_room",
- "last_active_satellite": "living_room_1",
- }
- candidates = [
- ArbitrationCandidate(
- satellite_id="kitchen_1",
- room_id="kitchen",
- audio_level=0.75,
- ),
- ArbitrationCandidate(
- satellite_id="living_room_1",
- room_id="living_room",
- audio_level=0.70,
- ),
- ]
- # living_room_1 könnte gewinnen trotz niedrigerem audio_level
- # wegen last_active_bonus
- winner = strategy.select(candidates, context)
- ```
- """
- def __init__(
- self,
- weights: ProximityWeights | None = None,
- room_relevance: RoomRelevance | None = None,
- min_audio_level: float = 0.1,
- min_confidence: float = 0.5,
- ) -> None:
- """
- Initialisiert die Strategie.
- Args:
- weights: Gewichtungen für Score-Berechnung
- room_relevance: Raum-Relevanz-Konfiguration
- min_audio_level: Minimales Audio-Level
- min_confidence: Minimale Confidence
- """
- self.weights = weights or ProximityWeights()
- self.room_relevance = room_relevance or RoomRelevance()
- self.min_audio_level = min_audio_level
- self.min_confidence = min_confidence
- @property
- def name(self) -> str:
- return "proximity"
- @property
- def description(self) -> str:
- return "Berücksichtigt Audio-Level, Confidence und Raum-Relevanz"
- def calculate_score(
- self,
- candidate: ArbitrationCandidate,
- context: dict[str, Any] | None = None,
- ) -> float:
- """
- Berechnet Score mit Raum-Relevanz.
- Args:
- candidate: Der Kandidat
- context: Kontext mit:
- - last_active_room: Letzter aktiver Raum
- - last_active_satellite: Letzter aktiver Satellite
- - intent_type: Art der erwarteten Aktion (optional)
- Returns:
- Gewichteter Score (0.0-1.0+)
- """
- context = context or {}
- # Basis-Scores
- audio_score = candidate.audio_level
- confidence_score = candidate.confidence
- # Raum-Relevanz berechnen
- room_score = self._calculate_room_relevance(candidate, context)
- # History-Bonus
- history_score = self._calculate_history_bonus(candidate, context)
- # Gewichteter Score
- score = (
- audio_score * self.weights.audio_level +
- confidence_score * self.weights.confidence +
- room_score * self.weights.room_relevance +
- history_score * self.weights.history_bonus
- )
- # Score-Details speichern
- candidate.score_details = {
- "audio_level": audio_score,
- "audio_weighted": audio_score * self.weights.audio_level,
- "confidence": confidence_score,
- "confidence_weighted": confidence_score * self.weights.confidence,
- "room_relevance": room_score,
- "room_weighted": room_score * self.weights.room_relevance,
- "history_bonus": history_score,
- "history_weighted": history_score * self.weights.history_bonus,
- }
- return score
- def _calculate_room_relevance(
- self,
- candidate: ArbitrationCandidate,
- context: dict[str, Any],
- ) -> float:
- """Berechnet Raum-Relevanz-Score."""
- if not candidate.room_id:
- return 0.5 # Neutral wenn kein Raum bekannt
- intent_type = context.get("intent_type", "")
- room_priorities = self.room_relevance.room_priorities
- # Prüfe ob Raum für Intent-Typ bevorzugt wird
- if intent_type and intent_type in room_priorities:
- preferred_rooms = room_priorities[intent_type]
- if candidate.room_id in preferred_rooms:
- # Position in Liste bestimmt Bonus
- position = preferred_rooms.index(candidate.room_id)
- return 1.0 - (position * 0.1)
- # Prüfe ob Raum benachbart zum letzten aktiven Raum ist
- last_active = context.get("last_active_room", "")
- if last_active and last_active in self.room_relevance.adjacent_rooms:
- adjacent = self.room_relevance.adjacent_rooms[last_active]
- if candidate.room_id in adjacent:
- return 0.7 + self.room_relevance.adjacent_bonus
- return 0.5 # Neutral
- def _calculate_history_bonus(
- self,
- candidate: ArbitrationCandidate,
- context: dict[str, Any],
- ) -> float:
- """Berechnet History-Bonus für kürzliche Aktivität."""
- score = 0.0
- # Bonus wenn selber Raum wie zuletzt aktiv
- last_active_room = context.get("last_active_room", "")
- if last_active_room and candidate.room_id == last_active_room:
- score += self.room_relevance.last_active_bonus
- # Zusätzlicher Bonus wenn exakt selber Satellite
- last_active_satellite = context.get("last_active_satellite", "")
- if last_active_satellite and candidate.satellite_id == last_active_satellite:
- score += self.room_relevance.last_active_bonus
- return min(1.0, score)
- def select(
- self,
- candidates: list[ArbitrationCandidate],
- context: dict[str, Any] | None = None,
- ) -> ArbitrationCandidate | None:
- """
- Wählt Kandidaten mit höchstem Proximity-Score.
- Args:
- candidates: Liste der Kandidaten
- context: Kontext-Informationen
- Returns:
- Kandidat mit höchstem Score oder None
- """
- valid = self.filter_valid(candidates)
- if not valid:
- return None
- # Scores berechnen
- for candidate in valid:
- candidate.score = self.calculate_score(candidate, context)
- # Höchsten Score auswählen
- winner = max(valid, key=lambda c: c.score)
- return winner
- def validate_candidate(self, candidate: ArbitrationCandidate) -> bool:
- """Prüft Audio-Level und Confidence."""
- base_valid = super().validate_candidate(candidate)
- return (
- base_valid and
- candidate.audio_level >= self.min_audio_level and
- candidate.confidence >= self.min_confidence
- )
|