File: test_recognize.py

package info (click to toggle)
hassil 3.0.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 432 kB
  • sloc: python: 4,824; makefile: 2
file content (2072 lines) | stat: -rw-r--r-- 59,335 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
import io
from typing import Set, cast

import pytest

from hassil import Intents, recognize, recognize_all, recognize_best
from hassil.expression import TextChunk
from hassil.intents import TextSlotList
from hassil.models import MatchEntity, UnmatchedRangeEntity, UnmatchedTextEntity
from hassil.recognize import MISSING_ENTITY

TEST_YAML = """
language: "en"
intents:
  TurnOnTV:
    data:
      - sentences:
          - "turn on [the] TV in <area>"
          - "turn on <area> TV"
        slots:
          domain: "media_player"
          name: "roku"
  SetBrightness:
    data:
      - sentences:
          - "set [the] brightness in <area> to <brightness>"
        slots:
          domain: "light"
          name: "all"
      - sentences:
          - "set [the] brightness of <name> to <brightness>"
        requires_context:
          domain: "light"
        slots:
          domain: "light"
  GetTemperature:
    data:
      - sentences:
          - "<what_is> [the] temperature in <area>"
        slots:
          domain: "climate"
  CloseCover:
    data:
      - sentences:
          - "close <name>"
        requires_context:
          domain: "cover"
        slots:
          domain: "cover"
  Play:
    data:
      - sentences:
          - "play <name>"
        excludes_context:
          domain:
            - "cover"
            - "light"
  CloseCurtains:
    data:
      - sentences:
          - "close [the] curtains [in <area>]"
        slots:
          domain: "cover"
          device_class: "curtain"
        requires_context:
          area:
            slot: true
          not_copied: "not copied value"
          copied_to_different:
            value: null
            slot: "different_slot"
expansion_rules:
  area: "[the] {area}"
  name: "[the] {name}"
  brightness: "{brightness_pct}[%| percent]"
  what_is: "(what's | whats | what is)"
lists:
  brightness_pct:
    range:
      type: percentage
      from: 0
      to: 100
skip_words:
  - "please"
"""


@pytest.fixture
def intents():
    with io.StringIO(TEST_YAML) as test_file:
        return Intents.from_yaml(test_file)


@pytest.fixture
def slot_lists():
    return {
        "area": TextSlotList.from_tuples(
            [("kitchen", "area.kitchen"), ("living room", "area.living_room")]
        ),
        "name": TextSlotList.from_tuples(
            [
                ("hue", "light.hue", {"domain": "light"}),
                (
                    "garage door",
                    "cover.garage_door",
                    {"domain": "cover"},
                ),
                (
                    "blue curtains",
                    "cover.blue_curtains",
                    {
                        "domain": "cover",
                        "device_class": "curtain",
                        "area": "living_room",
                    },
                ),
                (
                    "roku",
                    "media_player.roku",
                    {"domain": "media_player"},
                ),
            ]
        ),
    }


# pylint: disable=redefined-outer-name
def test_turn_on(intents, slot_lists):
    result = recognize("turn on kitchen TV, please", intents, slot_lists=slot_lists)
    assert result is not None
    assert result.intent.name == "TurnOnTV"

    assert result.text_chunks_matched > 0

    area = result.entities["area"]
    assert area.name == "area"
    assert area.value == "area.kitchen"

    # From YAML
    assert result.entities["domain"].value == "media_player"
    assert result.entities["name"].value == "roku"


# pylint: disable=redefined-outer-name
def test_brightness_area(intents, slot_lists):
    result = recognize(
        "set the brightness in the living room to 75%", intents, slot_lists=slot_lists
    )
    assert result is not None
    assert result.intent.name == "SetBrightness"

    assert result.text_chunks_matched > 0

    assert result.entities["area"].value == "area.living_room"
    assert result.entities["brightness_pct"].value == 75

    # From YAML
    assert result.entities["domain"].value == "light"
    assert result.entities["name"].value == "all"


# pylint: disable=redefined-outer-name
def test_brightness_area_words(intents, slot_lists):
    result = recognize(
        "set brightness in the living room to forty-two percent",
        intents,
        slot_lists=slot_lists,
        language="en",
    )
    assert result is not None
    assert result.intent.name == "SetBrightness"

    assert result.entities["area"].value == "area.living_room"
    assert result.entities["brightness_pct"].value == 42

    # From YAML
    assert result.entities["domain"].value == "light"
    assert result.entities["name"].value == "all"


# pylint: disable=redefined-outer-name
def test_brightness_name(intents, slot_lists):
    result = recognize(
        "set brightness of the hue to 50%", intents, slot_lists=slot_lists
    )
    assert result is not None
    assert result.intent.name == "SetBrightness"

    assert result.entities["name"].value == "light.hue"
    assert result.entities["brightness_pct"].value == 50

    # From YAML
    assert result.entities["domain"].value == "light"


# pylint: disable=redefined-outer-name
def test_brightness_not_cover(intents, slot_lists):
    result = recognize(
        "set brightness of the garage door to 50%", intents, slot_lists=slot_lists
    )
    assert result is None


# pylint: disable=redefined-outer-name
def test_temperature(intents, slot_lists):
    result = recognize(
        "what is the temperature in the living room?", intents, slot_lists=slot_lists
    )
    assert result is not None
    assert result.intent.name == "GetTemperature"

    assert result.entities["area"].value == "area.living_room"

    # From YAML
    assert result.entities["domain"].value == "climate"


# pylint: disable=redefined-outer-name
def test_close_name(intents, slot_lists):
    result = recognize("close the garage door", intents, slot_lists=slot_lists)
    assert result is not None
    assert result.intent.name == "CloseCover"

    assert result.entities["name"].value == "cover.garage_door"

    # From YAML
    assert result.entities["domain"].value == "cover"


# pylint: disable=redefined-outer-name
def test_close_not_light(intents, slot_lists):
    result = recognize("close the hue", intents, slot_lists=slot_lists)
    assert result is None


