lystn 0.1.0__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.
lystn-0.1.0/.gitignore ADDED
@@ -0,0 +1,86 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ .Python
7
+ *.egg-info/
8
+ *.egg
9
+ .eggs/
10
+ build/
11
+ dist/
12
+ wheels/
13
+ .installed.cfg
14
+ MANIFEST
15
+
16
+ # Virtual envs
17
+ .venv/
18
+ venv/
19
+ env/
20
+ ENV/
21
+ .conda/
22
+
23
+ # Editor / OS
24
+ .vscode/
25
+ .idea/
26
+ *.swp
27
+ *.swo
28
+ *~
29
+ .DS_Store
30
+ Thumbs.db
31
+ Desktop.ini
32
+
33
+ # Tauri / Node (if/when the desktop app lands)
34
+ node_modules/
35
+ **/dist/
36
+ **/target/
37
+ src-tauri/target/
38
+ .next/
39
+
40
+ # Lystn-specific
41
+ hook.log
42
+ server.log
43
+ summary.log
44
+ *.wav
45
+ *.mp3
46
+ *.flac
47
+ *.pt
48
+ *.pth
49
+ *.onnx
50
+ lystn_debug.wav
51
+ .lystn/
52
+ cache/
53
+
54
+ # Models cache (HuggingFace downloads Kokoro here)
55
+ .cache/
56
+ hf_cache/
57
+
58
+ # Secrets
59
+ .env
60
+ .env.*
61
+ !.env.example
62
+ *.key
63
+ *.pem
64
+ secrets/
65
+
66
+ # Coverage / test
67
+ htmlcov/
68
+ .tox/
69
+ .nox/
70
+ .coverage
71
+ .coverage.*
72
+ .cache
73
+ coverage.xml
74
+ *.cover
75
+ .pytest_cache/
76
+ .mypy_cache/
77
+ .ruff_cache/
78
+
79
+ # Build artifacts
80
+ *.spec
81
+ pip-wheel-metadata/
82
+
83
+ # Local-only docs/notes
84
+ NOTES.md
85
+ TODO.md
86
+ SCRATCH.md
lystn-0.1.0/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or Derivative
95
+ Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and do
117
+ not modify the License. You may add Your own attribution notices
118
+ within Derivative Works that You distribute, alongside or as an
119
+ addendum to the NOTICE text from the Work, provided that such
120
+ additional attribution notices cannot be construed as modifying
121
+ the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions for
125
+ use, reproduction, or distribution of Your modifications, or for any
126
+ such Derivative Works as a whole, provided Your use, reproduction,
127
+ and distribution of the Work otherwise complies with the conditions
128
+ stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Burak Akın Yener
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
lystn-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,99 @@
1
+ Metadata-Version: 2.4
2
+ Name: lystn
3
+ Version: 0.1.0
4
+ Summary: Listen to AI coding assistant responses via Kokoro TTS.
5
+ Project-URL: Homepage, https://github.com/burakayener/Lystn
6
+ Project-URL: Repository, https://github.com/burakayener/Lystn
7
+ Project-URL: Issues, https://github.com/burakayener/Lystn/issues
8
+ Author: Burak Akın Yener
9
+ License: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: adhd,claude,claude-code,codex,tts,voice
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Requires-Python: >=3.10
22
+ Requires-Dist: click>=8.1
23
+ Requires-Dist: numpy>=1.24
24
+ Requires-Dist: requests>=2.31
25
+ Requires-Dist: sounddevice>=0.4.6
26
+ Requires-Dist: websocket-client>=1.7
27
+ Description-Content-Type: text/markdown
28
+
29
+ # lystn CLI
30
+
31
+ Cross-platform command-line client for the Lystn TTS server. Replaces
32
+ the Windows-only PowerShell hook with a Python package that works on
33
+ Windows, Mac, and Linux.
34
+
35
+ ## Install
36
+
37
+ ```bash
38
+ pipx install -e . # from this folder, while developing
39
+ # or once published:
40
+ pipx install lystn
41
+ ```
42
+
43
+ `pipx` puts `lystn` on your PATH in an isolated environment — no
44
+ conflicts with your other Python packages.
45
+
46
+ ## Configure
47
+
48
+ ```bash
49
+ lystn config set server http://127.0.0.1:7878 # local server (default)
50
+ lystn config set voice af_heart # any voice from `lystn voices`
51
+ lystn config set api_key sk_... # only needed for cloud server later
52
+ lystn config show
53
+ ```
54
+
55
+ Config lives at:
56
+ - Windows: `%APPDATA%\lystn\config.json`
57
+ - Mac/Linux: `~/.config/lystn/config.json`
58
+
59
+ ## Use
60
+
61
+ ```bash
62
+ lystn test # speak "Lystn is connected and working."
63
+ lystn speak "Hello there." # speak the argument
64
+ echo "Hello there." | lystn speak # speak stdin
65
+ lystn voices # list voices
66
+ lystn doctor # check server reachable
67
+ ```
68
+
69
+ ## Wire into Claude Code
70
+
71
+ ```bash
72
+ lystn install
73
+ ```
74
+
75
+ Prints a JSON snippet — copy the `hooks` block into
76
+ `~/.claude/settings.json`. Restart Claude Code. Every completed
77
+ response will be spoken aloud.
78
+
79
+ The hook is fire-and-forget: if the Lystn server is down or the text
80
+ is empty, the hook exits silently and doesn't break Claude's UI.
81
+
82
+ ## Commands
83
+
84
+ | Command | What it does |
85
+ |---|---|
86
+ | `lystn speak [TEXT]` | Speak text from argument or stdin |
87
+ | `lystn hook` | Claude Code Stop-hook entry — reads JSON from stdin |
88
+ | `lystn test` | Speak a short connection-test message |
89
+ | `lystn voices` | List voices the server offers |
90
+ | `lystn doctor` | Print config + server health |
91
+ | `lystn config show` | Show current config |
92
+ | `lystn config set KEY VALUE` | Update config (`server`, `voice`, `api_key`) |
93
+ | `lystn install` | Print the Claude Code settings snippet |
94
+
95
+ ## Requirements
96
+
97
+ - Python 3.10+
98
+ - A running Lystn server (local Kokoro for now; cloud server later)
99
+ - Audio output device (`sounddevice` handles it cross-platform)
lystn-0.1.0/README.md ADDED
@@ -0,0 +1,71 @@
1
+ # lystn CLI
2
+
3
+ Cross-platform command-line client for the Lystn TTS server. Replaces
4
+ the Windows-only PowerShell hook with a Python package that works on
5
+ Windows, Mac, and Linux.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pipx install -e . # from this folder, while developing
11
+ # or once published:
12
+ pipx install lystn
13
+ ```
14
+
15
+ `pipx` puts `lystn` on your PATH in an isolated environment — no
16
+ conflicts with your other Python packages.
17
+
18
+ ## Configure
19
+
20
+ ```bash
21
+ lystn config set server http://127.0.0.1:7878 # local server (default)
22
+ lystn config set voice af_heart # any voice from `lystn voices`
23
+ lystn config set api_key sk_... # only needed for cloud server later
24
+ lystn config show
25
+ ```
26
+
27
+ Config lives at:
28
+ - Windows: `%APPDATA%\lystn\config.json`
29
+ - Mac/Linux: `~/.config/lystn/config.json`
30
+
31
+ ## Use
32
+
33
+ ```bash
34
+ lystn test # speak "Lystn is connected and working."
35
+ lystn speak "Hello there." # speak the argument
36
+ echo "Hello there." | lystn speak # speak stdin
37
+ lystn voices # list voices
38
+ lystn doctor # check server reachable
39
+ ```
40
+
41
+ ## Wire into Claude Code
42
+
43
+ ```bash
44
+ lystn install
45
+ ```
46
+
47
+ Prints a JSON snippet — copy the `hooks` block into
48
+ `~/.claude/settings.json`. Restart Claude Code. Every completed
49
+ response will be spoken aloud.
50
+
51
+ The hook is fire-and-forget: if the Lystn server is down or the text
52
+ is empty, the hook exits silently and doesn't break Claude's UI.
53
+
54
+ ## Commands
55
+
56
+ | Command | What it does |
57
+ |---|---|
58
+ | `lystn speak [TEXT]` | Speak text from argument or stdin |
59
+ | `lystn hook` | Claude Code Stop-hook entry — reads JSON from stdin |
60
+ | `lystn test` | Speak a short connection-test message |
61
+ | `lystn voices` | List voices the server offers |
62
+ | `lystn doctor` | Print config + server health |
63
+ | `lystn config show` | Show current config |
64
+ | `lystn config set KEY VALUE` | Update config (`server`, `voice`, `api_key`) |
65
+ | `lystn install` | Print the Claude Code settings snippet |
66
+
67
+ ## Requirements
68
+
69
+ - Python 3.10+
70
+ - A running Lystn server (local Kokoro for now; cloud server later)
71
+ - Audio output device (`sounddevice` handles it cross-platform)
@@ -0,0 +1,42 @@
1
+ [project]
2
+ name = "lystn"
3
+ version = "0.1.0"
4
+ description = "Listen to AI coding assistant responses via Kokoro TTS."
5
+ readme = "README.md"
6
+ requires-python = ">=3.10"
7
+ license = { text = "Apache-2.0" }
8
+ authors = [{ name = "Burak Akın Yener" }]
9
+ keywords = ["tts", "claude", "claude-code", "codex", "voice", "adhd"]
10
+ classifiers = [
11
+ "Development Status :: 3 - Alpha",
12
+ "Environment :: Console",
13
+ "Intended Audience :: Developers",
14
+ "License :: OSI Approved :: Apache Software License",
15
+ "Operating System :: OS Independent",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3.10",
18
+ "Programming Language :: Python :: 3.11",
19
+ "Programming Language :: Python :: 3.12",
20
+ ]
21
+ dependencies = [
22
+ "click>=8.1",
23
+ "requests>=2.31",
24
+ "websocket-client>=1.7",
25
+ "sounddevice>=0.4.6",
26
+ "numpy>=1.24",
27
+ ]
28
+
29
+ [project.scripts]
30
+ lystn = "lystn.cli:main"
31
+
32
+ [project.urls]
33
+ Homepage = "https://github.com/burakayener/Lystn"
34
+ Repository = "https://github.com/burakayener/Lystn"
35
+ Issues = "https://github.com/burakayener/Lystn/issues"
36
+
37
+ [build-system]
38
+ requires = ["hatchling"]
39
+ build-backend = "hatchling.build"
40
+
41
+ [tool.hatch.build.targets.wheel]
42
+ packages = ["src/lystn"]
@@ -0,0 +1,2 @@
1
+ """Lystn — listen to AI coding assistant responses."""
2
+ __version__ = "0.1.0"
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
@@ -0,0 +1,69 @@
1
+ """Text cleaning for TTS — port of the original PowerShell hook regexes.
2
+
3
+ Strips URLs, code blocks, markdown, file paths — anything that sounds bad
4
+ or slows Kokoro down. Caps length to a safe ceiling.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import re
9
+
10
+ DEFAULT_MAX_CHARS = 3500
11
+
12
+ _RE_FENCED_CODE = re.compile(r"```[\s\S]*?```", re.MULTILINE)
13
+ _RE_INDENTED_CODE = re.compile(r"(?m)^ [^\n]+\n?")
14
+ _RE_INLINE_CODE = re.compile(r"`[^`\n]+`")
15
+ _RE_MD_LINK = re.compile(r"\[([^\]]+)\]\([^)]+\)")
16
+ _RE_URL_HTTP = re.compile(r"https?://\S+")
17
+ _RE_URL_WWW = re.compile(r"www\.\S+")
18
+ _RE_WIN_PATH = re.compile(r"[A-Za-z]:\\\S+")
19
+ _RE_UNIX_PATH = re.compile(r"(?<=\s)/[\w./\-]+")
20
+ _RE_FILENAME = re.compile(
21
+ r"\b[\w\-]+\.(?:py|ts|tsx|js|jsx|json|md|rs|go|java|cs|cpp|c|h|html|"
22
+ r"css|sh|bat|ps1|yaml|yml|toml|xml|sql|rb|php|swift|kt)\b"
23
+ )
24
+ _RE_HEADER = re.compile(r"(?m)^#{1,6}\s+")
25
+ _RE_BULLET = re.compile(r"(?m)^[\-*+]\s+")
26
+ _RE_NUMBER_LIST = re.compile(r"(?m)^\d+\.\s+")
27
+ _RE_BLOCKQUOTE = re.compile(r"(?m)^>\s*")
28
+ _RE_TABLE_ROW = re.compile(r"(?m)^\|.*\|\s*$")
29
+ _RE_TABLE_SEP = re.compile(r"(?m)^[\-|: ]+$")
30
+ _RE_BOLD_STAR = re.compile(r"\*\*([^*]+)\*\*")
31
+ _RE_BOLD_UNDER = re.compile(r"__([^_]+)__")
32
+ _RE_ITALIC_STAR = re.compile(r"(?<!\*)\*([^*\n]+)\*(?!\*)")
33
+ _RE_ITALIC_UNDER = re.compile(r"(?<!_)_([^_\n]+)_(?!_)")
34
+ _RE_SPACES = re.compile(r"[ \t]+")
35
+ _RE_NEWLINES = re.compile(r"\n{2,}")
36
+
37
+
38
+ def clean_for_tts(text: str, max_chars: int = DEFAULT_MAX_CHARS) -> str:
39
+ """Strip noise from `text` so Kokoro doesn't mangle or stall on it."""
40
+ if not text:
41
+ return ""
42
+
43
+ t = text
44
+ t = _RE_FENCED_CODE.sub(" code block omitted. ", t)
45
+ t = _RE_INDENTED_CODE.sub("", t)
46
+ t = _RE_INLINE_CODE.sub("", t)
47
+ t = _RE_MD_LINK.sub(r"\1", t)
48
+ t = _RE_URL_HTTP.sub("", t)
49
+ t = _RE_URL_WWW.sub("", t)
50
+ t = _RE_WIN_PATH.sub("", t)
51
+ t = _RE_UNIX_PATH.sub("", t)
52
+ t = _RE_FILENAME.sub("", t)
53
+ t = _RE_HEADER.sub("", t)
54
+ t = _RE_BULLET.sub("", t)
55
+ t = _RE_NUMBER_LIST.sub("", t)
56
+ t = _RE_BLOCKQUOTE.sub("", t)
57
+ t = _RE_TABLE_ROW.sub("", t)
58
+ t = _RE_TABLE_SEP.sub("", t)
59
+ t = _RE_BOLD_STAR.sub(r"\1", t)
60
+ t = _RE_BOLD_UNDER.sub(r"\1", t)
61
+ t = _RE_ITALIC_STAR.sub(r"\1", t)
62
+ t = _RE_ITALIC_UNDER.sub(r"\1", t)
63
+ t = _RE_SPACES.sub(" ", t)
64
+ t = _RE_NEWLINES.sub(". ", t)
65
+ t = t.strip()
66
+
67
+ if len(t) > max_chars:
68
+ t = t[:max_chars] + " ... response truncated."
69
+ return t
@@ -0,0 +1,403 @@
1
+ """Lystn CLI — `lystn <command> ...`."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import sys
6
+ import traceback
7
+ from datetime import datetime
8
+
9
+ import click
10
+
11
+ from . import __version__, client, config
12
+ from .clean import clean_for_tts
13
+ from .player import play_chunks, resolve_device
14
+
15
+
16
+ def _hook_log(msg: str) -> None:
17
+ """Append a diagnostic line to ~/.config/lystn/hook.log (or %APPDATA% equiv).
18
+
19
+ The Stop hook runs as a Claude Code subprocess so its stdout is invisible.
20
+ A file log is the only way to find out why a hook silently failed.
21
+ """
22
+ try:
23
+ log_path = config.config_dir() / "hook.log"
24
+ with log_path.open("a", encoding="utf-8") as f:
25
+ f.write(f"[{datetime.now().isoformat(timespec='seconds')}] {msg}\n")
26
+ except Exception:
27
+ # Logging itself failed — nothing useful we can do.
28
+ pass
29
+
30
+
31
+ def _stream_and_play(
32
+ server: str,
33
+ text: str,
34
+ voice: str | None,
35
+ api_key: str | None,
36
+ device: int | str | None = None,
37
+ ) -> None:
38
+ """Synthesize via the server and play chunks as they arrive."""
39
+ chunks = client.synthesize(server, text, voice=voice, api_key=api_key)
40
+ play_chunks(chunks, device=device)
41
+
42
+
43
+ @click.group(context_settings={"help_option_names": ["-h", "--help"]})
44
+ @click.version_option(__version__, prog_name="lystn")
45
+ def main() -> None:
46
+ """Listen to AI coding assistant responses.
47
+
48
+ Set up: `lystn config set server <url>` then wire `lystn hook` into
49
+ your Claude Code Stop hook (see `lystn install --help`).
50
+ """
51
+
52
+
53
+ @main.command()
54
+ @click.argument("text", required=False)
55
+ @click.option("--voice", default=None, help="Voice override.")
56
+ @click.option("--server", default=None, help="Server URL override.")
57
+ def speak(text: str | None, voice: str | None, server: str | None) -> None:
58
+ """Speak TEXT (or stdin if omitted)."""
59
+ if not text:
60
+ text = sys.stdin.read()
61
+ cleaned = clean_for_tts(text)
62
+ if not cleaned:
63
+ click.echo("nothing to speak", err=True)
64
+ return
65
+ cfg = config.load()
66
+ srv = server or cfg["server"]
67
+ _stream_and_play(
68
+ srv, cleaned, voice or cfg["voice"], cfg["api_key"], cfg.get("device")
69
+ )
70
+
71
+
72
+ @main.command()
73
+ def hook() -> None:
74
+ """Claude Code Stop-hook entry point. Reads JSON from stdin."""
75
+ _hook_log("hook invoked")
76
+ _log_audio_device()
77
+ raw = sys.stdin.read()
78
+ if not raw:
79
+ _hook_log("empty stdin, exiting")
80
+ return
81
+ try:
82
+ payload = json.loads(raw)
83
+ except json.JSONDecodeError as e:
84
+ _hook_log(f"bad JSON on stdin: {e}")
85
+ return
86
+ text = payload.get("last_assistant_message") or ""
87
+ cleaned = clean_for_tts(text)
88
+ if len(cleaned) < 3:
89
+ _hook_log(f"cleaned text too short ({len(cleaned)} chars), skipping")
90
+ return
91
+ cfg = config.load()
92
+ device = cfg.get("device")
93
+ resolved = resolve_device(device)
94
+ _hook_log(
95
+ f"speaking {len(cleaned)} chars via {cfg['server']} "
96
+ f"(device cfg={device!r}, resolved={resolved})"
97
+ )
98
+ try:
99
+ _stream_and_play(
100
+ cfg["server"], cleaned, cfg["voice"], cfg["api_key"], device
101
+ )
102
+ _hook_log("playback complete")
103
+ except Exception as e:
104
+ _hook_log(f"playback FAILED: {type(e).__name__}: {e}")
105
+ _hook_log(traceback.format_exc())
106
+ # Still don't propagate — Claude's UI must not break.
107
+
108
+
109
+ def _resolve_default_output() -> int | None:
110
+ """Return the index of sounddevice's default output device, or None."""
111
+ import sounddevice as sd
112
+ default = sd.default.device
113
+ # default may be: int, (in, out) tuple/list, or sd._InputOutputPair
114
+ try:
115
+ _in, out_idx = default
116
+ except (TypeError, ValueError):
117
+ out_idx = default
118
+ if out_idx is None:
119
+ return None
120
+ try:
121
+ out_idx = int(out_idx)
122
+ except (TypeError, ValueError):
123
+ return None
124
+ return out_idx if out_idx >= 0 else None
125
+
126
+
127
+ def _log_audio_device() -> None:
128
+ """Log which audio output device sounddevice will use."""
129
+ try:
130
+ import sounddevice as sd
131
+ out_idx = _resolve_default_output()
132
+ if out_idx is None:
133
+ _hook_log(f"audio: NO default output device (sd.default.device={sd.default.device!r})")
134
+ return
135
+ info = sd.query_devices(out_idx)
136
+ hostapi = sd.query_hostapis(info["hostapi"])["name"]
137
+ _hook_log(
138
+ f"audio: default out [{out_idx}] {info['name']} "
139
+ f"({hostapi}, {info['max_output_channels']} ch, "
140
+ f"{int(info['default_samplerate'])} Hz)"
141
+ )
142
+ except Exception as e:
143
+ _hook_log(f"audio: device query failed: {e}")
144
+
145
+
146
+ @main.command()
147
+ @click.option("--server", default=None)
148
+ def test(server: str | None) -> None:
149
+ """Speak a short test message."""
150
+ cfg = config.load()
151
+ srv = server or cfg["server"]
152
+ _stream_and_play(
153
+ srv,
154
+ "Lystn is connected and working.",
155
+ cfg["voice"],
156
+ cfg["api_key"],
157
+ cfg.get("device"),
158
+ )
159
+
160
+
161
+ @main.command()
162
+ def voices() -> None:
163
+ """List available voices from the server."""
164
+ cfg = config.load()
165
+ try:
166
+ for v in client.voices(cfg["server"]):
167
+ marker = " *" if v == cfg["voice"] else ""
168
+ click.echo(f"{v}{marker}")
169
+ except Exception as e:
170
+ click.echo(f"error: {e}", err=True)
171
+ sys.exit(1)
172
+
173
+
174
+ @main.command()
175
+ def doctor() -> None:
176
+ """Check connection to the Lystn server."""
177
+ cfg = config.load()
178
+ click.echo(f"server: {cfg['server']}")
179
+ click.echo(f"voice: {cfg['voice']}")
180
+ click.echo(f"key: {'set' if cfg['api_key'] else 'not set'}")
181
+ device_cfg = cfg.get("device")
182
+ if device_cfg is None:
183
+ click.echo("device: system default")
184
+ else:
185
+ resolved = resolve_device(device_cfg)
186
+ if resolved is None:
187
+ click.echo(f"device: {device_cfg!r} (NOT FOUND — will fall back)")
188
+ else:
189
+ try:
190
+ import sounddevice as sd
191
+ info = sd.query_devices(resolved)
192
+ hostapi = sd.query_hostapis(info["hostapi"])["name"]
193
+ click.echo(
194
+ f"device: {device_cfg!r} -> [{resolved}] {info['name']} ({hostapi})"
195
+ )
196
+ except Exception:
197
+ click.echo(f"device: {device_cfg!r} -> [{resolved}]")
198
+ ok = client.health(cfg["server"])
199
+ click.echo(f"health: {'ok' if ok else 'unreachable'}")
200
+ click.echo(f"log: {config.config_dir() / 'hook.log'}")
201
+ sys.exit(0 if ok else 1)
202
+
203
+
204
+ @main.command()
205
+ @click.option("--pick", is_flag=True, help="Interactively choose and save a device.")
206
+ def devices(pick: bool) -> None:
207
+ """List audio output devices sounddevice can see.
208
+
209
+ With --pick, prompts for an index and saves it to config.
210
+ """
211
+ try:
212
+ import sounddevice as sd
213
+ cfg = config.load()
214
+ configured = cfg.get("device")
215
+ configured_idx = resolve_device(configured)
216
+ out_idx = _resolve_default_output()
217
+ click.echo(f"default output index: {out_idx}")
218
+ if configured is not None:
219
+ click.echo(f"configured: {configured!r} -> {configured_idx}")
220
+ click.echo()
221
+ rows = []
222
+ for i, d in enumerate(sd.query_devices()):
223
+ if d["max_output_channels"] <= 0:
224
+ continue
225
+ hostapi = sd.query_hostapis(d["hostapi"])["name"]
226
+ markers = []
227
+ if i == out_idx:
228
+ markers.append("system default")
229
+ if i == configured_idx:
230
+ markers.append("configured")
231
+ tag = f" <- {', '.join(markers)}" if markers else ""
232
+ click.echo(
233
+ f"[{i:>2}] {d['name']} ({hostapi}, "
234
+ f"{d['max_output_channels']} ch, "
235
+ f"{int(d['default_samplerate'])} Hz){tag}"
236
+ )
237
+ rows.append(i)
238
+ if not pick:
239
+ return
240
+ click.echo()
241
+ choice = click.prompt(
242
+ "Enter device index to save (or blank to use system default)",
243
+ default="",
244
+ show_default=False,
245
+ )
246
+ choice = choice.strip()
247
+ if choice == "":
248
+ config.set_value("device", None)
249
+ click.echo("device: cleared (system default)")
250
+ return
251
+ try:
252
+ idx = int(choice)
253
+ except ValueError:
254
+ click.echo("not a number, aborting", err=True)
255
+ sys.exit(1)
256
+ if idx not in rows:
257
+ click.echo(f"index {idx} is not a valid output device", err=True)
258
+ sys.exit(1)
259
+ config.set_value("device", idx)
260
+ click.echo(f"saved device: {idx}")
261
+ except Exception as e:
262
+ click.echo(f"error: {e}", err=True)
263
+ sys.exit(1)
264
+
265
+
266
+ @main.command()
267
+ @click.argument("text", required=False)
268
+ @click.option("--out", default="lystn_debug.wav", help="Output WAV path.")
269
+ def dump(text: str | None, out: str) -> None:
270
+ """Synthesize TEXT and save to a WAV file instead of playing.
271
+
272
+ Use this to verify the server is producing real audio when the hook
273
+ can't be heard — open the WAV in any media player.
274
+ """
275
+ import wave
276
+ import numpy as np
277
+ if not text:
278
+ text = sys.stdin.read()
279
+ cleaned = clean_for_tts(text or "Lystn dump test.")
280
+ cfg = config.load()
281
+ chunks = list(client.synthesize(cfg["server"], cleaned,
282
+ voice=cfg["voice"],
283
+ api_key=cfg["api_key"]))
284
+ if not chunks:
285
+ click.echo("no audio chunks returned from server", err=True)
286
+ sys.exit(1)
287
+ pcm_f32 = np.frombuffer(b"".join(chunks), dtype=np.float32)
288
+ pcm_i16 = np.clip(pcm_f32 * 32767, -32768, 32767).astype(np.int16)
289
+ with wave.open(out, "wb") as w:
290
+ w.setnchannels(1)
291
+ w.setsampwidth(2)
292
+ w.setframerate(24000)
293
+ w.writeframes(pcm_i16.tobytes())
294
+ click.echo(f"wrote {len(pcm_i16)} samples ({len(pcm_i16)/24000:.2f}s) to {out}")
295
+
296
+
297
+ @main.command()
298
+ @click.option("--tail", default=20, help="Show last N lines.")
299
+ def log(tail: int) -> None:
300
+ """Show recent hook.log lines."""
301
+ log_path = config.config_dir() / "hook.log"
302
+ if not log_path.exists():
303
+ click.echo(f"no log yet at {log_path}")
304
+ return
305
+ with log_path.open("r", encoding="utf-8") as f:
306
+ lines = f.readlines()
307
+ for line in lines[-tail:]:
308
+ click.echo(line.rstrip())
309
+
310
+
311
+ @main.group()
312
+ def config_cmd() -> None:
313
+ """View or change saved settings."""
314
+
315
+
316
+ main.add_command(config_cmd, name="config")
317
+
318
+
319
+ @config_cmd.command("show")
320
+ def config_show() -> None:
321
+ """Print the current config."""
322
+ cfg = config.load()
323
+ if cfg.get("api_key"):
324
+ cfg["api_key"] = cfg["api_key"][:4] + "…(hidden)"
325
+ click.echo(json.dumps(cfg, indent=2))
326
+ click.echo(f"\nfile: {config.config_path()}")
327
+
328
+
329
+ @config_cmd.command("set")
330
+ @click.argument(
331
+ "key", type=click.Choice(["server", "api_key", "voice", "device"])
332
+ )
333
+ @click.argument("value")
334
+ def config_set(key: str, value: str) -> None:
335
+ """Set KEY to VALUE.
336
+
337
+ For `device`, VALUE can be an integer index (see `lystn devices`),
338
+ a substring of a device name (e.g. `AirPods`), or `default` to clear.
339
+ """
340
+ if key == "device":
341
+ if value.lower() in ("default", "none", ""):
342
+ config.set_value("device", None)
343
+ click.echo("device: cleared (system default)")
344
+ return
345
+ try:
346
+ stored: int | str = int(value)
347
+ except ValueError:
348
+ stored = value
349
+ resolved = resolve_device(stored)
350
+ if resolved is None:
351
+ click.echo(
352
+ f"warning: {value!r} did not match any output device; "
353
+ "saving anyway, will fall back to system default at playback time",
354
+ err=True,
355
+ )
356
+ config.set_value("device", stored)
357
+ click.echo(f"saved device: {stored!r} (resolved to {resolved})")
358
+ return
359
+ config.set_value(key, value)
360
+ click.echo(f"saved {key}")
361
+
362
+
363
+ @main.command()
364
+ def install() -> None:
365
+ """Print the Claude Code Stop-hook snippet to wire `lystn hook`."""
366
+ import shutil
367
+ lystn_path = shutil.which("lystn") or "lystn"
368
+ # Claude Code runs hook commands through bash on Windows, which eats
369
+ # backslashes. Forward slashes work for both bash and Windows path
370
+ # resolution.
371
+ lystn_path = lystn_path.replace("\\", "/")
372
+ snippet = {
373
+ "hooks": {
374
+ "Stop": [
375
+ {
376
+ "matcher": "*",
377
+ "hooks": [
378
+ {"type": "command", "command": f"{lystn_path} hook"}
379
+ ],
380
+ }
381
+ ],
382
+ "UserPromptSubmit": [
383
+ {
384
+ "matcher": "*",
385
+ "hooks": [
386
+ {
387
+ "type": "command",
388
+ "command": (
389
+ "echo Your final response will be spoken aloud "
390
+ "by a TTS engine. Keep it short and "
391
+ "conversational. Skip markdown, headers, and "
392
+ "code blocks unless explicitly asked."
393
+ ),
394
+ }
395
+ ],
396
+ }
397
+ ],
398
+ }
399
+ }
400
+ click.echo("Add the following `hooks` key inside the top-level object")
401
+ click.echo("of ~/.claude/settings.json (merge with existing keys, comma-separated):\n")
402
+ inner = json.dumps(snippet["hooks"], indent=2)
403
+ click.echo(f'"hooks": {inner}')
@@ -0,0 +1,121 @@
1
+ """Client for the Lystn TTS server.
2
+
3
+ Posts text to /speak, then connects to the /stream WebSocket and yields
4
+ binary PCM chunks as they arrive. Stops yielding on the {event: end}
5
+ JSON message.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import queue
11
+ import threading
12
+ from typing import Iterator
13
+
14
+ import requests
15
+ import websocket
16
+
17
+
18
+ def synthesize(
19
+ server: str,
20
+ text: str,
21
+ voice: str | None = None,
22
+ api_key: str | None = None,
23
+ timeout: float = 5.0,
24
+ ) -> Iterator[bytes]:
25
+ """POST text to the server, yield PCM chunks streamed back via WS.
26
+
27
+ Caller is responsible for playing the chunks. Closes the WS on `end`.
28
+ """
29
+ ws_url = _http_to_ws(server) + "/stream"
30
+ speak_url = server.rstrip("/") + "/speak"
31
+
32
+ chunk_q: queue.Queue = queue.Queue()
33
+ started = threading.Event()
34
+ finished = threading.Event()
35
+
36
+ def on_open(_ws):
37
+ started.set()
38
+ _ws.send("hello") # server's recv loop needs a kick
39
+
40
+ def on_message(_ws, msg):
41
+ if isinstance(msg, (bytes, bytearray)):
42
+ chunk_q.put(bytes(msg))
43
+ return
44
+ try:
45
+ payload = json.loads(msg)
46
+ except json.JSONDecodeError:
47
+ return
48
+ if payload.get("event") == "end":
49
+ chunk_q.put(None)
50
+ finished.set()
51
+ elif payload.get("event") == "error":
52
+ chunk_q.put(None)
53
+ finished.set()
54
+
55
+ def on_close(*_):
56
+ chunk_q.put(None)
57
+ finished.set()
58
+
59
+ def on_error(*_):
60
+ chunk_q.put(None)
61
+ finished.set()
62
+
63
+ ws = websocket.WebSocketApp(
64
+ ws_url,
65
+ on_open=on_open,
66
+ on_message=on_message,
67
+ on_close=on_close,
68
+ on_error=on_error,
69
+ )
70
+ t = threading.Thread(target=ws.run_forever, daemon=True)
71
+ t.start()
72
+
73
+ if not started.wait(timeout=timeout):
74
+ ws.close()
75
+ raise ConnectionError(f"Could not connect to {ws_url} in {timeout}s")
76
+
77
+ headers = {"Content-Type": "application/json"}
78
+ if api_key:
79
+ headers["X-Lystn-Key"] = api_key
80
+
81
+ body = {"text": text}
82
+ if voice:
83
+ body["voice"] = voice
84
+
85
+ try:
86
+ r = requests.post(speak_url, json=body, headers=headers, timeout=timeout)
87
+ r.raise_for_status()
88
+ except requests.RequestException:
89
+ ws.close()
90
+ raise
91
+
92
+ try:
93
+ while True:
94
+ item = chunk_q.get()
95
+ if item is None:
96
+ return
97
+ yield item
98
+ finally:
99
+ ws.close()
100
+
101
+
102
+ def voices(server: str, timeout: float = 5.0) -> list[str]:
103
+ r = requests.get(server.rstrip("/") + "/voices", timeout=timeout)
104
+ r.raise_for_status()
105
+ return list(r.json().get("voices", []))
106
+
107
+
108
+ def health(server: str, timeout: float = 3.0) -> bool:
109
+ try:
110
+ r = requests.get(server.rstrip("/") + "/health", timeout=timeout)
111
+ return r.ok
112
+ except requests.RequestException:
113
+ return False
114
+
115
+
116
+ def _http_to_ws(url: str) -> str:
117
+ if url.startswith("https://"):
118
+ return "wss://" + url[len("https://"):]
119
+ if url.startswith("http://"):
120
+ return "ws://" + url[len("http://"):]
121
+ return url
@@ -0,0 +1,57 @@
1
+ """User config stored as JSON in the platform's config dir."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ DEFAULTS: dict[str, Any] = {
10
+ "server": "http://127.0.0.1:7878",
11
+ "api_key": None,
12
+ "voice": "af_heart",
13
+ "device": None,
14
+ }
15
+
16
+
17
+ def config_dir() -> Path:
18
+ if os.name == "nt":
19
+ base = os.environ.get("APPDATA") or str(Path.home() / "AppData" / "Roaming")
20
+ else:
21
+ base = os.environ.get("XDG_CONFIG_HOME") or str(Path.home() / ".config")
22
+ d = Path(base) / "lystn"
23
+ d.mkdir(parents=True, exist_ok=True)
24
+ return d
25
+
26
+
27
+ def config_path() -> Path:
28
+ return config_dir() / "config.json"
29
+
30
+
31
+ def load() -> dict[str, Any]:
32
+ p = config_path()
33
+ if not p.exists():
34
+ return dict(DEFAULTS)
35
+ try:
36
+ with p.open("r", encoding="utf-8") as f:
37
+ data = json.load(f)
38
+ except (OSError, json.JSONDecodeError):
39
+ return dict(DEFAULTS)
40
+ merged = dict(DEFAULTS)
41
+ merged.update({k: v for k, v in data.items() if v is not None})
42
+ return merged
43
+
44
+
45
+ def save(cfg: dict[str, Any]) -> None:
46
+ with config_path().open("w", encoding="utf-8") as f:
47
+ json.dump(cfg, f, indent=2)
48
+
49
+
50
+ def get(key: str) -> Any:
51
+ return load().get(key, DEFAULTS.get(key))
52
+
53
+
54
+ def set_value(key: str, value: Any) -> None:
55
+ cfg = load()
56
+ cfg[key] = value
57
+ save(cfg)
@@ -0,0 +1,210 @@
1
+ """Audio playback for streamed PCM chunks.
2
+
3
+ Two backends:
4
+
5
+ - Windows: write the audio to a temp WAV and play it via the OS default
6
+ audio path (winsound). This is the same path the browser and Media Player
7
+ use, and it works on machines where PortAudio/sounddevice is silent
8
+ (a real, common failure with Bluetooth + virtual audio drivers).
9
+ - Other platforms: stream chunks live through a sounddevice OutputStream.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ import subprocess
15
+ import sys
16
+ import tempfile
17
+ import wave
18
+ from typing import Iterable
19
+
20
+ import numpy as np
21
+ import sounddevice as sd
22
+
23
+ SAMPLE_RATE = 24_000
24
+
25
+
26
+ def resolve_device(device: int | str | None) -> int | None:
27
+ """Resolve a config `device` value to a concrete sounddevice index.
28
+
29
+ - None or empty: return None (use system default).
30
+ - int or numeric string: return that index if it exists and has output.
31
+ - non-numeric string: case-insensitive substring match on device name.
32
+
33
+ On Windows, when multiple host APIs expose the same device (e.g. MME,
34
+ WASAPI, DirectSound), prefer DirectSound. It always resamples and is the
35
+ most universally audible backend; WASAPI shared mode and MME both
36
+ silently swallow audio on some setups (Bluetooth, virtual mixers).
37
+ """
38
+ if device is None or device == "":
39
+ return None
40
+
41
+ devices = sd.query_devices()
42
+ hostapis = sd.query_hostapis()
43
+
44
+ def hostapi_name(d) -> str:
45
+ return hostapis[d["hostapi"]]["name"]
46
+
47
+ def wasapi_score(d) -> int:
48
+ name = hostapi_name(d).lower()
49
+ if "directsound" in name:
50
+ return 3
51
+ if "wasapi" in name:
52
+ return 2
53
+ if "mme" in name:
54
+ return 1
55
+ return 0
56
+
57
+ try:
58
+ idx = int(device)
59
+ except (TypeError, ValueError):
60
+ idx = None
61
+
62
+ if idx is not None:
63
+ if 0 <= idx < len(devices) and devices[idx]["max_output_channels"] > 0:
64
+ return idx
65
+ return None
66
+
67
+ needle = str(device).lower().strip()
68
+ matches = [
69
+ (i, d) for i, d in enumerate(devices)
70
+ if d["max_output_channels"] > 0 and needle in d["name"].lower()
71
+ ]
72
+ if not matches:
73
+ return None
74
+ matches.sort(key=lambda pair: wasapi_score(pair[1]), reverse=True)
75
+ return matches[0][0]
76
+
77
+
78
+ def _device_samplerate(index: int | None) -> int:
79
+ """Native default output rate for `index` (or the system default)."""
80
+ try:
81
+ if index is None:
82
+ default = sd.default.device
83
+ try:
84
+ _in, index = default
85
+ except (TypeError, ValueError):
86
+ index = default
87
+ info = sd.query_devices(index)
88
+ rate = int(info["default_samplerate"])
89
+ return rate if rate > 0 else SAMPLE_RATE
90
+ except Exception:
91
+ return SAMPLE_RATE
92
+
93
+
94
+ class Player:
95
+ """Plays 24kHz mono float32 PCM, resampled to the device's native rate.
96
+
97
+ Opening an OutputStream at Kokoro's 24kHz rate plays *silently* on some
98
+ Windows backends (notably DirectSound and Bluetooth). Opening at the
99
+ device's own default rate and resampling the audio up to match is the
100
+ reliable path: it's what plain `sd.play` does, and it's audible
101
+ everywhere we've tested.
102
+ """
103
+
104
+ def __init__(
105
+ self,
106
+ sample_rate: int = SAMPLE_RATE,
107
+ device: int | str | None = None,
108
+ ):
109
+ self.sample_rate = sample_rate
110
+ self.device = resolve_device(device)
111
+ self.out_rate = _device_samplerate(self.device)
112
+ self._stream: sd.OutputStream | None = None
113
+
114
+ def __enter__(self) -> "Player":
115
+ self._stream = sd.OutputStream(
116
+ samplerate=self.out_rate,
117
+ channels=1,
118
+ dtype="float32",
119
+ blocksize=0,
120
+ device=self.device,
121
+ )
122
+ self._stream.start()
123
+ return self
124
+
125
+ def __exit__(self, *_exc) -> None:
126
+ if self._stream is not None:
127
+ try:
128
+ self._stream.stop()
129
+ finally:
130
+ self._stream.close()
131
+ self._stream = None
132
+
133
+ def _resample(self, arr: np.ndarray) -> np.ndarray:
134
+ if self.out_rate == self.sample_rate or arr.size == 0:
135
+ return arr
136
+ n_out = int(round(arr.size * self.out_rate / self.sample_rate))
137
+ if n_out <= 0:
138
+ return arr
139
+ src_idx = np.linspace(0.0, 1.0, arr.size, endpoint=False)
140
+ dst_idx = np.linspace(0.0, 1.0, n_out, endpoint=False)
141
+ return np.interp(dst_idx, src_idx, arr).astype(np.float32)
142
+
143
+ def write_pcm_bytes(self, chunk: bytes) -> None:
144
+ if not chunk:
145
+ return
146
+ arr = np.frombuffer(chunk, dtype=np.float32)
147
+ assert self._stream is not None, "Player not started"
148
+ self._stream.write(self._resample(arr))
149
+
150
+
151
+ def _write_wav(chunks: Iterable[bytes], sample_rate: int) -> tuple[str, float]:
152
+ """Buffer float32 PCM chunks into a temp WAV. Returns (path, seconds)."""
153
+ pcm = b"".join(chunks)
154
+ if not pcm:
155
+ return "", 0.0
156
+ arr = np.frombuffer(pcm, dtype=np.float32)
157
+ pcm16 = np.clip(arr * 32767.0, -32768, 32767).astype(np.int16)
158
+ path = os.path.join(tempfile.gettempdir(), "lystn_play.wav")
159
+ with wave.open(path, "wb") as w:
160
+ w.setnchannels(1)
161
+ w.setsampwidth(2)
162
+ w.setframerate(sample_rate)
163
+ w.writeframes(pcm16.tobytes())
164
+ return path, len(pcm16) / float(sample_rate)
165
+
166
+
167
+ def _play_via_media_foundation(chunks: Iterable[bytes], sample_rate: int) -> None:
168
+ """Play through Windows Media Foundation (System.Windows.Media.MediaPlayer).
169
+
170
+ This is the modern audio path Windows Media Player uses. It works on
171
+ machines where the legacy MME path (winsound) and PortAudio are silent —
172
+ a common failure with Bluetooth headphones and virtual audio drivers.
173
+ Windowless; follows the system default output like any normal app.
174
+ """
175
+ path, seconds = _write_wav(chunks, sample_rate)
176
+ if not path:
177
+ return
178
+ uri = path.replace("'", "''")
179
+ ps = (
180
+ "Add-Type -AssemblyName PresentationCore;"
181
+ "$p=New-Object System.Windows.Media.MediaPlayer;"
182
+ f"$p.Open([uri]'{uri}');$p.Play();"
183
+ f"Start-Sleep -Milliseconds {int(seconds * 1000) + 1200};"
184
+ "$p.Stop();$p.Close()"
185
+ )
186
+ subprocess.run(
187
+ ["powershell", "-NoProfile", "-NonInteractive", "-Command", ps],
188
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
189
+ check=False,
190
+ )
191
+
192
+
193
+ def play_chunks(
194
+ chunks: Iterable[bytes],
195
+ sample_rate: int = SAMPLE_RATE,
196
+ device: int | str | None = None,
197
+ ) -> None:
198
+ """Play a stream of float32 PCM chunks synchronously.
199
+
200
+ On Windows we go through Media Foundation, which is far more reliable
201
+ than PortAudio/MME for Bluetooth and virtual-audio setups. `device` is
202
+ ignored there — playback follows the Windows default output, just like
203
+ the browser. On other platforms we stream via sounddevice.
204
+ """
205
+ if sys.platform == "win32":
206
+ _play_via_media_foundation(chunks, sample_rate)
207
+ return
208
+ with Player(sample_rate, device=device) as p:
209
+ for c in chunks:
210
+ p.write_pcm_bytes(c)