proximity.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. # -*- coding: utf-8 -*-
  2. """
  3. Proximity-Strategie für Arbitration.
  4. Berücksichtigt zusätzlich zum Audio-Level auch Raum-Relevanz
  5. und Kontext-Informationen (z.B. letzter aktiver Raum).
  6. """
  7. from dataclasses import dataclass, field
  8. from typing import Any
  9. from trixy_core.arbitration.candidate import ArbitrationCandidate
  10. from trixy_core.arbitration.strategies.base import ArbitrationStrategy
  11. @dataclass
  12. class ProximityWeights:
  13. """Gewichtungen für die Proximity-Strategie."""
  14. audio_level: float = 0.5 # Audio-Level
  15. confidence: float = 0.2 # Confidence
  16. room_relevance: float = 0.2 # Raum-Relevanz
  17. history_bonus: float = 0.1 # Bonus für kürzliche Aktivität
  18. @dataclass
  19. class RoomRelevance:
  20. """Raum-Relevanz-Konfiguration."""
  21. # Räume die für bestimmte Aktionen bevorzugt werden
  22. room_priorities: dict[str, list[str]] = field(default_factory=dict)
  23. # Letzter aktiver Raum bekommt Bonus
  24. last_active_bonus: float = 0.15
  25. # Räume in der Nähe bekommen Bonus
  26. adjacent_rooms: dict[str, list[str]] = field(default_factory=dict)
  27. adjacent_bonus: float = 0.1
  28. class ProximityStrategy(ArbitrationStrategy):
  29. """
  30. Strategie: Berücksichtigt Raum-Relevanz und Kontext.
  31. Diese Strategie kombiniert Audio-Level mit Kontext-Informationen:
  32. - Welcher Raum war zuletzt aktiv?
  33. - Welche Räume sind für bestimmte Aktionen relevant?
  34. - Welche Räume sind benachbart?
  35. Beispiel:
  36. ```python
  37. strategy = ProximityStrategy()
  38. # Kontext mit letztem aktiven Raum
  39. context = {
  40. "last_active_room": "living_room",
  41. "last_active_satellite": "living_room_1",
  42. }
  43. candidates = [
  44. ArbitrationCandidate(
  45. satellite_id="kitchen_1",
  46. room_id="kitchen",
  47. audio_level=0.75,
  48. ),
  49. ArbitrationCandidate(
  50. satellite_id="living_room_1",
  51. room_id="living_room",
  52. audio_level=0.70,
  53. ),
  54. ]
  55. # living_room_1 könnte gewinnen trotz niedrigerem audio_level
  56. # wegen last_active_bonus
  57. winner = strategy.select(candidates, context)
  58. ```
  59. """
  60. def __init__(
  61. self,
  62. weights: ProximityWeights | None = None,
  63. room_relevance: RoomRelevance | None = None,
  64. min_audio_level: float = 0.1,
  65. min_confidence: float = 0.5,
  66. ) -> None:
  67. """
  68. Initialisiert die Strategie.
  69. Args:
  70. weights: Gewichtungen für Score-Berechnung
  71. room_relevance: Raum-Relevanz-Konfiguration
  72. min_audio_level: Minimales Audio-Level
  73. min_confidence: Minimale Confidence
  74. """
  75. self.weights = weights or ProximityWeights()
  76. self.room_relevance = room_relevance or RoomRelevance()
  77. self.min_audio_level = min_audio_level
  78. self.min_confidence = min_confidence
  79. @property
  80. def name(self) -> str:
  81. return "proximity"
  82. @property
  83. def description(self) -> str:
  84. return "Berücksichtigt Audio-Level, Confidence und Raum-Relevanz"
  85. def calculate_score(
  86. self,
  87. candidate: ArbitrationCandidate,
  88. context: dict[str, Any] | None = None,
  89. ) -> float:
  90. """
  91. Berechnet Score mit Raum-Relevanz.
  92. Args:
  93. candidate: Der Kandidat
  94. context: Kontext mit:
  95. - last_active_room: Letzter aktiver Raum
  96. - last_active_satellite: Letzter aktiver Satellite
  97. - intent_type: Art der erwarteten Aktion (optional)
  98. Returns:
  99. Gewichteter Score (0.0-1.0+)
  100. """
  101. context = context or {}
  102. # Basis-Scores
  103. audio_score = candidate.audio_level
  104. confidence_score = candidate.confidence
  105. # Raum-Relevanz berechnen
  106. room_score = self._calculate_room_relevance(candidate, context)
  107. # History-Bonus
  108. history_score = self._calculate_history_bonus(candidate, context)
  109. # Gewichteter Score
  110. score = (
  111. audio_score * self.weights.audio_level +
  112. confidence_score * self.weights.confidence +
  113. room_score * self.weights.room_relevance +
  114. history_score * self.weights.history_bonus
  115. )
  116. # Score-Details speichern
  117. candidate.score_details = {
  118. "audio_level": audio_score,
  119. "audio_weighted": audio_score * self.weights.audio_level,
  120. "confidence": confidence_score,
  121. "confidence_weighted": confidence_score * self.weights.confidence,
  122. "room_relevance": room_score,
  123. "room_weighted": room_score * self.weights.room_relevance,
  124. "history_bonus": history_score,
  125. "history_weighted": history_score * self.weights.history_bonus,
  126. }
  127. return score
  128. def _calculate_room_relevance(
  129. self,
  130. candidate: ArbitrationCandidate,
  131. context: dict[str, Any],
  132. ) -> float:
  133. """Berechnet Raum-Relevanz-Score."""
  134. if not candidate.room_id:
  135. return 0.5 # Neutral wenn kein Raum bekannt
  136. intent_type = context.get("intent_type", "")
  137. room_priorities = self.room_relevance.room_priorities
  138. # Prüfe ob Raum für Intent-Typ bevorzugt wird
  139. if intent_type and intent_type in room_priorities:
  140. preferred_rooms = room_priorities[intent_type]
  141. if candidate.room_id in preferred_rooms:
  142. # Position in Liste bestimmt Bonus
  143. position = preferred_rooms.index(candidate.room_id)
  144. return 1.0 - (position * 0.1)
  145. # Prüfe ob Raum benachbart zum letzten aktiven Raum ist
  146. last_active = context.get("last_active_room", "")
  147. if last_active and last_active in self.room_relevance.adjacent_rooms:
  148. adjacent = self.room_relevance.adjacent_rooms[last_active]
  149. if candidate.room_id in adjacent:
  150. return 0.7 + self.room_relevance.adjacent_bonus
  151. return 0.5 # Neutral
  152. def _calculate_history_bonus(
  153. self,
  154. candidate: ArbitrationCandidate,
  155. context: dict[str, Any],
  156. ) -> float:
  157. """Berechnet History-Bonus für kürzliche Aktivität."""
  158. score = 0.0
  159. # Bonus wenn selber Raum wie zuletzt aktiv
  160. last_active_room = context.get("last_active_room", "")
  161. if last_active_room and candidate.room_id == last_active_room:
  162. score += self.room_relevance.last_active_bonus
  163. # Zusätzlicher Bonus wenn exakt selber Satellite
  164. last_active_satellite = context.get("last_active_satellite", "")
  165. if last_active_satellite and candidate.satellite_id == last_active_satellite:
  166. score += self.room_relevance.last_active_bonus
  167. return min(1.0, score)
  168. def select(
  169. self,
  170. candidates: list[ArbitrationCandidate],
  171. context: dict[str, Any] | None = None,
  172. ) -> ArbitrationCandidate | None:
  173. """
  174. Wählt Kandidaten mit höchstem Proximity-Score.
  175. Args:
  176. candidates: Liste der Kandidaten
  177. context: Kontext-Informationen
  178. Returns:
  179. Kandidat mit höchstem Score oder None
  180. """
  181. valid = self.filter_valid(candidates)
  182. if not valid:
  183. return None
  184. # Scores berechnen
  185. for candidate in valid:
  186. candidate.score = self.calculate_score(candidate, context)
  187. # Höchsten Score auswählen
  188. winner = max(valid, key=lambda c: c.score)
  189. return winner
  190. def validate_candidate(self, candidate: ArbitrationCandidate) -> bool:
  191. """Prüft Audio-Level und Confidence."""
  192. base_valid = super().validate_candidate(candidate)
  193. return (
  194. base_valid and
  195. candidate.audio_level >= self.min_audio_level and
  196. candidate.confidence >= self.min_confidence
  197. )