# pylint: disable=redefined-outer-name
def test_play(intents, slot_lists):
    result = recognize("play roku", intents, slot_lists=slot_lists)
    assert result is not None
    assert result.intent.name == "Play"

    assert result.entities["name"].value == "media_player.roku"

    # From context
    assert result.context["domain"] == "media_player"


# pylint: disable=redefined-outer-name
def test_play_no_cover(intents, slot_lists):
    result = recognize("play the garage door", intents, slot_lists=slot_lists)
    assert result is None


# pylint: disable=redefined-outer-name
def test_requires_context_implicit(intents, slot_lists):
    intent_context = {
        "area": "living room",
        "not_copied": "not copied value",
        "copied_to_different": "copied value",
    }

    result = recognize(
        "close the curtains",
        intents,
        slot_lists=slot_lists,
        intent_context=intent_context,
    )
    assert result is not None
    assert result.intent.name == "CloseCurtains"

    # test_slot should not be copied over
    assert set(result.entities.keys()) == {
        "area",
        "domain",
        "device_class",
        "different_slot",
    }
    assert result.entities["area"].value == "living room"
    assert result.entities["domain"].value == "cover"
    assert result.entities["device_class"].value == "curtain"
    assert result.entities["different_slot"].value == "copied value"


# pylint: disable=redefined-outer-name
def test_requires_context_none_provided(intents, slot_lists):
    result = recognize("close the curtains", intents, slot_lists=slot_lists)
    assert result is None


def test_lists_no_template() -> None:
    """Ensure list values without template syntax are plain text."""
    yaml_text = """
    language: "en"
    intents: {}
    lists:
      test:
        values:
          - "test value"
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    test_list = cast(TextSlotList, intents.slot_lists["test"])
    text_in = test_list.values[0].text_in
    assert isinstance(text_in, TextChunk)
    assert text_in.text == "test value"


def test_list_text_normalized() -> None:
    """Ensure list text in values are normalized."""
    yaml_text = """
    language: "en"
    intents:
      TestIntent:
        data:
          - sentences:
              - "run {test_name}"
    lists:
      test_name:
        values:
          - "tEsT    1"
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    result = recognize("run test 1", intents)
    assert result is not None
    assert result.entities["test_name"].value == "tEsT    1"


def test_skip_prefix() -> None:
    yaml_text = """
    language: "en"
    intents:
      TestIntent:
        data:
          - sentences:
              - "run {test_name}"
    lists:
      test_name:
        values:
          - "test"
    skip_words:
      - "the"
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    result = recognize("run the test", intents)
    assert result is not None
    assert result.entities["test_name"].value == "test"


def test_skip_sorted() -> None:
    """Ensure skip words are processed longest first"""
    yaml_text = """
    language: "en"
    intents:
      TestIntent:
        data:
          - sentences:
              - "run {test_name}"
    lists:
      test_name:
        values:
          - "test"
    skip_words:
      - "could"
      - "could you"
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    result = recognize("could you run test", intents)
    assert result is not None
    assert result.entities["test_name"].value == "test"


def test_response_key() -> None:
    """Check response key in intent data"""
    yaml_text = """
    language: "en"
    intents:
      TestIntent:
        data:
          - sentences:
              - "this is a test"
            response: "test_response"
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    result = recognize("this is a test", intents)
    assert result is not None
    assert result.response == "test_response"


def test_entity_text() -> None:
    """Ensure original text is returned as well as substituted list value"""
    yaml_text = """
    language: "en"
    intents:
      TestIntent:
        data:
          - sentences:
              - "run test {name} [now]"
              - "{name} test"
    lists:
      name:
        values:
          - in: "alpha "
            out: "A"
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    for sentence in ("run test alpha, now", "run test alpha!", "alpha test"):
        result = recognize(sentence, intents)
        assert result is not None, sentence
        assert result.entities["name"].value == "A"
        assert result.entities["name"].text_clean == "alpha"


def test_number_text() -> None:
    """Ensure original text is returned as well as substituted number"""
    yaml_text = """
    language: "en"
    intents:
      TestIntent:
        data:
          - sentences:
              - "set {percentage}[%] [now]"
              - "{percentage}[%] set"
    lists:
      percentage:
        range:
          from: 0
          to: 100
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    for sentence in ("set 50% now", "set 50%", "50% set"):
        result = recognize(sentence, intents)
        assert result is not None, sentence
        assert result.entities["percentage"].value == 50
        assert result.entities["percentage"].text.strip() == "50"


def test_recognize_all() -> None:
    """Test recognize_all method for returning all matches."""
    yaml_text = """
    language: "en"
    intents:
      TestIntent1:
        data:
          - sentences:
              - "run test"
      TestIntent2:
        data:
          - sentences:
              - "run test"
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    results = list(recognize_all("run test", intents))
    assert len(results) == 2
    assert {result.intent.name for result in results} == {
        "TestIntent1",
        "TestIntent2",
    }


def test_ignore_whitespace() -> None:
    """Test option to ignore whitespace during matching."""
    yaml_text = """
    language: "en"
    settings:
      ignore_whitespace: true
    intents:
      TestIntent1:
        data:
          - sentences:
              - "run [the] test"
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    for sentence in ("runtest", "runthetest", "r u n t h e t e s t"):
        result = recognize(sentence, intents)
        assert result is not None, sentence


def test_skip_words_ignore_whitespace() -> None:
    """Test option to ignore whitespace with skip words during matching."""
    yaml_text = """
    language: "en"
    settings:
      ignore_whitespace: true
    intents:
      TestIntent1:
        data:
          - sentences:
              - "ad"
    skip_words:
      - "bc"
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    result = recognize("abcd", intents)
    assert result is not None


