hunch-engine 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- hunch/__init__.py +90 -0
- hunch/client.py +128 -0
- hunch/config.py +57 -0
- hunch/engine.py +240 -0
- hunch/loaders.py +80 -0
- hunch/model.py +67 -0
- hunch/phrasing.py +625 -0
- hunch/questions.py +79 -0
- hunch/resolution.py +138 -0
- hunch/resolver.py +351 -0
- hunch/round1.py +303 -0
- hunch/round2.py +374 -0
- hunch/scope.py +181 -0
- hunch/vocabulary.py +224 -0
- hunch_engine-0.2.0.dist-info/METADATA +9 -0
- hunch_engine-0.2.0.dist-info/RECORD +17 -0
- hunch_engine-0.2.0.dist-info/WHEEL +4 -0
hunch/round1.py
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
"""Round 1: judge the *shape* of the request over a tiny state. Never shows Jev an entity list."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
|
|
8
|
+
from hunch.config import Thresholds
|
|
9
|
+
from hunch.model import Area, Entity, HomeModel
|
|
10
|
+
from hunch.phrasing import EN, PHRASEBOOKS, Phrasebook
|
|
11
|
+
from hunch.questions import JSON, Answers, ChoiceQ, NoulQ, Question
|
|
12
|
+
from hunch.resolution import Trace
|
|
13
|
+
from hunch.vocabulary import Verb, Vocabulary
|
|
14
|
+
|
|
15
|
+
FLAGS = (
|
|
16
|
+
"collective",
|
|
17
|
+
"names_specific",
|
|
18
|
+
"has_exception",
|
|
19
|
+
"has_condition",
|
|
20
|
+
"condition_numeric",
|
|
21
|
+
"has_timing",
|
|
22
|
+
"is_destructive",
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _label(area: Area) -> str:
|
|
27
|
+
return f"{area.name} ({', '.join(area.aliases)})" if area.aliases else area.name
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def build_round1_state(home: HomeModel, prompt: str) -> JSON:
|
|
31
|
+
from hunch.scope import verbatim_matches # local import: scope imports this module's Shape
|
|
32
|
+
|
|
33
|
+
# Code fetches, Jev decides: the exposed devices whose name, alias or device name appears in
|
|
34
|
+
# the prompt are handed over with their type and room, so a bare name like "Kücheninsel" can
|
|
35
|
+
# be judged as the light it is. Never the full entity list — that stays out of Round 1.
|
|
36
|
+
mentioned = [
|
|
37
|
+
{
|
|
38
|
+
"name": e.name,
|
|
39
|
+
"type": e.domain,
|
|
40
|
+
"area": home.area_by_id(e.area_id).name
|
|
41
|
+
if e.area_id and home.area_by_id(e.area_id)
|
|
42
|
+
else None,
|
|
43
|
+
}
|
|
44
|
+
for e in verbatim_matches(home.entities + home.scenes, prompt)[:10]
|
|
45
|
+
]
|
|
46
|
+
# The home as a hierarchy — floors with their areas, then areas on no floor — so Jev can see
|
|
47
|
+
# that "unten" is a floor holding these rooms rather than two flat lists to reconcile.
|
|
48
|
+
on_floor = {a for f in home.floors for a in f.area_ids}
|
|
49
|
+
hierarchy: list[JSON] = [
|
|
50
|
+
{
|
|
51
|
+
"floor": f.name,
|
|
52
|
+
"aliases": list(f.aliases),
|
|
53
|
+
"areas": [_label(a) for a in home.areas if a.area_id in f.area_ids],
|
|
54
|
+
}
|
|
55
|
+
for f in home.floors
|
|
56
|
+
]
|
|
57
|
+
loose = [_label(a) for a in home.areas if a.area_id not in on_floor]
|
|
58
|
+
if loose:
|
|
59
|
+
hierarchy.append({"floor": None, "areas": loose})
|
|
60
|
+
return {
|
|
61
|
+
"request": prompt,
|
|
62
|
+
"home": hierarchy,
|
|
63
|
+
"domains": list(home.domains),
|
|
64
|
+
"scenes": [s.name for s in home.scenes],
|
|
65
|
+
"mentioned_devices": mentioned,
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _place_options(home: HomeModel) -> list[str]:
|
|
70
|
+
"""Area labels and floor names as Choice options (floors first so 'unten' has a home)."""
|
|
71
|
+
return [f.name for f in home.floors] + [_label(a) for a in home.areas]
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _place_lookup(home: HomeModel) -> dict[str, tuple[str, ...]]:
|
|
75
|
+
"""Option label -> the area ids it stands for."""
|
|
76
|
+
out: dict[str, tuple[str, ...]] = {f.name: tuple(f.area_ids) for f in home.floors}
|
|
77
|
+
out.update({_label(a): (a.area_id,) for a in home.areas})
|
|
78
|
+
return out
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def build_round1_questions(
|
|
82
|
+
home: HomeModel, vocab: Vocabulary, pb: Phrasebook = EN
|
|
83
|
+
) -> dict[str, Question]:
|
|
84
|
+
qs: dict[str, Question] = {}
|
|
85
|
+
|
|
86
|
+
def _cued(v: Verb) -> str:
|
|
87
|
+
words: list[str] = []
|
|
88
|
+
for book in PHRASEBOOKS.values():
|
|
89
|
+
words.extend(w for w in book.verb_synonyms.get(v.name, ()) if w not in words)
|
|
90
|
+
base = pb.phrasing_for(v.name, v.phrasing)
|
|
91
|
+
return f"{base} — cue words: {', '.join(words)}" if words else base
|
|
92
|
+
|
|
93
|
+
for v in vocab.verbs:
|
|
94
|
+
qs[f"verb:{v.name}"] = NoulQ(pb.verb_question.format(phrasing=_cued(v)))
|
|
95
|
+
for f in home.floors:
|
|
96
|
+
qs[f"floor:{f.floor_id}"] = NoulQ(pb.floor_question.format(name=f.name))
|
|
97
|
+
for a in home.areas:
|
|
98
|
+
qs[f"area:{a.area_id}"] = NoulQ(pb.area_question.format(label=_label(a)))
|
|
99
|
+
for d in home.domains:
|
|
100
|
+
# Jev judges the domain; code just hands it the words people use for it, in every
|
|
101
|
+
# supported language, so "Licht", "lights" and "Rollos" are not left to inference.
|
|
102
|
+
words: list[str] = []
|
|
103
|
+
for book in PHRASEBOOKS.values():
|
|
104
|
+
words.extend(w for w in book.domain_synonyms.get(d, ()) if w not in words)
|
|
105
|
+
label = f"{pb.domain_label(d)} ({', '.join(words)})" if words else pb.domain_label(d)
|
|
106
|
+
qs[f"domain:{d}"] = NoulQ(pb.domain_question.format(domain=label))
|
|
107
|
+
for flag in FLAGS:
|
|
108
|
+
qs[f"flag:{flag}"] = NoulQ(pb.flags[flag])
|
|
109
|
+
if home.scenes:
|
|
110
|
+
qs["scene"] = ChoiceQ(
|
|
111
|
+
pb.scene_question,
|
|
112
|
+
tuple(s.name for s in home.scenes) + ("none",),
|
|
113
|
+
)
|
|
114
|
+
# Two comparators.
|
|
115
|
+
# COMPARE them — "auf" is open OR turn_on, not both — and say "none" or "whole home" outright.
|
|
116
|
+
qs["verb_primary"] = ChoiceQ(
|
|
117
|
+
pb.verb_primary_question,
|
|
118
|
+
tuple(v.name for v in vocab.verbs) + ("several", "none"),
|
|
119
|
+
{
|
|
120
|
+
**{v.name: _cued(v) for v in vocab.verbs},
|
|
121
|
+
"several": pb.special_descriptions["several_verbs"],
|
|
122
|
+
"none": pb.special_descriptions["no_verb"],
|
|
123
|
+
},
|
|
124
|
+
)
|
|
125
|
+
qs["area_primary"] = ChoiceQ(
|
|
126
|
+
pb.area_primary_question,
|
|
127
|
+
tuple(_place_options(home)) + ("several", "whole home", "none"),
|
|
128
|
+
{
|
|
129
|
+
"several": pb.special_descriptions["several_places"],
|
|
130
|
+
"whole home": pb.special_descriptions["whole_home"],
|
|
131
|
+
"none": pb.special_descriptions["no_place"],
|
|
132
|
+
},
|
|
133
|
+
)
|
|
134
|
+
if home.domains:
|
|
135
|
+
descriptions = {
|
|
136
|
+
d: pb.condition_domain_descriptions[d]
|
|
137
|
+
for d in home.domains
|
|
138
|
+
if d in pb.condition_domain_descriptions
|
|
139
|
+
}
|
|
140
|
+
descriptions["none"] = pb.special_descriptions["no_condition"]
|
|
141
|
+
qs["condition_domain"] = ChoiceQ(
|
|
142
|
+
pb.condition_domain_question,
|
|
143
|
+
tuple(home.domains) + ("none",),
|
|
144
|
+
descriptions,
|
|
145
|
+
)
|
|
146
|
+
return qs
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
@dataclass(frozen=True)
|
|
150
|
+
class Shape:
|
|
151
|
+
fired_verbs: tuple[Verb, ...]
|
|
152
|
+
scope_areas: tuple[str, ...]
|
|
153
|
+
scope_domains: tuple[str, ...]
|
|
154
|
+
area_probs: Mapping[str, float]
|
|
155
|
+
domain_probs: Mapping[str, float]
|
|
156
|
+
flags: Mapping[str, float]
|
|
157
|
+
scene: Entity | None
|
|
158
|
+
condition_domain: str | None
|
|
159
|
+
floor_probs: Mapping[str, float] = field(default_factory=dict)
|
|
160
|
+
whole_home: bool = False
|
|
161
|
+
primary_verb: str | None = None # the verb Choice's pick, when it named one
|
|
162
|
+
several_verbs: bool = False # the verb Choice said the request asks for several actions
|
|
163
|
+
|
|
164
|
+
def flag(self, name: str) -> float:
|
|
165
|
+
return self.flags.get(name, 0.0)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def interpret_round1(
|
|
169
|
+
home: HomeModel, vocab: Vocabulary, answers: Answers, thresholds: Thresholds, trace: Trace
|
|
170
|
+
) -> Shape:
|
|
171
|
+
trace.record(1, answers)
|
|
172
|
+
|
|
173
|
+
fired = [
|
|
174
|
+
v
|
|
175
|
+
for v in vocab.verbs
|
|
176
|
+
if trace.decide(f"verb:{v.name}", answers.noul(f"verb:{v.name}"), thresholds.verb_fire)
|
|
177
|
+
]
|
|
178
|
+
primary_verb: str | None = None
|
|
179
|
+
several_verbs = False
|
|
180
|
+
if "verb_primary" in answers.answers:
|
|
181
|
+
# Jev compares. A single winner drops co-firing echoes ("auf" -> open, not turn_on)
|
|
182
|
+
# and can promote a verb the Nouls left just under the bar; "none" means no device
|
|
183
|
+
# action at all ("Wie spät ist es?"); "several" leaves the Noul set alone.
|
|
184
|
+
vp = answers.choice("verb_primary")
|
|
185
|
+
if vp.choice == "none":
|
|
186
|
+
if trace.decide("verb_primary:none", vp.confidence, thresholds.flag):
|
|
187
|
+
for v in fired:
|
|
188
|
+
trace.note(f"verb_dropped:{v.name}:no_action")
|
|
189
|
+
fired = []
|
|
190
|
+
elif vp.choice == "several":
|
|
191
|
+
several_verbs = trace.decide("verb_primary:several", vp.confidence, thresholds.flag)
|
|
192
|
+
elif vp.choice in vocab.names:
|
|
193
|
+
primary = vocab.by_name(vp.choice)
|
|
194
|
+
primary_verb = primary.name
|
|
195
|
+
for v in list(fired):
|
|
196
|
+
if v is not primary:
|
|
197
|
+
trace.note(f"verb_conflict:{v.name}<{primary.name}")
|
|
198
|
+
fired.remove(v)
|
|
199
|
+
if primary not in fired and trace.decide(
|
|
200
|
+
f"verb_primary:{primary.name}",
|
|
201
|
+
max(vp.confidence, answers.noul(f"verb:{primary.name}")),
|
|
202
|
+
thresholds.confirm_band,
|
|
203
|
+
):
|
|
204
|
+
# The Noul and the comparison agree on this verb; neither is certain on its
|
|
205
|
+
# own ("Mach alles aus": 0.65 / 0.35). Fire it — its contribution stays low, so
|
|
206
|
+
# the request ends in a confirmation rather than silence.
|
|
207
|
+
trace.note(f"verb_promoted:{primary.name}")
|
|
208
|
+
fired = [primary]
|
|
209
|
+
if primary in fired:
|
|
210
|
+
# the verb's contribution is the stronger of its own Noul and the comparison
|
|
211
|
+
trace.decide(
|
|
212
|
+
f"verb:{primary.name}",
|
|
213
|
+
max(answers.noul(f"verb:{primary.name}"), vp.confidence),
|
|
214
|
+
thresholds.verb_fire,
|
|
215
|
+
)
|
|
216
|
+
fired_verbs = tuple(fired)
|
|
217
|
+
|
|
218
|
+
area_probs: dict[str, float] = {
|
|
219
|
+
a.area_id: answers.noul(f"area:{a.area_id}") for a in home.areas
|
|
220
|
+
}
|
|
221
|
+
scope_areas: list[str] = []
|
|
222
|
+
floor_probs: dict[str, float] = {
|
|
223
|
+
f.floor_id: answers.noul(f"floor:{f.floor_id}") for f in home.floors
|
|
224
|
+
}
|
|
225
|
+
for f in home.floors:
|
|
226
|
+
floor_fires = trace.decide(
|
|
227
|
+
f"floor:{f.floor_id}", answers.noul(f"floor:{f.floor_id}"), thresholds.scope_fire
|
|
228
|
+
)
|
|
229
|
+
if floor_fires:
|
|
230
|
+
scope_areas.extend(f.area_ids)
|
|
231
|
+
for a in home.areas:
|
|
232
|
+
area_fires = trace.decide(f"area:{a.area_id}", area_probs[a.area_id], thresholds.scope_fire)
|
|
233
|
+
if area_fires and a.area_id not in scope_areas:
|
|
234
|
+
scope_areas.append(a.area_id)
|
|
235
|
+
|
|
236
|
+
whole_home = False
|
|
237
|
+
if "area_primary" in answers.answers:
|
|
238
|
+
ap = answers.choice("area_primary")
|
|
239
|
+
lookup = _place_lookup(home)
|
|
240
|
+
if ap.choice == "none":
|
|
241
|
+
if trace.decide("area_primary:none", ap.confidence, thresholds.flag) and scope_areas:
|
|
242
|
+
trace.note("areas_dropped:no_place:" + ",".join(scope_areas))
|
|
243
|
+
scope_areas = []
|
|
244
|
+
elif ap.choice == "whole home":
|
|
245
|
+
if trace.decide("area_primary:whole_home", ap.confidence, thresholds.flag):
|
|
246
|
+
whole_home = True
|
|
247
|
+
scope_areas = []
|
|
248
|
+
elif ap.choice in lookup and trace.decide(
|
|
249
|
+
"area_primary", ap.confidence, thresholds.place_override
|
|
250
|
+
):
|
|
251
|
+
# Narrowing to one place removes options Jev could still compare in Round 2 (two
|
|
252
|
+
# "Dachterrassentür" doors), so it takes a sure pick; a hesitant one leaves the
|
|
253
|
+
# Noul set standing.
|
|
254
|
+
# Jev singled out one room or floor: that is the place, whatever else half-fired.
|
|
255
|
+
chosen = list(lookup[ap.choice])
|
|
256
|
+
dropped = [x for x in scope_areas if x not in chosen]
|
|
257
|
+
if dropped:
|
|
258
|
+
trace.note("areas_dropped:primary:" + ",".join(dropped))
|
|
259
|
+
scope_areas = chosen
|
|
260
|
+
# "several", or a hesitant pick: the Noul set stands
|
|
261
|
+
|
|
262
|
+
domain_probs = {d: answers.noul(f"domain:{d}") for d in home.domains}
|
|
263
|
+
scope_domains = tuple(
|
|
264
|
+
d
|
|
265
|
+
for d in home.domains
|
|
266
|
+
if trace.decide(f"domain:{d}", domain_probs[d], thresholds.scope_fire)
|
|
267
|
+
)
|
|
268
|
+
|
|
269
|
+
flags = {flag: answers.noul(f"flag:{flag}") for flag in FLAGS}
|
|
270
|
+
|
|
271
|
+
scene: Entity | None = None
|
|
272
|
+
if "scene" in answers.answers:
|
|
273
|
+
c = answers.choice("scene")
|
|
274
|
+
if c.choice != "none" and trace.decide(
|
|
275
|
+
"scene", c.confidence, thresholds.target_choice_conf
|
|
276
|
+
):
|
|
277
|
+
scene = next((s for s in home.scenes if s.name == c.choice), None)
|
|
278
|
+
|
|
279
|
+
condition_domain: str | None = None
|
|
280
|
+
if (
|
|
281
|
+
trace.decide("flag:has_condition", flags["has_condition"], thresholds.flag)
|
|
282
|
+
and "condition_domain" in answers.answers
|
|
283
|
+
):
|
|
284
|
+
c = answers.choice("condition_domain")
|
|
285
|
+
if c.choice != "none" and trace.decide(
|
|
286
|
+
"condition_domain", c.confidence, thresholds.target_choice_conf
|
|
287
|
+
):
|
|
288
|
+
condition_domain = c.choice
|
|
289
|
+
|
|
290
|
+
return Shape(
|
|
291
|
+
fired_verbs=fired_verbs,
|
|
292
|
+
scope_areas=tuple(scope_areas),
|
|
293
|
+
scope_domains=scope_domains,
|
|
294
|
+
area_probs=area_probs,
|
|
295
|
+
domain_probs=domain_probs,
|
|
296
|
+
flags=flags,
|
|
297
|
+
scene=scene,
|
|
298
|
+
condition_domain=condition_domain,
|
|
299
|
+
floor_probs=floor_probs,
|
|
300
|
+
whole_home=whole_home,
|
|
301
|
+
primary_verb=primary_verb,
|
|
302
|
+
several_verbs=several_verbs,
|
|
303
|
+
)
|
hunch/round2.py
ADDED
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
"""Round 2: resolve targets and parameters, only for verbs Round 1 couldn't finish."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
|
|
9
|
+
from hunch.config import Thresholds
|
|
10
|
+
from hunch.model import Entity, HomeModel
|
|
11
|
+
from hunch.phrasing import EN, Phrasebook
|
|
12
|
+
from hunch.questions import JSON, ChoiceQ, NoulQ, Question, ScoreQ
|
|
13
|
+
from hunch.round1 import Shape
|
|
14
|
+
from hunch.scope import device_label
|
|
15
|
+
from hunch.vocabulary import ChoiceSpec, ScoreSpec
|
|
16
|
+
|
|
17
|
+
# Sentinel option appended to every Round 2 Choice so the model can say nothing fits,
|
|
18
|
+
# rather than being forced to pick among options that all miss.
|
|
19
|
+
NO_MATCH = "none of these"
|
|
20
|
+
|
|
21
|
+
# Known states per domain for condition questions. Extend as domains are added.
|
|
22
|
+
DOMAIN_STATES: dict[str, tuple[str, ...]] = {
|
|
23
|
+
"lock": ("locked", "unlocked", "jammed"),
|
|
24
|
+
"cover": ("open", "closed", "opening", "closing"),
|
|
25
|
+
"light": ("on", "off"),
|
|
26
|
+
"switch": ("on", "off"),
|
|
27
|
+
"fan": ("on", "off"),
|
|
28
|
+
"media_player": ("playing", "paused", "idle", "off"),
|
|
29
|
+
"climate": ("heat", "cool", "auto", "off"),
|
|
30
|
+
"alarm_control_panel": ("armed_home", "armed_away", "armed_night", "disarmed", "triggered"),
|
|
31
|
+
"binary_sensor": ("on", "off"),
|
|
32
|
+
"person": ("home", "not_home"),
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _area_name(home: HomeModel, e: Entity) -> str:
|
|
37
|
+
area = home.area_by_id(e.area_id) if e.area_id else None
|
|
38
|
+
return area.name if area else "no area"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True)
|
|
42
|
+
class TargetOption:
|
|
43
|
+
label: str
|
|
44
|
+
entities: tuple[Entity, ...]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _group_by_device(candidates: tuple[Entity, ...]) -> list[list[Entity]]:
|
|
48
|
+
"""Entities grouped by device, in first-seen order. A deviceless entity is its own device."""
|
|
49
|
+
by_device: dict[str, list[Entity]] = {}
|
|
50
|
+
for e in candidates:
|
|
51
|
+
by_device.setdefault(e.device_id or f"entity:{e.entity_id}", []).append(e)
|
|
52
|
+
return list(by_device.values())
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _dedupe(
|
|
56
|
+
raw: list[TargetOption], area_names: Mapping[str, str] | None = None
|
|
57
|
+
) -> tuple[TargetOption, ...]:
|
|
58
|
+
"""Identical labels get the area in brackets when the duplicates sit in different areas
|
|
59
|
+
("Dachterrassentür (Galerie)"), so the model has something real to choose on; otherwise #n."""
|
|
60
|
+
counts: dict[str, int] = {}
|
|
61
|
+
for opt in raw:
|
|
62
|
+
counts[opt.label] = counts.get(opt.label, 0) + 1
|
|
63
|
+
seen: dict[str, int] = {}
|
|
64
|
+
out: list[TargetOption] = []
|
|
65
|
+
for opt in raw:
|
|
66
|
+
if counts[opt.label] == 1:
|
|
67
|
+
out.append(opt)
|
|
68
|
+
continue
|
|
69
|
+
area_id = opt.entities[0].area_id if opt.entities else None
|
|
70
|
+
area = (area_names or {}).get(area_id or "", None)
|
|
71
|
+
dups_share_area = len({o.entities[0].area_id for o in raw if o.label == opt.label}) == 1
|
|
72
|
+
if area and not dups_share_area:
|
|
73
|
+
out.append(TargetOption(f"{opt.label} ({area})", opt.entities))
|
|
74
|
+
else:
|
|
75
|
+
n = seen.get(opt.label, 0) + 1
|
|
76
|
+
seen[opt.label] = n
|
|
77
|
+
out.append(opt if n == 1 else TargetOption(f"{opt.label} #{n}", opt.entities))
|
|
78
|
+
return tuple(out)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def target_options(
|
|
82
|
+
candidates: tuple[Entity, ...], area_names: Mapping[str, str] | None = None
|
|
83
|
+
) -> tuple[TargetOption, ...]:
|
|
84
|
+
"""Options Jev can pick from. A device with one candidate entity is one option. A device
|
|
85
|
+
with several is offered as the device itself ("Bedside lamps" -> both lamps) AND as each
|
|
86
|
+
entity ("Bedside lamps — Bedside left"), because people name either; Jev decides which."""
|
|
87
|
+
raw: list[TargetOption] = []
|
|
88
|
+
for group in _group_by_device(candidates):
|
|
89
|
+
if len(group) == 1:
|
|
90
|
+
raw.append(TargetOption(device_label(group[0]), (group[0],)))
|
|
91
|
+
else:
|
|
92
|
+
raw.append(TargetOption(device_label(group[0]), tuple(group)))
|
|
93
|
+
raw.extend(TargetOption(f"{device_label(e)} — {e.name}", (e,)) for e in group)
|
|
94
|
+
return _dedupe(raw, area_names)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def device_options(
|
|
98
|
+
candidates: tuple[Entity, ...], area_names: Mapping[str, str] | None = None
|
|
99
|
+
) -> tuple[TargetOption, ...]:
|
|
100
|
+
"""One option per *device*: choosing it selects all of that device's candidate entities.
|
|
101
|
+
|
|
102
|
+
People name devices, not entities, so the narrowing device round offers device names
|
|
103
|
+
only; the per-entity split, if it is still needed, happens in Round 2.
|
|
104
|
+
"""
|
|
105
|
+
return _dedupe(
|
|
106
|
+
[TargetOption(device_label(g[0]), tuple(g)) for g in _group_by_device(candidates)],
|
|
107
|
+
area_names,
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@dataclass(frozen=True)
|
|
112
|
+
class Round2Plan:
|
|
113
|
+
exclude: dict[str, tuple[Entity, ...]] = field(default_factory=dict)
|
|
114
|
+
singular: dict[str, tuple[TargetOption, ...]] = field(default_factory=dict)
|
|
115
|
+
collective: dict[str, tuple[Entity, ...]] = field(default_factory=dict)
|
|
116
|
+
params: tuple[str, ...] = ()
|
|
117
|
+
condition_candidates: tuple[Entity, ...] = ()
|
|
118
|
+
# verb -> the numeric literals found in the prompt; Jev is asked which one (if any) is the value
|
|
119
|
+
numeric: Mapping[str, tuple[str, ...]] = field(default_factory=dict)
|
|
120
|
+
# options offered for the condition subject (labels must match the question exactly)
|
|
121
|
+
condition_options: tuple[TargetOption, ...] = ()
|
|
122
|
+
# singular verbs whose options differ only by area while the prompt names no area: ask
|
|
123
|
+
ambiguous_by_area: tuple[str, ...] = ()
|
|
124
|
+
# singular verbs also asked "all of these?" (Jev sees the candidates in the state)
|
|
125
|
+
all_of: tuple[str, ...] = ()
|
|
126
|
+
# collective verbs whose candidates span several device types: Jev is asked per candidate
|
|
127
|
+
include: Mapping[str, tuple[Entity, ...]] = field(default_factory=dict)
|
|
128
|
+
# verbs whose candidates lie outside the named room/floor: Jev is asked whether they were meant
|
|
129
|
+
outside_scope: tuple[str, ...] = ()
|
|
130
|
+
|
|
131
|
+
def all_candidates(self) -> tuple[Entity, ...]:
|
|
132
|
+
seen: dict[str, Entity] = {}
|
|
133
|
+
for ents in (*self.exclude.values(), *self.collective.values(), self.condition_candidates):
|
|
134
|
+
for e in ents:
|
|
135
|
+
seen.setdefault(e.entity_id, e)
|
|
136
|
+
for opts in self.singular.values():
|
|
137
|
+
for o in opts:
|
|
138
|
+
for e in o.entities:
|
|
139
|
+
seen.setdefault(e.entity_id, e)
|
|
140
|
+
return tuple(seen.values())
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
_NUMBER = re.compile(
|
|
144
|
+
r"(?<![\w.,])(\d{1,3}(?:[.,]\d+)?\s*(?:%|°\s*c?|grad\b|prozent\b|percent\b|degrees?\b|celsius\b)?)",
|
|
145
|
+
re.I,
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def numeric_literals(prompt: str) -> tuple[str, ...]:
|
|
150
|
+
"""Code looks up: every number in the prompt, with its unit if it has one, verbatim. Whether
|
|
151
|
+
one of them is the value to set — and how it is meant — is Jev's judgement, not ours."""
|
|
152
|
+
seen: list[str] = []
|
|
153
|
+
for m in _NUMBER.finditer(prompt):
|
|
154
|
+
lit = re.sub(r"\s+", " ", m.group(1).strip())
|
|
155
|
+
if lit and lit not in seen:
|
|
156
|
+
seen.append(lit)
|
|
157
|
+
return tuple(seen)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def parse_number(literal: str) -> float | None:
|
|
161
|
+
m = re.match(r"\d{1,3}(?:[.,]\d+)?", literal)
|
|
162
|
+
return float(m.group(0).replace(",", ".")) if m else None
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def plan_round2(
|
|
166
|
+
home: HomeModel,
|
|
167
|
+
shape: Shape,
|
|
168
|
+
per_verb: Mapping[str, tuple[Entity, ...]],
|
|
169
|
+
thresholds: Thresholds,
|
|
170
|
+
scope_cap: int,
|
|
171
|
+
prompt: str = "",
|
|
172
|
+
widened: frozenset[str] = frozenset(),
|
|
173
|
+
) -> Round2Plan:
|
|
174
|
+
has_exception = shape.flag("has_exception") >= thresholds.flag
|
|
175
|
+
# An exception ("außer der Stehlampe") only makes sense over a set: it implies collective
|
|
176
|
+
# even when the plural flag is low ("Licht im Untergeschoss aus ausser ...").
|
|
177
|
+
collective = shape.flag("collective") >= thresholds.collective or has_exception
|
|
178
|
+
if (
|
|
179
|
+
collective
|
|
180
|
+
and not has_exception # "everything except the fridge" names a device to EXCLUDE
|
|
181
|
+
and shape.flag("names_specific") >= thresholds.specific_device
|
|
182
|
+
):
|
|
183
|
+
collective = False # a plural-looking name of one device: pick it, don't sweep the scope
|
|
184
|
+
area_names = {a.area_id: a.name for a in home.areas}
|
|
185
|
+
exclude: dict[str, tuple[Entity, ...]] = {}
|
|
186
|
+
singular: dict[str, tuple[TargetOption, ...]] = {}
|
|
187
|
+
coll: dict[str, tuple[Entity, ...]] = {}
|
|
188
|
+
params: list[str] = []
|
|
189
|
+
numeric: dict[str, tuple[str, ...]] = {}
|
|
190
|
+
literals = numeric_literals(prompt)
|
|
191
|
+
ambiguous_by_area: list[str] = []
|
|
192
|
+
all_of: list[str] = []
|
|
193
|
+
include: dict[str, tuple[Entity, ...]] = {}
|
|
194
|
+
for verb in shape.fired_verbs:
|
|
195
|
+
cands = per_verb.get(verb.name, ())
|
|
196
|
+
if not cands:
|
|
197
|
+
continue
|
|
198
|
+
if verb.param is not None:
|
|
199
|
+
params.append(verb.name)
|
|
200
|
+
if literals and isinstance(verb.param, ScoreSpec):
|
|
201
|
+
numeric[verb.name] = literals
|
|
202
|
+
if collective and not has_exception:
|
|
203
|
+
coll[verb.name] = cands
|
|
204
|
+
if len({e.domain for e in cands}) > 1:
|
|
205
|
+
# "kitchen lights" over lights AND a fridge switch: Jev judges each candidate.
|
|
206
|
+
include[verb.name] = cands
|
|
207
|
+
elif collective:
|
|
208
|
+
exclude[verb.name] = cands
|
|
209
|
+
else:
|
|
210
|
+
opts = target_options(cands, area_names)
|
|
211
|
+
if len(opts) == 1:
|
|
212
|
+
coll[verb.name] = cands
|
|
213
|
+
else:
|
|
214
|
+
singular[verb.name] = opts
|
|
215
|
+
bases = {re.sub(r" \([^)]*\)$", "", o.label) for o in opts}
|
|
216
|
+
if len(bases) == 1 and not shape.scope_areas:
|
|
217
|
+
# 'Dachterrasse Rollo' in Galerie and Schlafzimmer, no room said: nothing
|
|
218
|
+
# in the request can tell them apart, whatever the model claims.
|
|
219
|
+
ambiguous_by_area.append(verb.name)
|
|
220
|
+
if not verb.is_query:
|
|
221
|
+
all_of.append(verb.name) # Jev, not code, decides "one of them or all of them"
|
|
222
|
+
cond: tuple[Entity, ...] = ()
|
|
223
|
+
if (
|
|
224
|
+
shape.condition_domain in DOMAIN_STATES # a sensor's number is not a state Jev can pick
|
|
225
|
+
and shape.flag("has_condition") >= thresholds.flag
|
|
226
|
+
):
|
|
227
|
+
in_domain = tuple(e for e in home.entities if e.domain == shape.condition_domain)
|
|
228
|
+
in_scope = tuple(e for e in in_domain if e.area_id in shape.scope_areas)
|
|
229
|
+
# The thing observed need not sit in the room being controlled ("Rollos in der Galerie
|
|
230
|
+
# zu wenn die Klimaanlage läuft"): prefer the room, fall back to the whole home.
|
|
231
|
+
cond = in_scope or in_domain
|
|
232
|
+
if len(cond) > scope_cap:
|
|
233
|
+
# Truncating would silently hide the right answer; ask nothing instead and let
|
|
234
|
+
# the engine record that the condition could not be resolved.
|
|
235
|
+
cond = ()
|
|
236
|
+
return Round2Plan(
|
|
237
|
+
exclude,
|
|
238
|
+
singular,
|
|
239
|
+
coll,
|
|
240
|
+
tuple(params),
|
|
241
|
+
cond,
|
|
242
|
+
numeric,
|
|
243
|
+
target_options(cond, area_names) if cond else (),
|
|
244
|
+
tuple(ambiguous_by_area),
|
|
245
|
+
tuple(all_of),
|
|
246
|
+
include,
|
|
247
|
+
tuple(
|
|
248
|
+
v.name
|
|
249
|
+
for v in shape.fired_verbs
|
|
250
|
+
if v.name in widened
|
|
251
|
+
and not shape.several_verbs # Jev already said: several distinct actions
|
|
252
|
+
and (
|
|
253
|
+
not shape.scope_areas
|
|
254
|
+
or any(e.area_id not in shape.scope_areas for e in per_verb.get(v.name, ()))
|
|
255
|
+
)
|
|
256
|
+
),
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def scope_description(home: HomeModel, shape: Shape) -> JSON:
|
|
261
|
+
"""What place the request resolved to, in Jev's terms: the floors it covers completely
|
|
262
|
+
(with their aliases, so 'oben' reads as the whole Obergeschoss), the rooms, or the whole
|
|
263
|
+
home. Round 2 candidates come from this place; without it Jev cannot tell 'Licht oben aus'
|
|
264
|
+
(every light up there) from 'Licht an' (one light, somewhere)."""
|
|
265
|
+
areas = set(shape.scope_areas)
|
|
266
|
+
if not areas:
|
|
267
|
+
return {"place": "the whole home" if shape.whole_home else "no place named"}
|
|
268
|
+
floors = [
|
|
269
|
+
{"name": f.name, "aliases": list(f.aliases)}
|
|
270
|
+
for f in home.floors
|
|
271
|
+
if f.area_ids and set(f.area_ids) <= areas
|
|
272
|
+
]
|
|
273
|
+
covered = {
|
|
274
|
+
a for f in home.floors if f.area_ids and set(f.area_ids) <= areas for a in f.area_ids
|
|
275
|
+
}
|
|
276
|
+
rooms = [a.name for a in home.areas if a.area_id in areas and a.area_id not in covered]
|
|
277
|
+
out: dict[str, JSON] = {"place": "the floors and rooms named in the request"}
|
|
278
|
+
if floors:
|
|
279
|
+
out["whole_floors"] = floors
|
|
280
|
+
if rooms:
|
|
281
|
+
out["rooms"] = rooms
|
|
282
|
+
return out
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def build_round2_state(
|
|
286
|
+
prompt: str, plan: Round2Plan, home: HomeModel, shape: Shape | None = None
|
|
287
|
+
) -> JSON:
|
|
288
|
+
state: dict[str, JSON] = {"request": prompt}
|
|
289
|
+
if shape is not None:
|
|
290
|
+
state["scope"] = scope_description(home, shape)
|
|
291
|
+
state["candidates"] = [
|
|
292
|
+
{
|
|
293
|
+
"name": e.name,
|
|
294
|
+
"aliases": list(e.aliases),
|
|
295
|
+
"area": _area_name(home, e),
|
|
296
|
+
"device": e.device_name,
|
|
297
|
+
"type": e.domain,
|
|
298
|
+
"state": e.state,
|
|
299
|
+
}
|
|
300
|
+
for e in plan.all_candidates()
|
|
301
|
+
]
|
|
302
|
+
return state
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def build_round2_questions(
|
|
306
|
+
shape: Shape, plan: Round2Plan, home: HomeModel, pb: Phrasebook = EN
|
|
307
|
+
) -> dict[str, Question]:
|
|
308
|
+
qs: dict[str, Question] = {}
|
|
309
|
+
for verb_name, ents in plan.exclude.items():
|
|
310
|
+
for e in ents:
|
|
311
|
+
qs[f"exclude:{verb_name}:{e.entity_id}"] = NoulQ(
|
|
312
|
+
pb.exclusion_question.format(name=e.name, area=_area_name(home, e))
|
|
313
|
+
)
|
|
314
|
+
for verb_name, opts in plan.singular.items():
|
|
315
|
+
verb = next(v for v in shape.fired_verbs if v.name == verb_name)
|
|
316
|
+
qs[f"target:{verb_name}"] = ChoiceQ(
|
|
317
|
+
pb.target_question.format(phrasing=pb.phrasing_for(verb.name, verb.phrasing)),
|
|
318
|
+
tuple(o.label for o in opts) + (NO_MATCH,),
|
|
319
|
+
)
|
|
320
|
+
for verb_name in plan.all_of:
|
|
321
|
+
qs[f"all_of:{verb_name}"] = NoulQ(pb.all_of_question)
|
|
322
|
+
for verb_name, ents in plan.include.items():
|
|
323
|
+
verb = next(v for v in shape.fired_verbs if v.name == verb_name)
|
|
324
|
+
for e in ents:
|
|
325
|
+
qs[f"include:{verb_name}:{e.entity_id}"] = NoulQ(
|
|
326
|
+
pb.include_question.format(
|
|
327
|
+
name=e.name,
|
|
328
|
+
type=e.domain,
|
|
329
|
+
area=_area_name(home, e),
|
|
330
|
+
phrasing=pb.phrasing_for(verb.name, verb.phrasing),
|
|
331
|
+
)
|
|
332
|
+
)
|
|
333
|
+
for verb_name in plan.outside_scope:
|
|
334
|
+
verb = next(v for v in shape.fired_verbs if v.name == verb_name)
|
|
335
|
+
qs[f"outside_scope:{verb_name}"] = NoulQ(
|
|
336
|
+
pb.outside_scope_question.format(phrasing=pb.phrasing_for(verb.name, verb.phrasing))
|
|
337
|
+
)
|
|
338
|
+
for verb_name in plan.params:
|
|
339
|
+
verb = next(v for v in shape.fired_verbs if v.name == verb_name)
|
|
340
|
+
spec = verb.param
|
|
341
|
+
if verb_name in plan.numeric and isinstance(spec, ScoreSpec):
|
|
342
|
+
label = pb.param_label(spec.name)
|
|
343
|
+
qs[f"param_value:{verb_name}"] = ChoiceQ(
|
|
344
|
+
pb.param_value_question.format(param=label),
|
|
345
|
+
plan.numeric[verb_name] + (NO_MATCH,),
|
|
346
|
+
{NO_MATCH: pb.param_value_descriptions.get(NO_MATCH, "")},
|
|
347
|
+
)
|
|
348
|
+
qs[f"param_relative:{verb_name}"] = NoulQ(pb.param_relative_question)
|
|
349
|
+
if spec.name == "position":
|
|
350
|
+
qs[f"param_inverted:{verb_name}"] = NoulQ(pb.param_inverted_question)
|
|
351
|
+
if isinstance(spec, ScoreSpec):
|
|
352
|
+
qs[f"param:{verb_name}"] = ScoreQ(
|
|
353
|
+
pb.param_question.format(param=pb.param_label(spec.name)),
|
|
354
|
+
pb.levels_for(spec.name, spec.levels),
|
|
355
|
+
)
|
|
356
|
+
elif isinstance(spec, ChoiceSpec):
|
|
357
|
+
qs[f"param:{verb_name}"] = ChoiceQ(
|
|
358
|
+
pb.param_question.format(param=pb.param_label(spec.name)), spec.options
|
|
359
|
+
)
|
|
360
|
+
if plan.condition_candidates and shape.condition_domain:
|
|
361
|
+
qs["cond_subject"] = ChoiceQ(
|
|
362
|
+
pb.cond_subject_question,
|
|
363
|
+
tuple(o.label for o in plan.condition_options) + (NO_MATCH,),
|
|
364
|
+
{NO_MATCH: pb.special_descriptions["no_condition_subject"]},
|
|
365
|
+
)
|
|
366
|
+
states = DOMAIN_STATES[shape.condition_domain]
|
|
367
|
+
state_desc = dict(pb.condition_state_descriptions.get(shape.condition_domain, {}))
|
|
368
|
+
state_desc[NO_MATCH] = pb.special_descriptions["no_condition_state"]
|
|
369
|
+
qs["cond_state"] = ChoiceQ(
|
|
370
|
+
pb.cond_state_question,
|
|
371
|
+
states + (NO_MATCH,),
|
|
372
|
+
state_desc,
|
|
373
|
+
)
|
|
374
|
+
return qs
|