ovos-spec-tools 0.0.1a2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2022 Casimiro Ferreira
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,99 @@
1
+ Metadata-Version: 2.4
2
+ Name: ovos-spec-tools
3
+ Version: 0.0.1a2
4
+ Summary: Reference implementation of the OVOS formal specifications
5
+ Author-email: jarbasai <jarbasai@mailfence.com>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/OpenVoiceOS/ovos-spec-tools
8
+ Requires-Python: >=3.8
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE.md
11
+ Provides-Extra: langcodes
12
+ Requires-Dist: langcodes; extra == "langcodes"
13
+ Provides-Extra: test
14
+ Requires-Dist: pytest; extra == "test"
15
+ Requires-Dist: langcodes; extra == "test"
16
+ Dynamic: license-file
17
+
18
+ # ovos-spec-tools
19
+
20
+ Reference implementation of the OVOS [formal
21
+ specifications](https://github.com/OpenVoiceOS/architecture) — the
22
+ low-level, dependency-light primitives those specifications describe.
23
+
24
+ OVOS components reimplement template expansion, resource loading, and language
25
+ matching in several places, and the copies drift. This package is the single
26
+ conformant implementation those components — and any third-party tool — can
27
+ depend on.
28
+
29
+ ## Status
30
+
31
+ | Tool | Spec | Code |
32
+ |------|------|-------|
33
+ | Sentence template expander | OVOS-INTENT-1 v2 | `expansion.py` |
34
+ | Locale resource loader | OVOS-INTENT-2 | `resources.py` |
35
+ | Dialog renderer | OVOS-INTENT-2 §4.2 | `dialog.py` |
36
+ | Prompt renderer | OVOS-INTENT-2 §4.4 | `prompt.py` |
37
+ | Language-tag matching | OVOS-INTENT-2 §2.2 | `language.py` |
38
+ | `ovos-spec-lint` locale linter | OVOS-INTENT-1 / -2 | `lint.py` |
39
+
40
+ ## Install
41
+
42
+ ```bash
43
+ pip install ovos-spec-tools # core — no dependencies
44
+ pip install ovos-spec-tools[langcodes] # adds the smart language fallback
45
+ ```
46
+
47
+ Requires Python 3.8+.
48
+
49
+ ## Quick taste
50
+
51
+ ```python
52
+ from ovos_spec_tools import (expand, LocaleResources, render, render_prompt,
53
+ closest_lang)
54
+
55
+ expand("(turn|switch) [the] light") # all 4 sentences it denotes
56
+ res = LocaleResources("my-skill/locale")
57
+ res.load_intent("play", "en-US") # a skill's intent samples
58
+ render(res.load_dialog("weather", "en-US"), # a spoken response
59
+ slots={"temperature": 21})
60
+ render_prompt(res.load_prompt("system", "en-US"), # a language-model prompt
61
+ slots={"query": "what time is it"})
62
+ closest_lang("en-AU", ["pt-BR", "en-US"]) # 'en-US'
63
+ ```
64
+
65
+ ```bash
66
+ ovos-spec-lint my-skill/locale # validate a locale folder
67
+ ```
68
+
69
+ ## Documentation
70
+
71
+ A zero-to-hero guide lives in [`docs/`](docs/README.md):
72
+
73
+ 1. [Getting started](docs/getting-started.md) — install, and a first taste of
74
+ every tool.
75
+ 2. [Sentence templates](docs/templates.md) — the grammar: alternatives,
76
+ optionals, slots, vocabulary references, malformed forms.
77
+ 3. [Locale resources](docs/locale-resources.md) — the `locale/` folder, the
78
+ six file roles, loading across languages, override precedence.
79
+ 4. [Dialog](docs/dialog.md) — choosing and filling a spoken response, and
80
+ rendering language-model prompts.
81
+ 5. [Language matching](docs/language-matching.md) — tag standardization,
82
+ distance, and closest-match resolution.
83
+ 6. [Linting](docs/linting.md) — validating a locale folder, on the CLI or in CI.
84
+ 7. [API reference](docs/api-reference.md) — every public name, in brief.
85
+
86
+ Runnable example scripts are in [`examples/`](examples/README.md).
87
+
88
+ ## Credits
89
+
90
+ This package was produced as part of a documentation and interoperability
91
+ effort for OpenVoiceOS, funded by NLnet's
92
+ [NGI0 Commons Fund](https://nlnet.nl/project/OpenVoiceOS) under grant
93
+ agreement No [101135429](https://cordis.europa.eu/project/id/101135429).
94
+
95
+ ![NGI0 / NLnet](./ngi.png)
96
+
97
+ ## License
98
+
99
+ Apache 2.0
@@ -0,0 +1,82 @@
1
+ # ovos-spec-tools
2
+
3
+ Reference implementation of the OVOS [formal
4
+ specifications](https://github.com/OpenVoiceOS/architecture) — the
5
+ low-level, dependency-light primitives those specifications describe.
6
+
7
+ OVOS components reimplement template expansion, resource loading, and language
8
+ matching in several places, and the copies drift. This package is the single
9
+ conformant implementation those components — and any third-party tool — can
10
+ depend on.
11
+
12
+ ## Status
13
+
14
+ | Tool | Spec | Code |
15
+ |------|------|-------|
16
+ | Sentence template expander | OVOS-INTENT-1 v2 | `expansion.py` |
17
+ | Locale resource loader | OVOS-INTENT-2 | `resources.py` |
18
+ | Dialog renderer | OVOS-INTENT-2 §4.2 | `dialog.py` |
19
+ | Prompt renderer | OVOS-INTENT-2 §4.4 | `prompt.py` |
20
+ | Language-tag matching | OVOS-INTENT-2 §2.2 | `language.py` |
21
+ | `ovos-spec-lint` locale linter | OVOS-INTENT-1 / -2 | `lint.py` |
22
+
23
+ ## Install
24
+
25
+ ```bash
26
+ pip install ovos-spec-tools # core — no dependencies
27
+ pip install ovos-spec-tools[langcodes] # adds the smart language fallback
28
+ ```
29
+
30
+ Requires Python 3.8+.
31
+
32
+ ## Quick taste
33
+
34
+ ```python
35
+ from ovos_spec_tools import (expand, LocaleResources, render, render_prompt,
36
+ closest_lang)
37
+
38
+ expand("(turn|switch) [the] light") # all 4 sentences it denotes
39
+ res = LocaleResources("my-skill/locale")
40
+ res.load_intent("play", "en-US") # a skill's intent samples
41
+ render(res.load_dialog("weather", "en-US"), # a spoken response
42
+ slots={"temperature": 21})
43
+ render_prompt(res.load_prompt("system", "en-US"), # a language-model prompt
44
+ slots={"query": "what time is it"})
45
+ closest_lang("en-AU", ["pt-BR", "en-US"]) # 'en-US'
46
+ ```
47
+
48
+ ```bash
49
+ ovos-spec-lint my-skill/locale # validate a locale folder
50
+ ```
51
+
52
+ ## Documentation
53
+
54
+ A zero-to-hero guide lives in [`docs/`](docs/README.md):
55
+
56
+ 1. [Getting started](docs/getting-started.md) — install, and a first taste of
57
+ every tool.
58
+ 2. [Sentence templates](docs/templates.md) — the grammar: alternatives,
59
+ optionals, slots, vocabulary references, malformed forms.
60
+ 3. [Locale resources](docs/locale-resources.md) — the `locale/` folder, the
61
+ six file roles, loading across languages, override precedence.
62
+ 4. [Dialog](docs/dialog.md) — choosing and filling a spoken response, and
63
+ rendering language-model prompts.
64
+ 5. [Language matching](docs/language-matching.md) — tag standardization,
65
+ distance, and closest-match resolution.
66
+ 6. [Linting](docs/linting.md) — validating a locale folder, on the CLI or in CI.
67
+ 7. [API reference](docs/api-reference.md) — every public name, in brief.
68
+
69
+ Runnable example scripts are in [`examples/`](examples/README.md).
70
+
71
+ ## Credits
72
+
73
+ This package was produced as part of a documentation and interoperability
74
+ effort for OpenVoiceOS, funded by NLnet's
75
+ [NGI0 Commons Fund](https://nlnet.nl/project/OpenVoiceOS) under grant
76
+ agreement No [101135429](https://cordis.europa.eu/project/id/101135429).
77
+
78
+ ![NGI0 / NLnet](./ngi.png)
79
+
80
+ ## License
81
+
82
+ Apache 2.0
@@ -0,0 +1,56 @@
1
+ """Reference implementation of the OVOS formal specifications.
2
+
3
+ `ovos-spec-tools` provides the low-level, dependency-light primitives the OVOS
4
+ formal specifications describe:
5
+
6
+ - :func:`~ovos_spec_tools.expansion.expand` — the OVOS-INTENT-1 sentence
7
+ template expander;
8
+ - :class:`~ovos_spec_tools.resources.LocaleResources` — the OVOS-INTENT-2
9
+ locale resource-file loader;
10
+ - :func:`~ovos_spec_tools.dialog.render` / :class:`~ovos_spec_tools.dialog.DialogRenderer`
11
+ — the OVOS-INTENT-2 §4.2 dialog renderer;
12
+ - :func:`~ovos_spec_tools.prompt.render_prompt` / :class:`~ovos_spec_tools.prompt.PromptRenderer`
13
+ — the OVOS-INTENT-2 §4.4 ``.prompt`` renderer;
14
+ - :func:`~ovos_spec_tools.language.standardize_lang`,
15
+ :func:`~ovos_spec_tools.language.lang_distance`, and
16
+ :func:`~ovos_spec_tools.language.closest_lang` — language-tag normalization,
17
+ distance, and closest-match resolution;
18
+ - :func:`~ovos_spec_tools.lint.lint_locale` — a locale resource linter, also
19
+ exposed as the ``ovos-spec-lint`` command.
20
+ """
21
+ from ovos_spec_tools.dialog import DialogRenderer, UnfilledSlot, render
22
+ from ovos_spec_tools.expansion import MalformedTemplate, expand
23
+ from ovos_spec_tools.language import (
24
+ closest_lang,
25
+ lang_distance,
26
+ standardize_lang,
27
+ )
28
+ from ovos_spec_tools.lint import Finding, lint_locale
29
+ from ovos_spec_tools.prompt import PromptRenderer, render_prompt
30
+ from ovos_spec_tools.resources import (
31
+ LocaleResources,
32
+ MalformedResource,
33
+ read_prompt_file,
34
+ read_resource_file,
35
+ )
36
+ from ovos_spec_tools.version import __version__
37
+
38
+ __all__ = [
39
+ "expand",
40
+ "MalformedTemplate",
41
+ "LocaleResources",
42
+ "MalformedResource",
43
+ "read_resource_file",
44
+ "read_prompt_file",
45
+ "render",
46
+ "DialogRenderer",
47
+ "UnfilledSlot",
48
+ "render_prompt",
49
+ "PromptRenderer",
50
+ "standardize_lang",
51
+ "lang_distance",
52
+ "closest_lang",
53
+ "lint_locale",
54
+ "Finding",
55
+ "__version__",
56
+ ]
@@ -0,0 +1,193 @@
1
+ """Reference dialog renderer for OVOS-INTENT-2 §4.2.
2
+
3
+ This is the reference implementation of the **Dialog renderer** conformance
4
+ role of OVOS-INTENT-1 §7. Rendering a dialog means: select one phrase from a
5
+ loaded ``.dialog``, expand its ``(a|b)`` / ``[x]`` variety to a single variant,
6
+ and fill every ``{name}`` slot with a value.
7
+
8
+ Two interfaces are provided:
9
+
10
+ - :func:`render` — a stateless one-shot function over explicit phrases;
11
+ - :class:`DialogRenderer` — a stateful, **multilingual** object backed by a
12
+ :class:`~ovos_spec_tools.resources.LocaleResources`: the language is given
13
+ per :meth:`DialogRenderer.render` call, and the renderer avoids repeating
14
+ the phrase it chose last (independently per language).
15
+
16
+ Only the single-brace slot form ``{name}`` is recognized; there is no ``{{ }}``
17
+ form (OVOS-INTENT-2 §4.2). A slot with no value raises :class:`UnfilledSlot`.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import random as _random
22
+ import re
23
+ from typing import Dict, Optional, Protocol, Sequence
24
+
25
+ from ovos_spec_tools.expansion import expand
26
+
27
+ __all__ = ["render", "DialogRenderer", "Chooser", "UnfilledSlot"]
28
+
29
+ _SLOT_TOKEN_RE = re.compile(r"\{([a-z][a-z0-9_]*)\}")
30
+
31
+
32
+ class Chooser(Protocol):
33
+ """A source of random selection: anything with a ``choice`` method.
34
+
35
+ The :mod:`random` module and a :class:`random.Random` instance both
36
+ satisfy it. Inject a seeded ``random.Random`` for deterministic output.
37
+ """
38
+
39
+ def choice(self, seq: Sequence[str]) -> str:
40
+ ...
41
+
42
+
43
+ class UnfilledSlot(ValueError):
44
+ """A chosen dialog phrase has a named slot with no value.
45
+
46
+ Per OVOS-INTENT-1 §5.1 the caller must supply a value for every slot in the
47
+ chosen phrase; a phrase with an unfilled slot must not be sent to TTS.
48
+ """
49
+
50
+
51
+ def render(phrases: Sequence[str],
52
+ slots: Optional[Dict[str, object]] = None,
53
+ vocabularies: Optional[Dict[str, Sequence[str]]] = None,
54
+ rng: Optional[Chooser] = None) -> str:
55
+ """Render one phrase from a list of dialog phrases (stateless).
56
+
57
+ This is the language-agnostic primitive: the caller has already chosen and
58
+ loaded the phrases. For a multilingual, resource-backed renderer use
59
+ :class:`DialogRenderer`.
60
+
61
+ Args:
62
+ phrases: the phrase strings of a ``.dialog``.
63
+ slots: caller-supplied values for the phrase's named slots, keyed by
64
+ slot name. Values are converted to text.
65
+ vocabularies: vocabularies for any ``<name>`` references in the phrase.
66
+ rng: an object with a ``choice`` method, for phrase and variant
67
+ selection; defaults to the :mod:`random` module.
68
+
69
+ Returns:
70
+ One rendered phrase, ready for text-to-speech.
71
+
72
+ Raises:
73
+ UnfilledSlot: a slot in the chosen phrase has no value.
74
+ ValueError: ``phrases`` is empty.
75
+ MalformedTemplate: the chosen phrase is not a valid template.
76
+ """
77
+ if not phrases:
78
+ raise ValueError("no dialog phrases to render")
79
+ chooser = rng if rng is not None else _random
80
+ phrase = chooser.choice(list(phrases))
81
+ return _render_phrase(phrase, slots or {}, vocabularies, chooser)
82
+
83
+
84
+ class DialogRenderer:
85
+ """A stateful, multilingual renderer for one named ``.dialog``.
86
+
87
+ Backed by a :class:`~ovos_spec_tools.resources.LocaleResources`: the dialog
88
+ name is fixed at construction, but the **language is given per**
89
+ :meth:`render` **call**, so one renderer serves every language the dialog
90
+ is shipped in. Each call loads that language's phrases, vocabularies, and
91
+ ``.entity`` value sets afresh.
92
+
93
+ Unlike the bare :func:`render`, it **avoids repeating the phrase it chose
94
+ on the previous call** — tracked independently per language — so a
95
+ repeatedly-spoken response does not sound mechanical. Repetition avoidance
96
+ is an implementation choice the spec explicitly allows (§4.2).
97
+ """
98
+
99
+ def __init__(self, resources, name: str,
100
+ rng: Optional[Chooser] = None,
101
+ slots: Optional[Dict[str, object]] = None):
102
+ """
103
+ Args:
104
+ resources: a :class:`~ovos_spec_tools.resources.LocaleResources`
105
+ (or anything with ``load_dialog``, ``vocabularies`` and
106
+ ``entities`` methods taking a language).
107
+ name: the base name of the ``.dialog`` to render.
108
+ rng: an object with a ``choice`` method; defaults to :mod:`random`.
109
+ slots: **default** slot values, held for the renderer's lifetime
110
+ and reused on every :meth:`render` call. A per-call value
111
+ overrides a default.
112
+ """
113
+ self.resources = resources
114
+ self.name = name
115
+ self.rng = rng if rng is not None else _random
116
+ self.default_slots: Dict[str, object] = dict(slots or {})
117
+ self._last: Dict[str, str] = {} # last phrase chosen, per language
118
+
119
+ def render(self, lang: str,
120
+ slots: Optional[Dict[str, object]] = None) -> str:
121
+ """Render one phrase of the dialog in ``lang``.
122
+
123
+ A slot is filled, in order of precedence, from: the per-call ``slots``;
124
+ then the renderer's default slots; then a random value from the slot's
125
+ ``.entity`` set for ``lang``. A slot none of these supply raises
126
+ :class:`UnfilledSlot`.
127
+
128
+ The phrase chosen on the previous call **for the same language** is
129
+ avoided when the dialog has more than one phrase.
130
+
131
+ Args:
132
+ lang: the BCP-47 language tag to render in.
133
+ slots: per-call slot values; each overrides a default.
134
+
135
+ Returns:
136
+ One rendered phrase, ready for text-to-speech.
137
+
138
+ Raises:
139
+ UnfilledSlot: a slot in the chosen phrase has no value.
140
+ FileNotFoundError: the dialog does not exist for ``lang``.
141
+ MalformedTemplate: the chosen phrase is not a valid template.
142
+ """
143
+ phrases = self.resources.load_dialog(self.name, lang)
144
+ effective = dict(self.default_slots)
145
+ if slots:
146
+ effective.update(slots)
147
+
148
+ last = self._last.get(lang)
149
+ choices = [p for p in phrases if p != last] or phrases
150
+ phrase = self.rng.choice(choices)
151
+ self._last[lang] = phrase
152
+
153
+ return _render_phrase(phrase, effective,
154
+ self.resources.vocabularies(lang), self.rng,
155
+ self.resources.entities(lang))
156
+
157
+
158
+ def _render_phrase(phrase: str,
159
+ slots: Dict[str, object],
160
+ vocabularies: Optional[Dict[str, Sequence[str]]],
161
+ chooser: Chooser,
162
+ entities: Optional[Dict[str, Sequence[str]]] = None) -> str:
163
+ """Expand one phrase to a variant, then fill its slots.
164
+
165
+ Expansion keeps slots opaque (OVOS-INTENT-1 §4), so it runs first and a
166
+ slot value can never be parsed as grammar.
167
+ """
168
+ variant = chooser.choice(expand(phrase, vocabularies))
169
+ return _fill_slots(variant, slots, entities, chooser)
170
+
171
+
172
+ def _fill_slots(variant: str,
173
+ slots: Dict[str, object],
174
+ entities: Optional[Dict[str, Sequence[str]]],
175
+ chooser: Chooser) -> str:
176
+ """Replace every ``{name}`` in ``variant`` with a value.
177
+
178
+ A value is taken from ``slots``; failing that, a random valid value from
179
+ the slot's ``.entity`` set in ``entities``; failing that, the slot has no
180
+ value and :class:`UnfilledSlot` is raised.
181
+ """
182
+
183
+ def replace(match: "re.Match") -> str:
184
+ name = match.group(1)
185
+ if name in slots:
186
+ return str(slots[name])
187
+ if entities and entities.get(name):
188
+ return str(chooser.choice(list(entities[name])))
189
+ raise UnfilledSlot(
190
+ f"dialog slot {{{name}}} has no value: it was not filled by the "
191
+ f"caller and has no .entity fallback")
192
+
193
+ return _SLOT_TOKEN_RE.sub(replace, variant)