def test_local_expansion_rules() -> None:
    """Test local expansion rules, defined at the intent level"""
    yaml_text = """
    language: "en"
    intents:
      GetSmokeState:
        data:
          - expansion_rules:
              verb: "(are|is)"
              subject: "[all] [the] light[s]"
              state: "on"
              location: "[in <area>]"
            sentences:
              - "<verb> <subject> <state> <location>"
              - "<verb> <subject> <location> <state>"
    expansion_rules:
      area: "[the] {area}"
    lists:
      area:
        values:
          - kitchen
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    for sentence in (
        "are the lights on in the kitchen",
        "are the lights in the kitchen on",
    ):
        result = recognize(sentence, intents)
        assert result is not None, sentence
        assert result.intent.name == "GetSmokeState"


def test_local_slot_lists() -> None:
    """Test local slot lists, defined at the intent level"""
    yaml_text = """
    language: "en"
    intents:
      PlayTrackAtVolume:
        data:
          - sentences:
              - "play {track} at {volume}[%| percent] volume"
            lists:
              track:
                wildcard: true
    lists:
      volume:
        range:
          from: 1
          to: 100
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    for sentence in ("play paint it black at 90% volume",):
        result = recognize(sentence, intents)
        assert result is not None, sentence
        assert result.intent.name == "PlayTrackAtVolume"
        track = result.entities.get("track")
        volume = result.entities.get("volume")
        assert isinstance(track, MatchEntity)
        assert track.value == "paint it black"
        assert isinstance(volume, MatchEntity)
        assert volume.value == 90


def test_unmatched_entity() -> None:
    """Test allow_unmatched_entities option to provide better feedback."""
    yaml_text = """
    language: "en"
    intents:
      Test:
        data:
          - sentences:
              - "set [all] {domain} in {area} to {percent}[%] now"
              - "set {area} {domain} to {percent}"
    lists:
      area:
        values:
          - kitchen
          - bedroom
      domain:
        values:
          - lights
      percent:
        range:
          type: percentage
          from: 0
          to: 100
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    sentence = "set fans in living room to 101% now"

    # Should fail without unmatched entities enabled
    result = recognize(sentence, intents, allow_unmatched_entities=False)
    assert result is None, f"{sentence} should not match"

    # Should succeed now
    result = recognize(sentence, intents, allow_unmatched_entities=True)
    assert result is not None, f"{sentence} should match"
    assert set(result.unmatched_entities.keys()) == {"domain", "area", "percent"}
    domain = result.unmatched_entities["domain"]
    assert isinstance(domain, UnmatchedTextEntity)
    assert domain.text == "fans "

    area = result.unmatched_entities["area"]
    assert isinstance(area, UnmatchedTextEntity)
    assert area.text == "living room "

    percent = result.unmatched_entities["percent"]
    assert isinstance(percent, UnmatchedRangeEntity)
    assert percent.value == 101

    sentence = "set all lights in kitchen to blah blah blah now"
    result = recognize(sentence, intents, allow_unmatched_entities=True)
    assert result is not None, f"{sentence} should match"
    assert set(result.unmatched_entities.keys()) == {"percent"}

    percent = result.unmatched_entities["percent"]
    assert isinstance(percent, UnmatchedTextEntity)
    assert percent.text == "blah blah blah "

    # Test with unmatched entity at end of sentence
    sentence = "set kitchen lights to nothing"
    result = recognize(sentence, intents, allow_unmatched_entities=True)
    assert result is not None, f"{sentence} should match"
    assert set(result.unmatched_entities.keys()) == {"percent"}

    percent = result.unmatched_entities["percent"]
    assert isinstance(percent, UnmatchedTextEntity)
    assert percent.text == "nothing"


def test_unmatched_range_only() -> None:
    """Test allow_unmatched_entities option with an out-of-range value only."""
    yaml_text = """
    language: "en"
    intents:
      Test:
        data:
          - sentences:
              - "set {domain} to {percent}[%]"
    lists:
      domain:
        values:
          - lights
      percent:
        range:
          type: percentage
          from: 0
          to: 100
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    sentence = "set lights to 1001%"

    # Should fail without unmatched entities enabled
    result = recognize(sentence, intents, allow_unmatched_entities=False)
    assert result is None, f"{sentence} should not match"

    # Should succeed now
    result = recognize(sentence, intents, allow_unmatched_entities=True)
    assert result is not None, f"{sentence} should match"
    assert set(result.entities.keys()) == {"domain"}
    assert set(result.unmatched_entities.keys()) == {"percent"}

    domain = result.entities["domain"]
    assert domain.text == "lights"

    percent = result.unmatched_entities["percent"]
    assert isinstance(percent, UnmatchedRangeEntity)
    assert percent.value == 1001


def test_no_empty_unmatched_entity() -> None:
    """Test that unmatched entities are not empty."""
    yaml_text = """
    language: "en"
    intents:
      Test:
        data:
          - sentences:
              - "turn on {name}[ please]"
              - "illuminate all[ {area}] lights"
              - "activate {name} now"
    lists:
      name:
        values:
          - light
      area:
        values:
          - bedroom
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    sentence = "turn on "
    results = list(recognize_all(sentence, intents, allow_unmatched_entities=True))
    assert not results, f"{sentence} should not match"

    # With optional word at end
    sentence = "turn on please"
    results = list(recognize_all(sentence, intents, allow_unmatched_entities=True))
    assert not results, f"{sentence} should not match"

    sentence = "illuminate all lights"
    results = list(recognize_all(sentence, intents, allow_unmatched_entities=True))
    assert results, f"{sentence} should match"
    assert len(results) == 1, "Only 1 result expected"
    assert not results[0].unmatched_entities, "No unmatched entities expected"

    sentence = "illuminate all kitchen lights"
    results = list(recognize_all(sentence, intents, allow_unmatched_entities=True))
    assert results, f"{sentence} should match"
    assert len(results) == 1, "Only 1 result expected"
    result = results[0]
    assert set(result.unmatched_entities.keys()) == {"area"}
    area = result.unmatched_entities["area"]
    assert isinstance(area, UnmatchedTextEntity)
    assert area.text == "kitchen "

    # With required word at end
    sentence = "activate now"
    results = list(recognize_all(sentence, intents, allow_unmatched_entities=True))
    assert not results, f"{sentence} should not match"


def test_unmatched_entity_context() -> None:
    """Test that unmatched entities work with requires/excludes context."""
    yaml_text = """
    language: "en"
    intents:
      Test:
        data:
          - sentences:
              - "open {name}"
            requires_context:
              domain: cover
    lists:
      name:
        values:
          - garage door
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    sentence = "open garage door"

    # Should fail when unmatched entities aren't allowed
    result = recognize(sentence, intents, allow_unmatched_entities=False)
    assert result is None, f"{sentence} should not match"

    # Should succeed now with an unmatched domain entity
    result = recognize(sentence, intents, allow_unmatched_entities=True)
    assert result is not None, f"{sentence} should match"
    assert set(result.unmatched_entities.keys()) == {"domain"}
    domain = result.unmatched_entities["domain"]
    assert isinstance(domain, UnmatchedTextEntity)
    assert domain.text == MISSING_ENTITY

    # Now both entities are unmatched
    sentence = "open back door"
    result = recognize(sentence, intents, allow_unmatched_entities=True)
    assert result is not None, f"{sentence} should match"
    assert set(result.unmatched_entities.keys()) == {"domain", "name"}

    domain = result.unmatched_entities["domain"]
    assert isinstance(domain, UnmatchedTextEntity)
    assert domain.text == MISSING_ENTITY

    name = result.unmatched_entities["name"]
    assert isinstance(name, UnmatchedTextEntity)
    assert name.text == "back door"


