Debian Codegraph @

tests/test_recognize.py

raw
1 import io
2 from typing import Dict, Set, cast
3
4 import pytest
5
6 from hassil import Intents, recognize, recognize_all, recognize_best
7 from hassil.expression import TextChunk
8 from hassil.intents import SlotList, TextSlotList
9 from hassil.models import MatchEntity, UnmatchedRangeEntity, UnmatchedTextEntity
10 from hassil.recognize import MISSING_ENTITY
11 from hassil.util import normalize_for_matching
12
13 TEST_YAML = """
14 language: "en"
15 intents:
16 TurnOnTV:
17 data:
18 - sentences:
19 - "turn on [the] TV in <area>"
20 - "turn on <area> TV"
21 slots:
22 domain: "media_player"
23 name: "roku"
24 SetBrightness:
25 data:
26 - sentences:
27 - "set [the] brightness in <area> to <brightness>"
28 slots:
29 domain: "light"
30 name: "all"
31 - sentences:
32 - "set [the] brightness of <name> to <brightness>"
33 requires_context:
34 domain: "light"
35 slots:
36 domain: "light"
37 GetTemperature:
38 data:
39 - sentences:
40 - "<what_is> [the] temperature in <area>"
41 slots:
42 domain: "climate"
43 CloseCover:
44 data:
45 - sentences:
46 - "close <name>"
47 requires_context:
48 domain: "cover"
49 slots:
50 domain: "cover"
51 Play:
52 data:
53 - sentences:
54 - "play <name>"
55 excludes_context:
56 domain:
57 - "cover"
58 - "light"
59 CloseCurtains:
60 data:
61 - sentences:
62 - "close [the] curtains [in <area>]"
63 slots:
64 domain: "cover"
65 device_class: "curtain"
66 requires_context:
67 area:
68 slot: true
69 not_copied: "not copied value"
70 copied_to_different:
71 value: null
72 slot: "different_slot"
73 expansion_rules:
74 area: "[the] {area}"
75 name: "[the] {name}"
76 brightness: "{brightness_pct}[%| percent]"
77 what_is: "(what's | whats | what is)"
78 lists:
79 brightness_pct:
80 range:
81 type: percentage
82 from: 0
83 to: 100
84 skip_words:
85 - "please"
86 """
87
88
89 @pytest.fixture
90 def intents():
91 with io.StringIO(TEST_YAML) as test_file:
92 return Intents.from_yaml(test_file)
93
94
95 @pytest.fixture
96 def slot_lists():
97 return {
98 "area": TextSlotList.from_tuples(
99 [("kitchen", "area.kitchen"), ("living room", "area.living_room")]
100 ),
101 "name": TextSlotList.from_tuples(
102 [
103 ("hue", "light.hue", {"domain": "light"}),
104 (
105 "garage door",
106 "cover.garage_door",
107 {"domain": "cover"},
108 ),
109 (
110 "blue curtains",
111 "cover.blue_curtains",
112 {
113 "domain": "cover",
114 "device_class": "curtain",
115 "area": "living_room",
116 },
117 ),
118 (
119 "roku",
120 "media_player.roku",
121 {"domain": "media_player"},
122 ),
123 ]
124 ),
125 }
126
127
128 # pylint: disable=redefined-outer-name
129 def test_turn_on(intents, slot_lists):
130 result = recognize("turn on kitchen TV, please", intents, slot_lists=slot_lists)
131 assert result is not None
132 assert result.intent.name == "TurnOnTV"
133
134 assert result.text_chunks_matched > 0
135
136 area = result.entities["area"]
137 assert area.name == "area"
138 assert area.value == "area.kitchen"
139 assert area.text_span == (8, 15)
140
141 # From YAML
142 assert result.entities["domain"].value == "media_player"
143 assert result.entities["name"].value == "roku"
144
145
146 def test_name_with_trailing_initialism():
147 """A name ending in an initialism matches at the end of a sentence."""
148 yaml_text = """
149 language: "en"
150 intents:
151 TurnOff:
152 data:
153 - sentences:
154 - "turn off {name}"
155 """
156 with io.StringIO(yaml_text) as yaml_file:
157 intents = Intents.from_yaml(yaml_file)
158
159 slot_lists = {"name": TextSlotList.from_tuples([("A.C.", "climate.ac")])}
160
161 for text in ("turn off A.C.", "turn off a.c."):
162 result = recognize(text, intents, slot_lists=slot_lists)
163 assert result is not None, text
164 assert result.entities["name"].value == "climate.ac"
165
166
167 def test_elided_article_without_space():
168 """An elided article attaches to the next word: "nell'ingresso", "l'entrée"."""
169 # Shaped like the real it/fr templates, where the expansion rule carries its
170 # own trailing space and the sentence adds another one before the slot.
171 yaml_text = """
172 language: "it"
173 intents:
174 GetState:
175 data:
176 - sentences:
177 - "quante luci sono accese <in> [<the>] {area}"
178 expansion_rules:
179 in: "(dentro |in | ne[l |i |gli |llo |lla |lle |ll'[ ]])"
180 the: "(l(o |a |e )|i[l] |gli |l'[ ])"
181 """
182 with io.StringIO(yaml_text) as yaml_file:
183 intents = Intents.from_yaml(yaml_file)
184
185 slot_lists = {
186 "area": TextSlotList.from_tuples(
187 [("ingresso", "area.ingresso"), ("soggiorno", "area.soggiorno")]
188 )
189 }
190
191 # Elided, as the language is actually written and spoken.
192 for text in (
193 "quante luci sono accese nell'ingresso",
194 "quante luci sono accese nell’ingresso",
195 # Still accepted with a space, so existing sentences keep matching.
196 "quante luci sono accese nell' ingresso",
197 ):
198 result = recognize(text, intents, slot_lists=slot_lists)
199 assert result is not None, text
200 assert result.entities["area"].value == "area.ingresso", text
201
202 # Unelided forms must not regress.
203 for text in (
204 "quante luci sono accese nel soggiorno",
205 "quante luci sono accese in soggiorno",
206 "quante luci sono accese dentro il soggiorno",
207 ):
208 result = recognize(text, intents, slot_lists=slot_lists)
209 assert result is not None, text
210 assert result.entities["area"].value == "area.soggiorno", text
211
212 # An apostrophe does not license a missing word.
213 assert (
214 recognize("quante luci sono accese nell'atrio", intents, slot_lists=slot_lists)
215 is None
216 )
217
218
219 def test_elided_article_before_name():
220 """The same applies to a name: "l'aria condizionata è accesa"."""
221 yaml_text = """
222 language: "it"
223 intents:
224 GetState:
225 data:
226 - sentences:
227 - "[<the>] {name} è accesa"
228 expansion_rules:
229 the: "(l(o |a |e )|i[l] |gli |l'[ ])"
230 """
231 with io.StringIO(yaml_text) as yaml_file:
232 intents = Intents.from_yaml(yaml_file)
233
234 slot_lists = {
235 "name": TextSlotList.from_tuples(
236 [
237 ("aria condizionata", "climate.ac"),
238 ("lavastoviglie", "switch.dishwasher"),
239 ]
240 )
241 }
242
243 for text in ("l'aria condizionata è accesa", "l’aria condizionata è accesa"):
244 result = recognize(text, intents, slot_lists=slot_lists)
245 assert result is not None, text
246 assert result.entities["name"].value == "climate.ac", text
247
248 result = recognize("la lavastoviglie è accesa", intents, slot_lists=slot_lists)
249 assert result is not None
250 assert result.entities["name"].value == "switch.dishwasher"
251
252
253 # pylint: disable=redefined-outer-name
254 def test_brightness_area(intents, slot_lists):
255 result = recognize(
256 "set the brightness in the living room to 75%", intents, slot_lists=slot_lists
257 )
258 assert result is not None
259 assert result.intent.name == "SetBrightness"
260
261 assert result.text_chunks_matched > 0
262
263 assert result.entities["area"].value == "area.living_room"
264 assert result.entities["brightness_pct"].value == 75
265 assert result.entities["brightness_pct"].text_span == (41, 43)
266
267 # From YAML
268 assert result.entities["domain"].value == "light"
269 assert result.entities["name"].value == "all"
270
271
272 # pylint: disable=redefined-outer-name
273 def test_brightness_area_words(intents, slot_lists):
274 result = recognize(
275 "set brightness in the living room to forty-two percent",
276 intents,
277 slot_lists=slot_lists,
278 language="en",
279 )
280 assert result is not None
281 assert result.intent.name == "SetBrightness"
282
283 assert result.entities["area"].value == "area.living_room"
284 assert result.entities["brightness_pct"].value == 42
285 assert result.entities["brightness_pct"].text_span == (37, 46)
286
287 # From YAML
288 assert result.entities["domain"].value == "light"
289 assert result.entities["domain"].text_span is None
290
291 assert result.entities["name"].value == "all"
292 assert result.entities["name"].text_span is None
293
294
295 # pylint: disable=redefined-outer-name
296 def test_brightness_name(intents, slot_lists):
297 result = recognize(
298 "set brightness of the hue to 50%", intents, slot_lists=slot_lists
299 )
300 assert result is not None
301 assert result.intent.name == "SetBrightness"
302
303 assert result.entities["name"].value == "light.hue"
304 assert result.entities["brightness_pct"].value == 50
305
306 # From YAML
307 assert result.entities["domain"].value == "light"
308
309
310 # pylint: disable=redefined-outer-name
311 def test_brightness_not_cover(intents, slot_lists):
312 result = recognize(
313 "set brightness of the garage door to 50%", intents, slot_lists=slot_lists
314 )
315 assert result is None
316
317
318 # pylint: disable=redefined-outer-name
319 def test_temperature(intents, slot_lists):
320 result = recognize(
321 "what is the temperature in the living room?", intents, slot_lists=slot_lists
322 )
323 assert result is not None
324 assert result.intent.name == "GetTemperature"
325
326 assert result.entities["area"].value == "area.living_room"
327
328 # From YAML
329 assert result.entities["domain"].value == "climate"
330
331
332 # pylint: disable=redefined-outer-name
333 def test_close_name(intents, slot_lists):
334 result = recognize("close the garage door", intents, slot_lists=slot_lists)
335 assert result is not None
336 assert result.intent.name == "CloseCover"
337
338 assert result.entities["name"].value == "cover.garage_door"
339
340 # From YAML
341 assert result.entities["domain"].value == "cover"
342
343
344 # pylint: disable=redefined-outer-name
345 def test_close_not_light(intents, slot_lists):
346 result = recognize("close the hue", intents, slot_lists=slot_lists)
347 assert result is None
348
349
350 # pylint: disable=redefined-outer-name
351 def test_play(intents, slot_lists):
352 result = recognize("play roku", intents, slot_lists=slot_lists)
353 assert result is not None
354 assert result.intent.name == "Play"
355
356 assert result.entities["name"].value == "media_player.roku"
357
358 # From context
359 assert result.context["domain"] == "media_player"
360
361
362 # pylint: disable=redefined-outer-name
363 def test_play_no_cover(intents, slot_lists):
364 result = recognize("play the garage door", intents, slot_lists=slot_lists)
365 assert result is None
366
367
368 # pylint: disable=redefined-outer-name
369 def test_requires_context_implicit(intents, slot_lists):
370 intent_context = {
371 "area": "living room",
372 "not_copied": "not copied value",
373 "copied_to_different": "copied value",
374 }
375
376 result = recognize(
377 "close the curtains",
378 intents,
379 slot_lists=slot_lists,
380 intent_context=intent_context,
381 )
382 assert result is not None
383 assert result.intent.name == "CloseCurtains"
384
385 # test_slot should not be copied over
386 assert set(result.entities.keys()) == {
387 "area",
388 "domain",
389 "device_class",
390 "different_slot",
391 }
392 assert result.entities["area"].value == "living room"
393 assert result.entities["domain"].value == "cover"
394 assert result.entities["device_class"].value == "curtain"
395 assert result.entities["different_slot"].value == "copied value"
396
397
398 # pylint: disable=redefined-outer-name
399 def test_requires_context_none_provided(intents, slot_lists):
400 result = recognize("close the curtains", intents, slot_lists=slot_lists)
401 assert result is None
402
403
404 def test_lists_no_template() -> None:
405 """Ensure list values without template syntax are plain text."""
406 yaml_text = """
407 language: "en"
408 intents: {}
409 lists:
410 test:
411 values:
412 - "test value"
413 """
414
415 with io.StringIO(yaml_text) as test_file:
416 intents = Intents.from_yaml(test_file)
417
418 test_list = cast(TextSlotList, intents.slot_lists["test"])
419 text_in = test_list.values[0].text_in
420 assert isinstance(text_in, TextChunk)
421 assert text_in.text == "test value"
422
423
424 def test_list_text_normalized() -> None:
425 """Ensure list text in values are normalized."""
426 yaml_text = """
427 language: "en"
428 intents:
429 TestIntent:
430 data:
431 - sentences:
432 - "run {test_name}"
433 lists:
434 test_name:
435 values:
436 - "tEsT 1"
437 """
438
439 with io.StringIO(yaml_text) as test_file:
440 intents = Intents.from_yaml(test_file)
441
442 result = recognize("run test 1", intents)
443 assert result is not None
444 assert result.entities["test_name"].value == "tEsT 1"
445
446
447 def test_sentence_text_normalized() -> None:
448 """Ensure sentence text is normalized."""
449 yaml_text = """
450 language: "en"
451 intents:
452 TestIntent:
453 data:
454 - sentences:
455 - "what's the time"
456 """
457
458 with io.StringIO(yaml_text) as test_file:
459 intents = Intents.from_yaml(test_file)
460
461 result = recognize("what’s the time", intents)
462 assert result is not None
463
464
465 def test_skip_prefix() -> None:
466 yaml_text = """
467 language: "en"
468 intents:
469 TestIntent:
470 data:
471 - sentences:
472 - "run {test_name}"
473 lists:
474 test_name:
475 values:
476 - "test"
477 skip_words:
478 - "the"
479 """
480
481 with io.StringIO(yaml_text) as test_file:
482 intents = Intents.from_yaml(test_file)
483
484 result = recognize("run the test", intents)
485 assert result is not None
486 assert result.original_text == "run the test"
487 assert result.entities["test_name"].value == "test"
488 assert result.entities["test_name"].text_span == (8, 12)
489
490
491 def test_skip_sorted() -> None:
492 """Ensure skip words are processed longest first"""
493 yaml_text = """
494 language: "en"
495 intents:
496 TestIntent:
497 data:
498 - sentences:
499 - "run {test_name}"
500 lists:
501 test_name:
502 values:
503 - "test"
504 skip_words:
505 - "could"
506 - "could you"
507 """
508
509 with io.StringIO(yaml_text) as test_file:
510 intents = Intents.from_yaml(test_file)
511
512 result = recognize("could you run test", intents)
513 assert result is not None
514 assert result.entities["test_name"].value == "test"
515
516
517 def test_skip_in_wildcard_start() -> None:
518 yaml_text = """
519 language: "en"
520 intents:
521 TestIntent:
522 data:
523 - sentences:
524 - "{message} broadcast"
525 lists:
526 message:
527 wildcard: true
528 skip_words:
529 - "please"
530 """
531
532 with io.StringIO(yaml_text) as test_file:
533 intents = Intents.from_yaml(test_file)
534
535 result = recognize("please come upstairs broadcast", intents)
536 assert result is not None
537 assert result.entities["message"].value == "please come upstairs"
538
539 # Only the first please should be removed
540 result = recognize("please come upstairs broadcast please", intents)
541 assert result is not None
542 assert result.entities["message"].value == "please come upstairs"
543
544
545 def test_skip_in_wildcard_end() -> None:
546 yaml_text = """
547 language: "en"
548 intents:
549 TestIntent:
550 data:
551 - sentences:
552 - "broadcast {message}"
553 lists:
554 message:
555 wildcard: true
556 skip_words:
557 - "please"
558 """
559
560 with io.StringIO(yaml_text) as test_file:
561 intents = Intents.from_yaml(test_file)
562
563 result = recognize("broadcast please come upstairs", intents)
564 assert result is not None
565 assert result.entities["message"].value == "please come upstairs"
566
567 # Only the first please should be removed
568 result = recognize("please broadcast please come upstairs", intents)
569 assert result is not None
570 assert result.entities["message"].value == "please come upstairs"
571
572
573 def test_skip_all_wildcard() -> None:
574 yaml_text = """
575 language: "en"
576 intents:
577 TestIntent:
578 data:
579 - sentences:
580 - "{message}"
581 lists:
582 message:
583 wildcard: true
584 skip_words:
585 - "please"
586 """
587
588 with io.StringIO(yaml_text) as test_file:
589 intents = Intents.from_yaml(test_file)
590
591 # No skip words should be removed
592 result = recognize("please come upstairs", intents)
593 assert result is not None
594 assert result.entities["message"].value == "please come upstairs"
595
596 result = recognize("come upstairs please", intents)
597 assert result is not None
598 assert result.entities["message"].value == "come upstairs please"
599
600
601 def test_dont_skip_real_text() -> None:
602 yaml_text = """
603 language: "en"
604 intents:
605 TestIntent:
606 data:
607 - sentences:
608 - "I want to watch TV"
609 skip_words:
610 - "I want"
611 """
612
613 with io.StringIO(yaml_text) as test_file:
614 intents = Intents.from_yaml(test_file)
615
616 result = recognize("I want to watch TV", intents)
617 assert result is not None
618
619
620 def test_response_key() -> None:
621 """Check response key in intent data"""
622 yaml_text = """
623 language: "en"
624 intents:
625 TestIntent:
626 data:
627 - sentences:
628 - "this is a test"
629 response: "test_response"
630 """
631
632 with io.StringIO(yaml_text) as test_file:
633 intents = Intents.from_yaml(test_file)
634
635 result = recognize("this is a test", intents)
636 assert result is not None
637 assert result.response == "test_response"
638
639
640 def test_entity_text() -> None:
641 """Ensure original text is returned as well as substituted list value"""
642 yaml_text = """
643 language: "en"
644 intents:
645 TestIntent:
646 data:
647 - sentences:
648 - "run test {name} [now]"
649 - "{name} test"
650 lists:
651 name:
652 values:
653 - in: "alpha "
654 out: "A"
655 """
656
657 with io.StringIO(yaml_text) as test_file:
658 intents = Intents.from_yaml(test_file)
659
660 for sentence in ("run test alpha, now", "run test alpha!", "alpha test"):
661 result = recognize(sentence, intents)
662 assert result is not None, sentence
663 assert result.entities["name"].value == "A"
664 assert result.entities["name"].text_clean == "alpha"
665
666
667 def test_number_text() -> None:
668 """Ensure original text is returned as well as substituted number"""
669 yaml_text = """
670 language: "en"
671 intents:
672 TestIntent:
673 data:
674 - sentences:
675 - "set {percentage}[%] [now]"
676 - "{percentage}[%] set"
677 lists:
678 percentage:
679 range:
680 from: 0
681 to: 100
682 """
683
684 with io.StringIO(yaml_text) as test_file:
685 intents = Intents.from_yaml(test_file)
686
687 for sentence in ("set 50% now", "set 50%", "50% set"):
688 result = recognize(sentence, intents)
689 assert result is not None, sentence
690 assert result.entities["percentage"].value == 50
691 assert result.entities["percentage"].text.strip() == "50"
692
693
694 def test_recognize_all() -> None:
695 """Test recognize_all method for returning all matches."""
696 yaml_text = """
697 language: "en"
698 intents:
699 TestIntent1:
700 data:
701 - sentences:
702 - "run test"
703 TestIntent2:
704 data:
705 - sentences:
706 - "run test"
707 """
708
709 with io.StringIO(yaml_text) as test_file:
710 intents = Intents.from_yaml(test_file)
711
712 results = list(recognize_all("run test", intents))
713 assert len(results) == 2
714 assert {result.intent.name for result in results} == {
715 "TestIntent1",
716 "TestIntent2",
717 }
718
719
720 def test_ignore_whitespace() -> None:
721 """Test option to ignore whitespace between CJK characters during matching."""
722 yaml_text = """
723 language: "zh-TW"
724 settings:
725 ignore_whitespace: true
726 intents:
727 TestIntent1:
728 data:
729 - sentences:
730 - "打開[大]燈"
731 """
732
733 with io.StringIO(yaml_text) as test_file:
734 intents = Intents.from_yaml(test_file)
735
736 # Whitespace between CJK characters is ignored, so all of these match a
737 # template written without spaces.
738 for sentence in ("打開燈", "打開大燈", "打 開 大 燈"):
739 result = recognize(sentence, intents)
740 assert result is not None, sentence
741
742
743 def test_skip_words_ignore_whitespace() -> None:
744 """Test option to ignore whitespace with skip words during matching."""
745 yaml_text = """
746 language: "en"
747 settings:
748 ignore_whitespace: true
749 intents:
750 TestIntent1:
751 data:
752 - sentences:
753 - "ad"
754 skip_words:
755 - "bc"
756 """
757
758 with io.StringIO(yaml_text) as test_file:
759 intents = Intents.from_yaml(test_file)
760
761 result = recognize("abcd", intents)
762 assert result is not None
763
764
765 def test_local_expansion_rules() -> None:
766 """Test local expansion rules, defined at the intent level"""
767 yaml_text = """
768 language: "en"
769 intents:
770 GetSmokeState:
771 data:
772 - expansion_rules:
773 verb: "(are|is)"
774 subject: "[all] [the] light[s]"
775 state: "on"
776 location: "[in <area>]"
777 sentences:
778 - "<verb> <subject> <state> <location>"
779 - "<verb> <subject> <location> <state>"
780 expansion_rules:
781 area: "[the] {area}"
782 lists:
783 area:
784 values:
785 - kitchen
786 """
787
788 with io.StringIO(yaml_text) as test_file:
789 intents = Intents.from_yaml(test_file)
790
791 for sentence in (
792 "are the lights on in the kitchen",
793 "are the lights in the kitchen on",
794 ):
795 result = recognize(sentence, intents)
796 assert result is not None, sentence
797 assert result.intent.name == "GetSmokeState"
798
799
800 def test_local_slot_lists() -> None:
801 """Test local slot lists, defined at the intent level"""
802 yaml_text = """
803 language: "en"
804 intents:
805 PlayTrackAtVolume:
806 data:
807 - sentences:
808 - "play {track} at {volume}[%| percent] volume"
809 lists:
810 track:
811 wildcard: true
812 lists:
813 volume:
814 range:
815 from: 1
816 to: 100
817 """
818
819 with io.StringIO(yaml_text) as test_file:
820 intents = Intents.from_yaml(test_file)
821
822 for sentence in ("play paint it black at 90% volume",):
823 result = recognize(sentence, intents)
824 assert result is not None, sentence
825 assert result.intent.name == "PlayTrackAtVolume"
826 track = result.entities.get("track")
827 volume = result.entities.get("volume")
828 assert isinstance(track, MatchEntity)
829 assert track.value == "paint it black"
830 assert isinstance(volume, MatchEntity)
831 assert volume.value == 90
832
833
834 def test_unmatched_entity() -> None:
835 """Test allow_unmatched_entities option to provide better feedback."""
836 yaml_text = """
837 language: "en"
838 intents:
839 Test:
840 data:
841 - sentences:
842 - "set [all] {domain} in {area} to {percent}[%] now"
843 - "set {area} {domain} to {percent}"
844 lists:
845 area:
846 values:
847 - kitchen
848 - bedroom
849 domain:
850 values:
851 - lights
852 percent:
853 range:
854 type: percentage
855 from: 0
856 to: 100
857 """
858
859 with io.StringIO(yaml_text) as test_file:
860 intents = Intents.from_yaml(test_file)
861
862 sentence = "set fans in living room to 101% now"
863
864 # Should fail without unmatched entities enabled
865 result = recognize(sentence, intents, allow_unmatched_entities=False)
866 assert result is None, f"{sentence} should not match"
867
868 # Should succeed now
869 result = recognize(sentence, intents, allow_unmatched_entities=True)
870 assert result is not None, f"{sentence} should match"
871 assert set(result.unmatched_entities.keys()) == {"domain", "area", "percent"}
872 domain = result.unmatched_entities["domain"]
873 assert isinstance(domain, UnmatchedTextEntity)
874 assert domain.text == "fans "
875
876 area = result.unmatched_entities["area"]
877 assert isinstance(area, UnmatchedTextEntity)
878 assert area.text == "living room "
879
880 percent = result.unmatched_entities["percent"]
881 assert isinstance(percent, UnmatchedRangeEntity)
882 assert percent.value == 101
883
884 sentence = "set all lights in kitchen to blah blah blah now"
885 result = recognize(sentence, intents, allow_unmatched_entities=True)
886 assert result is not None, f"{sentence} should match"
887 assert set(result.unmatched_entities.keys()) == {"percent"}
888
889 percent = result.unmatched_entities["percent"]
890 assert isinstance(percent, UnmatchedTextEntity)
891 assert percent.text == "blah blah blah "
892
893 # Test with unmatched entity at end of sentence
894 sentence = "set kitchen lights to nothing"
895 result = recognize(sentence, intents, allow_unmatched_entities=True)
896 assert result is not None, f"{sentence} should match"
897 assert set(result.unmatched_entities.keys()) == {"percent"}
898
899 percent = result.unmatched_entities["percent"]
900 assert isinstance(percent, UnmatchedTextEntity)
901 assert percent.text == "nothing"
902
903
904 def test_unmatched_range_only() -> None:
905 """Test allow_unmatched_entities option with an out-of-range value only."""
906 yaml_text = """
907 language: "en"
908 intents:
909 Test:
910 data:
911 - sentences:
912 - "set {domain} to {percent}[%]"
913 lists:
914 domain:
915 values:
916 - lights
917 percent:
918 range:
919 type: percentage
920 from: 0
921 to: 100
922 """
923
924 with io.StringIO(yaml_text) as test_file:
925 intents = Intents.from_yaml(test_file)
926
927 sentence = "set lights to 1001%"
928
929 # Should fail without unmatched entities enabled
930 result = recognize(sentence, intents, allow_unmatched_entities=False)
931 assert result is None, f"{sentence} should not match"
932
933 # Should succeed now
934 result = recognize(sentence, intents, allow_unmatched_entities=True)
935 assert result is not None, f"{sentence} should match"
936 assert set(result.entities.keys()) == {"domain"}
937 assert set(result.unmatched_entities.keys()) == {"percent"}
938
939 domain = result.entities["domain"]
940 assert domain.text == "lights"
941
942 percent = result.unmatched_entities["percent"]
943 assert isinstance(percent, UnmatchedRangeEntity)
944 assert percent.value == 1001
945
946
947 def test_no_empty_unmatched_entity() -> None:
948 """Test that unmatched entities are not empty."""
949 yaml_text = """
950 language: "en"
951 intents:
952 Test:
953 data:
954 - sentences:
955 - "turn on {name}[ please]"
956 - "illuminate all[ {area}] lights"
957 - "activate {name} now"
958 lists:
959 name:
960 values:
961 - light
962 area:
963 values:
964 - bedroom
965 """
966
967 with io.StringIO(yaml_text) as test_file:
968 intents = Intents.from_yaml(test_file)
969
970 sentence = "turn on "
971 results = list(recognize_all(sentence, intents, allow_unmatched_entities=True))
972 assert not results, f"{sentence} should not match"
973
974 # With optional word at end
975 sentence = "turn on please"
976 results = list(recognize_all(sentence, intents, allow_unmatched_entities=True))
977 assert not results, f"{sentence} should not match"
978
979 sentence = "illuminate all lights"
980 results = list(recognize_all(sentence, intents, allow_unmatched_entities=True))
981 assert results, f"{sentence} should match"
982 assert len(results) == 1, "Only 1 result expected"
983 assert not results[0].unmatched_entities, "No unmatched entities expected"
984
985 sentence = "illuminate all kitchen lights"
986 results = list(recognize_all(sentence, intents, allow_unmatched_entities=True))
987 assert results, f"{sentence} should match"
988 assert len(results) == 1, "Only 1 result expected"
989 result = results[0]
990 assert set(result.unmatched_entities.keys()) == {"area"}
991 area = result.unmatched_entities["area"]
992 assert isinstance(area, UnmatchedTextEntity)
993 assert area.text == "kitchen "
994
995 # With required word at end
996 sentence = "activate now"
997 results = list(recognize_all(sentence, intents, allow_unmatched_entities=True))
998 assert not results, f"{sentence} should not match"
999
1000
1001 def test_unmatched_entity_context() -> None:
1002 """Test that unmatched entities work with requires/excludes context."""
1003 yaml_text = """
1004 language: "en"
1005 intents:
1006 Test:
1007 data:
1008 - sentences:
1009 - "open {name}"
1010 requires_context:
1011 domain: cover
1012 lists:
1013 name:
1014 values:
1015 - garage door
1016 """
1017
1018 with io.StringIO(yaml_text) as test_file:
1019 intents = Intents.from_yaml(test_file)
1020
1021 sentence = "open garage door"
1022
1023 # Should fail when unmatched entities aren't allowed
1024 result = recognize(sentence, intents, allow_unmatched_entities=False)
1025 assert result is None, f"{sentence} should not match"
1026
1027 # Should succeed now with an unmatched domain entity
1028 result = recognize(sentence, intents, allow_unmatched_entities=True)
1029 assert result is not None, f"{sentence} should match"
1030 assert set(result.unmatched_entities.keys()) == {"domain"}
1031 domain = result.unmatched_entities["domain"]
1032 assert isinstance(domain, UnmatchedTextEntity)
1033 assert domain.text == MISSING_ENTITY
1034
1035 # Now both entities are unmatched
1036 sentence = "open back door"
1037 result = recognize(sentence, intents, allow_unmatched_entities=True)
1038 assert result is not None, f"{sentence} should match"
1039 assert set(result.unmatched_entities.keys()) == {"domain", "name"}
1040
1041 domain = result.unmatched_entities["domain"]
1042 assert isinstance(domain, UnmatchedTextEntity)
1043 assert domain.text == MISSING_ENTITY
1044
1045 name = result.unmatched_entities["name"]
1046 assert isinstance(name, UnmatchedTextEntity)
1047 assert name.text == "back door"
1048
1049
1050 def test_unmatched_slot_name() -> None:
1051 """Test that unmatched entities use slot name instead of list name."""
1052 yaml_text = """
1053 language: "en"
1054 intents:
1055 Test:
1056 data:
1057 - sentences:
1058 - "run {script_name:name}"
1059 - "execute script {script_number:number}"
1060 lists:
1061 script_name:
1062 values:
1063 - stealth mode
1064 script_number:
1065 range:
1066 from: 1
1067 to: 100
1068 """
1069
1070 with io.StringIO(yaml_text) as test_file:
1071 intents = Intents.from_yaml(test_file)
1072
1073 sentence = "run missing name"
1074 result = recognize(sentence, intents, allow_unmatched_entities=True)
1075 assert result is not None, f"{sentence} should match"
1076 assert set(result.unmatched_entities.keys()) == {"name"}
1077
1078 sentence = "execute script wrong number"
1079 result = recognize(sentence, intents, allow_unmatched_entities=True)
1080 assert result is not None, f"{sentence} should match"
1081 assert set(result.unmatched_entities.keys()) == {"number"}
1082
1083 # Outside range
1084 sentence = "execute script 0"
1085 result = recognize(sentence, intents, allow_unmatched_entities=True)
1086 assert result is not None, f"{sentence} should match"
1087 assert set(result.unmatched_entities.keys()) == {"number"}
1088
1089
1090 def test_unmatched_entity_stops_at_optional() -> None:
1091 """Test that unmatched entities do not cross optional text chunks."""
1092 yaml_text = """
1093 language: "en"
1094 intents:
1095 Test:
1096 data:
1097 - sentences:
1098 - "set {area} [to] brightness <brightness>"
1099 - "set {name} [to] brightness <brightness>"
1100 lists:
1101 name:
1102 values:
1103 - lamp
1104 area:
1105 values:
1106 - kitchen
1107 brightness_pct:
1108 range:
1109 type: percentage
1110 from: 0
1111 to: 100
1112 expansion_rules:
1113 brightness: "{brightness_pct}[%| percent]"
1114 """
1115
1116 with io.StringIO(yaml_text) as test_file:
1117 intents = Intents.from_yaml(test_file)
1118
1119 sentence = "set unknown thing to brightness 100%"
1120
1121 # Should fail without unmatched entities enabled
1122 result = recognize(sentence, intents, allow_unmatched_entities=False)
1123 assert result is None, f"{sentence} should not match"
1124
1125 results = list(recognize_all(sentence, intents, allow_unmatched_entities=True))
1126 assert len(results) == 4
1127
1128 area_names: Set[str] = set()
1129 entity_names: Set[str] = set()
1130
1131 for result in results:
1132 assert len(result.unmatched_entities) == 1
1133 area_entity = result.unmatched_entities.get("area")
1134 if area_entity is not None:
1135 assert isinstance(area_entity, UnmatchedTextEntity)
1136 area_names.add(area_entity.text)
1137 else:
1138 name_entity = result.unmatched_entities.get("name")
1139 assert name_entity is not None
1140 assert isinstance(name_entity, UnmatchedTextEntity)
1141 entity_names.add(name_entity.text)
1142
1143 assert area_names == {"unknown thing ", "unknown thing to "}
1144 assert entity_names == {"unknown thing ", "unknown thing to "}
1145
1146
1147 def test_unmatched_entities_dont_share_text() -> None:
1148 """Test that text only goes into one unmatched entity."""
1149 yaml_text = """
1150 language: "en"
1151 intents:
1152 Test:
1153 data:
1154 - sentences:
1155 - "set [the] brightness [of] {name} [to] <brightness>"
1156 lists:
1157 name:
1158 values:
1159 - lamp
1160 brightness_pct:
1161 range:
1162 type: percentage
1163 from: 0
1164 to: 100
1165 expansion_rules:
1166 brightness: "{brightness_pct}[%| percent]"
1167 """
1168
1169 with io.StringIO(yaml_text) as test_file:
1170 intents = Intents.from_yaml(test_file)
1171
1172 sentence = "set brightness of unknown thing to 100%"
1173
1174 # Should fail without unmatched entities enabled
1175 result = recognize(sentence, intents, allow_unmatched_entities=False)
1176 assert result is None, f"{sentence} should not match"
1177
1178 results = list(recognize_all(sentence, intents, allow_unmatched_entities=True))
1179 assert len(results) == 2
1180
1181 possible_names: Set[str] = set()
1182 for result in results:
1183 assert len(result.unmatched_entities) == 1
1184 assert "name" in result.unmatched_entities
1185 name_entity = result.unmatched_entities["name"]
1186 assert isinstance(name_entity, UnmatchedTextEntity)
1187 possible_names.add(name_entity.text)
1188
1189 assert possible_names == {"unknown thing ", "of unknown thing "}
1190
1191
1192 def test_unmatched_entities_cant_skip_words() -> None:
1193 yaml_text = """
1194 language: "en"
1195 intents:
1196 Test:
1197 data:
1198 - sentences:
1199 - "[turn] {name} [to] on"
1200 lists:
1201 name:
1202 values:
1203 - lamp
1204 """
1205
1206 with io.StringIO(yaml_text) as test_file:
1207 intents = Intents.from_yaml(test_file)
1208
1209 sentence = "turn on unknown thing"
1210
1211 # Should fail without unmatched entities enabled
1212 result = recognize(sentence, intents, allow_unmatched_entities=False)
1213 assert result is None, f"{sentence} should not match"
1214
1215 # Should also fail with unmatched entities enabled
1216 results = list(recognize_all(sentence, intents, allow_unmatched_entities=True))
1217 assert len(results) == 0
1218
1219
1220 def test_unmatched_entities_text_chunks_matched() -> None:
1221 yaml_text = """
1222 language: "en"
1223 intents:
1224 Test:
1225 data:
1226 - sentences:
1227 - "[turn] on {name}"
1228 - "[turn] on {name} light"
1229 lists:
1230 name:
1231 values:
1232 - test
1233 """
1234
1235 with io.StringIO(yaml_text) as test_file:
1236 intents = Intents.from_yaml(test_file)
1237
1238 sentence = "turn on unknown light"
1239
1240 results = list(recognize_all(sentence, intents, allow_unmatched_entities=True))
1241 assert len(results) == 2
1242
1243 # '[turn] on {name} light' should have more literal text matched
1244 result_1, result_2 = results
1245 assert result_1.intent_sentence is not None
1246 if result_1.intent_sentence.text == "[turn] on {name}":
1247 assert result_1.text_chunks_matched < result_2.text_chunks_matched
1248 else:
1249 assert result_2.text_chunks_matched < result_1.text_chunks_matched
1250
1251
1252 def test_wildcard() -> None:
1253 """Test wildcard slot lists/entities."""
1254 yaml_text = """
1255 language: "en"
1256 intents:
1257 Test:
1258 data:
1259 - sentences:
1260 - "play {album} by {artist}[ please] now"
1261 - "start {album} by {artist}"
1262 - "begin {album} by artist {artist}"
1263 lists:
1264 album:
1265 wildcard: true
1266 artist:
1267 wildcard: true
1268 """
1269
1270 with io.StringIO(yaml_text) as test_file:
1271 intents = Intents.from_yaml(test_file)
1272
1273 # Case should be kept
1274 sentence = "play The White Album by The Beatles please now"
1275 result = recognize(sentence, intents)
1276 assert result is not None, f"{sentence} should match"
1277 assert set(result.entities.keys()) == {"album", "artist"}
1278 assert result.entities["album"].value == "The White Album"
1279 assert result.entities["album"].is_wildcard
1280 assert result.entities["album"].text_span == (5, 20)
1281 assert result.entities["artist"].value == "The Beatles"
1282 assert result.entities["artist"].is_wildcard
1283 assert result.entities["artist"].text_span == (24, 35)
1284
1285 # Wildcards cannot be empty
1286 sentence = "play by please now"
1287 result = recognize(sentence, intents)
1288 assert result is None, f"{sentence} should not match"
1289
1290 # Test without text at the end
1291 sentence = "start the white album by the beatles."
1292 result = recognize(sentence, intents)
1293 assert result is not None, f"{sentence} should match"
1294 assert set(result.entities.keys()) == {"album", "artist"}
1295 assert result.entities["album"].value == "the white album"
1296 assert result.entities["album"].is_wildcard
1297 assert result.entities["album"].text_span == (6, 21)
1298 assert result.entities["artist"].value == "the beatles"
1299 assert result.entities["artist"].is_wildcard
1300 assert result.entities["artist"].text_span == (25, 36)
1301
1302 # Test use of next word in wildcard
1303 sentence = "play day by day by taken by trees now"
1304 results = list(recognize_all(sentence, intents))
1305 assert results, f"{sentence} should match"
1306 assert len(results) == 3 # 3 "by" words
1307
1308 # Verify each combination of album/artist is present
1309 album_artist = {
1310 (result.entities["album"].value, result.entities["artist"].value)
1311 for result in results
1312 }
1313 assert album_artist == {
1314 ("day", "day by taken by trees"),
1315 ("day by day", "taken by trees"),
1316 ("day by day by taken", "trees"),
1317 }
1318 for result in results:
1319 assert result.entities["album"].is_wildcard
1320 assert result.entities["artist"].is_wildcard
1321
1322 # Test use of next word at end of word in wildcard
1323 sentence = "play Moby by Moby please now"
1324 result = recognize(sentence, intents)
1325 assert result is not None, f"{sentence} should match"
1326 assert set(result.entities.keys()) == {"album", "artist"}
1327 assert result.entities["album"].value == "Moby"
1328 assert result.entities["album"].is_wildcard
1329 assert result.entities["artist"].value == "Moby"
1330 assert result.entities["artist"].is_wildcard
1331
1332 # Add "artist" word
1333 sentence = "begin day by day by artist taken by trees"
1334 result = recognize(sentence, intents)
1335 assert result is not None, f"{sentence} should match"
1336 assert set(result.entities.keys()) == {"album", "artist"}
1337 assert result.entities["album"].value == "day by day"
1338 assert result.entities["album"].is_wildcard
1339 assert result.entities["artist"].value == "taken by trees"
1340 assert result.entities["artist"].is_wildcard
1341
1342
1343 def test_wildcard_degenerate() -> None:
1344 """Test degenerate case for wildcards."""
1345 yaml_text = """
1346 language: "en"
1347 intents:
1348 Test:
1349 data:
1350 - sentences:
1351 - "play {album} by {artist}"
1352 lists:
1353 album:
1354 wildcard: true
1355 artist:
1356 wildcard: true
1357 """
1358
1359 with io.StringIO(yaml_text) as test_file:
1360 intents = Intents.from_yaml(test_file)
1361
1362 sentence = "play by by by by by"
1363 results = list(recognize_all(sentence, intents))
1364 assert results, f"{sentence} should match"
1365 assert len(results) == 3 # 3 valid splits
1366
1367 # Verify each combination
1368 album_artist = {
1369 (result.entities["album"].value, result.entities["artist"].value)
1370 for result in results
1371 }
1372 assert album_artist == {
1373 ("by", "by by by"),
1374 ("by by", "by by"),
1375 ("by by by", "by"),
1376 }
1377
1378
1379 def test_optional_wildcard() -> None:
1380 """Test optional wildcard slot list."""
1381 yaml_text = """
1382 language: "en"
1383 intents:
1384 Test:
1385 data:
1386 - sentences:
1387 - "play {album}[by {artist}]"
1388 lists:
1389 album:
1390 wildcard: true
1391 artist:
1392 wildcard: true
1393 """
1394
1395 with io.StringIO(yaml_text) as test_file:
1396 intents = Intents.from_yaml(test_file)
1397
1398 # With all wildcards
1399 sentence = "play the white album by the beatles"
1400 result = recognize(sentence, intents)
1401 assert result is not None, f"{sentence} should match"
1402 assert set(result.entities.keys()) == {"album", "artist"}
1403 assert result.entities["album"].value == "the white album"
1404 assert result.entities["artist"].value == "the beatles"
1405
1406 # Missing one wildcard
1407 sentence = "play the white album"
1408 result = recognize(sentence, intents)
1409 assert result is not None, f"{sentence} should match"
1410 assert set(result.entities.keys()) == {"album"}
1411 assert result.entities["album"].value == "the white album"
1412
1413
1414 def test_wildcard_slot_name() -> None:
1415 """Test wildcard uses slot instead of list name."""
1416 yaml_text = """
1417 language: "en"
1418 intents:
1419 Test:
1420 data:
1421 - sentences:
1422 - "run {script_name:name}"
1423 lists:
1424 script_name:
1425 wildcard: true
1426 """
1427
1428 with io.StringIO(yaml_text) as test_file:
1429 intents = Intents.from_yaml(test_file)
1430
1431 sentence = "run script 1"
1432 result = recognize(sentence, intents)
1433 assert result is not None, f"{sentence} should match"
1434 assert set(result.entities.keys()) == {"name"}
1435 assert result.entities["name"].value == "script 1"
1436
1437
1438 def test_wildcard_ordering() -> None:
1439 """Test wildcard ordering by number of literal text chunks."""
1440 yaml_text = """
1441 language: "en"
1442 intents:
1443 Test:
1444 data:
1445 - sentences:
1446 - "play {album} by {artist}"
1447 - "play {album} by {artist} in {room}"
1448 lists:
1449 album:
1450 wildcard: true
1451 artist:
1452 wildcard: true
1453 room:
1454 wildcard: true
1455 """
1456
1457 with io.StringIO(yaml_text) as test_file:
1458 intents = Intents.from_yaml(test_file)
1459
1460 sentence = "play the white album by the beatles in the living room"
1461 result = recognize(sentence, intents)
1462 assert result is not None, f"{sentence} should match"
1463 assert set(result.entities.keys()) == {"album", "artist", "room"}
1464 assert result.entities["album"].value == "the white album"
1465 assert result.entities["artist"].value == "the beatles"
1466 assert result.entities["room"].value == "the living room"
1467
1468 # Check that the first sentence can still be used
1469 sentence = "play the white album by the beatles"
1470 result = recognize(sentence, intents)
1471 assert result is not None, f"{sentence} should match"
1472 assert set(result.entities.keys()) == {"album", "artist"}
1473 assert result.entities["album"].value == "the white album"
1474 assert result.entities["artist"].value == "the beatles"
1475
1476
1477 def test_ordering_only_wildcards() -> None:
1478 """Test that re-ordering only affects wildcards."""
1479 yaml_text = """
1480 language: "en"
1481 intents:
1482 Test:
1483 data:
1484 - sentences:
1485 - "turn on {light} in {room}"
1486 - "turn on {light}"
1487 lists:
1488 light:
1489 values:
1490 - light
1491 - light in bedroom
1492 room:
1493 values:
1494 - bedroom
1495 """
1496
1497 with io.StringIO(yaml_text) as test_file:
1498 intents = Intents.from_yaml(test_file)
1499
1500 sentence = "turn on light in bedroom"
1501 result = recognize(sentence, intents)
1502 assert result is not None, f"{sentence} should match"
1503 assert set(result.entities.keys()) == {"light", "room"}
1504 assert result.entities["light"].value == "light"
1505 assert result.entities["room"].value == "bedroom"
1506
1507
1508 def test_wildcard_punctuation() -> None:
1509 """Test that wildcards do not include punctuation."""
1510 yaml_text = """
1511 language: "en"
1512 intents:
1513 Test:
1514 data:
1515 - sentences:
1516 - "is {name} in {zone}"
1517 lists:
1518 name:
1519 wildcard: true
1520 zone:
1521 wildcard: true
1522 """
1523
1524 with io.StringIO(yaml_text) as test_file:
1525 intents = Intents.from_yaml(test_file)
1526
1527 sentence = "is Alice in New York!?"
1528 result = recognize(sentence, intents)
1529 assert result is not None, f"{sentence} should match"
1530 assert set(result.entities.keys()) == {"name", "zone"}
1531 assert result.entities["name"].value == "Alice"
1532 assert result.entities["zone"].value == "New York"
1533
1534
1535 def test_wildcard_inside_word() -> None:
1536 """Test wildcard inside of a word."""
1537 yaml_text = """
1538 language: "en"
1539 intents:
1540 Test:
1541 data:
1542 - sentences:
1543 - "ab{test}cd"
1544 lists:
1545 test:
1546 wildcard: true
1547 """
1548
1549 with io.StringIO(yaml_text) as test_file:
1550 intents = Intents.from_yaml(test_file)
1551
1552 sentence = "ab123cd"
1553 result = recognize(sentence, intents)
1554 assert result is not None, f"{sentence} should match"
1555 assert set(result.entities.keys()) == {"test"}
1556 assert result.entities["test"].value == "123"
1557 assert result.entities["test"].is_wildcard
1558
1559
1560 def test_wildcard_outside_word() -> None:
1561 """Test wildcard outside of a word."""
1562 yaml_text = """
1563 language: "en"
1564 intents:
1565 Test:
1566 data:
1567 - sentences:
1568 - "ab{test} cd"
1569 lists:
1570 test:
1571 wildcard: true
1572 """
1573
1574 with io.StringIO(yaml_text) as test_file:
1575 intents = Intents.from_yaml(test_file)
1576
1577 sentence = "ab123 cd"
1578 result = recognize(sentence, intents)
1579 assert result is not None, f"{sentence} should match"
1580 assert set(result.entities.keys()) == {"test"}
1581 assert result.entities["test"].value == "123"
1582 assert result.entities["test"].is_wildcard
1583
1584 sentence = "ab123cd"
1585 result = recognize(sentence, intents)
1586 assert result is None, f"{sentence} should not match"
1587
1588
1589 def test_wildcard_outside_word_ignore_whitespace() -> None:
1590 """Test wildcard outside of a word when ignoring whitespace."""
1591 yaml_text = """
1592 language: "zh-TW"
1593 settings:
1594 ignore_whitespace: true
1595 intents:
1596 Test:
1597 data:
1598 - sentences:
1599 - "播放{search_query}"
1600 lists:
1601 search_query:
1602 wildcard: true
1603 """
1604
1605 with io.StringIO(yaml_text) as test_file:
1606 intents = Intents.from_yaml(test_file)
1607
1608 # Whitespace *between* CJK characters is ignored on both sides.
1609 for sentence in ("播放五月天", "播放 五月天", "播放 五 月 天"):
1610 result = recognize(sentence, intents)
1611 assert result is not None, f"{sentence} should match"
1612 assert result.entities["search_query"].value == "五月天"
1613
1614 # Whitespace inside a non-CJK value is preserved (issue #276): the setting
1615 # must not glue "Taylor Swift" into "TaylorSwift".
1616 result = recognize("播放 Taylor Swift", intents)
1617 assert result is not None
1618 entity = result.entities["search_query"]
1619 assert entity.value == "Taylor Swift"
1620 assert entity.text == "Taylor Swift"
1621 assert entity.text_clean == "Taylor Swift"
1622
1623
1624 def test_entity_metadata() -> None:
1625 """Ensure metadata is returned for text slots"""
1626 yaml_text = """
1627 language: "en"
1628 intents:
1629 TestIntent:
1630 data:
1631 - sentences:
1632 - "run test {name} [now]"
1633 - "{name} test"
1634 lists:
1635 name:
1636 values:
1637 - in: "alpha "
1638 out: "A"
1639 metadata:
1640 is_alpha: true
1641 """
1642
1643 with io.StringIO(yaml_text) as test_file:
1644 intents = Intents.from_yaml(test_file)
1645
1646 for sentence in ("run test alpha, now", "run test alpha!", "alpha test"):
1647 result = recognize(sentence, intents)
1648 assert result is not None, sentence
1649 assert result.entities["name"].value == "A"
1650 assert result.entities["name"].text_clean == "alpha"
1651 assert result.entities["name"].metadata == {"is_alpha": True}
1652
1653
1654 def test_sentence_metadata() -> None:
1655 """Test that metadata attached to sentences is passed through to the result."""
1656 yaml_text = """
1657 language: "en"
1658 intents:
1659 Test:
1660 data:
1661 - sentences:
1662 - "this is a test"
1663 metadata:
1664 string_key: "test value"
1665 int_key: 1234
1666 """
1667
1668 with io.StringIO(yaml_text) as test_file:
1669 intents = Intents.from_yaml(test_file)
1670
1671 sentence = "this is a test"
1672 result = recognize(sentence, intents)
1673 assert result is not None, f"{sentence} should match"
1674 assert result.intent_metadata is not None, "No metadata"
1675 assert result.intent_metadata == {"string_key": "test value", "int_key": 1234}
1676
1677
1678 def test_digits_calc() -> None:
1679 """Test that metadata attached to sentences is passed through to the result."""
1680 yaml_text = """
1681 language: "en"
1682 intents:
1683 Calculate:
1684 data:
1685 - sentences:
1686 - "calc[ulate] {x} {operator} {y}"
1687 lists:
1688 operator:
1689 values:
1690 - in: "(+|plus)"
1691 out: "+"
1692 x:
1693 range:
1694 from: 0
1695 to: 100
1696 digits: true
1697 words: true
1698 y:
1699 range:
1700 from: 0
1701 to: 100
1702 digits: true
1703 words: true
1704 """
1705
1706 with io.StringIO(yaml_text) as test_file:
1707 intents = Intents.from_yaml(test_file)
1708
1709 sentence = "calc 1 + 2"
1710 result = recognize(sentence, intents)
1711 assert result is not None, f"{sentence} should match"
1712 assert result.entities.keys() == {"x", "operator", "y"}
1713 assert result.entities["x"].value == 1
1714 assert result.entities["operator"].value == "+"
1715 assert result.entities["y"].value == 2
1716
1717 sentence = "calc 1 plus two"
1718 result = recognize(sentence, intents)
1719 assert result is not None, f"{sentence} should match"
1720 assert result.entities.keys() == {"x", "operator", "y"}
1721 assert result.entities["x"].value == 1
1722 assert result.entities["operator"].value == "+"
1723 assert result.entities["y"].value == 2
1724
1725
1726 def test_range_params_calc() -> None:
1727 """Test that params attached to RangeSlotList affect the parsing."""
1728 yaml_text = """
1729 language: "en"
1730 intents:
1731 Calculate:
1732 data:
1733 - sentences:
1734 - "calc[ulate] {x} {operator} {y}"
1735 lists:
1736 operator:
1737 values:
1738 - in: "(+|plus)"
1739 out: "+"
1740 x:
1741 range:
1742 from: 0
1743 to: 100
1744 digits: false
1745 words: true
1746 y:
1747 range:
1748 from: 0
1749 to: 100
1750 digits: true
1751 words: false
1752 """
1753
1754 with io.StringIO(yaml_text) as test_file:
1755 intents = Intents.from_yaml(test_file)
1756
1757 # x can't have digits
1758 sentence = "calc 1 + 2"
1759 result = recognize(sentence, intents)
1760 assert result is None, f"{sentence} should not match"
1761
1762 # y can't have words
1763 sentence = "calc one plus two"
1764 result = recognize(sentence, intents)
1765 assert result is None, f"{sentence} should not match"
1766
1767 sentence = "calc one + 2"
1768 result = recognize(sentence, intents)
1769 assert result is not None, f"{sentence} should match"
1770 assert result.entities.keys() == {"x", "operator", "y"}
1771 assert result.entities["x"].value == 1
1772 assert result.entities["operator"].value == "+"
1773 assert result.entities["y"].value == 2
1774
1775
1776 def test_range_rule_sets_calc() -> None:
1777 """Test that params attached to RangeSlotList affect the parsing."""
1778 # https://github.com/rhasspy/unicode-rbnf/blob/master/unicode_rbnf/engine.py#L13
1779 yaml_text = """
1780 language: "en"
1781 intents:
1782 Calculate:
1783 data:
1784 - sentences:
1785 - "calc[ulate] {x} {operator} {y}"
1786 lists:
1787 operator:
1788 values:
1789 - in: "(+|plus)"
1790 out: "+"
1791 x:
1792 range:
1793 from: 0
1794 to: 3000
1795 digits: true
1796 words: true
1797 y:
1798 range:
1799 from: 0
1800 to: 3000
1801 digits: true
1802 words: true
1803 """
1804
1805 with io.StringIO(yaml_text) as test_file:
1806 intents = Intents.from_yaml(test_file)
1807
1808 sentence = "calc one thousand nine hundred ninety-nine + 23"
1809 result = recognize(sentence, intents)
1810 assert result is not None, f"{sentence} should match"
1811 assert result.entities.keys() == {"x", "operator", "y"}
1812 assert result.entities["x"].value == 1999
1813 assert result.entities["operator"].value == "+"
1814 assert result.entities["y"].value == 23
1815
1816 sentence = "calc 23 + nineteen ninety-nine"
1817 result = recognize(sentence, intents)
1818 assert result is None, f"{sentence} should not match"
1819
1820
1821 # pylint: disable=redefined-outer-name
1822 def test_context_dict(intents, slot_lists):
1823 yaml_text = """
1824 language: "en"
1825 intents:
1826 TestIntent:
1827 data:
1828 - sentences:
1829 - "test sentence"
1830 requires_context:
1831 slot1:
1832 value: value1
1833 slot: true
1834 excludes_context:
1835 slot2: value2
1836 """
1837
1838 with io.StringIO(yaml_text) as test_file:
1839 intents = Intents.from_yaml(test_file)
1840
1841 slot1 = {"value": "value1", "text": "Value One"}
1842
1843 # Try includes context
1844 result = recognize(
1845 "test sentence",
1846 intents,
1847 slot_lists=slot_lists,
1848 intent_context={"slot1": slot1},
1849 )
1850 assert result is not None
1851 assert result.context.keys() == {"slot1"}
1852 assert result.context["slot1"] == slot1
1853 assert result.entities.keys() == {"slot1"}
1854 assert result.entities["slot1"].value == "value1"
1855 assert result.entities["slot1"].text == "Value One"
1856
1857 # Try excludes context
1858 result = recognize(
1859 "test sentence",
1860 intents,
1861 slot_lists=slot_lists,
1862 intent_context={"slot1": slot1, "slot2": {"value": "value2"}},
1863 )
1864 assert result is None
1865
1866
1867 # pylint: disable=redefined-outer-name
1868 def test_range_multiplier(intents, slot_lists):
1869 yaml_text = """
1870 language: "en"
1871 intents:
1872 SetVolume:
1873 data:
1874 - sentences:
1875 - "set volume to {volume_level}"
1876 lists:
1877 volume_level:
1878 range:
1879 from: 0
1880 to: 100
1881 multiplier: 0.01
1882 """
1883
1884 with io.StringIO(yaml_text) as test_file:
1885 intents = Intents.from_yaml(test_file)
1886
1887 result = recognize("set volume to 50", intents)
1888 assert result is not None
1889 assert result.entities.keys() == {"volume_level"}
1890 assert result.entities["volume_level"].value == 0.5
1891 assert result.entities["volume_level"].text == "50"
1892
1893
1894 def test_recognize_best():
1895 yaml_text = """
1896 language: "en"
1897 intents:
1898 TurnOn:
1899 data:
1900 - sentences:
1901 - "{anything} lamp"
1902 metadata:
1903 best_key: "best value"
1904 - sentences:
1905 - "turn on {area} lamp"
1906 - "turn on {name}"
1907 lists:
1908 area:
1909 values:
1910 - bedroom
1911 name:
1912 values:
1913 - bedroom lamp
1914 anything:
1915 wildcard: true
1916 """
1917
1918 with io.StringIO(yaml_text) as test_file:
1919 intents = Intents.from_yaml(test_file)
1920
1921 # Should match the sentence with the wildcard slot because it's listed first.
1922 result = recognize("turn on bedroom lamp", intents) # not best
1923 assert result is not None
1924 assert result.entities.keys() == {"anything"}
1925
1926 # Should match the sentence with the wildcard slot because of its metadata.
1927 result = recognize_best(
1928 "turn on bedroom lamp", intents, best_metadata_key="best_key"
1929 )
1930 assert result is not None
1931 assert result.entities.keys() == {"anything"}
1932
1933 # Should match the sentence with the "area" slot because it has the most
1934 # literal text matched.
1935 result = recognize_best("turn on bedroom lamp", intents)
1936 assert result is not None
1937 assert result.entities.keys() == {"area"}
1938
1939 # Should match the sentence with the "name" slot because it's a priority
1940 result = recognize_best("turn on bedroom lamp", intents, best_slot_name="name")
1941 assert result is not None
1942 assert result.entities.keys() == {"name"}
1943 assert result.entities["name"].value == "bedroom lamp"
1944
1945
1946 def test_regex_branching():
1947 yaml_text = """
1948 language: "en"
1949 intents:
1950 TurnOn:
1951 data:
1952 - sentences:
1953 - "turn on ({area} {name}|{name})"
1954 lists:
1955 area:
1956 values:
1957 - bedroom
1958 name:
1959 values:
1960 - bedroom lamp
1961 - lamp
1962 """
1963
1964 with io.StringIO(yaml_text) as test_file:
1965 intents = Intents.from_yaml(test_file)
1966
1967 results = list(recognize_all("turn on bedroom lamp", intents))
1968 assert len(results) == 2
1969
1970
1971 def test_commas_dont_change() -> None:
1972 """Ensure commas don't change the interpretation of a sentence."""
1973 yaml_text = """
1974 language: "en"
1975 intents:
1976 TurnOn:
1977 data:
1978 - sentences:
1979 - "turn on [the] {name}"
1980 - "turn on [the] {area} lights"
1981 lists:
1982 name:
1983 values:
1984 - lamp
1985 area:
1986 values:
1987 - living room
1988 """
1989
1990 with io.StringIO(yaml_text) as test_file:
1991 intents = Intents.from_yaml(test_file)
1992
1993 for sentence in (
1994 "turn on the living room lights",
1995 "turn, on the, living room lights",
1996 "turn on, the living room lights",
1997 "turn on the, living room lights",
1998 "turn on the living room, lights",
1999 ):
2000 result = recognize(sentence, intents)
2001 assert result is not None, sentence
2002 assert result.entities.keys() == {"area"}
2003
2004
2005 def test_wildcard_then_other_stuff() -> None:
2006 """Test wildcard followed by expansion rule and list."""
2007 yaml_text = """
2008 language: "en"
2009 intents:
2010 SetTimer:
2011 data:
2012 - sentences:
2013 - "set timer {timer_name:name} <timer_duration>"
2014 - "set timer {timer_name:name} {timer_state:state} [now]"
2015 AddItem:
2016 data:
2017 - sentences:
2018 - "add {item} [to [my]] {todo_list}"
2019 lists:
2020 timer_name:
2021 wildcard: true
2022 item:
2023 wildcard: true
2024 minutes:
2025 range:
2026 from: 1
2027 to: 59
2028 timer_state:
2029 values:
2030 - "on"
2031 - "off"
2032 todo_list:
2033 values:
2034 - "shopping list"
2035 expansion_rules:
2036 timer_duration: "{minutes} minute[s]"
2037 """
2038
2039 with io.StringIO(yaml_text) as test_file:
2040 intents = Intents.from_yaml(test_file)
2041
2042 # Check ranges
2043 for sentence in ("set timer pizza 5 minutes", "set timer pizza five minutes"):
2044 result = recognize(sentence, intents)
2045 assert result is not None, f"{sentence} should match"
2046 assert set(result.entities.keys()) == {"name", "minutes"}
2047 assert result.entities["name"].text == "pizza"
2048 assert result.entities["name"].value == "pizza"
2049 assert result.entities["minutes"].text.strip() in {"5", "five"}
2050 assert result.entities["minutes"].value == 5
2051
2052 # Check value list
2053 sentence = "set timer a big long name on now"
2054 result = recognize(sentence, intents)
2055 assert result is not None, f"{sentence} should match"
2056 assert set(result.entities.keys()) == {"name", "state"}
2057 assert result.entities["name"].text == "a big long name"
2058 assert result.entities["name"].value == "a big long name"
2059 assert result.entities["state"].text == "on"
2060 assert result.entities["state"].value == "on"
2061
2062 sentence = "add apples to my shopping list"
2063 result = recognize(sentence, intents)
2064 assert result is not None, f"{sentence} should match"
2065 assert set(result.entities.keys()) == {"item", "todo_list"}
2066 assert result.entities["item"].text == "apples"
2067 assert result.entities["item"].value == "apples"
2068 assert result.entities["todo_list"].text == "shopping list"
2069 assert result.entities["todo_list"].value == "shopping list"
2070
2071
2072 def test_range_list_with_one_number() -> None:
2073 """Test a range list with the same start/stop value."""
2074 yaml_text = """
2075 language: "en"
2076 intents:
2077 TestIntent:
2078 data:
2079 - sentences:
2080 - "test {value}"
2081 lists:
2082 value:
2083 range:
2084 from: 1
2085 to: 1
2086 """
2087
2088 with io.StringIO(yaml_text) as test_file:
2089 intents = Intents.from_yaml(test_file)
2090
2091 # Check ranges
2092 assert recognize("test 1", intents)
2093 assert not recognize("test 2", intents)
2094
2095
2096 def test_range_list_with_halves() -> None:
2097 """Test a range list with fractions (1/2)."""
2098 yaml_text = """
2099 language: "en"
2100 intents:
2101 TestIntent:
2102 data:
2103 - sentences:
2104 - "test {value}"
2105 lists:
2106 value:
2107 range:
2108 from: 1
2109 to: 2
2110 fractions: halves
2111 """
2112
2113 with io.StringIO(yaml_text) as test_file:
2114 intents = Intents.from_yaml(test_file)
2115
2116 assert recognize("test 1", intents)
2117 result = recognize("test 1.5", intents)
2118 assert result is not None
2119 value = result.entities.get("value")
2120 assert value is not None
2121 assert value.value == 1.5
2122 assert value.text == "1.5"
2123 assert value.text_clean == "1.5"
2124
2125 result = recognize("test one point five", intents, language="en")
2126 assert result is not None
2127 value = result.entities.get("value")
2128 assert value is not None
2129 assert value.value == 1.5
2130 assert value.text == "one point five"
2131 assert value.text_clean == "one point five"
2132
2133 result = recognize("test 2.0", intents)
2134 assert result is not None
2135 value = result.entities.get("value")
2136 assert value is not None
2137 assert value.value == 2
2138 assert value.text == "2.0"
2139 assert value.text_clean == "2.0"
2140
2141 result = recognize("test 2.5", intents)
2142 assert result is not None
2143 value = result.entities.get("value")
2144 assert value is not None
2145 assert value.value == 2.5
2146 assert value.text == "2.5"
2147 assert value.text_clean == "2.5"
2148
2149 # Only halves
2150 assert not recognize("test 2.1", intents)
2151
2152 # Comma separator
2153 result = recognize("test 2,5", intents)
2154 assert result is not None
2155 value = result.entities.get("value")
2156 assert value is not None
2157 assert value.value == 2.5
2158 assert value.text == "2,5"
2159 assert value.text_clean == "2,5"
2160
2161
2162 def test_range_list_with_tenths() -> None:
2163 """Test a range list with fractions (1/10)."""
2164 yaml_text = """
2165 language: "en"
2166 intents:
2167 TestIntent:
2168 data:
2169 - sentences:
2170 - "test {value}"
2171 lists:
2172 value:
2173 range:
2174 from: 1
2175 to: 2
2176 fractions: tenths
2177 """
2178
2179 with io.StringIO(yaml_text) as test_file:
2180 intents = Intents.from_yaml(test_file)
2181
2182 assert recognize("test 1", intents)
2183 assert recognize("test 2", intents)
2184
2185 for integer in range(1, 3):
2186 for tenth in range(1, 10):
2187 value_str = f"{integer}.{tenth}"
2188 result = recognize(f"test {value_str}", intents)
2189 assert result is not None
2190 value = result.entities.get("value")
2191 assert value is not None
2192 assert value.value == float(value_str)
2193 assert value.text == value_str
2194 assert value.text_clean == value_str
2195
2196 result = recognize("test one point one", intents, language="en")
2197 assert result is not None
2198 value = result.entities.get("value")
2199 assert value is not None
2200 assert value.value == 1.1
2201 assert value.text == "one point one"
2202
2203 result = recognize("test two point six", intents, language="en")
2204 assert result is not None
2205 value = result.entities.get("value")
2206 assert value is not None
2207 assert value.value == 2.6
2208 assert value.text == "two point six"
2209
2210 # Only tenths
2211 assert not recognize("test 2.12", intents)
2212
2213
2214 def test_range_lists_separated_by_punctuation() -> None:
2215 """Test range lists separated by punctuation."""
2216 yaml_text = """
2217 language: "en"
2218 intents:
2219 TestIntent:
2220 data:
2221 - sentences:
2222 - "test {value1}.{value2}"
2223 lists:
2224 value1:
2225 range:
2226 from: 0
2227 to: 1
2228 value2:
2229 range:
2230 from: 0
2231 to: 2
2232 """
2233
2234 with io.StringIO(yaml_text) as test_file:
2235 intents = Intents.from_yaml(test_file)
2236
2237 result = recognize("test 1.2", intents)
2238 assert result is not None
2239
2240 value1 = result.entities.get("value1")
2241 assert value1 is not None
2242 assert value1.value == 1
2243
2244 value2 = result.entities.get("value2")
2245 assert value2 is not None
2246 assert value2.value == 2
2247
2248
2249 def test_range_lists_separated_by_punctuation_with_wildcard() -> None:
2250 """Test range lists separated by punctuation preceeded by a wildcard."""
2251 yaml_text = """
2252 language: "en"
2253 intents:
2254 TestIntent:
2255 data:
2256 - sentences:
2257 - "test {anything} {value1}.{value2}"
2258 lists:
2259 anything:
2260 wildcard: true
2261 value1:
2262 range:
2263 from: 0
2264 to: 1
2265 value2:
2266 range:
2267 from: 0
2268 to: 2
2269 """
2270
2271 with io.StringIO(yaml_text) as test_file:
2272 intents = Intents.from_yaml(test_file)
2273
2274 result = recognize("test for the big 1.2", intents)
2275 assert result is not None
2276
2277 anything = result.entities.get("anything")
2278 assert anything is not None
2279 assert anything.value == "for the big"
2280
2281 value1 = result.entities.get("value1")
2282 assert value1 is not None
2283 assert value1.value == 1
2284
2285 value2 = result.entities.get("value2")
2286 assert value2 is not None
2287 assert value2.value == 2
2288
2289
2290 def test_list_value_in_no_out() -> None:
2291 """Test list values with "in" but no "out"."""
2292 yaml_text = """
2293 language: "en"
2294 intents:
2295 TestIntent:
2296 data:
2297 - sentences:
2298 - "test {value1}"
2299 - sentences:
2300 - "also test {value2}"
2301 lists:
2302 value2:
2303 values:
2304 - g[h]i
2305 - j[k]l
2306 lists:
2307 value1:
2308 values:
2309 - a[b]c
2310 - in: d[e]f
2311 """
2312
2313 with io.StringIO(yaml_text) as test_file:
2314 intents = Intents.from_yaml(test_file)
2315
2316 for value in ("abc", "ac", "def", "df"):
2317 result = recognize(f"test {value}", intents)
2318 assert result is not None, value
2319 assert "value1" in result.entities
2320 assert result.entities["value1"].value == value
2321
2322 for value in ("ghi", "gi", "jkl", "jl"):
2323 result = recognize(f"also test {value}", intents)
2324 assert result is not None, value
2325 assert "value2" in result.entities
2326 assert result.entities["value2"].value == value
2327
2328
2329 def test_captures() -> None:
2330 """Test captures for response only."""
2331 yaml_text = """
2332 language: "en"
2333 intents:
2334 TestIntent:
2335 data:
2336 - sentences:
2337 - "open windows {preposition:@preposition} the {area}"
2338 - "close windows {@preposition} the {area}"
2339 lists:
2340 preposition:
2341 values:
2342 - "in"
2343 - "on"
2344 area:
2345 values:
2346 - kitchen
2347 - deck
2348 """
2349
2350 with io.StringIO(yaml_text) as test_file:
2351 intents = Intents.from_yaml(test_file)
2352
2353 result = recognize("open windows in the kitchen", intents)
2354 assert result is not None
2355
2356 # area is an entity
2357 assert result.entities.keys() == {"area"}
2358
2359 # preposition is a capture
2360 assert result.captures.keys() == {"preposition"}
2361 prep = result.captures["preposition"]
2362 assert prep.name == "preposition"
2363 assert prep.text == "in"
2364
2365 assert len(result.captures_list) == 1
2366 assert result.captures_list[0] == prep
2367
2368 # Test compact syntax
2369 result = recognize("close windows on the deck", intents)
2370 assert result is not None
2371
2372 assert result.entities.keys() == {"area"}
2373 assert result.captures.keys() == {"preposition"}
2374 assert result.captures["preposition"].text == "on"
2375
2376
2377 def test_number_language_with_region() -> None:
2378 """Test that the number language can contain a region."""
2379 yaml_text = """
2380 language: "en"
2381 intents:
2382 TestIntent:
2383 data:
2384 - sentences:
2385 - "set volume to {volume}"
2386 lists:
2387 volume:
2388 range:
2389 from: 0
2390 to: 100
2391 """
2392
2393 with io.StringIO(yaml_text) as test_file:
2394 intents = Intents.from_yaml(test_file)
2395
2396 # Use language with region (US)
2397 result = recognize("set volume to fifty", intents, language="en-US")
2398 assert result is not None
2399
2400 assert result.entities.keys() == {"volume"}
2401 assert result.entities["volume"].value == 50
2402
2403
2404 def test_number_word_casing() -> None:
2405 """Test that a number word's case can vary."""
2406 yaml_text = """
2407 language: "en"
2408 intents:
2409 TestIntent:
2410 data:
2411 - sentences:
2412 - "set volume to {volume}"
2413 lists:
2414 volume:
2415 range:
2416 from: 0
2417 to: 100
2418 """
2419
2420 with io.StringIO(yaml_text) as test_file:
2421 intents = Intents.from_yaml(test_file)
2422
2423 for number_word in ("fifty", "FIFTY", "Fifty", "fifTy"):
2424 result = recognize(f"set volume to {number_word}", intents, language="en-US")
2425 assert result is not None, number_word
2426 assert result.entities.keys() == {"volume"}
2427 assert result.entities["volume"].value == 50
2428
2429
2430 def test_wildcard_text_spans() -> None:
2431 """Test that text spans accurately capture wildcards."""
2432 yaml_text = """
2433 language: "en"
2434 intents:
2435 TestIntent:
2436 data:
2437 - sentences:
2438 - "play [the] {search_query}"
2439 - "play [the] {search_query} {media_class}"
2440 lists:
2441 search_query:
2442 wildcard: true
2443 media_class:
2444 values:
2445 - movie
2446 - artist
2447 - album
2448 """
2449
2450 with io.StringIO(yaml_text) as test_file:
2451 intents = Intents.from_yaml(test_file)
2452
2453 result = recognize("play the Inception movie", intents)
2454 assert result is not None
2455 assert result.entities.keys() == {"search_query", "media_class"}
2456 assert result.entities["search_query"].text == "Inception"
2457 assert result.entities["search_query"].text_span == (9, 18)
2458
2459 assert result.entities["media_class"].text == "movie"
2460 assert result.entities["media_class"].text_span == (19, 24)
2461
2462
2463 def test_text_spans_after_range_numbers() -> None:
2464 """Text spans of slots that follow a range number must stay aligned.
2465
2466 A range number match leaves a leading space before the next chunk; that
2467 space must be counted in text_index, otherwise every following slot's span
2468 drifts left by one per preceding number.
2469 """
2470 yaml_text = """
2471 language: "en"
2472 intents:
2473 SetTimer:
2474 data:
2475 - sentences:
2476 - "{minutes} minutes {seconds} seconds timer named {name}"
2477 lists:
2478 minutes:
2479 range:
2480 from: 0
2481 to: 100
2482 seconds:
2483 range:
2484 from: 0
2485 to: 100
2486 name:
2487 wildcard: true
2488 """
2489
2490 with io.StringIO(yaml_text) as test_file:
2491 intents = Intents.from_yaml(test_file)
2492
2493 text = "5 minutes 30 seconds timer named pizza"
2494 result = recognize(text, intents)
2495 assert result is not None
2496 assert result.entities.keys() == {"minutes", "seconds", "name"}
2497
2498 for slot_name, expected in (
2499 ("minutes", "5"),
2500 ("seconds", "30"),
2501 ("name", "pizza"),
2502 ):
2503 entity = result.entities[slot_name]
2504 span = entity.text_span
2505 assert span is not None
2506 # The span must point at exactly the matched text in the original.
2507 assert text[span[0] : span[1]] == expected, slot_name
2508 assert entity.text == expected
2509
2510
2511 def test_inline_range_lists() -> None:
2512 """Test that inline range lists word ({N..M:slot})."""
2513 yaml_text = """
2514 language: "en"
2515 intents:
2516 TestIntent:
2517 data:
2518 - sentences:
2519 - "set brightness to {0..100:brightness}"
2520 - "set position to {0..100:position}"
2521 - "start timer for {10..100,10:seconds} seconds"
2522 """
2523
2524 with io.StringIO(yaml_text) as test_file:
2525 intents = Intents.from_yaml(test_file)
2526
2527 result = recognize("set brightness to 50", intents)
2528 assert result is not None
2529 assert result.entities.keys() == {"brightness"}
2530 assert result.entities["brightness"].value == 50
2531
2532 result = recognize("set position to 25", intents)
2533 assert result is not None
2534 assert result.entities.keys() == {"position"}
2535 assert result.entities["position"].value == 25
2536
2537 # Check step
2538 assert recognize("start timer for 10 seconds", intents) is not None
2539 assert recognize("start timer for 11 seconds", intents) is None
2540
2541 # Range list is only created during matching
2542 assert not intents.slot_lists
2543
2544
2545 def test_required_fragment_prefilter_is_sound() -> None:
2546 """Templates must not be skipped by the prefilter when they can still match.
2547
2548 Each case here defeated the old regex-based prefilter, which compiled a
2549 pattern per template and dropped any template whose pattern did not match.
2550 """
2551 # Everything is optional, so there is no literal to require.
2552 yaml_text = """
2553 language: "en"
2554 lists:
2555 name:
2556 values:
2557 - "kitchen light"
2558 intents:
2559 TestIntent:
2560 data:
2561 - sentences:
2562 - "[turn] [on] {name}"
2563 """
2564 with io.StringIO(yaml_text) as test_file:
2565 intents = Intents.from_yaml(test_file)
2566
2567 assert recognize("kitchen light", intents) is not None
2568
2569 # Optional space between literals ("uit[ ]schakelen"), as used by nl/de.
2570 yaml_text = """
2571 language: "en"
2572 lists:
2573 name:
2574 values:
2575 - "lamp"
2576 intents:
2577 TestIntent:
2578 data:
2579 - sentences:
2580 - "{name} uit[ ]schakelen"
2581 """
2582 with io.StringIO(yaml_text) as test_file:
2583 intents = Intents.from_yaml(test_file)
2584
2585 for sentence in ("lamp uitschakelen", "lamp uit schakelen"):
2586 assert recognize(sentence, intents) is not None, sentence
2587
2588 # The matcher breaks "-"/"_" apart, so a hyphenated input still matches a
2589 # template written with a space. A decoy template keeps any
2590 # "nothing matched, try everything" fallback from hiding a mistake.
2591 yaml_text = """
2592 language: "en"
2593 intents:
2594 TestIntent:
2595 data:
2596 - sentences:
2597 - "turn on the living room light"
2598 DecoyIntent:
2599 data:
2600 - sentences:
2601 - "turn on the living-room light [now]"
2602 """
2603 with io.StringIO(yaml_text) as test_file:
2604 intents = Intents.from_yaml(test_file)
2605
2606 for sentence in ("turn on the living-room light", "turn on the living_room light"):
2607 intent_names = {r.intent.name for r in recognize_all(sentence, intents)}
2608 assert "TestIntent" in intent_names, sentence
2609
2610 # A skip word can be a real part of a template.
2611 yaml_text = """
2612 language: "en"
2613 skip_words:
2614 - "i want"
2615 intents:
2616 TestIntent:
2617 data:
2618 - sentences:
2619 - "i want to watch tv"
2620 DecoyIntent:
2621 data:
2622 - sentences:
2623 - "to watch tv"
2624 """
2625 with io.StringIO(yaml_text) as test_file:
2626 intents = Intents.from_yaml(test_file)
2627
2628 intent_names = {r.intent.name for r in recognize_all("i want to watch tv", intents)}
2629 assert "TestIntent" in intent_names
2630
2631
2632 def test_required_fragment_prefilter_rejects() -> None:
2633 """The prefilter must still skip templates that cannot match."""
2634 yaml_text = """
2635 language: "en"
2636 intents:
2637 TestIntent:
2638 data:
2639 - sentences:
2640 - "(open|close) the door"
2641 """
2642 with io.StringIO(yaml_text) as test_file:
2643 intents = Intents.from_yaml(test_file)
2644
2645 assert recognize("open the door", intents) is not None
2646 assert recognize("close the door", intents) is not None
2647 assert recognize("smash the door", intents) is None
2648
2649
2650 def test_range_multi_digit_after_wildcard() -> None:
2651 """A multi-digit number after an open wildcard must not be truncated."""
2652 yaml_text = """
2653 language: "en"
2654 lists:
2655 query:
2656 wildcard: true
2657 num:
2658 range:
2659 from: 1
2660 to: 500
2661 words: false
2662 intents:
2663 TestIntent:
2664 data:
2665 - sentences:
2666 - "play {query} {num}"
2667 """
2668 with io.StringIO(yaml_text) as test_file:
2669 intents = Intents.from_yaml(test_file)
2670
2671 for sentence, number in (
2672 ("play song 7", 7),
2673 ("play song 42", 42),
2674 ("play song 137", 137),
2675 ):
2676 result = recognize(sentence, intents)
2677 assert result is not None, sentence
2678 assert result.entities["num"].value == number, sentence
2679 assert result.entities["query"].value == "song", sentence
2680
2681
2682 def test_wildcard_not_corrupted_by_number_words() -> None:
2683 """An open wildcard must not accumulate text from other number candidates."""
2684 yaml_text = """
2685 language: "en"
2686 lists:
2687 query:
2688 wildcard: true
2689 num:
2690 range:
2691 from: 1
2692 to: 10
2693 digits: false
2694 intents:
2695 TestIntent:
2696 data:
2697 - sentences:
2698 - "play {query} {num}"
2699 """
2700 with io.StringIO(yaml_text) as test_file:
2701 intents = Intents.from_yaml(test_file)
2702
2703 # "one" and "two" are also number words, so the trie yields several
2704 # candidates and the wildcard is visited more than once.
2705 result = recognize("play one two three", intents)
2706 assert result is not None
2707 assert result.entities["num"].value == 3
2708 assert result.entities["query"].value == "one two"
2709
2710 result = recognize("play one two three four", intents)
2711 assert result is not None
2712 assert result.entities["num"].value == 4
2713 assert result.entities["query"].value == "one two three"
2714
2715
2716 def test_text_spans_index_original_text() -> None:
2717 """text_span must delimit the region of the original text it came from.
2718
2719 Matching runs on text that has had punctuation and skip words removed and
2720 whitespace collapsed, so spans have to be mapped back. The slice equals
2721 entity.text except where normalization rewrote characters inside it (a
2722 collapsed whitespace run, a typographic apostrophe).
2723 """
2724 yaml_text = """
2725 language: "en"
2726 skip_words:
2727 - "please"
2728 - "the"
2729 lists:
2730 album:
2731 wildcard: true
2732 brightness:
2733 range:
2734 from: 0
2735 to: 100
2736 name:
2737 values:
2738 - "kitchen light"
2739 - "A.C."
2740 intents:
2741 Play:
2742 data:
2743 - sentences:
2744 - "play {album}"
2745 Bright:
2746 data:
2747 - sentences:
2748 - "set {name} to {brightness} percent"
2749 Turn:
2750 data:
2751 - sentences:
2752 - "turn on {name}"
2753 """
2754
2755 with io.StringIO(yaml_text) as test_file:
2756 intents = Intents.from_yaml(test_file)
2757
2758 sentences = [
2759 "turn on kitchen light",
2760 "turn on the kitchen light",
2761 "please turn on the kitchen light",
2762 "Turn on KITCHEN LIGHT!",
2763 "turn on A.C.",
2764 "set kitchen light to 42 percent",
2765 "set the kitchen light to 7 percent",
2766 "play the white album",
2767 " play the white album, please ",
2768 "turn on kitchen-light",
2769 ]
2770
2771 checked = 0
2772 for sentence in sentences:
2773 for result in recognize_all(sentence, intents):
2774 for entity in result.entities_list:
2775 if entity.text_span is None:
2776 continue
2777
2778 start, end = entity.text_span
2779 assert 0 <= start <= end <= len(sentence), (sentence, entity.name)
2780
2781 # Normalizing the slice the same way the matcher normalizes
2782 # input must reproduce entity.text exactly. The raw slice can
2783 # still differ (a collapsed whitespace run, a stripped comma),
2784 # because the span delimits the *source* of the entity.
2785 sliced = sentence[start:end]
2786 assert (
2787 normalize_for_matching(sliced).text.lower()
2788 == entity.text.strip().lower()
2789 ), (sentence, entity.name, sliced, entity.text)
2790 checked += 1
2791
2792 assert checked > 0
2793
2794
2795 def test_empty_slot_list_value_never_matches() -> None:
2796 """A slot list value with no text must not match.
2797
2798 An empty value matches at any position without consuming text, yielding an
2799 entity with an empty value. Lists built from user data (entity aliases, for
2800 example) can easily contain one.
2801 """
2802 yaml_text = """
2803 language: "en"
2804 intents:
2805 TestIntent:
2806 data:
2807 - sentences:
2808 - "turn on {name}"
2809 """
2810
2811 with io.StringIO(yaml_text) as test_file:
2812 intents = Intents.from_yaml(test_file)
2813
2814 slot_lists: Dict[str, SlotList] = {
2815 "name": TextSlotList.from_tuples(
2816 [("", "empty"), (" ", "whitespace"), ("kitchen light", "light.kitchen")],
2817 allow_template=False,
2818 )
2819 }
2820
2821 results = list(
2822 recognize_all("turn on kitchen light", intents, slot_lists=slot_lists)
2823 )
2824 assert len(results) == 1
2825 assert results[0].entities["name"].value == "light.kitchen"
2826
2827 # The empty values must not let an otherwise-unmatched sentence through.
2828 assert recognize("turn on ", intents, slot_lists=slot_lists) is None
2829 assert recognize("turn on bedroom lamp", intents, slot_lists=slot_lists) is None