streamcore 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.
@@ -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
95
+ Derivative 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
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying 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
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions 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 [yyyy] [name of copyright owner]
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.
@@ -0,0 +1,145 @@
1
+ Metadata-Version: 2.4
2
+ Name: streamcore
3
+ Version: 0.1.0
4
+ Summary: Python SDK for connecting to a Pion Voice Agent server via WebRTC + WHIP
5
+ License-Expression: Apache-2.0
6
+ Keywords: webrtc,whip,voice-agent,pion,real-time,audio
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: aiortc>=1.9.0
11
+ Requires-Dist: aiohttp>=3.9.0
12
+ Requires-Dist: av>=12.0.0
13
+ Requires-Dist: numpy>=1.24.0
14
+ Provides-Extra: dev
15
+ Requires-Dist: pytest; extra == "dev"
16
+ Requires-Dist: pytest-asyncio; extra == "dev"
17
+ Dynamic: license-file
18
+
19
+ # streamcore (Python)
20
+
21
+ Python SDK for connecting to a [streamcore](https://github.com/streamcore/streamcore-server) server via WebRTC + WHIP, powered by [aiortc](https://github.com/aiortc/aiortc).
22
+
23
+ ## Requirements
24
+
25
+ - **Python 3.10+**
26
+
27
+ ## Installation
28
+
29
+ ```bash
30
+ pip install streamcore
31
+ ```
32
+
33
+ Or install from source:
34
+
35
+ ```bash
36
+ cd python-sdk
37
+ pip install -e .
38
+ ```
39
+
40
+ ## Quick Start
41
+
42
+ ```python
43
+ import asyncio
44
+ import numpy as np
45
+ import streamcore
46
+
47
+
48
+ async def main():
49
+ def on_transcript(entry, all_entries):
50
+ print(f"[{entry.role}] {entry.text}")
51
+
52
+ client = streamcore.Client(
53
+ config=streamcore.Config(whip_endpoint="http://localhost:8080/whip"),
54
+ events=streamcore.EventHandler(
55
+ on_transcript=on_transcript,
56
+ on_error=lambda err: print(f"Error: {err}"),
57
+ ),
58
+ )
59
+
60
+ await client.connect()
61
+
62
+ # Send a 20 ms frame of silence
63
+ pcm = np.zeros(streamcore.FRAME_SIZE, dtype=np.int16)
64
+ await client.send_pcm(pcm)
65
+
66
+ # Receive decoded audio from the agent
67
+ audio = await client.recv_pcm() # numpy int16 array
68
+
69
+ await client.disconnect()
70
+
71
+
72
+ asyncio.run(main())
73
+ ```
74
+
75
+ ## API
76
+
77
+ ### `Client(config?, events?)`
78
+
79
+ Creates a new voice agent client.
80
+
81
+ #### `Config`
82
+
83
+ | Field | Type | Default | Description |
84
+ | --------------- | ------------ | ------------------------------ | --------------------------- |
85
+ | `whip_endpoint` | `str` | `"http://localhost:8080/whip"` | WHIP signaling endpoint URL |
86
+ | `ice_servers` | `list[str]` | `["stun:stun.l.google.com:19302"]` | ICE server URLs |
87
+
88
+ #### `EventHandler`
89
+
90
+ | Callback | Signature | Description |
91
+ | ------------------------ | --------------------------------------------------------------- | ------------------------------------- |
92
+ | `on_status_change` | `(status: ConnectionStatus) -> None` | Fired when connection status changes |
93
+ | `on_transcript` | `(entry: TranscriptEntry, all: list[TranscriptEntry]) -> None` | Fired on new or updated transcript |
94
+ | `on_error` | `(error: Exception) -> None` | Fired on connection or server errors |
95
+ | `on_data_channel_message`| `(msg: DataChannelMessage) -> None` | Fired for every raw DC message |
96
+
97
+ #### Methods
98
+
99
+ | Method | Description |
100
+ | ------------------------------- | ------------------------------------------------------------ |
101
+ | `await client.connect(track?)` | Connect via WHIP. Optionally pass an aiortc audio track. |
102
+ | `await client.disconnect()` | Tear down connection and free resources. |
103
+ | `await client.send_pcm(pcm)` | Send a numpy int16 PCM buffer (mono 48 kHz) to the agent. |
104
+ | `await client.recv_pcm()` | Receive decoded PCM audio as a numpy int16 array. |
105
+ | `client.status` | Current `ConnectionStatus`. |
106
+ | `client.transcript` | Current conversation as `list[TranscriptEntry]`. |
107
+ | `client.remote_track` | Inbound audio track from the agent (available after connect).|
108
+
109
+ #### Audio Constants
110
+
111
+ | Constant | Value | Description |
112
+ | ------------- | -------- | -------------------------------- |
113
+ | `SAMPLE_RATE` | `48000` | Audio sample rate in Hz |
114
+ | `CHANNELS` | `1` | Number of channels (mono) |
115
+ | `FRAME_SIZE` | `960` | Samples per 20 ms frame |
116
+
117
+ ## Audio I/O
118
+
119
+ The SDK handles aiortc track management, `av.AudioFrame` construction, and
120
+ resampling internally. Callers only deal with raw PCM data as numpy int16
121
+ arrays:
122
+
123
+ ```python
124
+ # Send microphone audio (960 samples = 20 ms at 48 kHz)
125
+ await client.send_pcm(pcm_int16)
126
+
127
+ # Receive agent audio
128
+ audio = await client.recv_pcm()
129
+ ```
130
+
131
+ If you need direct track access (e.g. for a custom aiortc pipeline), pass
132
+ your own `AudioStreamTrack` via `client.connect(user_track=my_track)`.
133
+
134
+ ## Dependencies
135
+
136
+ | Package | Purpose |
137
+ | -------- | ------------------------------ |
138
+ | `aiortc` | WebRTC stack |
139
+ | `aiohttp`| HTTP client for WHIP signaling |
140
+ | `av` | Audio frame encoding/decoding |
141
+ | `numpy` | PCM audio buffers |
142
+
143
+ ## License
144
+
145
+ Apache-2.0
@@ -0,0 +1,127 @@
1
+ # streamcore (Python)
2
+
3
+ Python SDK for connecting to a [streamcore](https://github.com/streamcore/streamcore-server) server via WebRTC + WHIP, powered by [aiortc](https://github.com/aiortc/aiortc).
4
+
5
+ ## Requirements
6
+
7
+ - **Python 3.10+**
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ pip install streamcore
13
+ ```
14
+
15
+ Or install from source:
16
+
17
+ ```bash
18
+ cd python-sdk
19
+ pip install -e .
20
+ ```
21
+
22
+ ## Quick Start
23
+
24
+ ```python
25
+ import asyncio
26
+ import numpy as np
27
+ import streamcore
28
+
29
+
30
+ async def main():
31
+ def on_transcript(entry, all_entries):
32
+ print(f"[{entry.role}] {entry.text}")
33
+
34
+ client = streamcore.Client(
35
+ config=streamcore.Config(whip_endpoint="http://localhost:8080/whip"),
36
+ events=streamcore.EventHandler(
37
+ on_transcript=on_transcript,
38
+ on_error=lambda err: print(f"Error: {err}"),
39
+ ),
40
+ )
41
+
42
+ await client.connect()
43
+
44
+ # Send a 20 ms frame of silence
45
+ pcm = np.zeros(streamcore.FRAME_SIZE, dtype=np.int16)
46
+ await client.send_pcm(pcm)
47
+
48
+ # Receive decoded audio from the agent
49
+ audio = await client.recv_pcm() # numpy int16 array
50
+
51
+ await client.disconnect()
52
+
53
+
54
+ asyncio.run(main())
55
+ ```
56
+
57
+ ## API
58
+
59
+ ### `Client(config?, events?)`
60
+
61
+ Creates a new voice agent client.
62
+
63
+ #### `Config`
64
+
65
+ | Field | Type | Default | Description |
66
+ | --------------- | ------------ | ------------------------------ | --------------------------- |
67
+ | `whip_endpoint` | `str` | `"http://localhost:8080/whip"` | WHIP signaling endpoint URL |
68
+ | `ice_servers` | `list[str]` | `["stun:stun.l.google.com:19302"]` | ICE server URLs |
69
+
70
+ #### `EventHandler`
71
+
72
+ | Callback | Signature | Description |
73
+ | ------------------------ | --------------------------------------------------------------- | ------------------------------------- |
74
+ | `on_status_change` | `(status: ConnectionStatus) -> None` | Fired when connection status changes |
75
+ | `on_transcript` | `(entry: TranscriptEntry, all: list[TranscriptEntry]) -> None` | Fired on new or updated transcript |
76
+ | `on_error` | `(error: Exception) -> None` | Fired on connection or server errors |
77
+ | `on_data_channel_message`| `(msg: DataChannelMessage) -> None` | Fired for every raw DC message |
78
+
79
+ #### Methods
80
+
81
+ | Method | Description |
82
+ | ------------------------------- | ------------------------------------------------------------ |
83
+ | `await client.connect(track?)` | Connect via WHIP. Optionally pass an aiortc audio track. |
84
+ | `await client.disconnect()` | Tear down connection and free resources. |
85
+ | `await client.send_pcm(pcm)` | Send a numpy int16 PCM buffer (mono 48 kHz) to the agent. |
86
+ | `await client.recv_pcm()` | Receive decoded PCM audio as a numpy int16 array. |
87
+ | `client.status` | Current `ConnectionStatus`. |
88
+ | `client.transcript` | Current conversation as `list[TranscriptEntry]`. |
89
+ | `client.remote_track` | Inbound audio track from the agent (available after connect).|
90
+
91
+ #### Audio Constants
92
+
93
+ | Constant | Value | Description |
94
+ | ------------- | -------- | -------------------------------- |
95
+ | `SAMPLE_RATE` | `48000` | Audio sample rate in Hz |
96
+ | `CHANNELS` | `1` | Number of channels (mono) |
97
+ | `FRAME_SIZE` | `960` | Samples per 20 ms frame |
98
+
99
+ ## Audio I/O
100
+
101
+ The SDK handles aiortc track management, `av.AudioFrame` construction, and
102
+ resampling internally. Callers only deal with raw PCM data as numpy int16
103
+ arrays:
104
+
105
+ ```python
106
+ # Send microphone audio (960 samples = 20 ms at 48 kHz)
107
+ await client.send_pcm(pcm_int16)
108
+
109
+ # Receive agent audio
110
+ audio = await client.recv_pcm()
111
+ ```
112
+
113
+ If you need direct track access (e.g. for a custom aiortc pipeline), pass
114
+ your own `AudioStreamTrack` via `client.connect(user_track=my_track)`.
115
+
116
+ ## Dependencies
117
+
118
+ | Package | Purpose |
119
+ | -------- | ------------------------------ |
120
+ | `aiortc` | WebRTC stack |
121
+ | `aiohttp`| HTTP client for WHIP signaling |
122
+ | `av` | Audio frame encoding/decoding |
123
+ | `numpy` | PCM audio buffers |
124
+
125
+ ## License
126
+
127
+ Apache-2.0
@@ -0,0 +1,27 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "streamcore"
7
+ version = "0.1.0"
8
+ description = "Python SDK for connecting to a Pion Voice Agent server via WebRTC + WHIP"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.10"
12
+ keywords = ["webrtc", "whip", "voice-agent", "pion", "real-time", "audio"]
13
+ dependencies = [
14
+ "aiortc>=1.9.0",
15
+ "aiohttp>=3.9.0",
16
+ "av>=12.0.0",
17
+ "numpy>=1.24.0",
18
+ ]
19
+
20
+ [project.optional-dependencies]
21
+ dev = [
22
+ "pytest",
23
+ "pytest-asyncio",
24
+ ]
25
+
26
+ [tool.setuptools.packages.find]
27
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,21 @@
1
+ from .audio import CHANNELS, FRAME_SIZE, SAMPLE_RATE
2
+ from .types import (
3
+ ConnectionStatus,
4
+ TranscriptEntry,
5
+ DataChannelMessage,
6
+ Config,
7
+ EventHandler,
8
+ )
9
+ from .client import Client
10
+ from .whip import whip_offer, whip_delete
11
+
12
+ __all__ = [
13
+ "Client",
14
+ "Config",
15
+ "EventHandler",
16
+ "ConnectionStatus",
17
+ "TranscriptEntry",
18
+ "DataChannelMessage",
19
+ "whip_offer",
20
+ "whip_delete",
21
+ ]
@@ -0,0 +1,54 @@
1
+ """Audio helpers for the StreamCoreAI Python SDK.
2
+
3
+ Provides PCM-level send/receive so callers never need to deal with
4
+ aiortc tracks, av.AudioFrame construction, or resampling.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import fractions
11
+
12
+ import av
13
+ import numpy as np
14
+ from aiortc.mediastreams import AudioStreamTrack, MediaStreamError
15
+
16
+ SAMPLE_RATE: int = 48_000
17
+ """Audio sample rate in Hz (48 kHz)."""
18
+
19
+ CHANNELS: int = 1
20
+ """Number of audio channels (mono)."""
21
+
22
+ FRAME_SIZE: int = 960
23
+ """Number of samples per 20 ms frame at 48 kHz."""
24
+
25
+
26
+ class _SDKAudioTrack(AudioStreamTrack):
27
+ """Internal aiortc track fed by :meth:`Client.send_pcm`."""
28
+
29
+ kind = "audio"
30
+
31
+ def __init__(self) -> None:
32
+ super().__init__()
33
+ self._queue: asyncio.Queue[np.ndarray] = asyncio.Queue()
34
+ self._samples: int = 0
35
+ self._time_base = fractions.Fraction(1, SAMPLE_RATE)
36
+
37
+ async def recv(self) -> av.AudioFrame:
38
+ if self.readyState != "live":
39
+ raise MediaStreamError
40
+ try:
41
+ pcm = await asyncio.wait_for(self._queue.get(), timeout=0.02)
42
+ except asyncio.TimeoutError:
43
+ pcm = np.zeros(FRAME_SIZE, dtype=np.int16)
44
+
45
+ pts = self._samples
46
+ n = len(pcm)
47
+ self._samples += n
48
+
49
+ frame = av.AudioFrame(format="s16", layout="mono", samples=n)
50
+ frame.planes[0].update(pcm.tobytes())
51
+ frame.pts = pts
52
+ frame.sample_rate = SAMPLE_RATE
53
+ frame.time_base = self._time_base
54
+ return frame
@@ -0,0 +1,277 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import json
5
+ import logging
6
+ from threading import Lock
7
+
8
+ import av
9
+ import numpy as np
10
+ from aiortc import (
11
+ RTCConfiguration,
12
+ RTCIceServer,
13
+ RTCPeerConnection,
14
+ RTCSessionDescription,
15
+ )
16
+ from aiortc.contrib.media import MediaBlackhole
17
+
18
+ from .audio import SAMPLE_RATE, _SDKAudioTrack
19
+ from .types import (
20
+ Config,
21
+ ConnectionStatus,
22
+ DataChannelMessage,
23
+ EventHandler,
24
+ TranscriptEntry,
25
+ )
26
+ from .whip import whip_delete, whip_offer
27
+
28
+ logger = logging.getLogger("streamcore")
29
+
30
+
31
+ class Client:
32
+ """Manages a WebRTC connection to a Voice Agent server via WHIP signaling.
33
+
34
+ After :meth:`connect` returns, the peer connection is active. Remote audio
35
+ is consumed internally (or via the ``remote_track`` attribute). Provide an
36
+ audio track via ``user_track`` to send microphone audio to the server.
37
+ """
38
+
39
+ def __init__(
40
+ self,
41
+ config: Config | None = None,
42
+ events: EventHandler | None = None,
43
+ ) -> None:
44
+ self.config = config or Config()
45
+ self.events = events or EventHandler()
46
+
47
+ self._pc: RTCPeerConnection | None = None
48
+ self._session_url: str = ""
49
+ self._blackhole: MediaBlackhole | None = None
50
+
51
+ self._lock = Lock()
52
+ self._status = ConnectionStatus.IDLE
53
+ self._transcript: list[TranscriptEntry] = []
54
+ self._assist_buf: str = ""
55
+
56
+ self.remote_track = None
57
+ """The inbound audio track from the agent, available after connect."""
58
+
59
+ self._sdk_track: _SDKAudioTrack | None = None
60
+ self._remote_track_ready = asyncio.Event()
61
+ self._resampler: av.AudioResampler | None = None
62
+
63
+ @property
64
+ def status(self) -> ConnectionStatus:
65
+ with self._lock:
66
+ return self._status
67
+
68
+ @property
69
+ def transcript(self) -> list[TranscriptEntry]:
70
+ with self._lock:
71
+ return list(self._transcript)
72
+
73
+ async def connect(self, user_track=None) -> None:
74
+ """Establish a WebRTC connection to the voice agent server.
75
+
76
+ Args:
77
+ user_track: An optional aiortc MediaStreamTrack for the user's
78
+ microphone audio. If provided it will be added to the peer
79
+ connection so the server receives audio from the user.
80
+ """
81
+ self._set_status(ConnectionStatus.CONNECTING)
82
+
83
+ try:
84
+ ice_servers = [RTCIceServer(urls=url) for url in self.config.ice_servers]
85
+ pc = RTCPeerConnection(RTCConfiguration(iceServers=ice_servers))
86
+ self._pc = pc
87
+
88
+ # Add user audio track if provided, otherwise create SDK track.
89
+ if user_track is not None:
90
+ pc.addTrack(user_track)
91
+ else:
92
+ self._sdk_track = _SDKAudioTrack()
93
+ pc.addTrack(self._sdk_track)
94
+
95
+ # Create data channel for receiving events from the server.
96
+ dc = pc.createDataChannel("events")
97
+
98
+ @dc.on("message")
99
+ def on_dc_message(message):
100
+ try:
101
+ data = json.loads(message)
102
+ msg = DataChannelMessage(
103
+ type=data.get("type", ""),
104
+ text=data.get("text", ""),
105
+ final=data.get("final", False),
106
+ message=data.get("message", ""),
107
+ )
108
+ if self.events.on_data_channel_message:
109
+ self.events.on_data_channel_message(msg)
110
+ self._handle_data_channel_message(msg)
111
+ except Exception as exc:
112
+ logger.warning("Failed to parse DC message: %s", exc)
113
+
114
+ @pc.on("track")
115
+ def on_track(track):
116
+ self.remote_track = track
117
+ self._remote_track_ready.set()
118
+
119
+ @pc.on("connectionstatechange")
120
+ async def on_connection_state_change():
121
+ state = pc.connectionState
122
+ if state == "connected":
123
+ self._set_status(ConnectionStatus.CONNECTED)
124
+ elif state in ("failed", "closed", "disconnected"):
125
+ self._set_status(ConnectionStatus.DISCONNECTED)
126
+
127
+ # Create offer and gather ICE candidates.
128
+ offer = await pc.createOffer()
129
+ await pc.setLocalDescription(offer)
130
+
131
+ # aiortc gathers ICE candidates during setLocalDescription,
132
+ # so localDescription.sdp already contains all candidates.
133
+ offer_sdp = pc.localDescription.sdp
134
+
135
+ # WHIP exchange.
136
+ result = await whip_offer(self.config.whip_endpoint, offer_sdp)
137
+ self._session_url = result.session_url
138
+
139
+ answer = RTCSessionDescription(sdp=result.answer_sdp, type="answer")
140
+ await pc.setRemoteDescription(answer)
141
+
142
+ except Exception as exc:
143
+ logger.error("Connect error: %s", exc)
144
+ self._set_status(ConnectionStatus.ERROR)
145
+ if self.events.on_error:
146
+ self.events.on_error(exc)
147
+ raise
148
+
149
+ async def disconnect(self) -> None:
150
+ """Tear down the WebRTC connection and free resources."""
151
+ # Stop SDK track first so aiortc's internal consumer unblocks.
152
+ if self._sdk_track is not None:
153
+ self._sdk_track.stop()
154
+ self._sdk_track = None
155
+ await whip_delete(self._session_url)
156
+ self._session_url = ""
157
+ if self._blackhole:
158
+ await self._blackhole.stop()
159
+ self._blackhole = None
160
+ if self._pc:
161
+ pc = self._pc
162
+ self._pc = None
163
+ try:
164
+ await asyncio.wait_for(pc.close(), timeout=3)
165
+ except (asyncio.TimeoutError, Exception):
166
+ pass
167
+ self._remote_track_ready.clear()
168
+ self._resampler = None
169
+ self._set_status(ConnectionStatus.IDLE)
170
+ self._assist_buf = ""
171
+
172
+ # ── Audio helpers ────────────────────────────────────────────────
173
+
174
+ async def send_pcm(self, pcm: np.ndarray) -> None:
175
+ """Send a buffer of 16-bit PCM samples to the voice agent.
176
+
177
+ Args:
178
+ pcm: numpy int16 array of audio samples (mono, 48 kHz).
179
+ Typically ``FRAME_SIZE`` (960) samples for a 20 ms frame.
180
+ """
181
+ if self._sdk_track is None:
182
+ raise RuntimeError(
183
+ "send_pcm requires the built-in audio track; "
184
+ "do not pass user_track to connect()"
185
+ )
186
+ await self._sdk_track._queue.put(pcm)
187
+
188
+ async def recv_pcm(self) -> np.ndarray:
189
+ """Receive decoded PCM audio from the voice agent.
190
+
191
+ Blocks until the remote audio track is available, then returns
192
+ a numpy int16 array of mono 48 kHz samples.
193
+ """
194
+ await self._remote_track_ready.wait()
195
+ track = self.remote_track
196
+
197
+ if self._resampler is None:
198
+ self._resampler = av.AudioResampler(
199
+ format="s16", layout="mono", rate=SAMPLE_RATE
200
+ )
201
+
202
+ frame = await track.recv()
203
+ arrays = []
204
+ for resampled in self._resampler.resample(frame):
205
+ arrays.append(resampled.to_ndarray().flatten())
206
+ if arrays:
207
+ return np.concatenate(arrays)
208
+ return np.array([], dtype=np.int16)
209
+
210
+ # ── Internal helpers ─────────────────────────────────────────────
211
+
212
+ def _set_status(self, status: ConnectionStatus) -> None:
213
+ with self._lock:
214
+ self._status = status
215
+ if self.events.on_status_change:
216
+ self.events.on_status_change(status)
217
+
218
+ def _handle_data_channel_message(self, msg: DataChannelMessage) -> None:
219
+ with self._lock:
220
+ if msg.type == "transcript":
221
+ if msg.final:
222
+ pending_assistant = self._assist_buf
223
+ self._assist_buf = ""
224
+
225
+ updated = [
226
+ e
227
+ for e in self._transcript
228
+ if not (e.role == "user" and e.partial)
229
+ and not (e.role == "assistant" and e.partial)
230
+ ]
231
+ if pending_assistant:
232
+ updated.append(
233
+ TranscriptEntry(role="assistant", text=pending_assistant)
234
+ )
235
+ updated.append(TranscriptEntry(role="user", text=msg.text))
236
+ self._transcript = updated
237
+ else:
238
+ updated = [
239
+ e
240
+ for e in self._transcript
241
+ if not (e.role == "user" and e.partial)
242
+ ]
243
+ updated.append(
244
+ TranscriptEntry(role="user", text=msg.text, partial=True)
245
+ )
246
+ self._transcript = updated
247
+
248
+ entry = self._transcript[-1]
249
+ all_entries = list(self._transcript)
250
+
251
+ elif msg.type == "response":
252
+ self._assist_buf += msg.text
253
+ current_text = self._assist_buf
254
+
255
+ updated = [
256
+ e
257
+ for e in self._transcript
258
+ if not (e.role == "assistant" and e.partial)
259
+ ]
260
+ updated.append(
261
+ TranscriptEntry(role="assistant", text=current_text, partial=True)
262
+ )
263
+ self._transcript = updated
264
+
265
+ entry = self._transcript[-1]
266
+ all_entries = list(self._transcript)
267
+
268
+ elif msg.type == "error":
269
+ logger.error("Server error: %s", msg.message)
270
+ if self.events.on_error:
271
+ self.events.on_error(RuntimeError(msg.message))
272
+ return
273
+ else:
274
+ return
275
+
276
+ if self.events.on_transcript:
277
+ self.events.on_transcript(entry, all_entries)
@@ -0,0 +1,50 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from enum import Enum
5
+ from typing import Callable
6
+
7
+
8
+ class ConnectionStatus(str, Enum):
9
+ IDLE = "idle"
10
+ CONNECTING = "connecting"
11
+ CONNECTED = "connected"
12
+ ERROR = "error"
13
+ DISCONNECTED = "disconnected"
14
+
15
+
16
+ @dataclass
17
+ class TranscriptEntry:
18
+ role: str # "user" or "assistant"
19
+ text: str
20
+ partial: bool = False
21
+
22
+
23
+ @dataclass
24
+ class DataChannelMessage:
25
+ type: str # "transcript", "response", or "error"
26
+ text: str = ""
27
+ final: bool = False
28
+ message: str = "" # for error type
29
+
30
+
31
+ @dataclass
32
+ class Config:
33
+ """Configuration for a StreamCoreAIClient."""
34
+
35
+ whip_endpoint: str = "http://localhost:8080/whip"
36
+ ice_servers: list[str] = field(
37
+ default_factory=lambda: ["stun:stun.l.google.com:19302"]
38
+ )
39
+
40
+
41
+ @dataclass
42
+ class EventHandler:
43
+ """Callbacks for voice agent events. All callbacks are optional."""
44
+
45
+ on_status_change: Callable[[ConnectionStatus], None] | None = None
46
+ on_transcript: Callable[[TranscriptEntry, list[TranscriptEntry]], None] | None = (
47
+ None
48
+ )
49
+ on_error: Callable[[Exception], None] | None = None
50
+ on_data_channel_message: Callable[[DataChannelMessage], None] | None = None
@@ -0,0 +1,56 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from urllib.parse import urlparse, urlunparse
5
+
6
+ import aiohttp
7
+
8
+
9
+ @dataclass
10
+ class WhipResult:
11
+ answer_sdp: str
12
+ session_url: str
13
+
14
+
15
+ async def whip_offer(endpoint: str, offer_sdp: str) -> WhipResult:
16
+ """Perform a WHIP signaling exchange per RFC 9725 §4.2.
17
+
18
+ POST an SDP offer, receive a 201 Created with SDP answer and Location header.
19
+ """
20
+ async with aiohttp.ClientSession() as session:
21
+ async with session.post(
22
+ endpoint,
23
+ data=offer_sdp,
24
+ headers={"Content-Type": "application/sdp"},
25
+ ) as resp:
26
+ if resp.status != 201:
27
+ body = await resp.text()
28
+ raise RuntimeError(f"WHIP: unexpected status {resp.status}: {body}")
29
+
30
+ answer_sdp = await resp.text()
31
+
32
+ location = resp.headers.get("Location", "")
33
+ session_url = location
34
+ if location and not location.startswith("http"):
35
+ parsed = urlparse(endpoint)
36
+ session_url = urlunparse(
37
+ (parsed.scheme, parsed.netloc, location, "", "", "")
38
+ )
39
+
40
+ return WhipResult(answer_sdp=answer_sdp, session_url=session_url)
41
+
42
+
43
+ async def whip_delete(session_url: str) -> None:
44
+ """Terminate a WHIP session per RFC 9725 §4.2.
45
+
46
+ Send HTTP DELETE to the WHIP session URL. Best-effort; errors are ignored.
47
+ """
48
+ if not session_url:
49
+ return
50
+ try:
51
+ timeout = aiohttp.ClientTimeout(total=3)
52
+ async with aiohttp.ClientSession(timeout=timeout) as session:
53
+ async with session.delete(session_url):
54
+ pass
55
+ except Exception:
56
+ pass
@@ -0,0 +1,145 @@
1
+ Metadata-Version: 2.4
2
+ Name: streamcore
3
+ Version: 0.1.0
4
+ Summary: Python SDK for connecting to a Pion Voice Agent server via WebRTC + WHIP
5
+ License-Expression: Apache-2.0
6
+ Keywords: webrtc,whip,voice-agent,pion,real-time,audio
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: aiortc>=1.9.0
11
+ Requires-Dist: aiohttp>=3.9.0
12
+ Requires-Dist: av>=12.0.0
13
+ Requires-Dist: numpy>=1.24.0
14
+ Provides-Extra: dev
15
+ Requires-Dist: pytest; extra == "dev"
16
+ Requires-Dist: pytest-asyncio; extra == "dev"
17
+ Dynamic: license-file
18
+
19
+ # streamcore (Python)
20
+
21
+ Python SDK for connecting to a [streamcore](https://github.com/streamcore/streamcore-server) server via WebRTC + WHIP, powered by [aiortc](https://github.com/aiortc/aiortc).
22
+
23
+ ## Requirements
24
+
25
+ - **Python 3.10+**
26
+
27
+ ## Installation
28
+
29
+ ```bash
30
+ pip install streamcore
31
+ ```
32
+
33
+ Or install from source:
34
+
35
+ ```bash
36
+ cd python-sdk
37
+ pip install -e .
38
+ ```
39
+
40
+ ## Quick Start
41
+
42
+ ```python
43
+ import asyncio
44
+ import numpy as np
45
+ import streamcore
46
+
47
+
48
+ async def main():
49
+ def on_transcript(entry, all_entries):
50
+ print(f"[{entry.role}] {entry.text}")
51
+
52
+ client = streamcore.Client(
53
+ config=streamcore.Config(whip_endpoint="http://localhost:8080/whip"),
54
+ events=streamcore.EventHandler(
55
+ on_transcript=on_transcript,
56
+ on_error=lambda err: print(f"Error: {err}"),
57
+ ),
58
+ )
59
+
60
+ await client.connect()
61
+
62
+ # Send a 20 ms frame of silence
63
+ pcm = np.zeros(streamcore.FRAME_SIZE, dtype=np.int16)
64
+ await client.send_pcm(pcm)
65
+
66
+ # Receive decoded audio from the agent
67
+ audio = await client.recv_pcm() # numpy int16 array
68
+
69
+ await client.disconnect()
70
+
71
+
72
+ asyncio.run(main())
73
+ ```
74
+
75
+ ## API
76
+
77
+ ### `Client(config?, events?)`
78
+
79
+ Creates a new voice agent client.
80
+
81
+ #### `Config`
82
+
83
+ | Field | Type | Default | Description |
84
+ | --------------- | ------------ | ------------------------------ | --------------------------- |
85
+ | `whip_endpoint` | `str` | `"http://localhost:8080/whip"` | WHIP signaling endpoint URL |
86
+ | `ice_servers` | `list[str]` | `["stun:stun.l.google.com:19302"]` | ICE server URLs |
87
+
88
+ #### `EventHandler`
89
+
90
+ | Callback | Signature | Description |
91
+ | ------------------------ | --------------------------------------------------------------- | ------------------------------------- |
92
+ | `on_status_change` | `(status: ConnectionStatus) -> None` | Fired when connection status changes |
93
+ | `on_transcript` | `(entry: TranscriptEntry, all: list[TranscriptEntry]) -> None` | Fired on new or updated transcript |
94
+ | `on_error` | `(error: Exception) -> None` | Fired on connection or server errors |
95
+ | `on_data_channel_message`| `(msg: DataChannelMessage) -> None` | Fired for every raw DC message |
96
+
97
+ #### Methods
98
+
99
+ | Method | Description |
100
+ | ------------------------------- | ------------------------------------------------------------ |
101
+ | `await client.connect(track?)` | Connect via WHIP. Optionally pass an aiortc audio track. |
102
+ | `await client.disconnect()` | Tear down connection and free resources. |
103
+ | `await client.send_pcm(pcm)` | Send a numpy int16 PCM buffer (mono 48 kHz) to the agent. |
104
+ | `await client.recv_pcm()` | Receive decoded PCM audio as a numpy int16 array. |
105
+ | `client.status` | Current `ConnectionStatus`. |
106
+ | `client.transcript` | Current conversation as `list[TranscriptEntry]`. |
107
+ | `client.remote_track` | Inbound audio track from the agent (available after connect).|
108
+
109
+ #### Audio Constants
110
+
111
+ | Constant | Value | Description |
112
+ | ------------- | -------- | -------------------------------- |
113
+ | `SAMPLE_RATE` | `48000` | Audio sample rate in Hz |
114
+ | `CHANNELS` | `1` | Number of channels (mono) |
115
+ | `FRAME_SIZE` | `960` | Samples per 20 ms frame |
116
+
117
+ ## Audio I/O
118
+
119
+ The SDK handles aiortc track management, `av.AudioFrame` construction, and
120
+ resampling internally. Callers only deal with raw PCM data as numpy int16
121
+ arrays:
122
+
123
+ ```python
124
+ # Send microphone audio (960 samples = 20 ms at 48 kHz)
125
+ await client.send_pcm(pcm_int16)
126
+
127
+ # Receive agent audio
128
+ audio = await client.recv_pcm()
129
+ ```
130
+
131
+ If you need direct track access (e.g. for a custom aiortc pipeline), pass
132
+ your own `AudioStreamTrack` via `client.connect(user_track=my_track)`.
133
+
134
+ ## Dependencies
135
+
136
+ | Package | Purpose |
137
+ | -------- | ------------------------------ |
138
+ | `aiortc` | WebRTC stack |
139
+ | `aiohttp`| HTTP client for WHIP signaling |
140
+ | `av` | Audio frame encoding/decoding |
141
+ | `numpy` | PCM audio buffers |
142
+
143
+ ## License
144
+
145
+ Apache-2.0
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/streamcore/__init__.py
5
+ src/streamcore/audio.py
6
+ src/streamcore/client.py
7
+ src/streamcore/types.py
8
+ src/streamcore/whip.py
9
+ src/streamcore.egg-info/PKG-INFO
10
+ src/streamcore.egg-info/SOURCES.txt
11
+ src/streamcore.egg-info/dependency_links.txt
12
+ src/streamcore.egg-info/requires.txt
13
+ src/streamcore.egg-info/top_level.txt
@@ -0,0 +1,8 @@
1
+ aiortc>=1.9.0
2
+ aiohttp>=3.9.0
3
+ av>=12.0.0
4
+ numpy>=1.24.0
5
+
6
+ [dev]
7
+ pytest
8
+ pytest-asyncio
@@ -0,0 +1 @@
1
+ streamcore