def test_unmatched_slot_name() -> None:
    """Test that unmatched entities use slot name instead of list name."""
    yaml_text = """
    language: "en"
    intents:
      Test:
        data:
          - sentences:
              - "run {script_name:name}"
              - "execute script {script_number:number}"
    lists:
      script_name:
        values:
          - stealth mode
      script_number:
        range:
          from: 1
          to: 100
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    sentence = "run missing name"
    result = recognize(sentence, intents, allow_unmatched_entities=True)
    assert result is not None, f"{sentence} should match"
    assert set(result.unmatched_entities.keys()) == {"name"}

    sentence = "execute script wrong number"
    result = recognize(sentence, intents, allow_unmatched_entities=True)
    assert result is not None, f"{sentence} should match"
    assert set(result.unmatched_entities.keys()) == {"number"}

    # Outside range
    sentence = "execute script 0"
    result = recognize(sentence, intents, allow_unmatched_entities=True)
    assert result is not None, f"{sentence} should match"
    assert set(result.unmatched_entities.keys()) == {"number"}


def test_unmatched_entity_stops_at_optional() -> None:
    """Test that unmatched entities do not cross optional text chunks."""
    yaml_text = """
    language: "en"
    intents:
      Test:
        data:
          - sentences:
              - "set {area} [to] brightness <brightness>"
              - "set {name} [to] brightness <brightness>"
    lists:
      name:
        values:
          - lamp
      area:
        values:
          - kitchen
      brightness_pct:
          range:
            type: percentage
            from: 0
            to: 100
    expansion_rules:
        brightness: "{brightness_pct}[%| percent]"
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    sentence = "set unknown thing to brightness 100%"

    # Should fail without unmatched entities enabled
    result = recognize(sentence, intents, allow_unmatched_entities=False)
    assert result is None, f"{sentence} should not match"

    results = list(recognize_all(sentence, intents, allow_unmatched_entities=True))
    assert len(results) == 4

    area_names: Set[str] = set()
    entity_names: Set[str] = set()

    for result in results:
        assert len(result.unmatched_entities) == 1
        area_entity = result.unmatched_entities.get("area")
        if area_entity is not None:
            assert isinstance(area_entity, UnmatchedTextEntity)
            area_names.add(area_entity.text)
        else:
            name_entity = result.unmatched_entities.get("name")
            assert name_entity is not None
            assert isinstance(name_entity, UnmatchedTextEntity)
            entity_names.add(name_entity.text)

    assert area_names == {"unknown thing ", "unknown thing to "}
    assert entity_names == {"unknown thing ", "unknown thing to "}


def test_unmatched_entities_dont_share_text() -> None:
    """Test that text only goes into one unmatched entity."""
    yaml_text = """
    language: "en"
    intents:
      Test:
        data:
          - sentences:
              - "set [the] brightness [of] {name} [to] <brightness>"
    lists:
      name:
        values:
          - lamp
      brightness_pct:
          range:
            type: percentage
            from: 0
            to: 100
    expansion_rules:
        brightness: "{brightness_pct}[%| percent]"
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    sentence = "set brightness of unknown thing to 100%"

    # Should fail without unmatched entities enabled
    result = recognize(sentence, intents, allow_unmatched_entities=False)
    assert result is None, f"{sentence} should not match"

    results = list(recognize_all(sentence, intents, allow_unmatched_entities=True))
    assert len(results) == 2

    possible_names: Set[str] = set()
    for result in results:
        assert len(result.unmatched_entities) == 1
        assert "name" in result.unmatched_entities
        name_entity = result.unmatched_entities["name"]
        assert isinstance(name_entity, UnmatchedTextEntity)
        possible_names.add(name_entity.text)

    assert possible_names == {"unknown thing ", "of unknown thing "}


def test_unmatched_entities_cant_skip_words() -> None:
    yaml_text = """
    language: "en"
    intents:
      Test:
        data:
          - sentences:
              - "[turn] {name} [to] on"
    lists:
      name:
        values:
          - lamp
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    sentence = "turn on unknown thing"

    # Should fail without unmatched entities enabled
    result = recognize(sentence, intents, allow_unmatched_entities=False)
    assert result is None, f"{sentence} should not match"

    # Should also fail with unmatched entities enabled
    results = list(recognize_all(sentence, intents, allow_unmatched_entities=True))
    assert len(results) == 0


