speech-mds 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
speech_mds/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Deployment-managed speech context."""
speech_mds/api.py ADDED
@@ -0,0 +1,50 @@
1
+ """Version 1 contract for installed providers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from contextlib import AbstractAsyncContextManager
7
+ from dataclasses import dataclass
8
+ from importlib.resources.abc import Traversable
9
+ from pathlib import Path
10
+ from typing import Protocol
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class ReadRequest:
15
+ tenant: str
16
+ owner: tuple[str, str, str] | None
17
+ text: str
18
+ selected_language: str | None
19
+ input_language: str | None
20
+ deadline: float # absolute time.perf_counter() value in this process
21
+ max_bytes: int
22
+ session_id: str
23
+ response_key: str
24
+
25
+
26
+ class Reader(Protocol):
27
+ async def prepare_context(self, request: ReadRequest) -> tuple[str, ...] | None: ...
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class ProviderDefinition:
32
+ schema: dict
33
+ defaults: dict
34
+ open_provider: Callable[[dict], AbstractAsyncContextManager[Reader]]
35
+ validate: Callable[[dict], None]
36
+ settings_version: int = 1
37
+ capabilities: tuple[str, ...] = ("prepare_context",)
38
+ templates: Traversable | None = None
39
+ setup: Callable[[dict], None] | None = None
40
+ path_fields: tuple[str, ...] = ()
41
+
42
+
43
+ def resolved_settings(definition: ProviderDefinition, settings: dict, directory: Path) -> dict:
44
+ from jsonschema import Draft202012Validator
45
+
46
+ Draft202012Validator(definition.schema).validate(settings)
47
+ result = settings.copy()
48
+ for field in definition.path_fields:
49
+ result[field] = str((directory / result[field]).resolve())
50
+ return result
speech_mds/bridge.py ADDED
@@ -0,0 +1,79 @@
1
+ from contextlib import asynccontextmanager
2
+ from importlib.metadata import distribution
3
+ from time import perf_counter
4
+
5
+ from .api import ReadRequest
6
+ from .profiles import deploy, effective_timeout_ms, loaded, selected_profile
7
+
8
+
9
+ def authentication_middleware(data):
10
+ if "authentication" not in data:
11
+ return None
12
+ auth = data["authentication"]
13
+ if (
14
+ not isinstance(auth, dict)
15
+ or set(auth) != {"distribution", "entry"}
16
+ or any(not isinstance(value, str) or not value.strip() for value in auth.values())
17
+ ):
18
+ raise ValueError("Expected authentication distribution and entry")
19
+ entries = distribution(auth["distribution"]).entry_points.select(
20
+ group="speech_mds.authentication.v1", name=auth["entry"]
21
+ )
22
+ if len(entries) != 1:
23
+ raise ValueError("Expected one installed deployment authentication middleware")
24
+ middleware = next(iter(entries)).load()
25
+ if not callable(middleware):
26
+ raise ValueError("Authentication middleware must be callable")
27
+ return middleware
28
+
29
+
30
+ def configure(config_path):
31
+ from speech_to_speech.context_extension import ContextIntegration
32
+
33
+ data = deploy(config_path)
34
+ descriptor, settings = loaded(selected_profile(data), config_path.parent)
35
+ policy = data["scope"]
36
+ descriptor.validate(settings)
37
+ budget = effective_timeout_ms(data)
38
+
39
+ @asynccontextmanager
40
+ async def open_hooks():
41
+ if budget == 0:
42
+
43
+ class Disabled:
44
+ async def prepare_context(self, request):
45
+ return ()
46
+
47
+ yield Disabled()
48
+ return
49
+ async with descriptor.open_provider(settings) as provider:
50
+
51
+ class Hooks:
52
+ async def prepare_context(self, request):
53
+ lease = request.scope
54
+ if perf_counter() >= request.deadline:
55
+ return ()
56
+ if lease is not None and (not lease.valid() or lease.tenant != policy["tenant"]):
57
+ return ()
58
+ owner = None
59
+ if policy["mode"] == "private":
60
+ if lease is None:
61
+ return ()
62
+ owner = (lease.tenant, lease.issuer, lease.subject)
63
+ view = ReadRequest(
64
+ policy["tenant"],
65
+ owner,
66
+ request.text,
67
+ request.selected_language,
68
+ request.input_language,
69
+ request.deadline,
70
+ request.max_bytes,
71
+ request.session_id,
72
+ request.response_key,
73
+ )
74
+ return await provider.prepare_context(view)
75
+
76
+ yield Hooks()
77
+
78
+ options = {} if budget is None else {"wait_seconds": budget / 1000}
79
+ return ContextIntegration(open_hooks, scope_middleware=authentication_middleware(data), **options)
speech_mds/cli.py ADDED
@@ -0,0 +1,210 @@
1
+ import argparse
2
+ import json
3
+ import subprocess
4
+ import sys
5
+ from importlib.metadata import PackageNotFoundError, version
6
+ from pathlib import Path
7
+
8
+ from filelock import Timeout
9
+ from jsonschema.exceptions import ValidationError
10
+
11
+ from .api import resolved_settings
12
+ from .bridge import authentication_middleware
13
+ from .profiles import (
14
+ binding_path,
15
+ deploy,
16
+ editing,
17
+ effective_timeout_ms,
18
+ loaded,
19
+ location,
20
+ publish,
21
+ read,
22
+ selected_profile,
23
+ write,
24
+ )
25
+ from .registry import definition, entries, normalized, select
26
+
27
+
28
+ def parser():
29
+ cli = argparse.ArgumentParser(prog="speech-mds")
30
+ cli.add_argument("--config", help="Deployment profile file")
31
+ commands = cli.add_subparsers(dest="command", required=True)
32
+ commands.add_parser("init")
33
+ commands.add_parser("doctor").add_argument("--json", action="store_true")
34
+ providers = commands.add_parser("providers").add_subparsers(dest="action", required=True)
35
+ providers.add_parser("list")
36
+ describe = providers.add_parser("describe")
37
+ describe.add_argument("provider")
38
+ describe.add_argument("--distribution")
39
+ describe.add_argument("--json", action="store_true")
40
+ add = providers.add_parser("add")
41
+ add.add_argument("distribution")
42
+ add.add_argument("--installed", action="store_true")
43
+ add.add_argument("--provider")
44
+ add.add_argument("--profile")
45
+ add.add_argument("--settings", type=Path)
46
+ add.add_argument(
47
+ "--deployment-policy", type=Path, help="Initial scope and authentication; must match an existing deployment"
48
+ )
49
+ add.add_argument("--non-interactive", action="store_true")
50
+ providers.add_parser("use").add_argument("profile")
51
+ providers.add_parser("disable")
52
+ return cli
53
+
54
+
55
+ def validate_host():
56
+ from importlib.util import find_spec
57
+
58
+ try:
59
+ available = find_spec("speech_to_speech.context_extension") is not None
60
+ except ModuleNotFoundError:
61
+ available = False
62
+ return available
63
+
64
+
65
+ def run(args, argv):
66
+ action = getattr(args, "action", None)
67
+ if action == "list":
68
+ return [{"provider": e.name, "distribution": e.dist.name, "version": e.dist.version} for e in entries()]
69
+ if action == "describe":
70
+ d = definition(select(args.provider, args.distribution))
71
+ return {
72
+ "settings_version": d.settings_version,
73
+ "capabilities": d.capabilities,
74
+ "schema": d.schema,
75
+ "defaults": d.defaults,
76
+ }
77
+ if action == "add" and not args.installed:
78
+ import re
79
+
80
+ if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", args.distribution):
81
+ raise ValueError("Use a distribution name, or install the wheel and pass --installed")
82
+ subprocess.run([sys.executable, "-m", "pip", "install", args.distribution], check=True)
83
+ return subprocess.run([sys.executable, "-m", "speech_mds.cli", *argv, "--installed"]).returncode
84
+ if args.command == "doctor":
85
+ binding = binding_path()
86
+ path = location(binding, args.config)
87
+ data = deploy(path)
88
+ profile = selected_profile(data)
89
+ d, settings = loaded(profile, path.parent)
90
+ d.validate(settings)
91
+ middleware = authentication_middleware(data)
92
+ enabled = binding.is_file() and read(binding).get("enabled", True)
93
+ return {
94
+ "active": data["active"],
95
+ "distribution": profile["distribution"],
96
+ "version": version(profile["distribution"]),
97
+ "binding_enabled": enabled,
98
+ "authentication_configured": middleware is not None,
99
+ "host_hook_installed": validate_host(),
100
+ "prepare_timeout_ms": effective_timeout_ms(data),
101
+ "settings_valid": True,
102
+ "scope_mode": data["scope"]["mode"],
103
+ "capabilities": d.capabilities,
104
+ }
105
+ with editing(args.config) as (binding, path):
106
+ if action == "disable":
107
+ if not path.is_file():
108
+ raise ValueError("No configured deployment")
109
+ publish(binding, path, False)
110
+ return {"enabled": False, "config": str(path)}
111
+ if path.is_file():
112
+ data = deploy(path)
113
+ else:
114
+ data = {"format": 1, "scope": {"mode": "shared", "tenant": "exhibit"}, "profiles": {}}
115
+ if action == "add" and args.deployment_policy is not None:
116
+ policy = read(args.deployment_policy)
117
+ if set(policy) != {"scope", "authentication"}:
118
+ raise ValueError("Expected scope and authentication in the deployment policy")
119
+ scope = policy["scope"]
120
+ if (
121
+ not isinstance(scope, dict)
122
+ or scope.get("mode") != "private"
123
+ or not isinstance(scope.get("tenant"), str)
124
+ or not scope["tenant"].strip()
125
+ ):
126
+ raise ValueError("Expected a private scope with a tenant")
127
+ if path.is_file() and any(data.get(key) != value for key, value in policy.items()):
128
+ raise ValueError("Deployment policy conflicts with the existing profile file")
129
+ data.update(policy)
130
+ # A selection should be usable on the next server start. Keep disable
131
+ # available even if the authentication package needs repair.
132
+ authentication_middleware(data)
133
+ if action == "use":
134
+ name = args.profile
135
+ d, effective = loaded(data["profiles"][name], path.parent)
136
+ d.validate(effective)
137
+ else:
138
+ initial = args.command == "init"
139
+ entry = select("markdown", "speech-mds") if initial else select(args.provider, args.distribution)
140
+ name = entry.name if initial else args.profile or entry.name
141
+ d = definition(entry)
142
+ settings = dict(d.defaults)
143
+ if name in data["profiles"]:
144
+ old = data["profiles"][name]
145
+ if (
146
+ not isinstance(old, dict)
147
+ or old.get("provider") != entry.name
148
+ or not isinstance(old.get("distribution"), str)
149
+ or normalized(old["distribution"]) != normalized(entry.dist.name)
150
+ or type(old.get("settings_version")) is not int
151
+ or old["settings_version"] != d.settings_version
152
+ ):
153
+ raise ValueError("Profile is owned by a different provider or settings version")
154
+ if not isinstance(old.get("settings"), dict):
155
+ raise ValueError("Expected provider settings as a JSON object")
156
+ settings.update(old["settings"])
157
+ if not initial and args.settings:
158
+ settings.update(read(args.settings))
159
+ if not initial and not args.non_interactive and sys.stdin.isatty():
160
+ for key in d.schema.get("required", []):
161
+ if key not in settings:
162
+ settings[key] = input(f"{key}: ")
163
+ effective = resolved_settings(d, settings, path.parent)
164
+ if d.setup:
165
+ d.setup(effective)
166
+ d.validate(effective)
167
+ data["profiles"][name] = {
168
+ "provider": entry.name,
169
+ "distribution": entry.dist.name,
170
+ "settings_version": d.settings_version,
171
+ "settings": settings,
172
+ }
173
+ data["active"] = name
174
+ budget = effective_timeout_ms(data)
175
+ if budget is not None:
176
+ data["prepare_timeout_ms"] = budget
177
+ prior = read(path) if path.exists() else None
178
+ already_bound = binding.exists() and read(binding).get("enabled", True)
179
+ write(path, data)
180
+ if not already_bound:
181
+ try:
182
+ publish(binding, path)
183
+ except OSError:
184
+ if prior is None:
185
+ path.unlink(missing_ok=True)
186
+ else:
187
+ write(path, prior)
188
+ raise
189
+ return {"active": name, "config": str(path), "scope": data["scope"], "restart_required": True}
190
+
191
+
192
+ def main():
193
+ argv = sys.argv[1:]
194
+ args = parser().parse_args(argv)
195
+ try:
196
+ result = run(args, argv)
197
+ except ValidationError as error:
198
+ print(f"Invalid setting at {list(error.absolute_path)} ({error.validator})", file=sys.stderr)
199
+ return 1
200
+ except (ValueError, KeyError, OSError, Timeout, PackageNotFoundError, subprocess.CalledProcessError) as error:
201
+ print(f"speech-mds: {error}", file=sys.stderr)
202
+ return 1
203
+ if isinstance(result, int):
204
+ return result
205
+ print(json.dumps(result, indent=2, ensure_ascii=False))
206
+ return 0
207
+
208
+
209
+ if __name__ == "__main__":
210
+ raise SystemExit(main())
@@ -0,0 +1 @@
1
+ Speak as a friendly observatory guide. Give visitors time to answer.
@@ -0,0 +1,22 @@
1
+ {
2
+ "version": 1,
3
+ "topics": [
4
+ {
5
+ "id": "observatory",
6
+ "words": ["observatory", "observatorio", "observatoire", "المرصد"],
7
+ "literals": ["天文台"]
8
+ }
9
+ ],
10
+ "people": [
11
+ {
12
+ "id": "p01",
13
+ "words": ["coffee", "café", "قهوة"],
14
+ "literals": ["コーヒー", "咖啡"]
15
+ },
16
+ {
17
+ "id": "p02",
18
+ "words": ["coffee", "café", "قهوة"],
19
+ "literals": ["コーヒー", "咖啡"]
20
+ }
21
+ ]
22
+ }
@@ -0,0 +1 @@
1
+ Prefiero el café con canela.
@@ -0,0 +1 @@
1
+ コーヒーには豆乳を入れます。
@@ -0,0 +1 @@
1
+ Offer a clue before revealing an exhibit answer. Use the visitor’s chosen conversation language.
@@ -0,0 +1 @@
1
+ The observatory in this fictional exhibit uses a blue ticket for the evening tour.
speech_mds/profiles.py ADDED
@@ -0,0 +1,145 @@
1
+ import json
2
+ import os
3
+ import sys
4
+ import tempfile
5
+ from contextlib import contextmanager
6
+ from importlib import import_module
7
+ from pathlib import Path
8
+
9
+ from filelock import FileLock
10
+
11
+ from .api import resolved_settings
12
+ from .registry import definition, normalized, select
13
+
14
+
15
+ def read(path):
16
+ def unique(pairs):
17
+ result = {}
18
+ for key, value in pairs:
19
+ if key in result:
20
+ raise ValueError(f"Duplicate configuration key {key!r}")
21
+ result[key] = value
22
+ return result
23
+
24
+ with path.open(encoding="utf-8") as handle:
25
+ data = json.load(handle, object_pairs_hook=unique)
26
+ if not isinstance(data, dict):
27
+ raise ValueError(f"Expected a JSON object in {path.name}")
28
+ return data
29
+
30
+
31
+ def write(path, value):
32
+ path.parent.mkdir(parents=True, exist_ok=True)
33
+ with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=path.parent, delete=False) as output:
34
+ temporary = Path(output.name)
35
+ try:
36
+ json.dump(value, output, ensure_ascii=False, indent=2)
37
+ output.write("\n")
38
+ output.flush()
39
+ os.fsync(output.fileno())
40
+ except BaseException:
41
+ output.close()
42
+ temporary.unlink(missing_ok=True)
43
+ raise
44
+ try:
45
+ os.replace(temporary, path)
46
+ finally:
47
+ temporary.unlink(missing_ok=True)
48
+
49
+
50
+ def binding_path():
51
+ path = Path(os.environ.get("S2S_CONTEXT_BINDING", Path(sys.prefix) / "etc/speech-to-speech/context.json"))
52
+ if not path.is_absolute():
53
+ raise ValueError("S2S_CONTEXT_BINDING must be absolute")
54
+ return path
55
+
56
+
57
+ def location(binding, explicit):
58
+ if binding.exists():
59
+ record = read(binding)
60
+ if type(record.get("format")) is not int or record["format"] != 1:
61
+ raise ValueError("Unsupported binding version")
62
+ if type(record.get("enabled", True)) is not bool:
63
+ raise ValueError("Invalid context binding enabled flag")
64
+ if record != {"format": 1, "enabled": False}:
65
+ name = record.get("distribution")
66
+ if not isinstance(name, str) or normalized(name) != "speech-mds" or record.get("entry") != "mds":
67
+ raise ValueError("This service is bound to a different extension")
68
+ config = record.get("config")
69
+ if not isinstance(config, str):
70
+ raise ValueError("Expected a deployment config path")
71
+ path = Path(config)
72
+ if not path.is_absolute() or (explicit and path != Path(explicit).resolve()):
73
+ raise ValueError("Conflicting deployment config path")
74
+ return path
75
+ return Path(explicit or "mds.json").resolve()
76
+
77
+
78
+ @contextmanager
79
+ def editing(explicit):
80
+ binding = binding_path()
81
+ binding.parent.mkdir(parents=True, exist_ok=True)
82
+ with FileLock(str(binding) + ".lock", timeout=10):
83
+ path = location(binding, explicit)
84
+ if path == binding:
85
+ raise ValueError("Profile and host binding must use distinct paths")
86
+ path.parent.mkdir(parents=True, exist_ok=True)
87
+ with FileLock(str(path) + ".lock", timeout=10):
88
+ yield binding, path
89
+
90
+
91
+ def deploy(path):
92
+ data = read(path)
93
+ if type(data.get("format")) is not int or data["format"] != 1 or not isinstance(data.get("profiles"), dict):
94
+ raise ValueError("Unsupported deployment configuration")
95
+ budget = data.get("prepare_timeout_ms")
96
+ if "prepare_timeout_ms" in data and (type(budget) is not int or not 0 <= budget <= 1000):
97
+ raise ValueError("prepare_timeout_ms must be an integer between 0 and 1000")
98
+ scope = data.get("scope")
99
+ if (
100
+ not isinstance(scope, dict)
101
+ or scope.get("mode") not in ("shared", "private")
102
+ or not isinstance(scope.get("tenant"), str)
103
+ or not scope["tenant"]
104
+ ):
105
+ raise ValueError("Expected a tenant and a shared or private scope")
106
+ return data
107
+
108
+
109
+ def effective_timeout_ms(data):
110
+ requested = data.get("prepare_timeout_ms")
111
+ try:
112
+ host = import_module("speech_to_speech.context_extension")
113
+ except ModuleNotFoundError as error:
114
+ if error.name not in {"speech_to_speech", "speech_to_speech.context_extension"}:
115
+ raise
116
+ return requested
117
+ limit = getattr(host, "MAX_CONTEXT_WAIT_MS", None)
118
+ if limit is None:
119
+ return requested
120
+ return limit if requested is None else min(requested, limit)
121
+
122
+
123
+ def selected_profile(data):
124
+ active = data.get("active")
125
+ if not isinstance(active, str) or active not in data["profiles"]:
126
+ raise ValueError("Expected an active provider profile")
127
+ return data["profiles"][active]
128
+
129
+
130
+ def loaded(profile, directory):
131
+ if not isinstance(profile, dict) or any(
132
+ not isinstance(profile.get(field), str) or not profile[field] for field in ("provider", "distribution")
133
+ ):
134
+ raise ValueError("Expected a provider and distribution in the selected profile")
135
+ descriptor = definition(select(profile["provider"], profile["distribution"]))
136
+ if type(profile.get("settings_version")) is not int or profile["settings_version"] != descriptor.settings_version:
137
+ raise ValueError("Unsupported provider settings version")
138
+ if not isinstance(profile.get("settings"), dict):
139
+ raise ValueError("Expected provider settings as a JSON object")
140
+ settings = resolved_settings(descriptor, profile["settings"], directory)
141
+ return descriptor, settings
142
+
143
+
144
+ def publish(binding, path, enabled=True):
145
+ write(binding, {"format": 1, "enabled": enabled, "entry": "mds", "distribution": "speech-mds", "config": str(path)})
@@ -0,0 +1 @@
1
+ """Bundled providers."""
@@ -0,0 +1,116 @@
1
+ import asyncio
2
+ import os
3
+ import tempfile
4
+ from concurrent.futures import ThreadPoolExecutor
5
+ from contextlib import asynccontextmanager
6
+ from importlib.resources import files
7
+ from pathlib import Path
8
+ from time import perf_counter
9
+
10
+ from ..api import ProviderDefinition
11
+ from .pack import Pack
12
+
13
+
14
+ def load_pack(settings):
15
+ rows = settings.get("bindings", [])
16
+ bindings = {(r["tenant"], r["issuer"], r["subject"]): r["person"] for r in rows}
17
+ if len(bindings) != len(rows):
18
+ raise ValueError("Duplicate owner mapping")
19
+ return Pack.load(Path(settings["pack_dir"]), settings["tenant"], bindings)
20
+
21
+
22
+ def seed(tree, destination):
23
+ destination.mkdir(parents=True, exist_ok=True)
24
+ for resource in tree.iterdir():
25
+ target = destination / resource.name
26
+ if target.resolve() != target:
27
+ raise ValueError("Unexpected link in pack destination")
28
+ if resource.is_dir():
29
+ seed(resource, target)
30
+ elif resource.is_file() and not target.exists():
31
+ with tempfile.NamedTemporaryFile(dir=destination, delete=False) as f:
32
+ temporary = Path(f.name)
33
+ f.write(resource.read_bytes())
34
+ try:
35
+ try:
36
+ os.link(temporary, target)
37
+ except FileExistsError:
38
+ pass
39
+ finally:
40
+ temporary.unlink(missing_ok=True)
41
+
42
+
43
+ class MarkdownReader:
44
+ def __init__(self, pack, executor):
45
+ self.pack = pack
46
+ self.executor = executor
47
+ self.work = set()
48
+
49
+ async def prepare_context(self, request):
50
+ if perf_counter() >= request.deadline or len(self.work) >= 4:
51
+ return ()
52
+ args = (request.tenant, request.owner, request.text, request.max_bytes)
53
+ # Up to two shared records and one personal record. Each has at most
54
+ # 16 word and 16 literal aliases. This path performs no I/O.
55
+ if len(request.text) <= 128 and len(self.pack.topics) <= 2:
56
+ return self.pack.recall(*args)
57
+ future = asyncio.get_running_loop().run_in_executor(self.executor, self.pack.recall, *args)
58
+ self.work.add(future)
59
+
60
+ def finished(result):
61
+ self.work.discard(result)
62
+ if not result.cancelled():
63
+ result.exception()
64
+
65
+ future.add_done_callback(finished)
66
+ return await asyncio.shield(future)
67
+
68
+
69
+ @asynccontextmanager
70
+ async def open_provider(settings):
71
+ pack = load_pack(settings)
72
+ with ThreadPoolExecutor(max_workers=4, thread_name_prefix="mds-markdown") as executor:
73
+ reader = MarkdownReader(pack, executor)
74
+ # Start the lookup worker before the first spoken turn acquires its deadline.
75
+ await asyncio.get_running_loop().run_in_executor(executor, lambda: None)
76
+ try:
77
+ yield reader
78
+ finally:
79
+ if reader.work:
80
+ await asyncio.gather(*reader.work, return_exceptions=True)
81
+
82
+
83
+ def markdown_definition(*, templates, default_pack_dir):
84
+ string = {"type": "string", "minLength": 1}
85
+ fields = {key: string for key in ("tenant", "issuer", "subject", "person")}
86
+ schema = {
87
+ "type": "object",
88
+ "additionalProperties": False,
89
+ "required": ["tenant", "pack_dir"],
90
+ "properties": {
91
+ "pack_dir": string,
92
+ "tenant": string,
93
+ "bindings": {
94
+ "type": "array",
95
+ "items": {
96
+ "type": "object",
97
+ "additionalProperties": False,
98
+ "required": list(fields),
99
+ "properties": fields,
100
+ },
101
+ },
102
+ },
103
+ }
104
+ return ProviderDefinition(
105
+ schema,
106
+ {"tenant": "exhibit", "pack_dir": default_pack_dir},
107
+ open_provider,
108
+ load_pack,
109
+ templates=templates,
110
+ path_fields=("pack_dir",),
111
+ setup=lambda settings: seed(templates, Path(settings["pack_dir"])),
112
+ )
113
+
114
+
115
+ def describe():
116
+ return markdown_definition(templates=files("speech_mds").joinpath("data", "starter"), default_pack_dir="./memory")
@@ -0,0 +1,137 @@
1
+ """Read-only Markdown corpus with Unicode alias matching. All disk I/O is at load."""
2
+
3
+ import json
4
+ import re
5
+ import unicodedata
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+ from types import MappingProxyType
9
+ from typing import Mapping
10
+
11
+ Owner = tuple[str, str, str] # tenant, issuer, subject (exact, opaque strings)
12
+
13
+
14
+ def match_key(text: str) -> str:
15
+ return unicodedata.normalize("NFC", unicodedata.normalize("NFC", text).casefold())
16
+
17
+
18
+ def word_character(char: str) -> bool:
19
+ return char == "_" or unicodedata.category(char)[0] in "LMN"
20
+
21
+
22
+ def query_words(text: str) -> set[str]:
23
+ result = set()
24
+ start = 0
25
+ for index, char in enumerate(text):
26
+ if word_character(char):
27
+ continue
28
+ if index > start:
29
+ result.add(text[start:index])
30
+ start = index + 1
31
+ if start < len(text):
32
+ result.add(text[start:])
33
+ return result
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class Record:
38
+ key: str
39
+ words: tuple[str, ...]
40
+ literals: tuple[str, ...]
41
+ text: str
42
+
43
+ def matches(self, query: str, tokens: set[str]) -> bool:
44
+ return not tokens.isdisjoint(self.words) or any(s in query for s in self.literals)
45
+
46
+
47
+ def read_entry(root: Path, name: str, limit: int) -> str:
48
+ path = root / name
49
+ if path.resolve(strict=True) != path or not path.is_file():
50
+ raise ValueError("pack entry must be a regular file inside the installed pack")
51
+ with path.open("rb") as source:
52
+ data = source.read(limit + 1)
53
+ if len(data) > limit:
54
+ raise ValueError("pack entry exceeds size limit")
55
+ return data.decode("utf-8", errors="strict")
56
+
57
+
58
+ def read_aliases(values: list[str]) -> tuple[str, ...]:
59
+ if not isinstance(values, list) or len(values) > 16:
60
+ raise ValueError("invalid alias list")
61
+ if any(not isinstance(v, str) or not v.strip() or len(v.encode("utf-8")) > 96 for v in values):
62
+ raise ValueError("invalid alias")
63
+ return tuple(match_key(v) for v in values)
64
+
65
+
66
+ def unique_fields(pairs):
67
+ fields = {}
68
+ for key, value in pairs:
69
+ if key in fields:
70
+ raise ValueError("duplicate manifest field")
71
+ fields[key] = value
72
+ return fields
73
+
74
+
75
+ @dataclass(frozen=True)
76
+ class Pack:
77
+ tenant: str
78
+ topics: tuple[Record, ...]
79
+ people: Mapping[Owner, Record]
80
+
81
+ @classmethod
82
+ def load(cls, root: Path, tenant: str, bindings: Mapping[Owner, str]) -> "Pack":
83
+ # Deployment mounts an operator-owned, immutable pack directory.
84
+ root = root.resolve(strict=True)
85
+ manifest = json.loads(read_entry(root, "pack.json", 64 * 1024), object_pairs_hook=unique_fields)
86
+ if (
87
+ not isinstance(manifest, dict)
88
+ or set(manifest) != {"version", "topics", "people"}
89
+ or type(manifest["version"]) is not int
90
+ or manifest["version"] != 1
91
+ ):
92
+ raise ValueError("unsupported manifest")
93
+ entries: dict[str, dict[str, Record]] = {}
94
+ for kind in ("topics", "people"):
95
+ items = manifest[kind]
96
+ if not isinstance(items, list) or len(items) > 64:
97
+ raise ValueError("invalid record list")
98
+ records: dict[str, Record] = {}
99
+ for row in items:
100
+ if not isinstance(row, dict) or set(row) != {"id", "words", "literals"}:
101
+ raise ValueError("invalid record")
102
+ key = row["id"]
103
+ if not isinstance(key, str) or not re.fullmatch(r"[a-z][a-z0-9-]{0,39}", key) or key in records:
104
+ raise ValueError("invalid or duplicate record id")
105
+ words, literals = read_aliases(row["words"]), read_aliases(row["literals"])
106
+ if not (words or literals):
107
+ raise ValueError("record requires an alias")
108
+ if any(query_words(word) != {word} for word in words):
109
+ raise ValueError("each word alias must be a single token")
110
+ text = read_entry(root, f"{kind}/{key}.md", 4096).strip()
111
+ if not text:
112
+ raise ValueError("empty record")
113
+ records[key] = Record(key, words, literals, text)
114
+ entries[kind] = records
115
+ if not tenant or any(len(o) != 3 or not all(o) or o[0] != tenant for o in bindings):
116
+ raise ValueError("invalid deployment binding")
117
+ people = {owner: entries["people"][key] for owner, key in bindings.items()}
118
+ return cls(tenant, tuple(entries["topics"][k] for k in sorted(entries["topics"])), MappingProxyType(people))
119
+
120
+ def recall(self, tenant: str | None, owner: Owner | None, query: str, max_bytes: int) -> tuple[str, ...]:
121
+ if tenant != self.tenant or not query or len(query) > 2048 or len(query.encode("utf-8")) > 2048:
122
+ return ()
123
+ if owner is not None and owner[0] != tenant:
124
+ return ()
125
+ needle = match_key(query)
126
+ tokens = query_words(needle)
127
+ personal = self.people.get(owner) if owner is not None else None
128
+ candidates = ((personal,) if personal else ()) + self.topics
129
+ output = []
130
+ for record in candidates:
131
+ size = len(record.text.encode("utf-8"))
132
+ if size <= max_bytes and record.matches(needle, tokens):
133
+ output.append(record.text)
134
+ max_bytes -= size
135
+ if len(output) == 4:
136
+ break
137
+ return tuple(output)
speech_mds/registry.py ADDED
@@ -0,0 +1,45 @@
1
+ import re
2
+ from importlib.metadata import PackageNotFoundError, distribution, entry_points
3
+
4
+ from .api import ProviderDefinition
5
+
6
+ GROUP = "speech_mds.providers.v1"
7
+
8
+
9
+ def normalized(name):
10
+ return re.sub(r"[-_.]+", "-", name).lower()
11
+
12
+
13
+ def entries():
14
+ # pip can leave retired .dist-info directories on Windows after an upgrade.
15
+ # Resolve each owner just as the host does when it loads the installed wheel.
16
+ owners = {normalized(ep.dist.name) for ep in entry_points(group=GROUP)}
17
+ active = []
18
+ for owner in sorted(owners):
19
+ try:
20
+ installed = distribution(owner)
21
+ except PackageNotFoundError:
22
+ continue
23
+ active.extend(installed.entry_points.select(group=GROUP))
24
+ return sorted(active, key=lambda ep: (ep.name, normalized(ep.dist.name)))
25
+
26
+
27
+ def select(provider=None, distribution=None):
28
+ matches = [
29
+ ep
30
+ for ep in entries()
31
+ if (provider is None or ep.name == provider)
32
+ and (distribution is None or normalized(ep.dist.name) == normalized(distribution))
33
+ ]
34
+ if len(matches) != 1:
35
+ raise ValueError(
36
+ f"Expected one installed provider for {distribution or '*'} / {provider or '*'}, found {len(matches)}"
37
+ )
38
+ return matches[0]
39
+
40
+
41
+ def definition(entry):
42
+ result = entry.load()()
43
+ if not isinstance(result, ProviderDefinition):
44
+ raise ValueError(f"Invalid provider definition for {entry.name}")
45
+ return result
@@ -0,0 +1,41 @@
1
+ Metadata-Version: 2.4
2
+ Name: speech-mds
3
+ Version: 0.1.0
4
+ Summary: Deployment-managed context providers for speech-to-speech
5
+ License-Expression: MIT
6
+ Project-URL: Repository, https://github.com/joslat/speech-mds
7
+ Project-URL: Speech host integration, https://github.com/huggingface/speech-to-speech/pull/906
8
+ Requires-Python: >=3.11
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: filelock>=3.15
12
+ Requires-Dist: jsonschema>=4.18
13
+ Dynamic: license-file
14
+
15
+ # speech-mds
16
+
17
+ Memory Docking Station (MDS) lets a speech-to-speech server recall short references from an installed Python provider. The bundled read-only Markdown provider matches multilingual aliases against a curated set of notes. The starter notes are synthetic.
18
+
19
+ ## Install and try Markdown
20
+
21
+ Use Python 3.11 or later. Install into the same Python environment as your speech server. Start in a directory where you want the sample deployment and editable notes to live.
22
+
23
+ ```sh
24
+ python -m pip install speech-mds
25
+ speech-mds providers describe markdown --json
26
+ speech-mds init
27
+ speech-mds doctor --json
28
+ ```
29
+
30
+ To use memory during speech, the host needs the hook proposed in [speech-to-speech #906](https://github.com/huggingface/speech-to-speech/pull/906). Check that `doctor` reports `host_hook_installed: true`, then run `speech-to-speech serve` in that environment. Ask about the observatory to retrieve its shared starter note. The draft host allows up to 400 ms for retrieval per eligible turn.
31
+
32
+ ## Add a provider
33
+
34
+ Provider packages register a `speech_mds.providers.v1` entry point. Install packages from publishers you trust because providers run inside the speech service. Run `speech-mds providers list` to see what's installed. Activate a shared provider with `speech-mds providers add --installed DISTRIBUTION` and restart the service. For private recall, configure deployment authentication and owner mappings using the provider's setup instructions. The [AgentMemory adapter](https://github.com/joslat/agent-memory-dotnet/tree/main/integrations/agentmemory-mds) shows one implementation.
35
+
36
+ The 0.1.0 source distribution includes `PROVIDER_PROTOCOL.md`, the independently installable Observatory example under `examples/observatory-memory`, and tests. To get these files from PyPI:
37
+
38
+ ```sh
39
+ python -m pip download --no-deps --no-binary=speech-mds speech-mds==0.1.0
40
+ python -m tarfile -e speech_mds-0.1.0.tar.gz
41
+ ```
@@ -0,0 +1,21 @@
1
+ speech_mds/__init__.py,sha256=6eS9cpkyIgtZPhmjhDyq-AdInjhiS9lVPdN5v6_BvHU,42
2
+ speech_mds/api.py,sha256=WCu4i_m0GN0LD_YUSuXsjn-zHguNdt7xtHu9W9oZ67Y,1566
3
+ speech_mds/bridge.py,sha256=kBV0LDA6HzdWnNYSfP6OcAWe1hiS386s3a8jGft7BBY,3057
4
+ speech_mds/cli.py,sha256=JCYV8MSdkSO0tMOaw14QWeJixHnvEyADVq7zNOdxL7k,8867
5
+ speech_mds/profiles.py,sha256=B6vlMS-cA5tN1Nz_cICiR8Ax7bLBRGLXHjjEYTUYbnU,5738
6
+ speech_mds/registry.py,sha256=Jt8u9E8C32GK1SWjzuvlLCBCbkOuMlXd6ZNru4GNGu0,1490
7
+ speech_mds/data/starter/mind.md,sha256=MFfRw_nCpUQcp2EWyI1TUa7EFzLySdYCTOU4gWunxxo,70
8
+ speech_mds/data/starter/pack.json,sha256=zPdIShEKjgDdNjPtp4M5_MQpOgEdrmzsB2px1Qqh7M4,479
9
+ speech_mds/data/starter/principles.md,sha256=bvAp0p-UeFEhFy0cSvngnT8LCNi1twIrgC9fk4Eqi7s,100
10
+ speech_mds/data/starter/people/p01.md,sha256=FfoF2MdP1mnyU25mRIw4nbBBlzmLbgqf_QjjKjwMqro,31
11
+ speech_mds/data/starter/people/p02.md,sha256=foBdfhDaO6LrULuz2ApPlVILDwdyBizfUlsnFDFkA1c,44
12
+ speech_mds/data/starter/topics/observatory.md,sha256=DvzFluTIqnI38N4sxt_v1cJjxEEQxdS1G06VqDVTbq4,84
13
+ speech_mds/providers/__init__.py,sha256=51bOcwL1-Dv0rkJGxuejcKfxFiQTVIKuZ3C_-31cbJ8,26
14
+ speech_mds/providers/markdown.py,sha256=e62v0oBAb-iFa0aE5bra4WQC2iXtapeJTX_xkpKo4tM,4187
15
+ speech_mds/providers/pack.py,sha256=pKLEO0yexqSKTdon9vROLcyyxz5yrNbyKfvYwBD7yE8,5538
16
+ speech_mds-0.1.0.dist-info/licenses/LICENSE,sha256=AymPyCwYLZYD1OlelVO1Q03ktKKreX9xfYP3AaNhVG0,1102
17
+ speech_mds-0.1.0.dist-info/METADATA,sha256=_KF7aj9MIBM9EjTnEHrTVVIlKS9h7Y255NRch5izbY8,2432
18
+ speech_mds-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
19
+ speech_mds-0.1.0.dist-info/entry_points.txt,sha256=5Yd12PlWAAMQO9aw2XBbrNy9pKgHFMlT86y1L8LBQko,204
20
+ speech_mds-0.1.0.dist-info/top_level.txt,sha256=3wDaFL4Un4pFUxSXEv9gCsP3ajnux_94IZ6NiJ5M0rc,11
21
+ speech_mds-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,8 @@
1
+ [console_scripts]
2
+ speech-mds = speech_mds.cli:main
3
+
4
+ [speech_mds.providers.v1]
5
+ markdown = speech_mds.providers.markdown:describe
6
+
7
+ [speech_to_speech.context_extensions.v1]
8
+ mds = speech_mds.bridge:configure
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jose Luis Latorre Millas
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ speech_mds