phono-sdk 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.
- phono/__init__.py +14 -0
- phono/client.py +630 -0
- phono/errors.py +17 -0
- phono/events.py +58 -0
- phono/media.py +116 -0
- phono/webhook.py +24 -0
- phono_sdk-0.1.0.dist-info/METADATA +113 -0
- phono_sdk-0.1.0.dist-info/RECORD +10 -0
- phono_sdk-0.1.0.dist-info/WHEEL +4 -0
- phono_sdk-0.1.0.dist-info/licenses/LICENSE +21 -0
phono/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""Phono : appels, messages et vocaux pour vos agents.
|
|
2
|
+
|
|
3
|
+
Phono transporte la voix, il ne la produit pas : votre agent génère son audio,
|
|
4
|
+
Phono le livre — en vocal, ou en temps réel dans un appel.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from .client import Phono
|
|
8
|
+
from .errors import PhonoError
|
|
9
|
+
from .events import Event
|
|
10
|
+
from .media import MediaItem, MediaStream
|
|
11
|
+
from .webhook import parse_webhook, verify_signature
|
|
12
|
+
|
|
13
|
+
__all__ = ["Phono", "PhonoError", "Event", "MediaItem", "MediaStream", "parse_webhook", "verify_signature"]
|
|
14
|
+
__version__ = "0.1.0"
|
phono/client.py
ADDED
|
@@ -0,0 +1,630 @@
|
|
|
1
|
+
"""Le client de l'API Phono, asynchrone.
|
|
2
|
+
|
|
3
|
+
Phono transporte : il achemine les appels, les messages et les vocaux, mais ne
|
|
4
|
+
produit aucun son. Votre agent génère sa voix ; Phono la livre.
|
|
5
|
+
|
|
6
|
+
async with Phono("https://phonoapi.raucheacho.com", "phk_…") as phono:
|
|
7
|
+
await phono.messages.send("jean.acme", "Bonjour !")
|
|
8
|
+
call = await phono.calls.create("jean.acme")
|
|
9
|
+
async with phono.media(call["call"]["id"], rate=16000) as stream:
|
|
10
|
+
await stream.send(pcm) # votre voix, en PCM 16 bits
|
|
11
|
+
async for item in stream: # la sienne, et la fin de l'appel
|
|
12
|
+
...
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import os
|
|
18
|
+
from typing import Any, AsyncIterator, Optional, Union
|
|
19
|
+
from urllib.parse import quote
|
|
20
|
+
|
|
21
|
+
import httpx
|
|
22
|
+
|
|
23
|
+
from .errors import PhonoError
|
|
24
|
+
from .events import Event, parse_sse
|
|
25
|
+
from .media import MediaStream
|
|
26
|
+
|
|
27
|
+
#: L'API Phono en production.
|
|
28
|
+
DEFAULT_BASE_URL = "https://phonoapi.raucheacho.com"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _bare(handle: str) -> str:
|
|
32
|
+
"""« @alice » ou « alice » : l'API attend l'identifiant sans arobase."""
|
|
33
|
+
return quote(handle.lstrip("@"), safe="")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Phono:
|
|
37
|
+
"""Un client au nom d'une identité : une clé API (phk_…), un jeton
|
|
38
|
+
d'appareil (phd_…) ou un jeton client (pht_…).
|
|
39
|
+
|
|
40
|
+
Avec une clé serveur (phs_…), il gère les utilisateurs de votre
|
|
41
|
+
application (`identities`, `push_credentials`) et agit pour l'un d'eux
|
|
42
|
+
avec `as_()`.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
def __init__(
|
|
46
|
+
self,
|
|
47
|
+
base_url: str = "",
|
|
48
|
+
api_key: str = "",
|
|
49
|
+
*,
|
|
50
|
+
identity: Optional[str] = None,
|
|
51
|
+
timeout: float = 30.0,
|
|
52
|
+
http: Optional[httpx.AsyncClient] = None,
|
|
53
|
+
) -> None:
|
|
54
|
+
self.base_url = (base_url or os.environ.get("PHONO_URL", DEFAULT_BASE_URL)).rstrip("/")
|
|
55
|
+
self.api_key = api_key or os.environ.get("PHONO_API_KEY", "")
|
|
56
|
+
if not self.api_key:
|
|
57
|
+
raise ValueError("une clé API est requise (api_key, ou PHONO_API_KEY)")
|
|
58
|
+
self.identity = identity
|
|
59
|
+
self._http = http or httpx.AsyncClient(timeout=timeout)
|
|
60
|
+
self._own_http = http is None
|
|
61
|
+
self.messages = _Messages(self)
|
|
62
|
+
self.calls = _Calls(self)
|
|
63
|
+
self.contacts = _Contacts(self)
|
|
64
|
+
# phono.conversation.mute(id), .archive(id), .transfer(…) : ranger et passer la main.
|
|
65
|
+
self.conversation = _Conversations(self)
|
|
66
|
+
self.groups = _Groups(self)
|
|
67
|
+
# Avec une clé serveur : les utilisateurs de votre app, et vos clés de notification.
|
|
68
|
+
self.identities = _Identities(self)
|
|
69
|
+
self.push_credentials = _PushCredentials(self)
|
|
70
|
+
# Le talkie : des canaux où l'on parle à tour de rôle.
|
|
71
|
+
self.channels = _Channels(self)
|
|
72
|
+
|
|
73
|
+
def as_(self, identity: str) -> "Phono":
|
|
74
|
+
"""Avec une clé serveur : un client qui agit au nom d'une identité (son
|
|
75
|
+
id, son identifiant ou votre external_id). Il partage la connexion HTTP.
|
|
76
|
+
|
|
77
|
+
await server.as_("user_42").messages.send("support.acme", "Bonjour")
|
|
78
|
+
"""
|
|
79
|
+
other = Phono(self.base_url, self.api_key, identity=identity, http=self._http)
|
|
80
|
+
return other
|
|
81
|
+
|
|
82
|
+
async def __aenter__(self) -> "Phono":
|
|
83
|
+
return self
|
|
84
|
+
|
|
85
|
+
async def __aexit__(self, *exc: Any) -> None:
|
|
86
|
+
await self.close()
|
|
87
|
+
|
|
88
|
+
async def close(self) -> None:
|
|
89
|
+
if self._own_http:
|
|
90
|
+
await self._http.aclose()
|
|
91
|
+
|
|
92
|
+
# --- le transport HTTP ---------------------------------------------------
|
|
93
|
+
|
|
94
|
+
@property
|
|
95
|
+
def _auth(self) -> dict[str, str]:
|
|
96
|
+
h = {"Authorization": f"Bearer {self.api_key}"}
|
|
97
|
+
if self.identity:
|
|
98
|
+
h["X-Phono-Identity"] = self.identity
|
|
99
|
+
return h
|
|
100
|
+
|
|
101
|
+
async def request(self, method: str, path: str, *, json_body: Any = None, **kwargs: Any) -> Any:
|
|
102
|
+
resp = await self._http.request(
|
|
103
|
+
method, self.base_url + path, json=json_body, headers=self._auth, **kwargs
|
|
104
|
+
)
|
|
105
|
+
if resp.status_code >= 400:
|
|
106
|
+
try:
|
|
107
|
+
body = resp.json()
|
|
108
|
+
except ValueError:
|
|
109
|
+
body = {}
|
|
110
|
+
raise PhonoError(
|
|
111
|
+
resp.status_code,
|
|
112
|
+
body.get("error", "http_error"),
|
|
113
|
+
body.get("message", resp.text),
|
|
114
|
+
body.get("announcement"),
|
|
115
|
+
)
|
|
116
|
+
if resp.status_code == 204 or not resp.content:
|
|
117
|
+
return None
|
|
118
|
+
return resp.json()
|
|
119
|
+
|
|
120
|
+
# --- l'identité ------------------------------------------------------------
|
|
121
|
+
|
|
122
|
+
async def me(self) -> dict:
|
|
123
|
+
"""L'identifiant au nom duquel ce client agit, et son organisation."""
|
|
124
|
+
return await self.request("GET", "/v1/me")
|
|
125
|
+
|
|
126
|
+
async def announcements(self, lang: str | None = None) -> dict:
|
|
127
|
+
"""Les annonces d'opérateur de l'organisation, par code (`busy`,
|
|
128
|
+
`unavailable`, `not_assigned`) : {"code", "lang", "url"}."""
|
|
129
|
+
params = {"lang": lang} if lang else None
|
|
130
|
+
body = await self.request("GET", "/v1/announcements", params=params)
|
|
131
|
+
return body["announcements"]
|
|
132
|
+
|
|
133
|
+
async def lookup(self, handle: str) -> dict:
|
|
134
|
+
"""Un identifiant, et votre relation avec lui (`relation`)."""
|
|
135
|
+
return await self.request("GET", f"/v1/handles/{_bare(handle)}")
|
|
136
|
+
|
|
137
|
+
def avatar_url(self, handle: dict) -> Optional[str]:
|
|
138
|
+
"""L'adresse publique de la photo de profil d'un identifiant, ou None."""
|
|
139
|
+
avatar_id = handle.get("avatar_id")
|
|
140
|
+
return f"{self.base_url}/v1/avatars/{avatar_id}" if avatar_id else None
|
|
141
|
+
|
|
142
|
+
async def set_avatar(self, image: Union[bytes, str, os.PathLike]) -> dict:
|
|
143
|
+
"""Remplace votre photo de profil : JPEG, PNG ou WebP, 2 Mo au plus."""
|
|
144
|
+
if not isinstance(image, (bytes, bytearray)):
|
|
145
|
+
with open(os.fspath(image), "rb") as f:
|
|
146
|
+
image = f.read()
|
|
147
|
+
return await self.request("PUT", "/v1/me/avatar", files={"image": ("avatar", bytes(image))})
|
|
148
|
+
|
|
149
|
+
async def delete_avatar(self) -> dict:
|
|
150
|
+
return await self.request("DELETE", "/v1/me/avatar")
|
|
151
|
+
|
|
152
|
+
async def set_activity(self, to: str, state: str) -> None:
|
|
153
|
+
"""Annonce à `to` que vous écrivez (« typing »), préparez un vocal
|
|
154
|
+
(« recording ») ou avez fini (« idle »). Répétez toutes les 3 s tant
|
|
155
|
+
que ça dure : sans nouvelle, l'autre l'efface."""
|
|
156
|
+
await self.request("POST", "/v1/activity", json_body={"to": to, "state": state})
|
|
157
|
+
|
|
158
|
+
async def conversations(self, limit: int = 50) -> list[dict]:
|
|
159
|
+
return await self.request("GET", "/v1/conversations", params={"limit": limit})
|
|
160
|
+
|
|
161
|
+
# --- le temps réel ---------------------------------------------------------
|
|
162
|
+
|
|
163
|
+
async def events(self) -> AsyncIterator[Event]:
|
|
164
|
+
"""Les événements de l'identité, au fil de l'eau (Server-Sent Events) :
|
|
165
|
+
call.ringing, message.created, contact.requested…
|
|
166
|
+
|
|
167
|
+
async for ev in phono.events():
|
|
168
|
+
if ev.type == "call.ringing": ...
|
|
169
|
+
|
|
170
|
+
Le flux se reconnecte de lui-même après une coupure.
|
|
171
|
+
"""
|
|
172
|
+
async for ev in parse_sse(self._http, self.base_url + "/v1/events", self._auth):
|
|
173
|
+
yield ev
|
|
174
|
+
|
|
175
|
+
def media(self, call_id: str, *, rate: int = 16000, media_url: Optional[str] = None) -> MediaStream:
|
|
176
|
+
"""Le flux audio d'un appel où vous êtes (lancé, ou décroché) : vous
|
|
177
|
+
envoyez votre voix en PCM 16 bits mono à `rate` Hz, vous recevez celle
|
|
178
|
+
des autres au même format. À utiliser avec `async with`."""
|
|
179
|
+
return MediaStream(self, call_id, rate=rate, media_url=media_url)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
class _Messages:
|
|
183
|
+
def __init__(self, phono: Phono) -> None:
|
|
184
|
+
self._p = phono
|
|
185
|
+
|
|
186
|
+
async def send(
|
|
187
|
+
self,
|
|
188
|
+
to: str = "",
|
|
189
|
+
text: str = "",
|
|
190
|
+
*,
|
|
191
|
+
group: str = "",
|
|
192
|
+
reply_to: Optional[str] = None,
|
|
193
|
+
urgent: bool = False,
|
|
194
|
+
) -> dict:
|
|
195
|
+
"""Un message texte, à `to` ou dans un `group` ; en réponse à un
|
|
196
|
+
message précis avec `reply_to`. `urgent` : il passe la sourdine et le
|
|
197
|
+
mode Concentration — dans votre organisation seulement."""
|
|
198
|
+
body: dict[str, Any] = {"text": text}
|
|
199
|
+
if urgent:
|
|
200
|
+
body["urgent"] = True
|
|
201
|
+
if group:
|
|
202
|
+
body["group"] = group
|
|
203
|
+
else:
|
|
204
|
+
body["to"] = to
|
|
205
|
+
if reply_to:
|
|
206
|
+
body["reply_to"] = reply_to
|
|
207
|
+
return await self._p.request("POST", "/v1/messages", json_body=body)
|
|
208
|
+
|
|
209
|
+
async def edit(self, message_id: str, text: str) -> dict:
|
|
210
|
+
"""Corrige l'un de vos textes, dans les 15 minutes."""
|
|
211
|
+
return await self._p.request("PATCH", f"/v1/messages/{message_id}", json_body={"text": text})
|
|
212
|
+
|
|
213
|
+
async def delete(self, message_id: str) -> dict:
|
|
214
|
+
"""Supprime l'un de vos messages pour tout le monde."""
|
|
215
|
+
return await self._p.request("DELETE", f"/v1/messages/{message_id}")
|
|
216
|
+
|
|
217
|
+
async def send_file(
|
|
218
|
+
self,
|
|
219
|
+
to: str = "",
|
|
220
|
+
file: Union[bytes, str, os.PathLike, None] = None,
|
|
221
|
+
*,
|
|
222
|
+
filename: str = "fichier",
|
|
223
|
+
group: str = "",
|
|
224
|
+
caption: str = "",
|
|
225
|
+
reply_to: Optional[str] = None,
|
|
226
|
+
) -> dict:
|
|
227
|
+
"""Une photo (affichée dans le fil) ou un document, 25 Mo au plus —
|
|
228
|
+
des octets ou un chemin."""
|
|
229
|
+
if file is None:
|
|
230
|
+
raise ValueError("file est requis")
|
|
231
|
+
if not isinstance(file, (bytes, bytearray)):
|
|
232
|
+
path = os.fspath(file)
|
|
233
|
+
filename = os.path.basename(path)
|
|
234
|
+
with open(path, "rb") as f:
|
|
235
|
+
file = f.read()
|
|
236
|
+
data = {k: v for k, v in {"to": to, "group": group, "caption": caption, "reply_to": reply_to or ""}.items() if v}
|
|
237
|
+
return await self._p.request(
|
|
238
|
+
"POST", "/v1/messages/attachment", data=data, files={"file": (filename, bytes(file))}
|
|
239
|
+
)
|
|
240
|
+
|
|
241
|
+
async def send_location(
|
|
242
|
+
self, to: str = "", lat: float = 0, lng: float = 0, *, label: str = "", group: str = ""
|
|
243
|
+
) -> dict:
|
|
244
|
+
"""Une position, une fois — pas un suivi."""
|
|
245
|
+
body: dict[str, Any] = {"lat": lat, "lng": lng, "label": label}
|
|
246
|
+
body["group" if group else "to"] = group or to
|
|
247
|
+
return await self._p.request("POST", "/v1/messages/location", json_body=body)
|
|
248
|
+
|
|
249
|
+
async def search(self, query: str, *, limit: int = 30) -> list[dict]:
|
|
250
|
+
"""Cherche dans vos conversations (textes et transcriptions)."""
|
|
251
|
+
return await self._p.request("GET", "/v1/messages/search", params={"q": query, "limit": limit})
|
|
252
|
+
|
|
253
|
+
async def send_voice(
|
|
254
|
+
self,
|
|
255
|
+
to: str,
|
|
256
|
+
audio: Union[bytes, str, os.PathLike],
|
|
257
|
+
*,
|
|
258
|
+
sample_rate: Optional[int] = None,
|
|
259
|
+
filename: str = "voice",
|
|
260
|
+
) -> dict:
|
|
261
|
+
"""Un vocal : l'audio que vous avez produit — des octets ou un chemin.
|
|
262
|
+
Ogg Opus passe tel quel ; WAV, MP3, M4A, WebM, FLAC sont convertis par
|
|
263
|
+
Phono. Pour du PCM 16 bits mono brut, donnez `sample_rate`."""
|
|
264
|
+
if not isinstance(audio, (bytes, bytearray)):
|
|
265
|
+
path = os.fspath(audio)
|
|
266
|
+
filename = os.path.basename(path)
|
|
267
|
+
with open(path, "rb") as f:
|
|
268
|
+
audio = f.read()
|
|
269
|
+
data = {"to": to}
|
|
270
|
+
if sample_rate:
|
|
271
|
+
data["sample_rate"] = str(sample_rate)
|
|
272
|
+
return await self._p.request(
|
|
273
|
+
"POST", "/v1/messages/voice", data=data, files={"audio": (filename, bytes(audio))}
|
|
274
|
+
)
|
|
275
|
+
|
|
276
|
+
async def list(self, with_: str, *, limit: int = 50, before: Optional[str] = None) -> dict:
|
|
277
|
+
"""Le fil avec `with_`, le plus récent d'abord : {conversation_id, messages}."""
|
|
278
|
+
params: dict[str, Any] = {"with": with_.lstrip("@"), "limit": limit}
|
|
279
|
+
if before:
|
|
280
|
+
params["before"] = before
|
|
281
|
+
return await self._p.request("GET", "/v1/messages", params=params)
|
|
282
|
+
|
|
283
|
+
async def react(self, message_id: str, emoji: str) -> dict:
|
|
284
|
+
"""Pose votre réaction (un emoji) sur un message, ou remplace la vôtre."""
|
|
285
|
+
return await self._p.request("PUT", f"/v1/messages/{message_id}/reaction", json_body={"emoji": emoji})
|
|
286
|
+
|
|
287
|
+
async def unreact(self, message_id: str) -> dict:
|
|
288
|
+
"""Retire votre réaction."""
|
|
289
|
+
return await self._p.request("DELETE", f"/v1/messages/{message_id}/reaction")
|
|
290
|
+
|
|
291
|
+
async def mark_read(self, conversation_id: str) -> dict:
|
|
292
|
+
return await self._p.request("POST", f"/v1/conversations/{conversation_id}/read")
|
|
293
|
+
|
|
294
|
+
async def audio(self, media_id: str) -> bytes:
|
|
295
|
+
"""Le fichier d'un vocal (Ogg Opus)."""
|
|
296
|
+
resp = await self._p._http.get(f"{self._p.base_url}/v1/media/{media_id}", headers=self._p._auth)
|
|
297
|
+
if resp.status_code >= 400:
|
|
298
|
+
raise PhonoError(resp.status_code, "http_error", resp.text)
|
|
299
|
+
return resp.content
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
class _Calls:
|
|
303
|
+
def __init__(self, phono: Phono) -> None:
|
|
304
|
+
self._p = phono
|
|
305
|
+
|
|
306
|
+
async def create(self, to: str) -> dict:
|
|
307
|
+
"""Faire sonner `to`. Rend {call, audio} : vous êtes déjà dans l'appel,
|
|
308
|
+
ouvrez son flux audio avec `phono.media(call["call"]["id"])`."""
|
|
309
|
+
return await self._p.request("POST", "/v1/calls", json_body={"to": to})
|
|
310
|
+
|
|
311
|
+
async def connect(self, a: str, b: str) -> dict:
|
|
312
|
+
"""Mettre deux personnes en relation : les deux sonnent, l'appel a lieu
|
|
313
|
+
entre elles, sans vous."""
|
|
314
|
+
return await self._p.request("POST", "/v1/calls", json_body={"connect": [a, b]})
|
|
315
|
+
|
|
316
|
+
async def get(self, call_id: str) -> dict:
|
|
317
|
+
return await self._p.request("GET", f"/v1/calls/{call_id}")
|
|
318
|
+
|
|
319
|
+
async def list(self, limit: int = 50) -> list[dict]:
|
|
320
|
+
return await self._p.request("GET", "/v1/calls", params={"limit": limit})
|
|
321
|
+
|
|
322
|
+
async def answer(self, call_id: str) -> dict:
|
|
323
|
+
return await self._p.request("POST", f"/v1/calls/{call_id}/answer")
|
|
324
|
+
|
|
325
|
+
async def reject(self, call_id: str) -> dict:
|
|
326
|
+
return await self._p.request("POST", f"/v1/calls/{call_id}/reject")
|
|
327
|
+
|
|
328
|
+
async def hangup(self, call_id: str) -> dict:
|
|
329
|
+
return await self._p.request("POST", f"/v1/calls/{call_id}/hangup")
|
|
330
|
+
|
|
331
|
+
async def cancel(self, call_id: str) -> dict:
|
|
332
|
+
return await self._p.request("POST", f"/v1/calls/{call_id}/cancel")
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
class _Contacts:
|
|
336
|
+
"""Hors de votre organisation, on n'écrit et on n'appelle qu'un contact :
|
|
337
|
+
une demande, que l'autre accepte. Sinon : PhonoError `contact_required`."""
|
|
338
|
+
|
|
339
|
+
def __init__(self, phono: Phono) -> None:
|
|
340
|
+
self._p = phono
|
|
341
|
+
|
|
342
|
+
async def list(self) -> dict:
|
|
343
|
+
"""{team, contacts, recent}"""
|
|
344
|
+
return await self._p.request("GET", "/v1/contacts")
|
|
345
|
+
|
|
346
|
+
async def request(self, to: str, note: Optional[str] = None) -> dict:
|
|
347
|
+
body: dict[str, Any] = {"to": to}
|
|
348
|
+
if note:
|
|
349
|
+
body["note"] = note
|
|
350
|
+
return await self._p.request("POST", "/v1/contact-requests", json_body=body)
|
|
351
|
+
|
|
352
|
+
async def requests(self) -> dict:
|
|
353
|
+
"""{incoming, outgoing}"""
|
|
354
|
+
return await self._p.request("GET", "/v1/contact-requests")
|
|
355
|
+
|
|
356
|
+
async def accept(self, handle: str) -> dict:
|
|
357
|
+
return await self._p.request("POST", f"/v1/contact-requests/{_bare(handle)}/accept")
|
|
358
|
+
|
|
359
|
+
async def decline(self, handle: str) -> None:
|
|
360
|
+
await self._p.request("POST", f"/v1/contact-requests/{_bare(handle)}/decline")
|
|
361
|
+
|
|
362
|
+
async def remove(self, handle: str) -> None:
|
|
363
|
+
await self._p.request("DELETE", f"/v1/contacts/{_bare(handle)}")
|
|
364
|
+
|
|
365
|
+
async def block(self, handle: str) -> None:
|
|
366
|
+
await self._p.request("PUT", f"/v1/blocks/{_bare(handle)}")
|
|
367
|
+
|
|
368
|
+
async def unblock(self, handle: str) -> None:
|
|
369
|
+
await self._p.request("DELETE", f"/v1/blocks/{_bare(handle)}")
|
|
370
|
+
|
|
371
|
+
async def blocked(self) -> list[dict]:
|
|
372
|
+
return await self._p.request("GET", "/v1/blocks")
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
__all__ = ["Phono"]
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
class _Conversations:
|
|
379
|
+
"""Ranger ses conversations : sourdine, archives, accusés de réception."""
|
|
380
|
+
|
|
381
|
+
def __init__(self, phono: Phono) -> None:
|
|
382
|
+
self._p = phono
|
|
383
|
+
|
|
384
|
+
async def mute(self, conversation_id: str, until: Optional[str] = None) -> dict:
|
|
385
|
+
"""Coupe les notifications jusqu'à `until` (RFC 3339), ou pour toujours."""
|
|
386
|
+
return await self._p.request(
|
|
387
|
+
"PUT", f"/v1/conversations/{conversation_id}/mute", json_body={"until": until} if until else None
|
|
388
|
+
)
|
|
389
|
+
|
|
390
|
+
async def unmute(self, conversation_id: str) -> dict:
|
|
391
|
+
return await self._p.request("DELETE", f"/v1/conversations/{conversation_id}/mute")
|
|
392
|
+
|
|
393
|
+
async def archive(self, conversation_id: str, archived: bool = True) -> dict:
|
|
394
|
+
return await self._p.request("PUT" if archived else "DELETE", f"/v1/conversations/{conversation_id}/archive")
|
|
395
|
+
|
|
396
|
+
async def delivered(self, conversation_id: str) -> dict:
|
|
397
|
+
"""Vous avez reçu les messages de la conversation (✓✓ chez l'auteur)."""
|
|
398
|
+
return await self._p.request("POST", f"/v1/conversations/{conversation_id}/delivered")
|
|
399
|
+
|
|
400
|
+
async def transfer(self, with_: str, to: str, note: str = "") -> dict:
|
|
401
|
+
"""Passe votre conversation avec `with_` à `to`, de votre organisation."""
|
|
402
|
+
return await self._p.request("POST", "/v1/transfers", json_body={"with": with_, "to": to, "note": note})
|
|
403
|
+
|
|
404
|
+
async def transfer_history(self, transfer_id: str) -> dict:
|
|
405
|
+
"""L'échange qui précède un transfert reçu."""
|
|
406
|
+
return await self._p.request("GET", f"/v1/transfers/{transfer_id}/messages")
|
|
407
|
+
|
|
408
|
+
async def set_away(
|
|
409
|
+
self, message: str = "", *, always: bool = False, tz: str = "", days: Optional[dict] = None
|
|
410
|
+
) -> Any:
|
|
411
|
+
"""Votre réponse d'absence (envoyée en votre nom). Vide : la retire.
|
|
412
|
+
`days` : {"1": ["09:00", "18:00"], …}, 1 = lundi."""
|
|
413
|
+
if not message:
|
|
414
|
+
return await self._p.request("DELETE", "/v1/me/away")
|
|
415
|
+
body: dict[str, Any] = {"message": message, "always": always}
|
|
416
|
+
if days:
|
|
417
|
+
body["hours"] = {"tz": tz or "UTC", "days": days}
|
|
418
|
+
return await self._p.request("PUT", "/v1/me/away", json_body=body)
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
class _Groups:
|
|
422
|
+
"""Les petits groupes fermés : 12 membres au plus, joignables par vous."""
|
|
423
|
+
|
|
424
|
+
def __init__(self, phono: Phono) -> None:
|
|
425
|
+
self._p = phono
|
|
426
|
+
|
|
427
|
+
async def create(self, title: str, members: list[str]) -> dict:
|
|
428
|
+
return await self._p.request("POST", "/v1/groups", json_body={"title": title, "members": members})
|
|
429
|
+
|
|
430
|
+
async def get(self, group_id: str) -> dict:
|
|
431
|
+
return await self._p.request("GET", f"/v1/groups/{group_id}")
|
|
432
|
+
|
|
433
|
+
async def messages(self, group_id: str, *, limit: int = 50) -> dict:
|
|
434
|
+
return await self._p.request("GET", "/v1/messages", params={"group": group_id, "limit": limit})
|
|
435
|
+
|
|
436
|
+
async def rename(self, group_id: str, title: str) -> dict:
|
|
437
|
+
return await self._p.request("PATCH", f"/v1/groups/{group_id}", json_body={"title": title})
|
|
438
|
+
|
|
439
|
+
async def add(self, group_id: str, handle: str) -> dict:
|
|
440
|
+
return await self._p.request("POST", f"/v1/groups/{group_id}/members", json_body={"handle": handle})
|
|
441
|
+
|
|
442
|
+
async def remove(self, group_id: str, handle: str) -> None:
|
|
443
|
+
await self._p.request("DELETE", f"/v1/groups/{group_id}/members/{_bare(handle)}")
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
class _Identities:
|
|
447
|
+
"""Les utilisateurs de votre application, avec une clé serveur.
|
|
448
|
+
|
|
449
|
+
server = Phono(api_key=os.environ["PHONO_SERVER_KEY"])
|
|
450
|
+
await server.identities.create("Alice", external_id="user_42")
|
|
451
|
+
token = (await server.identities.token("user_42"))["token"] # pour son app
|
|
452
|
+
"""
|
|
453
|
+
|
|
454
|
+
def __init__(self, phono: Phono) -> None:
|
|
455
|
+
self._p = phono
|
|
456
|
+
|
|
457
|
+
async def create(
|
|
458
|
+
self, display_name: str, *, name: str = "", external_id: str = "", kind: str = "human"
|
|
459
|
+
) -> dict:
|
|
460
|
+
body: dict[str, Any] = {"display_name": display_name, "kind": kind}
|
|
461
|
+
if name:
|
|
462
|
+
body["name"] = name
|
|
463
|
+
if external_id:
|
|
464
|
+
body["external_id"] = external_id
|
|
465
|
+
return await self._p.request("POST", "/v1/identities", json_body=body)
|
|
466
|
+
|
|
467
|
+
async def list(self, limit: int = 50) -> list[dict]:
|
|
468
|
+
return await self._p.request("GET", "/v1/identities", params={"limit": limit})
|
|
469
|
+
|
|
470
|
+
async def get(self, ref: str) -> dict:
|
|
471
|
+
"""Par id, identifiant (alice.acme) ou external_id."""
|
|
472
|
+
return await self._p.request("GET", f"/v1/identities/{_quote(ref)}")
|
|
473
|
+
|
|
474
|
+
async def rename(self, ref: str, display_name: str) -> dict:
|
|
475
|
+
return await self._p.request("PATCH", f"/v1/identities/{_quote(ref)}", json_body={"display_name": display_name})
|
|
476
|
+
|
|
477
|
+
async def disable(self, ref: str) -> dict:
|
|
478
|
+
"""Coupe aussitôt tous ses jetons."""
|
|
479
|
+
return await self._p.request("PATCH", f"/v1/identities/{_quote(ref)}", json_body={"disabled": True})
|
|
480
|
+
|
|
481
|
+
async def enable(self, ref: str) -> dict:
|
|
482
|
+
return await self._p.request("PATCH", f"/v1/identities/{_quote(ref)}", json_body={"disabled": False})
|
|
483
|
+
|
|
484
|
+
async def token(self, ref: str, ttl_seconds: Optional[int] = None) -> dict:
|
|
485
|
+
"""Un jeton client (pht_…), de 60 s à 24 h ; une heure par défaut."""
|
|
486
|
+
body = {"ttl_seconds": ttl_seconds} if ttl_seconds else {}
|
|
487
|
+
return await self._p.request("POST", f"/v1/identities/{_quote(ref)}/tokens", json_body=body)
|
|
488
|
+
|
|
489
|
+
async def device(self, ref: str, name: str = "", platform: str = "") -> dict:
|
|
490
|
+
"""Un jeton d'appareil (phd_…), sans expiration : une app mobile qui sonne app fermée."""
|
|
491
|
+
return await self._p.request(
|
|
492
|
+
"POST", f"/v1/identities/{_quote(ref)}/devices", json_body={"name": name, "platform": platform}
|
|
493
|
+
)
|
|
494
|
+
|
|
495
|
+
async def devices(self, ref: str) -> list[dict]:
|
|
496
|
+
return await self._p.request("GET", f"/v1/identities/{_quote(ref)}/devices")
|
|
497
|
+
|
|
498
|
+
async def revoke_device(self, ref: str, device_id: str) -> None:
|
|
499
|
+
await self._p.request("DELETE", f"/v1/identities/{_quote(ref)}/devices/{_quote(device_id)}")
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
class _PushCredentials:
|
|
503
|
+
"""Les clés de notification de votre application. Les secrets entrent, ne ressortent jamais."""
|
|
504
|
+
|
|
505
|
+
def __init__(self, phono: Phono) -> None:
|
|
506
|
+
self._p = phono
|
|
507
|
+
|
|
508
|
+
async def get(self) -> dict:
|
|
509
|
+
return await self._p.request("GET", "/v1/push-credentials")
|
|
510
|
+
|
|
511
|
+
async def set_apns(
|
|
512
|
+
self,
|
|
513
|
+
key: Union[str, bytes, os.PathLike],
|
|
514
|
+
*,
|
|
515
|
+
key_id: str,
|
|
516
|
+
team_id: str,
|
|
517
|
+
bundle_id: str,
|
|
518
|
+
production: bool = True,
|
|
519
|
+
) -> dict:
|
|
520
|
+
"""La clé .p8 d'Apple : son contenu, ou le chemin du fichier."""
|
|
521
|
+
pem = _read_text(key, marker="PRIVATE KEY")
|
|
522
|
+
return await self._p.request(
|
|
523
|
+
"PUT",
|
|
524
|
+
"/v1/push-credentials/apns",
|
|
525
|
+
json_body={"key": pem, "key_id": key_id, "team_id": team_id, "bundle_id": bundle_id, "production": production},
|
|
526
|
+
)
|
|
527
|
+
|
|
528
|
+
async def set_fcm(self, service_account: Union[dict, str, bytes, os.PathLike]) -> dict:
|
|
529
|
+
"""Le compte de service Firebase : le dict, le texte JSON, ou le chemin du fichier."""
|
|
530
|
+
creds: Any = service_account
|
|
531
|
+
if not isinstance(service_account, dict):
|
|
532
|
+
creds = _read_text(service_account, marker="service_account")
|
|
533
|
+
return await self._p.request("PUT", "/v1/push-credentials/fcm", json_body={"credentials": creds})
|
|
534
|
+
|
|
535
|
+
async def clear(self, provider: str) -> dict:
|
|
536
|
+
"""Retire les clés d'Apple ("apns") ou de Google ("fcm")."""
|
|
537
|
+
return await self._p.request("DELETE", f"/v1/push-credentials/{provider}")
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def _quote(ref: str) -> str:
|
|
541
|
+
return quote(ref, safe="")
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
def _read_text(value: Union[str, bytes, os.PathLike], *, marker: str) -> str:
|
|
545
|
+
"""Le contenu tel quel s'il contient `marker`, sinon le fichier qu'il désigne."""
|
|
546
|
+
if isinstance(value, bytes):
|
|
547
|
+
return value.decode()
|
|
548
|
+
if isinstance(value, str) and marker in value:
|
|
549
|
+
return value
|
|
550
|
+
with open(os.fspath(value), encoding="utf-8") as f:
|
|
551
|
+
return f.read()
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
class _Channels:
|
|
555
|
+
"""Le talkie : des canaux fermés de votre organisation, où l'on parle à
|
|
556
|
+
tour de rôle comme à la radio. Votre agent écoute (les transmissions,
|
|
557
|
+
transcrites) et prend la parole avec l'audio qu'il a produit.
|
|
558
|
+
|
|
559
|
+
ch = await phono.channels.create("Livreurs", ["amina.acme", "karim.acme"])
|
|
560
|
+
await phono.channels.speak(ch["id"], "reponse.wav")
|
|
561
|
+
for t in await phono.channels.transmissions(ch["id"]):
|
|
562
|
+
print(t["speaker"]["handle"], t.get("transcript"))
|
|
563
|
+
"""
|
|
564
|
+
|
|
565
|
+
def __init__(self, phono: Phono) -> None:
|
|
566
|
+
self._p = phono
|
|
567
|
+
|
|
568
|
+
async def create(self, name: str, members: list[str], *, record: bool = True) -> dict:
|
|
569
|
+
return await self._p.request(
|
|
570
|
+
"POST", "/v1/channels", json_body={"name": name, "members": members, "record": record}
|
|
571
|
+
)
|
|
572
|
+
|
|
573
|
+
async def list(self) -> list[dict]:
|
|
574
|
+
return await self._p.request("GET", "/v1/channels")
|
|
575
|
+
|
|
576
|
+
async def get(self, channel_id: str) -> dict:
|
|
577
|
+
return await self._p.request("GET", f"/v1/channels/{_quote(channel_id)}")
|
|
578
|
+
|
|
579
|
+
async def rename(self, channel_id: str, name: str) -> dict:
|
|
580
|
+
return await self._p.request("PATCH", f"/v1/channels/{_quote(channel_id)}", json_body={"name": name})
|
|
581
|
+
|
|
582
|
+
async def add(self, channel_id: str, handle: str) -> dict:
|
|
583
|
+
return await self._p.request("POST", f"/v1/channels/{_quote(channel_id)}/members", json_body={"handle": handle})
|
|
584
|
+
|
|
585
|
+
async def remove(self, channel_id: str, handle: str) -> None:
|
|
586
|
+
"""Retire un membre ; avec votre propre identifiant, vous partez."""
|
|
587
|
+
await self._p.request("DELETE", f"/v1/channels/{_quote(channel_id)}/members/{_bare(handle)}")
|
|
588
|
+
|
|
589
|
+
async def delete(self, channel_id: str) -> None:
|
|
590
|
+
await self._p.request("DELETE", f"/v1/channels/{_quote(channel_id)}")
|
|
591
|
+
|
|
592
|
+
async def accept(self, channel_id: str) -> dict:
|
|
593
|
+
"""Accepte l'invitation d'un compte personnel à son canal
|
|
594
|
+
(`channel.invited`) : on l'entend désormais."""
|
|
595
|
+
return await self._p.request("POST", f"/v1/channels/{_quote(channel_id)}/accept")
|
|
596
|
+
|
|
597
|
+
async def decline(self, channel_id: str) -> None:
|
|
598
|
+
await self._p.request("POST", f"/v1/channels/{_quote(channel_id)}/decline")
|
|
599
|
+
|
|
600
|
+
async def transmissions(self, channel_id: str, *, limit: int = 50, before: Optional[str] = None) -> list[dict]:
|
|
601
|
+
"""Les prises de parole, la plus récente d'abord ; `transcript` pour une entreprise."""
|
|
602
|
+
params: dict[str, Any] = {"limit": limit}
|
|
603
|
+
if before:
|
|
604
|
+
params["before"] = before
|
|
605
|
+
return await self._p.request("GET", f"/v1/channels/{_quote(channel_id)}/transmissions", params=params)
|
|
606
|
+
|
|
607
|
+
async def speak(
|
|
608
|
+
self,
|
|
609
|
+
channel_id: str,
|
|
610
|
+
audio: Union[bytes, str, os.PathLike],
|
|
611
|
+
*,
|
|
612
|
+
sample_rate: Optional[int] = None,
|
|
613
|
+
filename: str = "audio",
|
|
614
|
+
) -> dict:
|
|
615
|
+
"""Prend la parole avec l'audio que vous avez produit (octets ou chemin ;
|
|
616
|
+
WAV, MP3, Ogg Opus… ou PCM 16 bits mono avec `sample_rate`). Phono prend
|
|
617
|
+
le canal à votre nom et le diffuse en temps réel. PhonoError 409
|
|
618
|
+
`floor_busy` si quelqu'un parle : on ne coupe pas la parole."""
|
|
619
|
+
if not isinstance(audio, (bytes, bytearray)):
|
|
620
|
+
path = os.fspath(audio)
|
|
621
|
+
filename = os.path.basename(path)
|
|
622
|
+
with open(path, "rb") as f:
|
|
623
|
+
audio = f.read()
|
|
624
|
+
data = {"sample_rate": str(sample_rate)} if sample_rate else {}
|
|
625
|
+
return await self._p.request(
|
|
626
|
+
"POST",
|
|
627
|
+
f"/v1/channels/{_quote(channel_id)}/transmissions",
|
|
628
|
+
data=data,
|
|
629
|
+
files={"audio": (filename, bytes(audio))},
|
|
630
|
+
)
|
phono/errors.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Les erreurs de l'API Phono."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class PhonoError(Exception):
|
|
7
|
+
"""Une réponse d'erreur de l'API : `status` HTTP, `code` stable
|
|
8
|
+
(`contact_required`, `busy`, `handle_not_found`…) et `message` lisible."""
|
|
9
|
+
|
|
10
|
+
def __init__(self, status: int, code: str, message: str, announcement: dict | None = None) -> None:
|
|
11
|
+
super().__init__(f"{status} {code}: {message}")
|
|
12
|
+
self.status = status
|
|
13
|
+
self.code = code
|
|
14
|
+
self.message = message
|
|
15
|
+
# Un appel qui n'aboutit pas : l'annonce d'opérateur à jouer,
|
|
16
|
+
# {"code": "busy", "lang": "fr", "url": "…"}.
|
|
17
|
+
self.announcement = announcement
|
phono/events.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Le flux d'événements (GET /v1/events), en Server-Sent Events."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from typing import Any, AsyncIterator
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class Event:
|
|
15
|
+
"""Un événement : `type` (call.ringing, message.created…) et `data`, la
|
|
16
|
+
même enveloppe que les webhooks."""
|
|
17
|
+
|
|
18
|
+
id: str
|
|
19
|
+
type: str
|
|
20
|
+
created_at: str
|
|
21
|
+
data: dict = field(default_factory=dict)
|
|
22
|
+
|
|
23
|
+
@classmethod
|
|
24
|
+
def from_json(cls, raw: str) -> "Event":
|
|
25
|
+
d: dict[str, Any] = json.loads(raw)
|
|
26
|
+
return cls(id=d.get("id", ""), type=d.get("type", ""), created_at=d.get("created_at", ""), data=d.get("data") or {})
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
async def parse_sse(http: httpx.AsyncClient, url: str, headers: dict[str, str]) -> AsyncIterator[Event]:
|
|
30
|
+
"""Lit le flux et se reconnecte après une coupure, au rythme que le
|
|
31
|
+
serveur annonce (`retry:`)."""
|
|
32
|
+
retry = 3.0
|
|
33
|
+
while True:
|
|
34
|
+
try:
|
|
35
|
+
async with http.stream("GET", url, headers={**headers, "Accept": "text/event-stream"}, timeout=None) as resp:
|
|
36
|
+
if resp.status_code in (401, 403):
|
|
37
|
+
from .errors import PhonoError
|
|
38
|
+
|
|
39
|
+
raise PhonoError(resp.status_code, "unauthorized", "clé refusée")
|
|
40
|
+
resp.raise_for_status()
|
|
41
|
+
data: list[str] = []
|
|
42
|
+
async for line in resp.aiter_lines():
|
|
43
|
+
if line == "":
|
|
44
|
+
if data:
|
|
45
|
+
yield Event.from_json("\n".join(data))
|
|
46
|
+
data = []
|
|
47
|
+
continue
|
|
48
|
+
if line.startswith(":"):
|
|
49
|
+
continue # commentaire : la pulsation du serveur
|
|
50
|
+
name, _, value = line.partition(":")
|
|
51
|
+
value = value[1:] if value.startswith(" ") else value
|
|
52
|
+
if name == "data":
|
|
53
|
+
data.append(value)
|
|
54
|
+
elif name == "retry" and value.isdigit():
|
|
55
|
+
retry = int(value) / 1000
|
|
56
|
+
except (httpx.TransportError, httpx.HTTPStatusError):
|
|
57
|
+
pass
|
|
58
|
+
await asyncio.sleep(retry)
|
phono/media.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""Le flux audio d'un appel, en PCM, par la passerelle phono-media.
|
|
2
|
+
|
|
3
|
+
Phono transporte : vous envoyez la voix que votre agent produit, Phono la
|
|
4
|
+
livre en temps réel, et vous rend celle d'en face.
|
|
5
|
+
|
|
6
|
+
async with phono.media(call_id, rate=16000) as stream:
|
|
7
|
+
await stream.send(pcm) # bytes, PCM 16 bits LE mono
|
|
8
|
+
async for item in stream:
|
|
9
|
+
if item.type == "audio":
|
|
10
|
+
stt.feed(item.pcm) # ce que dit l'autre
|
|
11
|
+
elif item.type == "drained":
|
|
12
|
+
... # votre phrase est partie en entier
|
|
13
|
+
elif item.type == "end":
|
|
14
|
+
break # l'appel est fini
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import json
|
|
20
|
+
from dataclasses import dataclass, field
|
|
21
|
+
from typing import TYPE_CHECKING, Any, AsyncIterator, Optional
|
|
22
|
+
from urllib.parse import urlencode
|
|
23
|
+
|
|
24
|
+
import websockets
|
|
25
|
+
|
|
26
|
+
from .errors import PhonoError
|
|
27
|
+
|
|
28
|
+
if TYPE_CHECKING:
|
|
29
|
+
from .client import Phono
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass
|
|
33
|
+
class MediaItem:
|
|
34
|
+
"""Ce que rend le flux : `audio` (avec `pcm`), `start`, `drained` ou `end`."""
|
|
35
|
+
|
|
36
|
+
type: str
|
|
37
|
+
pcm: bytes = b""
|
|
38
|
+
info: dict = field(default_factory=dict)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class MediaStream:
|
|
42
|
+
def __init__(self, phono: "Phono", call_id: str, *, rate: int, media_url: Optional[str]) -> None:
|
|
43
|
+
self._phono = phono
|
|
44
|
+
self.call_id = call_id
|
|
45
|
+
self.rate = rate
|
|
46
|
+
self._media_url = media_url
|
|
47
|
+
self._ws: Any = None
|
|
48
|
+
self.started: dict = {}
|
|
49
|
+
|
|
50
|
+
async def __aenter__(self) -> "MediaStream":
|
|
51
|
+
await self.open()
|
|
52
|
+
return self
|
|
53
|
+
|
|
54
|
+
async def __aexit__(self, *exc: Any) -> None:
|
|
55
|
+
await self.close()
|
|
56
|
+
|
|
57
|
+
async def open(self) -> None:
|
|
58
|
+
base = self._media_url
|
|
59
|
+
if not base:
|
|
60
|
+
# L'adresse de la passerelle vient avec les identifiants audio.
|
|
61
|
+
creds = await self._phono.request("POST", f"/v1/calls/{self.call_id}/audio")
|
|
62
|
+
base = (creds or {}).get("media_url")
|
|
63
|
+
if not base:
|
|
64
|
+
raise PhonoError(501, "no_media_gateway", "aucune passerelle audio annoncée par l'API")
|
|
65
|
+
url = f"{base.rstrip('/')}/v1/calls/{self.call_id}/media?{urlencode({'rate': self.rate})}"
|
|
66
|
+
try:
|
|
67
|
+
self._ws = await websockets.connect(
|
|
68
|
+
url,
|
|
69
|
+
additional_headers={"Authorization": f"Bearer {self._phono.api_key}"},
|
|
70
|
+
max_size=2**20,
|
|
71
|
+
)
|
|
72
|
+
except websockets.InvalidStatus as e: # refus avant l'ouverture
|
|
73
|
+
body = e.response.body or b"{}"
|
|
74
|
+
try:
|
|
75
|
+
err = json.loads(body)
|
|
76
|
+
except ValueError:
|
|
77
|
+
err = {}
|
|
78
|
+
raise PhonoError(e.response.status_code, err.get("error", "media_refused"), err.get("message", "")) from e
|
|
79
|
+
first = json.loads(await self._ws.recv())
|
|
80
|
+
if first.get("type") != "start":
|
|
81
|
+
raise PhonoError(502, "media_protocol", f"début de flux inattendu : {first}")
|
|
82
|
+
self.started = first
|
|
83
|
+
|
|
84
|
+
async def send(self, pcm: bytes) -> None:
|
|
85
|
+
"""Votre voix : PCM 16 bits little-endian mono à `rate` Hz, en morceaux
|
|
86
|
+
de n'importe quelle taille. Mise en file, elle part au rythme réel."""
|
|
87
|
+
await self._ws.send(bytes(pcm))
|
|
88
|
+
|
|
89
|
+
async def clear(self) -> None:
|
|
90
|
+
"""Couper ce qui n'est pas encore parti : l'autre a repris la parole."""
|
|
91
|
+
await self._ws.send(json.dumps({"type": "clear"}))
|
|
92
|
+
|
|
93
|
+
async def close(self) -> None:
|
|
94
|
+
if self._ws is not None:
|
|
95
|
+
try:
|
|
96
|
+
await self._ws.send(json.dumps({"type": "stop"}))
|
|
97
|
+
except websockets.ConnectionClosed:
|
|
98
|
+
pass
|
|
99
|
+
await self._ws.close()
|
|
100
|
+
self._ws = None
|
|
101
|
+
|
|
102
|
+
def __aiter__(self) -> AsyncIterator[MediaItem]:
|
|
103
|
+
return self._items()
|
|
104
|
+
|
|
105
|
+
async def _items(self) -> AsyncIterator[MediaItem]:
|
|
106
|
+
try:
|
|
107
|
+
async for msg in self._ws:
|
|
108
|
+
if isinstance(msg, bytes):
|
|
109
|
+
yield MediaItem("audio", pcm=msg)
|
|
110
|
+
continue
|
|
111
|
+
info = json.loads(msg)
|
|
112
|
+
yield MediaItem(info.get("type", ""), info=info)
|
|
113
|
+
if info.get("type") == "end":
|
|
114
|
+
return
|
|
115
|
+
except websockets.ConnectionClosed:
|
|
116
|
+
return
|
phono/webhook.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Vérifier un webhook Phono : l'en-tête X-Phono-Signature est
|
|
2
|
+
« sha256=<hex> », HMAC-SHA256 du corps brut avec le secret du point."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import hashlib
|
|
7
|
+
import hmac
|
|
8
|
+
|
|
9
|
+
from .events import Event
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def verify_signature(secret: str, body: bytes, signature: str) -> bool:
|
|
13
|
+
expected = "sha256=" + hmac.new(secret.encode(), body, hashlib.sha256).hexdigest()
|
|
14
|
+
return hmac.compare_digest(expected, signature or "")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def parse_webhook(secret: str, body: bytes, signature: str) -> Event:
|
|
18
|
+
"""L'événement, si la signature est bonne ; sinon ValueError."""
|
|
19
|
+
if not verify_signature(secret, body, signature):
|
|
20
|
+
raise ValueError("signature Phono invalide")
|
|
21
|
+
return Event.from_json(body.decode())
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
__all__ = ["verify_signature", "parse_webhook"]
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: phono-sdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Phono : appels, messages et vocaux pour vos agents — le transport, pas la voix.
|
|
5
|
+
License: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Requires-Python: >=3.10
|
|
8
|
+
Requires-Dist: httpx>=0.27
|
|
9
|
+
Requires-Dist: websockets>=13
|
|
10
|
+
Provides-Extra: dev
|
|
11
|
+
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
|
|
12
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
|
|
15
|
+
# phono — le SDK Python
|
|
16
|
+
|
|
17
|
+
Appels, messages et vocaux pour vos agents. **Phono transporte la voix, il ne la produit pas** : votre agent génère son audio (avec le moteur de synthèse de son choix), Phono le livre — en vocal, ou en temps réel dans un appel — et lui rend la voix d'en face.
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
pip install phono-sdk # Python ≥ 3.10, asyncio
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
from phono import Phono
|
|
25
|
+
|
|
26
|
+
async with Phono("https://phonoapi.raucheacho.com", "phk_…") as phono: # ou PHONO_URL, PHONO_API_KEY
|
|
27
|
+
await phono.messages.send("jean.acme", "Votre commande est prête.")
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Messages et vocaux
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
await phono.messages.send("alice", "Bonjour !")
|
|
34
|
+
|
|
35
|
+
# Un vocal : l'audio que VOTRE agent a produit. Ogg Opus passe tel quel ;
|
|
36
|
+
# WAV, MP3, M4A, WebM, FLAC sont convertis par Phono.
|
|
37
|
+
await phono.messages.send_voice("alice", "reponse.wav")
|
|
38
|
+
await phono.messages.send_voice("alice", tts_bytes) # des octets
|
|
39
|
+
await phono.messages.send_voice("alice", pcm, sample_rate=24000) # PCM 16 bits brut
|
|
40
|
+
|
|
41
|
+
thread = await phono.messages.list(with_="alice", limit=20) # le plus récent d'abord
|
|
42
|
+
for m in thread["messages"]:
|
|
43
|
+
print(m["kind"], m.get("body") or m.get("transcript"))
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Un vocal reçu arrive avec sa **transcription** (`transcript`, puis l'événement `message.transcribed`) quand une entreprise est d'un côté de la conversation.
|
|
47
|
+
|
|
48
|
+
## Les événements
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
async for ev in phono.events(): # Server-Sent Events, reconnexion automatique
|
|
52
|
+
if ev.type == "message.created":
|
|
53
|
+
print(ev.data["sender"]["handle"], ev.data["message"]["body"])
|
|
54
|
+
elif ev.type == "call.ringing":
|
|
55
|
+
call = ev.data
|
|
56
|
+
await phono.calls.answer(call["id"])
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Les mêmes événements partent en webhooks signés :
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
from phono import parse_webhook
|
|
63
|
+
event = parse_webhook(secret, request_body, request.headers["X-Phono-Signature"])
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## Les appels, en temps réel
|
|
67
|
+
|
|
68
|
+
Un appel, c'est un canal audio. Ouvrez son **flux média** : vous envoyez la voix de votre agent en PCM 16 bits little-endian mono, vous recevez celle de l'autre au même format.
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
placed = await phono.calls.create("alice") # alice sonne ; vous êtes dans l'appel
|
|
72
|
+
call_id = placed["call"]["id"]
|
|
73
|
+
|
|
74
|
+
async with phono.media(call_id, rate=16000) as stream:
|
|
75
|
+
await stream.send(greeting_pcm) # n'importe quelle taille : Phono cadence
|
|
76
|
+
|
|
77
|
+
async for item in stream:
|
|
78
|
+
if item.type == "audio":
|
|
79
|
+
transcriber.feed(item.pcm) # ce que dit alice, trame par trame
|
|
80
|
+
elif item.type == "drained":
|
|
81
|
+
pass # votre phrase est partie en entier
|
|
82
|
+
elif item.type == "end":
|
|
83
|
+
break # quelqu'un a raccroché
|
|
84
|
+
|
|
85
|
+
# L'autre reprend la parole pendant que vous parlez ? Coupez :
|
|
86
|
+
# await stream.clear()
|
|
87
|
+
|
|
88
|
+
await phono.calls.hangup(call_id)
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
`rate` : 8000, 16000, 24000 ou 48000. Pour un appel entrant, `await phono.calls.answer(call_id)`, puis `phono.media(call_id)`.
|
|
92
|
+
|
|
93
|
+
Mettre deux personnes en relation, sans être dans l'appel : `await phono.calls.connect("jean.acme", "alice")`.
|
|
94
|
+
|
|
95
|
+
## Les contacts
|
|
96
|
+
|
|
97
|
+
Hors de votre organisation, on n'écrit et on n'appelle qu'un **contact** : une demande, que l'autre accepte. Sinon, `PhonoError` avec `code == "contact_required"`.
|
|
98
|
+
|
|
99
|
+
```python
|
|
100
|
+
await phono.contacts.request("alice", note="Le support d'Acme, pour votre commande")
|
|
101
|
+
pending = await phono.contacts.requests() # {incoming, outgoing}
|
|
102
|
+
await phono.contacts.accept("bob")
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
## Les erreurs
|
|
106
|
+
|
|
107
|
+
```python
|
|
108
|
+
from phono import PhonoError
|
|
109
|
+
try:
|
|
110
|
+
await phono.calls.create("alice")
|
|
111
|
+
except PhonoError as e:
|
|
112
|
+
print(e.status, e.code, e.message) # 409 busy « @alice est déjà en ligne »
|
|
113
|
+
```
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
phono/__init__.py,sha256=PmzI5lQL3fS2cPlPn6h6eppl_DfAfuT0_adE4sNMAN0,513
|
|
2
|
+
phono/client.py,sha256=4YuPDhwt3RDm7iSF2K8VOfRS7F3aGtoN0bETvR5ibKo,27023
|
|
3
|
+
phono/errors.py,sha256=FJZtWKE0pWOTgKOg9Av9UcbaGHVgxaKllJYJTTPms68,666
|
|
4
|
+
phono/events.py,sha256=QgNaSoC4hdl0srUpMrKsbC1Jzt7NjOWYh2jzW7QneNs,2166
|
|
5
|
+
phono/media.py,sha256=5oNm4U7iLmlOFVPW5pWtjLX7ybi9cZU1Uv6xLHb1LOk,4236
|
|
6
|
+
phono/webhook.py,sha256=tceh_D0KoyjHGp4SJFPYiTQFWxLYBJUCxN-OgstB5dI,791
|
|
7
|
+
phono_sdk-0.1.0.dist-info/METADATA,sha256=TahWxx29smxTdmYp7Z8lgUPM2R4LoS8pxkyDodqqL-I,4196
|
|
8
|
+
phono_sdk-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
9
|
+
phono_sdk-0.1.0.dist-info/licenses/LICENSE,sha256=UpHBDXIz64nkJM_xuYqCtauMX-heeYnixsgkTsty8U0,1068
|
|
10
|
+
phono_sdk-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Rauche Acho
|
|
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.
|