def test_unmatched_entities_text_chunks_matched() -> None:
    yaml_text = """
    language: "en"
    intents:
      Test:
        data:
          - sentences:
              - "[turn] on {name}"
              - "[turn] on {name} light"
    lists:
      name:
        values:
          - test
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    sentence = "turn on unknown light"

    results = list(recognize_all(sentence, intents, allow_unmatched_entities=True))
    assert len(results) == 2

    # '[turn] on {name} light' should have more literal text matched
    result_1, result_2 = results
    assert result_1.intent_sentence is not None
    if result_1.intent_sentence.text == "[turn] on {name}":
        assert result_1.text_chunks_matched < result_2.text_chunks_matched
    else:
        assert result_2.text_chunks_matched < result_1.text_chunks_matched


def test_wildcard() -> None:
    """Test wildcard slot lists/entities."""
    yaml_text = """
    language: "en"
    intents:
      Test:
        data:
          - sentences:
              - "play {album} by {artist}[ please] now"
              - "start {album} by {artist}"
              - "begin {album} by artist {artist}"
    lists:
      album:
        wildcard: true
      artist:
        wildcard: true
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    # Case should be kept
    sentence = "play The White Album by The Beatles please now"
    result = recognize(sentence, intents)
    assert result is not None, f"{sentence} should match"
    assert set(result.entities.keys()) == {"album", "artist"}
    assert result.entities["album"].value == "The White Album"
    assert result.entities["album"].is_wildcard
    assert result.entities["artist"].value == "The Beatles"
    assert result.entities["artist"].is_wildcard

    # Wildcards cannot be empty
    sentence = "play by please now"
    result = recognize(sentence, intents)
    assert result is None, f"{sentence} should not match"

    # Test without text at the end
    sentence = "start the white album by the beatles."
    result = recognize(sentence, intents)
    assert result is not None, f"{sentence} should match"
    assert set(result.entities.keys()) == {"album", "artist"}
    assert result.entities["album"].value == "the white album"
    assert result.entities["album"].is_wildcard
    assert result.entities["artist"].value == "the beatles"
    assert result.entities["artist"].is_wildcard

    # Test use of next word in wildcard
    sentence = "play day by day by taken by trees now"
    results = list(recognize_all(sentence, intents))
    assert results, f"{sentence} should match"
    assert len(results) == 3  # 3 "by" words

    # Verify each combination of album/artist is present
    album_artist = {
        (result.entities["album"].value, result.entities["artist"].value)
        for result in results
    }
    assert album_artist == {
        ("day", "day by taken by trees"),
        ("day by day", "taken by trees"),
        ("day by day by taken", "trees"),
    }
    for result in results:
        assert result.entities["album"].is_wildcard
        assert result.entities["artist"].is_wildcard

    # Test use of next word at end of word in wildcard
    sentence = "play Moby by Moby please now"
    result = recognize(sentence, intents)
    assert result is not None, f"{sentence} should match"
    assert set(result.entities.keys()) == {"album", "artist"}
    assert result.entities["album"].value == "Moby"
    assert result.entities["album"].is_wildcard
    assert result.entities["artist"].value == "Moby"
    assert result.entities["artist"].is_wildcard

    # Add "artist" word
    sentence = "begin day by day by artist taken by trees"
    result = recognize(sentence, intents)
    assert result is not None, f"{sentence} should match"
    assert set(result.entities.keys()) == {"album", "artist"}
    assert result.entities["album"].value == "day by day"
    assert result.entities["album"].is_wildcard
    assert result.entities["artist"].value == "taken by trees"
    assert result.entities["artist"].is_wildcard


def test_wildcard_degenerate() -> None:
    """Test degenerate case for wildcards."""
    yaml_text = """
    language: "en"
    intents:
      Test:
        data:
          - sentences:
              - "play {album} by {artist}"
    lists:
      album:
        wildcard: true
      artist:
        wildcard: true
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    sentence = "play by by by by by"
    results = list(recognize_all(sentence, intents))
    assert results, f"{sentence} should match"
    assert len(results) == 3  # 3 valid splits

    # Verify each combination
    album_artist = {
        (result.entities["album"].value, result.entities["artist"].value)
        for result in results
    }
    assert album_artist == {
        ("by", "by by by"),
        ("by by", "by by"),
        ("by by by", "by"),
    }


def test_optional_wildcard() -> None:
    """Test optional wildcard slot list."""
    yaml_text = """
    language: "en"
    intents:
      Test:
        data:
          - sentences:
              - "play {album}[by {artist}]"
    lists:
      album:
        wildcard: true
      artist:
        wildcard: true
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    # With all wildcards
    sentence = "play the white album by the beatles"
    result = recognize(sentence, intents)
    assert result is not None, f"{sentence} should match"
    assert set(result.entities.keys()) == {"album", "artist"}
    assert result.entities["album"].value == "the white album"
    assert result.entities["artist"].value == "the beatles"

    # Missing one wildcard
    sentence = "play the white album"
    result = recognize(sentence, intents)
    assert result is not None, f"{sentence} should match"
    assert set(result.entities.keys()) == {"album"}
    assert result.entities["album"].value == "the white album"


def test_wildcard_slot_name() -> None:
    """Test wildcard uses slot instead of list name."""
    yaml_text = """
    language: "en"
    intents:
      Test:
        data:
          - sentences:
              - "run {script_name:name}"
    lists:
      script_name:
        wildcard: true
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    sentence = "run script 1"
    result = recognize(sentence, intents)
    assert result is not None, f"{sentence} should match"
    assert set(result.entities.keys()) == {"name"}
    assert result.entities["name"].value == "script 1"


def test_wildcard_ordering() -> None:
    """Test wildcard ordering by number of literal text chunks."""
    yaml_text = """
    language: "en"
    intents:
      Test:
        data:
          - sentences:
              - "play {album} by {artist}"
              - "play {album} by {artist} in {room}"
    lists:
      album:
        wildcard: true
      artist:
        wildcard: true
      room:
        wildcard: true
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    sentence = "play the white album by the beatles in the living room"
    result = recognize(sentence, intents)
    assert result is not None, f"{sentence} should match"
    assert set(result.entities.keys()) == {"album", "artist", "room"}
    assert result.entities["album"].value == "the white album"
    assert result.entities["artist"].value == "the beatles"
    assert result.entities["room"].value == "the living room"

    # Check that the first sentence can still be used
    sentence = "play the white album by the beatles"
    result = recognize(sentence, intents)
    assert result is not None, f"{sentence} should match"
    assert set(result.entities.keys()) == {"album", "artist"}
    assert result.entities["album"].value == "the white album"
    assert result.entities["artist"].value == "the beatles"


def test_ordering_only_wildcards() -> None:
    """Test that re-ordering only affects wildcards."""
    yaml_text = """
    language: "en"
    intents:
      Test:
        data:
          - sentences:
              - "turn on {light} in {room}"
              - "turn on {light}"
    lists:
      light:
        values:
          - light
          - light in bedroom
      room:
        values:
          - bedroom
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    sentence = "turn on light in bedroom"
    result = recognize(sentence, intents)
    assert result is not None, f"{sentence} should match"
    assert set(result.entities.keys()) == {"light", "room"}
    assert result.entities["light"].value == "light"
    assert result.entities["room"].value == "bedroom"


def test_wildcard_punctuation() -> None:
    """Test that wildcards do not include punctuation."""
    yaml_text = """
    language: "en"
    intents:
      Test:
        data:
          - sentences:
              - "is {name} in {zone}"
    lists:
      name:
        wildcard: true
      zone:
        wildcard: true
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    sentence = "is Alice in New York!?"
    result = recognize(sentence, intents)
    assert result is not None, f"{sentence} should match"
    assert set(result.entities.keys()) == {"name", "zone"}
    assert result.entities["name"].value == "Alice"
    assert result.entities["zone"].value == "New York"


def test_wildcard_inside_word() -> None:
    """Test wildcard inside of a word."""
    yaml_text = """
    language: "en"
    intents:
      Test:
        data:
          - sentences:
              - "ab{test}cd"
    lists:
      test:
        wildcard: true
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    sentence = "ab123cd"
    result = recognize(sentence, intents)
    assert result is not None, f"{sentence} should match"
    assert set(result.entities.keys()) == {"test"}
    assert result.entities["test"].value == "123"
    assert result.entities["test"].is_wildcard


def test_wildcard_outside_word() -> None:
    """Test wildcard outside of a word."""
    yaml_text = """
    language: "en"
    intents:
      Test:
        data:
          - sentences:
              - "ab{test} cd"
    lists:
      test:
        wildcard: true
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    sentence = "ab123 cd"
    result = recognize(sentence, intents)
    assert result is not None, f"{sentence} should match"
    assert set(result.entities.keys()) == {"test"}
    assert result.entities["test"].value == "123"
    assert result.entities["test"].is_wildcard

    sentence = "ab123cd"
    result = recognize(sentence, intents)
    assert result is None, f"{sentence} should not match"


def test_wildcard_outside_word_ignore_whitespace() -> None:
    """Test wildcard outside of a word when ignoring whitespace."""
    yaml_text = """
    language: "en"
    settings:
      ignore_whitespace: true
    intents:
      Test:
        data:
          - sentences:
              - "ab{test} cd"
    lists:
      test:
        wildcard: true
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    for sentence in ("abc123 cd", "abc123cd"):
        result = recognize(sentence, intents)
        assert result is not None, f"{sentence} should match"


def test_entity_metadata() -> None:
    """Ensure metadata is returned for text slots"""
    yaml_text = """
    language: "en"
    intents:
      TestIntent:
        data:
          - sentences:
              - "run test {name} [now]"
              - "{name} test"
    lists:
      name:
        values:
          - in: "alpha "
            out: "A"
            metadata:
              is_alpha: true
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    for sentence in ("run test alpha, now", "run test alpha!", "alpha test"):
        result = recognize(sentence, intents)
        assert result is not None, sentence
        assert result.entities["name"].value == "A"
        assert result.entities["name"].text_clean == "alpha"
        assert result.entities["name"].metadata == {"is_alpha": True}


def test_sentence_metadata() -> None:
    """Test that metadata attached to sentences is passed through to the result."""
    yaml_text = """
    language: "en"
    intents:
      Test:
        data:
          - sentences:
              - "this is a test"
            metadata:
              string_key: "test value"
              int_key: 1234
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    sentence = "this is a test"
    result = recognize(sentence, intents)
    assert result is not None, f"{sentence} should match"
    assert result.intent_metadata is not None, "No metadata"
    assert result.intent_metadata == {"string_key": "test value", "int_key": 1234}


def test_digits_calc() -> None:
    """Test that metadata attached to sentences is passed through to the result."""
    yaml_text = """
    language: "en"
    intents:
      Calculate:
        data:
          - sentences:
              - "calc[ulate] {x} {operator} {y}"
    lists:
      operator:
        values:
          - in: "(+|plus)"
            out: "+"
      x:
        range:
          from: 0
          to: 100
          digits: true
          words: true
      y:
        range:
          from: 0
          to: 100
          digits: true
          words: true
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    sentence = "calc 1 + 2"
    result = recognize(sentence, intents)
    assert result is not None, f"{sentence} should match"
    assert result.entities.keys() == {"x", "operator", "y"}
    assert result.entities["x"].value == 1
    assert result.entities["operator"].value == "+"
    assert result.entities["y"].value == 2

    sentence = "calc 1 plus two"
    result = recognize(sentence, intents)
    assert result is not None, f"{sentence} should match"
    assert result.entities.keys() == {"x", "operator", "y"}
    assert result.entities["x"].value == 1
    assert result.entities["operator"].value == "+"
    assert result.entities["y"].value == 2


def test_range_params_calc() -> None:
    """Test that params attached to RangeSlotList affect the parsing."""
    yaml_text = """
    language: "en"
    intents:
      Calculate:
        data:
          - sentences:
              - "calc[ulate] {x} {operator} {y}"
    lists:
      operator:
        values:
          - in: "(+|plus)"
            out: "+"
      x:
        range:
          from: 0
          to: 100
          digits: false
          words: true
      y:
        range:
          from: 0
          to: 100
          digits: true
          words: false
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    # x can't have digits
    sentence = "calc 1 + 2"
    result = recognize(sentence, intents)
    assert result is None, f"{sentence} should not match"

    # y can't have words
    sentence = "calc one plus two"
    result = recognize(sentence, intents)
    assert result is None, f"{sentence} should not match"

    sentence = "calc one + 2"
    result = recognize(sentence, intents)
    assert result is not None, f"{sentence} should match"
    assert result.entities.keys() == {"x", "operator", "y"}
    assert result.entities["x"].value == 1
    assert result.entities["operator"].value == "+"
    assert result.entities["y"].value == 2


def test_range_rule_sets_calc() -> None:
    """Test that params attached to RangeSlotList affect the parsing."""
    # https://github.com/rhasspy/unicode-rbnf/blob/master/unicode_rbnf/engine.py#L13
    yaml_text = """
    language: "en"
    intents:
      Calculate:
        data:
          - sentences:
              - "calc[ulate] {x} {operator} {y}"
    lists:
      operator:
        values:
          - in: "(+|plus)"
            out: "+"
      x:
        range:
          from: 0
          to: 3000
          digits: true
          words: true
      y:
        range:
          from: 0
          to: 3000
          digits: true
          words: true
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    sentence = "calc one thousand nine hundred ninety-nine + 23"
    result = recognize(sentence, intents)
    assert result is not None, f"{sentence} should match"
    assert result.entities.keys() == {"x", "operator", "y"}
    assert result.entities["x"].value == 1999
    assert result.entities["operator"].value == "+"
    assert result.entities["y"].value == 23

    sentence = "calc 23 + nineteen ninety-nine"
    result = recognize(sentence, intents)
    assert result is None, f"{sentence} should not match"


# pylint: disable=redefined-outer-name
def test_context_dict(intents, slot_lists):
    yaml_text = """
    language: "en"
    intents:
      TestIntent:
        data:
          - sentences:
              - "test sentence"
            requires_context:
              slot1:
                value: value1
                slot: true
            excludes_context:
              slot2: value2
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    slot1 = {"value": "value1", "text": "Value One"}

    # Try includes context
    result = recognize(
        "test sentence",
        intents,
        slot_lists=slot_lists,
        intent_context={"slot1": slot1},
    )
    assert result is not None
    assert result.context.keys() == {"slot1"}
    assert result.context["slot1"] == slot1
    assert result.entities.keys() == {"slot1"}
    assert result.entities["slot1"].value == "value1"
    assert result.entities["slot1"].text == "Value One"

    # Try excludes context
    result = recognize(
        "test sentence",
        intents,
        slot_lists=slot_lists,
        intent_context={"slot1": slot1, "slot2": {"value": "value2"}},
    )
    assert result is None


# pylint: disable=redefined-outer-name
def test_range_multiplier(intents, slot_lists):
    yaml_text = """
    language: "en"
    intents:
      SetVolume:
        data:
          - sentences:
              - "set volume to {volume_level}"
    lists:
      volume_level:
        range:
          from: 0
          to: 100
          multiplier: 0.01
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    result = recognize("set volume to 50", intents)
    assert result is not None
    assert result.entities.keys() == {"volume_level"}
    assert result.entities["volume_level"].value == 0.5
    assert result.entities["volume_level"].text == "50"


def test_recognize_best():
    yaml_text = """
    language: "en"
    intents:
      TurnOn:
        data:
          - sentences:
              - "{anything} lamp"
            metadata:
              best_key: "best value"
          - sentences:
              - "turn on {area} lamp"
              - "turn on {name}"
    lists:
      area:
        values:
          - bedroom
      name:
        values:
          - bedroom lamp
      anything:
        wildcard: true
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    # Should match the sentence with the wildcard slot because it's listed first.
    result = recognize("turn on bedroom lamp", intents)  # not best
    assert result is not None
    assert result.entities.keys() == {"anything"}

    # Should match the sentence with the wildcard slot because of its metadata.
    result = recognize_best(
        "turn on bedroom lamp", intents, best_metadata_key="best_key"
    )
    assert result is not None
    assert result.entities.keys() == {"anything"}

    # Should match the sentence with the "area" slot because it has the most
    # literal text matched.
    result = recognize_best("turn on bedroom lamp", intents)
    assert result is not None
    assert result.entities.keys() == {"area"}

    # Should match the sentence with the "name" slot because it's a priority
    result = recognize_best("turn on bedroom lamp", intents, best_slot_name="name")
    assert result is not None
    assert result.entities.keys() == {"name"}
    assert result.entities["name"].value == "bedroom lamp"


def test_regex_branching():
    yaml_text = """
    language: "en"
    intents:
      TurnOn:
        data:
          - sentences:
              - "turn on ({area} {name}|{name})"
    lists:
      area:
        values:
          - bedroom
      name:
        values:
          - bedroom lamp
          - lamp
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    results = list(recognize_all("turn on bedroom lamp", intents))
    assert len(results) == 2


def test_commas_dont_change() -> None:
    """Ensure commas don't change the interpretation of a sentence."""
    yaml_text = """
    language: "en"
    intents:
      TurnOn:
        data:
          - sentences:
              - "turn on [the] {name}"
              - "turn on [the] {area} lights"
    lists:
      name:
        values:
          - lamp
      area:
        values:
          - living room
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    for sentence in (
        "turn on the living room lights",
        "turn, on the, living room lights",
        "turn on, the living room lights",
        "turn on the, living room lights",
        "turn on the living room, lights",
    ):
        result = recognize(sentence, intents)
        assert result is not None, sentence
        assert result.entities.keys() == {"area"}


def test_wildcard_then_other_stuff() -> None:
    """Test wildcard followed by expansion rule and list."""
    yaml_text = """
    language: "en"
    intents:
      SetTimer:
        data:
          - sentences:
              - "set timer {timer_name:name} <timer_duration>"
              - "set timer {timer_name:name} {timer_state:state} [now]"
      AddItem:
        data:
          - sentences:
              - "add {item} [to [my]] {todo_list}"
    lists:
      timer_name:
        wildcard: true
      item:
        wildcard: true
      minutes:
        range:
          from: 1
          to: 59
      timer_state:
        values:
          - "on"
          - "off"
      todo_list:
        values:
          - "shopping list"
    expansion_rules:
      timer_duration: "{minutes} minute[s]"
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    # Check ranges
    for sentence in ("set timer pizza 5 minutes", "set timer pizza five minutes"):
        result = recognize(sentence, intents)
        assert result is not None, f"{sentence} should match"
        assert set(result.entities.keys()) == {"name", "minutes"}
        assert result.entities["name"].text == "pizza"
        assert result.entities["name"].value == "pizza"
        assert result.entities["minutes"].text.strip() in {"5", "five"}
        assert result.entities["minutes"].value == 5

    # Check value list
    sentence = "set timer a big long name on now"
    result = recognize(sentence, intents)
    assert result is not None, f"{sentence} should match"
    assert set(result.entities.keys()) == {"name", "state"}
    assert result.entities["name"].text == "a big long name"
    assert result.entities["name"].value == "a big long name"
    assert result.entities["state"].text == "on"
    assert result.entities["state"].value == "on"

    sentence = "add apples to my shopping list"
    result = recognize(sentence, intents)
    assert result is not None, f"{sentence} should match"
    assert set(result.entities.keys()) == {"item", "todo_list"}
    assert result.entities["item"].text == "apples"
    assert result.entities["item"].value == "apples"
    assert result.entities["todo_list"].text == "shopping list"
    assert result.entities["todo_list"].value == "shopping list"


def test_range_list_with_one_number() -> None:
    """Test a range list with the same start/stop value."""
    yaml_text = """
    language: "en"
    intents:
      TestIntent:
        data:
          - sentences:
              - "test {value}"
    lists:
      value:
        range:
          from: 1
          to: 1
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    # Check ranges
    assert recognize("test 1", intents)
    assert not recognize("test 2", intents)


def test_range_list_with_halves() -> None:
    """Test a range list with fractions (1/2)."""
    yaml_text = """
    language: "en"
    intents:
      TestIntent:
        data:
          - sentences:
              - "test {value}"
    lists:
      value:
        range:
          from: 1
          to: 2
          fractions: halves
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    assert recognize("test 1", intents)
    result = recognize("test 1.5", intents)
    assert result is not None
    value = result.entities.get("value")
    assert value is not None
    assert value.value == 1.5
    assert value.text == "1.5"
    assert value.text_clean == "1.5"

    result = recognize("test one point five", intents, language="en")
    assert result is not None
    value = result.entities.get("value")
    assert value is not None
    assert value.value == 1.5
    assert value.text == "one point five"
    assert value.text_clean == "one point five"

    result = recognize("test 2.0", intents)
    assert result is not None
    value = result.entities.get("value")
    assert value is not None
    assert value.value == 2
    assert value.text == "2.0"
    assert value.text_clean == "2.0"

    result = recognize("test 2.5", intents)
    assert result is not None
    value = result.entities.get("value")
    assert value is not None
    assert value.value == 2.5
    assert value.text == "2.5"
    assert value.text_clean == "2.5"

    # Only halves
    assert not recognize("test 2.1", intents)

    # Comma separator
    result = recognize("test 2,5", intents)
    assert result is not None
    value = result.entities.get("value")
    assert value is not None
    assert value.value == 2.5
    assert value.text == "2,5"
    assert value.text_clean == "2,5"


def test_range_list_with_tenths() -> None:
    """Test a range list with fractions (1/10)."""
    yaml_text = """
    language: "en"
    intents:
      TestIntent:
        data:
          - sentences:
              - "test {value}"
    lists:
      value:
        range:
          from: 1
          to: 2
          fractions: tenths
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    assert recognize("test 1", intents)
    assert recognize("test 2", intents)

    for integer in range(1, 3):
        for tenth in range(1, 10):
            value_str = f"{integer}.{tenth}"
            result = recognize(f"test {value_str}", intents)
            assert result is not None
            value = result.entities.get("value")
            assert value is not None
            assert value.value == float(value_str)
            assert value.text == value_str
            assert value.text_clean == value_str

    result = recognize("test one point one", intents, language="en")
    assert result is not None
    value = result.entities.get("value")
    assert value is not None
    assert value.value == 1.1
    assert value.text == "one point one"

    result = recognize("test two point six", intents, language="en")
    assert result is not None
    value = result.entities.get("value")
    assert value is not None
    assert value.value == 2.6
    assert value.text == "two point six"

    # Only tenths
    assert not recognize("test 2.12", intents)


def test_range_lists_separated_by_punctuation() -> None:
    """Test range lists separated by punctuation."""
    yaml_text = """
    language: "en"
    intents:
      TestIntent:
        data:
          - sentences:
              - "test {value1}.{value2}"
    lists:
      value1:
        range:
          from: 0
          to: 1
      value2:
        range:
          from: 0
          to: 2
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    result = recognize("test 1.2", intents)
    assert result is not None

    value1 = result.entities.get("value1")
    assert value1 is not None
    assert value1.value == 1

    value2 = result.entities.get("value2")
    assert value2 is not None
    assert value2.value == 2


def test_range_lists_separated_by_punctuation_with_wildcard() -> None:
    """Test range lists separated by punctuation preceeded by a wildcard."""
    yaml_text = """
    language: "en"
    intents:
      TestIntent:
        data:
          - sentences:
              - "test {anything} {value1}.{value2}"
    lists:
      anything:
        wildcard: true
      value1:
        range:
          from: 0
          to: 1
      value2:
        range:
          from: 0
          to: 2
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    result = recognize("test for the big 1.2", intents)
    assert result is not None

    anything = result.entities.get("anything")
    assert anything is not None
    assert anything.value == "for the big"

    value1 = result.entities.get("value1")
    assert value1 is not None
    assert value1.value == 1

    value2 = result.entities.get("value2")
    assert value2 is not None
    assert value2.value == 2


def test_list_value_in_no_out() -> None:
    """Test list values with "in" but no "out"."""
    yaml_text = """
    language: "en"
    intents:
      TestIntent:
        data:
          - sentences:
              - "test {value1}"
          - sentences:
              - "also test {value2}"
            lists:
              value2:
                values:
                  - g[h]i
                  - j[k]l
    lists:
      value1:
        values:
          - a[b]c
          - in: d[e]f
    """

    with io.StringIO(yaml_text) as test_file:
        intents = Intents.from_yaml(test_file)

    for value in ("abc", "ac", "def", "df"):
        result = recognize(f"test {value}", intents)
        assert result is not None, value
        assert "value1" in result.entities
        assert result.entities["value1"].value == value

    for value in ("ghi", "gi", "jkl", "jl"):
        result = recognize(f"also test {value}", intents)
        assert result is not None, value
        assert "value2" in result.entities
        assert result.entities["value2"].value == value