namu-ai 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.
- namu_ai-0.1.0/.gitignore +5 -0
- namu_ai-0.1.0/CHANGELOG.md +7 -0
- namu_ai-0.1.0/LICENSE +202 -0
- namu_ai-0.1.0/PKG-INFO +137 -0
- namu_ai-0.1.0/README.md +111 -0
- namu_ai-0.1.0/pyproject.toml +46 -0
- namu_ai-0.1.0/src/namu/__init__.py +33 -0
- namu_ai-0.1.0/src/namu/_client.py +195 -0
- namu_ai-0.1.0/src/namu/_errors.py +112 -0
- namu_ai-0.1.0/src/namu/_version.py +1 -0
- namu_ai-0.1.0/src/namu/py.typed +0 -0
- namu_ai-0.1.0/src/namu/types.py +84 -0
- namu_ai-0.1.0/tests/test_client.py +190 -0
- namu_ai-0.1.0/tests/test_live.py +22 -0
namu_ai-0.1.0/.gitignore
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0 (8 November 2026)
|
|
4
|
+
|
|
5
|
+
First version: `Namu` with `speech`, `transcribe`, `translate`, `converse`, `usage`, `voices` and `models`; typed
|
|
6
|
+
responses; one error class per status; retries for network errors, `rate_limited` and 502/503/504; timeouts; the
|
|
7
|
+
`NAMU_API_KEY` and `NAMU_BASE_URL` environment variables.
|
namu_ai-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
namu_ai-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: namu-ai
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: The Namu API for Python: speech recognition, speech synthesis and translation for Hausa, Zarma and French.
|
|
5
|
+
Project-URL: Homepage, https://www.namuai-lab.com/api
|
|
6
|
+
Project-URL: Documentation, https://www.namuai-lab.com/docs
|
|
7
|
+
Author-email: Namu AI Lab <contact@namuai.org>
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: french,hausa,namu,sahel,speech,speech-to-text,text-to-speech,translation,zarma
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
15
|
+
Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
|
|
16
|
+
Classifier: Typing :: Typed
|
|
17
|
+
Requires-Python: >=3.9
|
|
18
|
+
Requires-Dist: requests<3,>=2.28
|
|
19
|
+
Requires-Dist: typing-extensions>=4.5; python_version < '3.11'
|
|
20
|
+
Provides-Extra: dev
|
|
21
|
+
Requires-Dist: build>=1.2; extra == 'dev'
|
|
22
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
23
|
+
Requires-Dist: responses>=0.25; extra == 'dev'
|
|
24
|
+
Requires-Dist: twine>=5; extra == 'dev'
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# Namu API for Python
|
|
28
|
+
|
|
29
|
+
Speech recognition, speech synthesis, translation and a voice agent for **Hausa, Zarma and French**, from Python.
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install namu-ai
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
from namu import Namu
|
|
37
|
+
|
|
38
|
+
client = Namu() # reads NAMU_API_KEY
|
|
39
|
+
|
|
40
|
+
audio = client.speech("Sannu da zuwa! Muna farin cikin jin muryarku.", voice="nadia", format="mp3")
|
|
41
|
+
open("welcome.mp3", "wb").write(audio)
|
|
42
|
+
|
|
43
|
+
print(client.transcribe("welcome.mp3", language="ha")["text"])
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Get a key at [namuai-lab.com/account/keys](https://www.namuai-lab.com/account/keys) and keep it on your server: never in
|
|
47
|
+
a mobile app or a web page. During the beta every account gets 30 minutes of audio a month, free.
|
|
48
|
+
|
|
49
|
+
## Usage
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
# Text to speech: Hausa (nadia), Zarma and Hausa (mouhamad), French (fr); wav, mp3 or opus
|
|
53
|
+
audio = client.speech("Fofo! Mate ni go?", voice="mouhamad", language="dje", format="opus")
|
|
54
|
+
|
|
55
|
+
# Speech to text: a path, bytes or an open file; ha, dje or fr (not detected: say which)
|
|
56
|
+
result = client.transcribe("voice-note.ogg", language="ha")
|
|
57
|
+
|
|
58
|
+
# Translation, Hausa ⇄ French, from text or speech, optionally spoken back (base64 WAV)
|
|
59
|
+
fr = client.translate("Ina kwana? Yau za a yi zafi sosai.", source="ha", target="fr")
|
|
60
|
+
spoken = client.translate(audio="question.ogg", source="ha", target="fr", include_audio=True)
|
|
61
|
+
|
|
62
|
+
# Voice agent (research preview; the key needs the converse scope)
|
|
63
|
+
turn = client.converse("hello.ogg", session_id="demo-42")
|
|
64
|
+
|
|
65
|
+
# Account and catalogue
|
|
66
|
+
client.usage() # {'month_audio_seconds_used': 312.4, 'month_audio_seconds_limit': 1800.0}
|
|
67
|
+
client.voices() # no key needed
|
|
68
|
+
client.models()
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Responses are plain dictionaries, typed with `TypedDict` (`namu.types`) for your editor.
|
|
72
|
+
|
|
73
|
+
## Errors
|
|
74
|
+
|
|
75
|
+
Every error is a `NamuError`. Errors the API answered carry its stable `type`, the HTTP `status`, a `message` and the
|
|
76
|
+
`request_id` to send Namu.
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
from namu import Namu, NamuError, QuotaExceededError, BadRequestError
|
|
80
|
+
|
|
81
|
+
try:
|
|
82
|
+
audio = client.speech(text)
|
|
83
|
+
except QuotaExceededError:
|
|
84
|
+
... # this month's allowance is used
|
|
85
|
+
except BadRequestError as e:
|
|
86
|
+
print(e.type, e.message) # unknown_voice, unsupported_language, missing_text, ...
|
|
87
|
+
except NamuError as e:
|
|
88
|
+
print(e.status, e.type, e.request_id)
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
| Class | Status | `type` |
|
|
92
|
+
| --- | --- | --- |
|
|
93
|
+
| `BadRequestError` | 400 | `invalid_request`, `invalid_json`, `missing_text`, `missing_file`, `empty_audio`, `unknown_voice`, `unsupported_language`, `unsupported_pair`, `unknown_persona` |
|
|
94
|
+
| `AuthenticationError` | 401 | `missing_api_key`, `invalid_api_key`, `key_revoked` |
|
|
95
|
+
| `PermissionDeniedError` | 403 | `insufficient_scope`, `account_paused` |
|
|
96
|
+
| `PayloadTooLargeError` | 413 | `payload_too_large`, `audio_too_long`, `text_too_long` |
|
|
97
|
+
| `UnsupportedAudioError` | 415 | `unsupported_audio` |
|
|
98
|
+
| `NothingHeardError` | 422 | `nothing_heard` |
|
|
99
|
+
| `RateLimitError` / `QuotaExceededError` | 429 | `rate_limited` / `quota_exceeded` |
|
|
100
|
+
| `InternalServerError` | 5xx | `internal_error`, `upstream_error`, `upstream_timeout`, ... |
|
|
101
|
+
| `APIConnectionError` / `APITimeoutError` | none | the API could not be reached, or did not answer in time |
|
|
102
|
+
|
|
103
|
+
## Retries and timeouts
|
|
104
|
+
|
|
105
|
+
Network errors, `429 rate_limited` and `502`/`503`/`504` are retried up to 3 times, after `Retry-After` or 1, 2, 4
|
|
106
|
+
seconds (with jitter). `quota_exceeded` and other 4xx never are. The default timeout is 300 seconds: the first request
|
|
107
|
+
after a quiet spell can take a minute while a model wakes up.
|
|
108
|
+
|
|
109
|
+
```python
|
|
110
|
+
client = Namu(timeout=120, max_retries=5)
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
## Configuration
|
|
114
|
+
|
|
115
|
+
| Argument | Environment | Default |
|
|
116
|
+
| --- | --- | --- |
|
|
117
|
+
| `api_key` | `NAMU_API_KEY` | none |
|
|
118
|
+
| `base_url` | `NAMU_BASE_URL` | `https://api.namuai-lab.com` |
|
|
119
|
+
| `timeout` | | 300 seconds |
|
|
120
|
+
| `max_retries` | | 3 |
|
|
121
|
+
| `session` | | a new `requests.Session` |
|
|
122
|
+
|
|
123
|
+
## Data
|
|
124
|
+
|
|
125
|
+
Speech to text and text to speech run on Namu's own models. Translation and the voice agent's replies are written by
|
|
126
|
+
Google Gemini through OpenRouter, which receives the text they work on. Namu keeps usage records, not your audio or
|
|
127
|
+
text.
|
|
128
|
+
|
|
129
|
+
## Development
|
|
130
|
+
|
|
131
|
+
```bash
|
|
132
|
+
pip install -e ".[dev]"
|
|
133
|
+
pytest # mocked, no network
|
|
134
|
+
NAMU_LIVE=1 pytest -m live # the free endpoints of the real API
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
Requires Python 3.9+. Licensed under Apache 2.0.
|
namu_ai-0.1.0/README.md
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
# Namu API for Python
|
|
2
|
+
|
|
3
|
+
Speech recognition, speech synthesis, translation and a voice agent for **Hausa, Zarma and French**, from Python.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pip install namu-ai
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```python
|
|
10
|
+
from namu import Namu
|
|
11
|
+
|
|
12
|
+
client = Namu() # reads NAMU_API_KEY
|
|
13
|
+
|
|
14
|
+
audio = client.speech("Sannu da zuwa! Muna farin cikin jin muryarku.", voice="nadia", format="mp3")
|
|
15
|
+
open("welcome.mp3", "wb").write(audio)
|
|
16
|
+
|
|
17
|
+
print(client.transcribe("welcome.mp3", language="ha")["text"])
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Get a key at [namuai-lab.com/account/keys](https://www.namuai-lab.com/account/keys) and keep it on your server: never in
|
|
21
|
+
a mobile app or a web page. During the beta every account gets 30 minutes of audio a month, free.
|
|
22
|
+
|
|
23
|
+
## Usage
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
# Text to speech: Hausa (nadia), Zarma and Hausa (mouhamad), French (fr); wav, mp3 or opus
|
|
27
|
+
audio = client.speech("Fofo! Mate ni go?", voice="mouhamad", language="dje", format="opus")
|
|
28
|
+
|
|
29
|
+
# Speech to text: a path, bytes or an open file; ha, dje or fr (not detected: say which)
|
|
30
|
+
result = client.transcribe("voice-note.ogg", language="ha")
|
|
31
|
+
|
|
32
|
+
# Translation, Hausa ⇄ French, from text or speech, optionally spoken back (base64 WAV)
|
|
33
|
+
fr = client.translate("Ina kwana? Yau za a yi zafi sosai.", source="ha", target="fr")
|
|
34
|
+
spoken = client.translate(audio="question.ogg", source="ha", target="fr", include_audio=True)
|
|
35
|
+
|
|
36
|
+
# Voice agent (research preview; the key needs the converse scope)
|
|
37
|
+
turn = client.converse("hello.ogg", session_id="demo-42")
|
|
38
|
+
|
|
39
|
+
# Account and catalogue
|
|
40
|
+
client.usage() # {'month_audio_seconds_used': 312.4, 'month_audio_seconds_limit': 1800.0}
|
|
41
|
+
client.voices() # no key needed
|
|
42
|
+
client.models()
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Responses are plain dictionaries, typed with `TypedDict` (`namu.types`) for your editor.
|
|
46
|
+
|
|
47
|
+
## Errors
|
|
48
|
+
|
|
49
|
+
Every error is a `NamuError`. Errors the API answered carry its stable `type`, the HTTP `status`, a `message` and the
|
|
50
|
+
`request_id` to send Namu.
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
from namu import Namu, NamuError, QuotaExceededError, BadRequestError
|
|
54
|
+
|
|
55
|
+
try:
|
|
56
|
+
audio = client.speech(text)
|
|
57
|
+
except QuotaExceededError:
|
|
58
|
+
... # this month's allowance is used
|
|
59
|
+
except BadRequestError as e:
|
|
60
|
+
print(e.type, e.message) # unknown_voice, unsupported_language, missing_text, ...
|
|
61
|
+
except NamuError as e:
|
|
62
|
+
print(e.status, e.type, e.request_id)
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
| Class | Status | `type` |
|
|
66
|
+
| --- | --- | --- |
|
|
67
|
+
| `BadRequestError` | 400 | `invalid_request`, `invalid_json`, `missing_text`, `missing_file`, `empty_audio`, `unknown_voice`, `unsupported_language`, `unsupported_pair`, `unknown_persona` |
|
|
68
|
+
| `AuthenticationError` | 401 | `missing_api_key`, `invalid_api_key`, `key_revoked` |
|
|
69
|
+
| `PermissionDeniedError` | 403 | `insufficient_scope`, `account_paused` |
|
|
70
|
+
| `PayloadTooLargeError` | 413 | `payload_too_large`, `audio_too_long`, `text_too_long` |
|
|
71
|
+
| `UnsupportedAudioError` | 415 | `unsupported_audio` |
|
|
72
|
+
| `NothingHeardError` | 422 | `nothing_heard` |
|
|
73
|
+
| `RateLimitError` / `QuotaExceededError` | 429 | `rate_limited` / `quota_exceeded` |
|
|
74
|
+
| `InternalServerError` | 5xx | `internal_error`, `upstream_error`, `upstream_timeout`, ... |
|
|
75
|
+
| `APIConnectionError` / `APITimeoutError` | none | the API could not be reached, or did not answer in time |
|
|
76
|
+
|
|
77
|
+
## Retries and timeouts
|
|
78
|
+
|
|
79
|
+
Network errors, `429 rate_limited` and `502`/`503`/`504` are retried up to 3 times, after `Retry-After` or 1, 2, 4
|
|
80
|
+
seconds (with jitter). `quota_exceeded` and other 4xx never are. The default timeout is 300 seconds: the first request
|
|
81
|
+
after a quiet spell can take a minute while a model wakes up.
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
client = Namu(timeout=120, max_retries=5)
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
## Configuration
|
|
88
|
+
|
|
89
|
+
| Argument | Environment | Default |
|
|
90
|
+
| --- | --- | --- |
|
|
91
|
+
| `api_key` | `NAMU_API_KEY` | none |
|
|
92
|
+
| `base_url` | `NAMU_BASE_URL` | `https://api.namuai-lab.com` |
|
|
93
|
+
| `timeout` | | 300 seconds |
|
|
94
|
+
| `max_retries` | | 3 |
|
|
95
|
+
| `session` | | a new `requests.Session` |
|
|
96
|
+
|
|
97
|
+
## Data
|
|
98
|
+
|
|
99
|
+
Speech to text and text to speech run on Namu's own models. Translation and the voice agent's replies are written by
|
|
100
|
+
Google Gemini through OpenRouter, which receives the text they work on. Namu keeps usage records, not your audio or
|
|
101
|
+
text.
|
|
102
|
+
|
|
103
|
+
## Development
|
|
104
|
+
|
|
105
|
+
```bash
|
|
106
|
+
pip install -e ".[dev]"
|
|
107
|
+
pytest # mocked, no network
|
|
108
|
+
NAMU_LIVE=1 pytest -m live # the free endpoints of the real API
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
Requires Python 3.9+. Licensed under Apache 2.0.
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.24"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "namu-ai"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "The Namu API for Python: speech recognition, speech synthesis and translation for Hausa, Zarma and French."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = "Apache-2.0"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [{ name = "Namu AI Lab", email = "contact@namuai.org" }]
|
|
14
|
+
keywords = ["namu", "speech", "text-to-speech", "speech-to-text", "translation", "hausa", "zarma", "french", "sahel"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
20
|
+
"Topic :: Multimedia :: Sound/Audio :: Speech",
|
|
21
|
+
"Typing :: Typed",
|
|
22
|
+
]
|
|
23
|
+
dependencies = [
|
|
24
|
+
"requests>=2.28,<3",
|
|
25
|
+
"typing_extensions>=4.5; python_version<'3.11'",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
[project.optional-dependencies]
|
|
29
|
+
dev = ["pytest>=8", "responses>=0.25", "build>=1.2", "twine>=5"]
|
|
30
|
+
|
|
31
|
+
[project.urls]
|
|
32
|
+
Homepage = "https://www.namuai-lab.com/api"
|
|
33
|
+
Documentation = "https://www.namuai-lab.com/docs"
|
|
34
|
+
|
|
35
|
+
[tool.hatch.version]
|
|
36
|
+
path = "src/namu/_version.py"
|
|
37
|
+
|
|
38
|
+
[tool.hatch.build.targets.wheel]
|
|
39
|
+
packages = ["src/namu"]
|
|
40
|
+
|
|
41
|
+
[tool.hatch.build.targets.sdist]
|
|
42
|
+
include = ["src", "tests", "README.md", "CHANGELOG.md", "LICENSE", "pyproject.toml"]
|
|
43
|
+
|
|
44
|
+
[tool.pytest.ini_options]
|
|
45
|
+
testpaths = ["tests"]
|
|
46
|
+
markers = ["live: calls the real API (only the endpoints that need no key); run with NAMU_LIVE=1"]
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""The Namu API for Python: speech recognition, speech synthesis, translation and a voice agent for Hausa, Zarma and
|
|
2
|
+
French. https://www.namuai-lab.com
|
|
3
|
+
|
|
4
|
+
from namu import Namu
|
|
5
|
+
|
|
6
|
+
client = Namu() # reads NAMU_API_KEY
|
|
7
|
+
audio = client.speech("Sannu da zuwa!", voice="nadia", format="mp3")
|
|
8
|
+
"""
|
|
9
|
+
from ._client import DEFAULT_BASE_URL, AudioInput, Namu
|
|
10
|
+
from ._errors import (
|
|
11
|
+
APIConnectionError,
|
|
12
|
+
APIStatusError,
|
|
13
|
+
APITimeoutError,
|
|
14
|
+
AuthenticationError,
|
|
15
|
+
BadRequestError,
|
|
16
|
+
InternalServerError,
|
|
17
|
+
NamuError,
|
|
18
|
+
NotFoundError,
|
|
19
|
+
NothingHeardError,
|
|
20
|
+
PayloadTooLargeError,
|
|
21
|
+
PermissionDeniedError,
|
|
22
|
+
QuotaExceededError,
|
|
23
|
+
RateLimitError,
|
|
24
|
+
UnsupportedAudioError,
|
|
25
|
+
)
|
|
26
|
+
from ._version import __version__
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"Namu", "AudioInput", "DEFAULT_BASE_URL", "__version__",
|
|
30
|
+
"NamuError", "APIConnectionError", "APITimeoutError", "APIStatusError", "BadRequestError", "AuthenticationError",
|
|
31
|
+
"PermissionDeniedError", "NotFoundError", "PayloadTooLargeError", "UnsupportedAudioError", "NothingHeardError",
|
|
32
|
+
"RateLimitError", "QuotaExceededError", "InternalServerError",
|
|
33
|
+
]
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import random
|
|
5
|
+
import time
|
|
6
|
+
from typing import Any, BinaryIO, Dict, List, Optional, Union, cast
|
|
7
|
+
|
|
8
|
+
import requests
|
|
9
|
+
|
|
10
|
+
from ._errors import APIConnectionError, APITimeoutError, AuthenticationError, error_for
|
|
11
|
+
from ._version import __version__
|
|
12
|
+
from .types import ConverseTurn, Language, Model, SpeechFormat, Transcription, Translation, Usage, Voice, VoiceInfo
|
|
13
|
+
|
|
14
|
+
__all__ = ["Namu", "AudioInput", "DEFAULT_BASE_URL"]
|
|
15
|
+
|
|
16
|
+
DEFAULT_BASE_URL = "https://api.namuai-lab.com"
|
|
17
|
+
AudioInput = Union[str, "os.PathLike[str]", bytes, bytearray, BinaryIO]
|
|
18
|
+
"""A path to an audio file, its bytes, or an open binary file. Any of WAV, MP3, M4A/AAC, OGG/Opus, WebM or FLAC."""
|
|
19
|
+
|
|
20
|
+
_RETRY_STATUSES = frozenset({429, 502, 503, 504})
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Namu:
|
|
24
|
+
"""A client for the Namu API: speech recognition, speech synthesis, translation and a voice agent for Hausa,
|
|
25
|
+
Zarma and French.
|
|
26
|
+
|
|
27
|
+
from namu import Namu
|
|
28
|
+
|
|
29
|
+
client = Namu() # reads NAMU_API_KEY
|
|
30
|
+
audio = client.speech("Sannu da zuwa!", voice="nadia", format="mp3")
|
|
31
|
+
|
|
32
|
+
Keep it on your server: the key must never reach a phone or a browser.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
def __init__(
|
|
36
|
+
self,
|
|
37
|
+
api_key: Optional[str] = None,
|
|
38
|
+
*,
|
|
39
|
+
base_url: Optional[str] = None,
|
|
40
|
+
timeout: float = 300.0,
|
|
41
|
+
max_retries: int = 3,
|
|
42
|
+
session: Optional[requests.Session] = None,
|
|
43
|
+
) -> None:
|
|
44
|
+
"""
|
|
45
|
+
:param api_key: your secret key (`namu_sk_...`). Defaults to the `NAMU_API_KEY` environment variable.
|
|
46
|
+
:param base_url: defaults to `NAMU_BASE_URL`, then https://api.namuai-lab.com.
|
|
47
|
+
:param timeout: seconds to wait for an answer. Generous by default: a model waking up after a quiet spell can
|
|
48
|
+
take a minute or more.
|
|
49
|
+
:param max_retries: how many times to retry network errors, `429 rate_limited` and `502`/`503`/`504`, with a
|
|
50
|
+
growing pause (or the `Retry-After` the API sends). `quota_exceeded` and other 4xx are never retried.
|
|
51
|
+
:param session: a `requests.Session` to reuse (proxies, adapters, connection pooling).
|
|
52
|
+
"""
|
|
53
|
+
self.api_key = api_key if api_key is not None else os.environ.get("NAMU_API_KEY")
|
|
54
|
+
self.base_url = (base_url or os.environ.get("NAMU_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
|
|
55
|
+
self.timeout = timeout
|
|
56
|
+
self.max_retries = max(0, max_retries)
|
|
57
|
+
self._session = session or requests.Session()
|
|
58
|
+
self._owns_session = session is None
|
|
59
|
+
|
|
60
|
+
# ---- text to speech -------------------------------------------------------------------------------------------
|
|
61
|
+
def speech(self, text: str, *, voice: Union[Voice, str] = "nadia", language: Optional[Union[Language, str]] = None,
|
|
62
|
+
format: Union[SpeechFormat, str] = "wav") -> bytes:
|
|
63
|
+
"""Speak `text` (up to 2,000 characters). Returns the audio: WAV (24 kHz mono, default), MP3 or Ogg Opus.
|
|
64
|
+
|
|
65
|
+
`language` defaults to the voice's first language and must be one the voice speaks.
|
|
66
|
+
"""
|
|
67
|
+
body: Dict[str, Any] = {"text": text, "voice": voice, "format": format}
|
|
68
|
+
if language:
|
|
69
|
+
body["language"] = language
|
|
70
|
+
return self._request("POST", "/v1/speech", json=body).content
|
|
71
|
+
|
|
72
|
+
# ---- speech to text -------------------------------------------------------------------------------------------
|
|
73
|
+
def transcribe(self, audio: AudioInput, *, language: Union[Language, str] = "ha") -> Transcription:
|
|
74
|
+
"""Write down what was said in `audio` (up to 25 MB and 5 minutes). `language` is not detected: send the
|
|
75
|
+
language you expect."""
|
|
76
|
+
response = self._request("POST", "/v1/transcribe", files=_file(audio), data={"language": language})
|
|
77
|
+
return cast(Transcription, response.json())
|
|
78
|
+
|
|
79
|
+
# ---- translation ----------------------------------------------------------------------------------------------
|
|
80
|
+
def translate(self, text: Optional[str] = None, *, audio: Optional[AudioInput] = None, target: str = "fr",
|
|
81
|
+
source: Optional[str] = None, include_audio: bool = False) -> Translation:
|
|
82
|
+
"""Translate Hausa ⇄ French, from `text` (up to 2,000 characters) or from `audio`.
|
|
83
|
+
|
|
84
|
+
`source` defaults to the other language from `target`. With `include_audio`, the answer's `audio` field holds
|
|
85
|
+
the translation spoken, as base64 WAV.
|
|
86
|
+
"""
|
|
87
|
+
if (text is None) == (audio is None):
|
|
88
|
+
raise ValueError("Give either text or audio.")
|
|
89
|
+
fields: Dict[str, Any] = {"target": target}
|
|
90
|
+
if source:
|
|
91
|
+
fields["source"] = source
|
|
92
|
+
if text is not None:
|
|
93
|
+
response = self._request("POST", "/v1/translate", json={"text": text, "include_audio": include_audio, **fields})
|
|
94
|
+
else:
|
|
95
|
+
if include_audio:
|
|
96
|
+
fields["include_audio"] = "true"
|
|
97
|
+
response = self._request("POST", "/v1/translate", files=_file(cast(AudioInput, audio)), data=fields)
|
|
98
|
+
return cast(Translation, response.json())
|
|
99
|
+
|
|
100
|
+
# ---- voice agent (research preview) ---------------------------------------------------------------------------
|
|
101
|
+
def converse(self, audio: AudioInput, *, session_id: Optional[str] = None, persona: str = "nadia") -> ConverseTurn:
|
|
102
|
+
"""One turn with the voice agent, in Hausa. The key needs the `converse` scope. The answer's `audio` is the
|
|
103
|
+
reply spoken, base64 WAV. Each turn stands alone: the API keeps no conversation."""
|
|
104
|
+
fields: Dict[str, Any] = {"persona": persona}
|
|
105
|
+
if session_id:
|
|
106
|
+
fields["session_id"] = session_id
|
|
107
|
+
return cast(ConverseTurn, self._request("POST", "/v1/converse", files=_file(audio), data=fields).json())
|
|
108
|
+
|
|
109
|
+
# ---- account and catalogue ------------------------------------------------------------------------------------
|
|
110
|
+
def usage(self) -> Usage:
|
|
111
|
+
"""Audio seconds used this calendar month (UTC) and the allowance. Free: counts nothing."""
|
|
112
|
+
return cast(Usage, self._request("GET", "/v1/usage").json())
|
|
113
|
+
|
|
114
|
+
def voices(self) -> List[VoiceInfo]:
|
|
115
|
+
"""The voices `speech` can use. No key needed."""
|
|
116
|
+
return cast(List[VoiceInfo], self._request("GET", "/v1/voices", auth=False).json()["data"])
|
|
117
|
+
|
|
118
|
+
def models(self) -> List[Model]:
|
|
119
|
+
"""The models, their endpoints, languages and status. No key needed."""
|
|
120
|
+
return cast(List[Model], self._request("GET", "/v1/models", auth=False).json()["data"])
|
|
121
|
+
|
|
122
|
+
# ---- lifecycle ------------------------------------------------------------------------------------------------
|
|
123
|
+
def close(self) -> None:
|
|
124
|
+
if self._owns_session:
|
|
125
|
+
self._session.close()
|
|
126
|
+
|
|
127
|
+
def __enter__(self) -> "Namu":
|
|
128
|
+
return self
|
|
129
|
+
|
|
130
|
+
def __exit__(self, *exc: object) -> None:
|
|
131
|
+
self.close()
|
|
132
|
+
|
|
133
|
+
def __repr__(self) -> str:
|
|
134
|
+
return f"Namu(base_url={self.base_url!r})"
|
|
135
|
+
|
|
136
|
+
# ---- plumbing -------------------------------------------------------------------------------------------------
|
|
137
|
+
def _request(self, method: str, path: str, *, auth: bool = True, **kwargs: Any) -> requests.Response:
|
|
138
|
+
headers = {"User-Agent": f"namu-python/{__version__}", "Accept": "application/json"}
|
|
139
|
+
if auth:
|
|
140
|
+
if not self.api_key:
|
|
141
|
+
raise AuthenticationError("Set NAMU_API_KEY or pass api_key=.", status=401, type="missing_api_key")
|
|
142
|
+
headers["Authorization"] = f"Bearer {self.api_key}"
|
|
143
|
+
attempt = 0
|
|
144
|
+
while True:
|
|
145
|
+
try:
|
|
146
|
+
response = self._session.request(method, self.base_url + path, headers=headers, timeout=self.timeout,
|
|
147
|
+
**kwargs)
|
|
148
|
+
except requests.Timeout as e:
|
|
149
|
+
error: Exception = APITimeoutError(f"No answer within {self.timeout:g} s.")
|
|
150
|
+
cause: Exception = e
|
|
151
|
+
except requests.RequestException as e:
|
|
152
|
+
error, cause = APIConnectionError(f"Could not reach the Namu API: {e.__class__.__name__}."), e
|
|
153
|
+
else:
|
|
154
|
+
if response.ok:
|
|
155
|
+
return response
|
|
156
|
+
error = _api_error(response)
|
|
157
|
+
cause = None # type: ignore[assignment]
|
|
158
|
+
retryable = response.status_code in _RETRY_STATUSES and getattr(error, "type", "") != "quota_exceeded"
|
|
159
|
+
if not retryable or attempt >= self.max_retries:
|
|
160
|
+
raise error
|
|
161
|
+
time.sleep(_delay(attempt, response.headers.get("Retry-After")))
|
|
162
|
+
attempt += 1
|
|
163
|
+
continue
|
|
164
|
+
if attempt >= self.max_retries:
|
|
165
|
+
raise error from cause
|
|
166
|
+
time.sleep(_delay(attempt, None))
|
|
167
|
+
attempt += 1
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _file(audio: AudioInput) -> Dict[str, Any]:
|
|
171
|
+
if isinstance(audio, (str, os.PathLike)):
|
|
172
|
+
with open(audio, "rb") as f:
|
|
173
|
+
return {"file": (os.path.basename(os.fspath(audio)), f.read())}
|
|
174
|
+
if isinstance(audio, (bytes, bytearray)):
|
|
175
|
+
return {"file": ("audio", bytes(audio))}
|
|
176
|
+
return {"file": (os.path.basename(str(getattr(audio, "name", "audio"))), audio.read())}
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _delay(attempt: int, retry_after: Optional[str]) -> float:
|
|
180
|
+
if retry_after:
|
|
181
|
+
try:
|
|
182
|
+
return max(0.0, min(float(retry_after), 60.0))
|
|
183
|
+
except ValueError:
|
|
184
|
+
pass
|
|
185
|
+
return min(2.0 ** attempt, 16.0) * (0.75 + random.random() / 2) # 1, 2, 4 … seconds, with jitter
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _api_error(response: requests.Response) -> Exception:
|
|
189
|
+
request_id = response.headers.get("X-Request-Id")
|
|
190
|
+
try:
|
|
191
|
+
body = response.json()["error"]
|
|
192
|
+
return error_for(response.status_code, str(body.get("type") or "http_error"), str(body.get("message") or ""),
|
|
193
|
+
body.get("request_id") or request_id)
|
|
194
|
+
except (ValueError, KeyError, TypeError, AttributeError):
|
|
195
|
+
return error_for(response.status_code, "http_error", response.text[:200], request_id)
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Errors raised by the Namu client.
|
|
2
|
+
|
|
3
|
+
Every error is a `NamuError`. Errors the API answered carry its stable `type` (branch on it), the HTTP `status`, a
|
|
4
|
+
`message` written for developers, and the `request_id` to send Namu when asking about a request.
|
|
5
|
+
|
|
6
|
+
NamuError
|
|
7
|
+
├── APIConnectionError the request did not reach the API, or no answer came back
|
|
8
|
+
│ └── APITimeoutError no answer within the client's timeout
|
|
9
|
+
└── APIStatusError the API answered with an error status
|
|
10
|
+
├── BadRequestError 400 invalid_request, missing_text, unknown_voice, unsupported_language, ...
|
|
11
|
+
├── AuthenticationError 401 missing_api_key, invalid_api_key, key_revoked
|
|
12
|
+
├── PermissionDeniedError 403 insufficient_scope, account_paused
|
|
13
|
+
├── NotFoundError 404
|
|
14
|
+
├── PayloadTooLargeError 413 payload_too_large, audio_too_long, text_too_long
|
|
15
|
+
├── UnsupportedAudioError 415 unsupported_audio
|
|
16
|
+
├── NothingHeardError 422 nothing_heard
|
|
17
|
+
├── RateLimitError 429 rate_limited
|
|
18
|
+
│ └── QuotaExceededError 429 quota_exceeded (the month's allowance is used; not retried)
|
|
19
|
+
└── InternalServerError 5xx internal_error, upstream_error, upstream_timeout, ...
|
|
20
|
+
"""
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
from typing import Optional
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"NamuError", "APIConnectionError", "APITimeoutError", "APIStatusError", "BadRequestError", "AuthenticationError",
|
|
27
|
+
"PermissionDeniedError", "NotFoundError", "PayloadTooLargeError", "UnsupportedAudioError", "NothingHeardError",
|
|
28
|
+
"RateLimitError", "QuotaExceededError", "InternalServerError",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class NamuError(Exception):
|
|
33
|
+
"""Base class for every error this package raises."""
|
|
34
|
+
|
|
35
|
+
def __init__(self, message: str, *, status: Optional[int] = None, type: Optional[str] = None,
|
|
36
|
+
request_id: Optional[str] = None) -> None:
|
|
37
|
+
self.message = message
|
|
38
|
+
self.status = status
|
|
39
|
+
self.type = type
|
|
40
|
+
self.request_id = request_id
|
|
41
|
+
prefix = " ".join(str(x) for x in (status, type) if x is not None)
|
|
42
|
+
super().__init__(f"{prefix}: {message}" + (f" (request {request_id})" if request_id else "") if prefix else message)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class APIConnectionError(NamuError):
|
|
46
|
+
"""The request did not reach the API, or the connection broke before an answer came back."""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class APITimeoutError(APIConnectionError):
|
|
50
|
+
"""No answer within the client's timeout."""
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class APIStatusError(NamuError):
|
|
54
|
+
"""The API answered with an error status. `type` is the stable code from the error body."""
|
|
55
|
+
|
|
56
|
+
status: int
|
|
57
|
+
type: str
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class BadRequestError(APIStatusError):
|
|
61
|
+
pass
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class AuthenticationError(APIStatusError):
|
|
65
|
+
pass
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class PermissionDeniedError(APIStatusError):
|
|
69
|
+
pass
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class NotFoundError(APIStatusError):
|
|
73
|
+
pass
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class PayloadTooLargeError(APIStatusError):
|
|
77
|
+
pass
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class UnsupportedAudioError(APIStatusError):
|
|
81
|
+
pass
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class NothingHeardError(APIStatusError):
|
|
85
|
+
pass
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class RateLimitError(APIStatusError):
|
|
89
|
+
pass
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class QuotaExceededError(RateLimitError):
|
|
93
|
+
pass
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class InternalServerError(APIStatusError):
|
|
97
|
+
pass
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
_BY_STATUS = {400: BadRequestError, 401: AuthenticationError, 403: PermissionDeniedError, 404: NotFoundError,
|
|
101
|
+
413: PayloadTooLargeError, 415: UnsupportedAudioError, 422: NothingHeardError, 429: RateLimitError}
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def error_for(status: int, type: str, message: str, request_id: Optional[str]) -> APIStatusError:
|
|
105
|
+
"""The most specific error class for an API answer."""
|
|
106
|
+
if status == 429 and type == "quota_exceeded":
|
|
107
|
+
cls: type[APIStatusError] = QuotaExceededError
|
|
108
|
+
elif status >= 500:
|
|
109
|
+
cls = InternalServerError
|
|
110
|
+
else:
|
|
111
|
+
cls = _BY_STATUS.get(status, APIStatusError)
|
|
112
|
+
return cls(message, status=status, type=type, request_id=request_id)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
|
File without changes
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""The shapes of the API's JSON answers, as typed dictionaries. Responses are plain dicts: index them as usual."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import sys
|
|
5
|
+
from typing import List, Optional
|
|
6
|
+
|
|
7
|
+
if sys.version_info >= (3, 11):
|
|
8
|
+
from typing import Literal, NotRequired, TypedDict
|
|
9
|
+
else: # pragma: no cover
|
|
10
|
+
from typing_extensions import Literal, NotRequired, TypedDict
|
|
11
|
+
|
|
12
|
+
__all__ = ["Language", "Voice", "SpeechFormat", "Transcription", "Translation", "ConverseTurn", "Usage", "Model",
|
|
13
|
+
"VoiceInfo"]
|
|
14
|
+
|
|
15
|
+
Language = Literal["ha", "dje", "fr"]
|
|
16
|
+
"""`ha` Hausa, `dje` Zarma, `fr` French."""
|
|
17
|
+
|
|
18
|
+
Voice = Literal["nadia", "warm", "mouhamad", "fr"]
|
|
19
|
+
"""`nadia` (Hausa; `warm` is the same voice), `mouhamad` (Zarma and Hausa), `fr` (French)."""
|
|
20
|
+
|
|
21
|
+
SpeechFormat = Literal["wav", "mp3", "opus"]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Transcription(TypedDict):
|
|
25
|
+
model: str
|
|
26
|
+
text: str
|
|
27
|
+
"""What was said, in lower case, without punctuation."""
|
|
28
|
+
language: str
|
|
29
|
+
audio_seconds: float
|
|
30
|
+
"""The length of the audio sent: what was counted."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Translation(TypedDict):
|
|
34
|
+
model: str
|
|
35
|
+
source: str
|
|
36
|
+
target: str
|
|
37
|
+
source_text: str
|
|
38
|
+
"""The text sent, or what was heard in the audio."""
|
|
39
|
+
text: str
|
|
40
|
+
"""The translation."""
|
|
41
|
+
characters: NotRequired[int]
|
|
42
|
+
"""Text requests: the characters translated."""
|
|
43
|
+
audio_seconds: NotRequired[float]
|
|
44
|
+
"""Audio requests: the length of the audio sent."""
|
|
45
|
+
audio: NotRequired[Optional[str]]
|
|
46
|
+
"""With include_audio: the translation spoken, base64 WAV."""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class ConverseTurn(TypedDict):
|
|
50
|
+
model: str
|
|
51
|
+
persona: str
|
|
52
|
+
session_id: Optional[str]
|
|
53
|
+
heard: str
|
|
54
|
+
"""What the person said, as text."""
|
|
55
|
+
reply: str
|
|
56
|
+
"""The answer, as text."""
|
|
57
|
+
audio: str
|
|
58
|
+
"""The answer spoken, base64 WAV."""
|
|
59
|
+
sample_rate: int
|
|
60
|
+
audio_seconds: float
|
|
61
|
+
"""Audio sent plus the reply: what was counted."""
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class Usage(TypedDict):
|
|
65
|
+
month_audio_seconds_used: float
|
|
66
|
+
month_audio_seconds_limit: float
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class Model(TypedDict):
|
|
70
|
+
id: str
|
|
71
|
+
task: str
|
|
72
|
+
endpoint: str
|
|
73
|
+
scope: str
|
|
74
|
+
languages: List[str]
|
|
75
|
+
status: str
|
|
76
|
+
"""`beta` or `research`."""
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class VoiceInfo(TypedDict):
|
|
80
|
+
id: str
|
|
81
|
+
languages: List[str]
|
|
82
|
+
language: str
|
|
83
|
+
"""The voice's first language."""
|
|
84
|
+
description: str
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
"""The client against a mocked API (responses). Nothing here touches the network."""
|
|
2
|
+
import base64
|
|
3
|
+
import json
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
import requests
|
|
7
|
+
import responses
|
|
8
|
+
|
|
9
|
+
import namu
|
|
10
|
+
from namu import (
|
|
11
|
+
APIConnectionError, APITimeoutError, AuthenticationError, BadRequestError, InternalServerError, Namu, NamuError,
|
|
12
|
+
NothingHeardError, PayloadTooLargeError, PermissionDeniedError, QuotaExceededError, RateLimitError,
|
|
13
|
+
UnsupportedAudioError,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
BASE = "https://api.namuai-lab.com"
|
|
17
|
+
KEY = "namu_sk_" + "a" * 43
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@pytest.fixture(autouse=True)
|
|
21
|
+
def no_sleep(monkeypatch):
|
|
22
|
+
monkeypatch.setattr(namu._client.time, "sleep", lambda s: None)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@pytest.fixture
|
|
26
|
+
def client():
|
|
27
|
+
return Namu(api_key=KEY)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def err(status, type, message="m", request_id="rid"):
|
|
31
|
+
return responses.Response("POST", "", status=status, json={"error": {"type": type, "message": message, "request_id": request_id}})
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@responses.activate
|
|
35
|
+
def test_speech_sends_json_and_returns_bytes(client):
|
|
36
|
+
responses.post(f"{BASE}/v1/speech", body=b"OggS...", headers={"X-Audio-Seconds": "2.4"}, content_type="audio/ogg")
|
|
37
|
+
audio = client.speech("Fofo! Mate ni go?", voice="mouhamad", language="dje", format="opus")
|
|
38
|
+
assert audio == b"OggS..."
|
|
39
|
+
call = responses.calls[0].request
|
|
40
|
+
assert json.loads(call.body) == {"text": "Fofo! Mate ni go?", "voice": "mouhamad", "format": "opus", "language": "dje"}
|
|
41
|
+
assert call.headers["Authorization"] == f"Bearer {KEY}"
|
|
42
|
+
assert call.headers["User-Agent"] == f"namu-python/{namu.__version__}"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@responses.activate
|
|
46
|
+
def test_speech_defaults(client):
|
|
47
|
+
responses.post(f"{BASE}/v1/speech", body=b"RIFF")
|
|
48
|
+
client.speech("Sannu")
|
|
49
|
+
assert json.loads(responses.calls[0].request.body) == {"text": "Sannu", "voice": "nadia", "format": "wav"}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@responses.activate
|
|
53
|
+
@pytest.mark.parametrize("make", [lambda p: str(p), lambda p: p, lambda p: p.read_bytes(), lambda p: open(p, "rb")])
|
|
54
|
+
def test_transcribe_accepts_paths_bytes_and_files(client, tmp_path, make):
|
|
55
|
+
note = tmp_path / "note.ogg"
|
|
56
|
+
note.write_bytes(b"OggS\x00voice")
|
|
57
|
+
responses.post(f"{BASE}/v1/transcribe", json={"model": "speech-recognition", "text": "sannu", "language": "ha", "audio_seconds": 2.0})
|
|
58
|
+
result = client.transcribe(make(note), language="ha")
|
|
59
|
+
assert result["text"] == "sannu"
|
|
60
|
+
body = responses.calls[0].request.body
|
|
61
|
+
assert b'name="file"' in body and b"OggS\x00voice" in body and b'name="language"' in body
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@responses.activate
|
|
65
|
+
def test_translate_text_and_audio(client, tmp_path):
|
|
66
|
+
responses.post(f"{BASE}/v1/translate", json={"model": "translation", "source": "ha", "target": "fr", "source_text": "x", "text": "y", "characters": 1})
|
|
67
|
+
out = client.translate("Ina kwana?", source="ha", target="fr")
|
|
68
|
+
assert out["text"] == "y"
|
|
69
|
+
assert json.loads(responses.calls[0].request.body) == {"text": "Ina kwana?", "include_audio": False, "target": "fr", "source": "ha"}
|
|
70
|
+
|
|
71
|
+
clip = tmp_path / "q.wav"
|
|
72
|
+
clip.write_bytes(b"RIFF")
|
|
73
|
+
client.translate(audio=clip, target="ha", include_audio=True)
|
|
74
|
+
body = responses.calls[1].request.body
|
|
75
|
+
assert b'name="include_audio"' in body and b"true" in body and b'name="target"' in body
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def test_translate_needs_text_or_audio(client):
|
|
79
|
+
with pytest.raises(ValueError):
|
|
80
|
+
client.translate()
|
|
81
|
+
with pytest.raises(ValueError):
|
|
82
|
+
client.translate("x", audio=b"y")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@responses.activate
|
|
86
|
+
def test_converse(client):
|
|
87
|
+
wav = base64.b64encode(b"RIFF").decode()
|
|
88
|
+
responses.post(f"{BASE}/v1/converse", json={"model": "voice-agent", "persona": "nadia", "session_id": "s1", "heard": "sannu",
|
|
89
|
+
"reply": "Lafiya lau", "audio": wav, "sample_rate": 24000, "audio_seconds": 3.0})
|
|
90
|
+
turn = client.converse(b"RIFF", session_id="s1")
|
|
91
|
+
assert turn["reply"] == "Lafiya lau" and base64.b64decode(turn["audio"]) == b"RIFF"
|
|
92
|
+
assert b'name="session_id"' in responses.calls[0].request.body
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@responses.activate
|
|
96
|
+
def test_catalogue_needs_no_key():
|
|
97
|
+
responses.get(f"{BASE}/v1/voices", json={"data": [{"id": "nadia", "languages": ["ha"], "language": "ha", "description": "d"}]})
|
|
98
|
+
responses.get(f"{BASE}/v1/models", json={"data": [{"id": "speech-synthesis", "task": "speech", "endpoint": "/v1/speech", "scope": "speech", "languages": ["ha"], "status": "beta"}]})
|
|
99
|
+
keyless = Namu(api_key="")
|
|
100
|
+
assert [v["id"] for v in keyless.voices()] == ["nadia"]
|
|
101
|
+
assert keyless.models()[0]["status"] == "beta"
|
|
102
|
+
assert "Authorization" not in responses.calls[0].request.headers
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@responses.activate
|
|
106
|
+
def test_usage(client):
|
|
107
|
+
responses.get(f"{BASE}/v1/usage", json={"month_audio_seconds_used": 312.4, "month_audio_seconds_limit": 1800.0})
|
|
108
|
+
assert client.usage()["month_audio_seconds_limit"] == 1800.0
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def test_missing_key_raises_before_any_request(monkeypatch):
|
|
112
|
+
monkeypatch.delenv("NAMU_API_KEY", raising=False)
|
|
113
|
+
with pytest.raises(AuthenticationError) as e:
|
|
114
|
+
Namu().speech("x")
|
|
115
|
+
assert e.value.type == "missing_api_key" and e.value.status == 401
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def test_environment(monkeypatch):
|
|
119
|
+
monkeypatch.setenv("NAMU_API_KEY", KEY)
|
|
120
|
+
monkeypatch.setenv("NAMU_BASE_URL", "https://example.test/")
|
|
121
|
+
c = Namu()
|
|
122
|
+
assert c.api_key == KEY and c.base_url == "https://example.test"
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
@responses.activate
|
|
126
|
+
@pytest.mark.parametrize("status,type,cls", [
|
|
127
|
+
(400, "unknown_voice", BadRequestError), (401, "invalid_api_key", AuthenticationError),
|
|
128
|
+
(403, "insufficient_scope", PermissionDeniedError), (413, "text_too_long", PayloadTooLargeError),
|
|
129
|
+
(415, "unsupported_audio", UnsupportedAudioError), (422, "nothing_heard", NothingHeardError),
|
|
130
|
+
(429, "quota_exceeded", QuotaExceededError), (500, "internal_error", InternalServerError),
|
|
131
|
+
])
|
|
132
|
+
def test_errors_map_to_classes_and_are_not_retried(client, status, type, cls):
|
|
133
|
+
responses.post(f"{BASE}/v1/speech", status=status, json={"error": {"type": type, "message": "why", "request_id": "r1"}})
|
|
134
|
+
with pytest.raises(cls) as e:
|
|
135
|
+
client.speech("x")
|
|
136
|
+
assert isinstance(e.value, NamuError)
|
|
137
|
+
assert (e.value.status, e.value.type, e.value.message, e.value.request_id) == (status, type, "why", "r1")
|
|
138
|
+
assert len(responses.calls) == 1 # 4xx and 500 are not retried; quota_exceeded never
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
@responses.activate
|
|
142
|
+
def test_rate_limited_is_retried_after_retry_after(client, monkeypatch):
|
|
143
|
+
slept = []
|
|
144
|
+
monkeypatch.setattr(namu._client.time, "sleep", slept.append)
|
|
145
|
+
responses.post(f"{BASE}/v1/speech", status=429, headers={"Retry-After": "3"}, json={"error": {"type": "rate_limited", "message": "m", "request_id": "r"}})
|
|
146
|
+
responses.post(f"{BASE}/v1/speech", body=b"RIFF")
|
|
147
|
+
assert client.speech("x") == b"RIFF"
|
|
148
|
+
assert slept == [3.0] and len(responses.calls) == 2
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
@responses.activate
|
|
152
|
+
def test_upstream_errors_retry_then_give_up(client):
|
|
153
|
+
for _ in range(4):
|
|
154
|
+
responses.post(f"{BASE}/v1/speech", status=502, json={"error": {"type": "upstream_error", "message": "m", "request_id": "r"}})
|
|
155
|
+
with pytest.raises(InternalServerError):
|
|
156
|
+
client.speech("x")
|
|
157
|
+
assert len(responses.calls) == 4 # first try + 3 retries
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
@responses.activate
|
|
161
|
+
def test_rate_limit_class_hierarchy(client):
|
|
162
|
+
responses.post(f"{BASE}/v1/speech", status=429, json={"error": {"type": "rate_limited", "message": "m", "request_id": "r"}})
|
|
163
|
+
with pytest.raises(RateLimitError) as e:
|
|
164
|
+
Namu(api_key=KEY, max_retries=0).speech("x")
|
|
165
|
+
assert not isinstance(e.value, QuotaExceededError)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
@responses.activate
|
|
169
|
+
def test_non_json_error_still_has_request_id(client):
|
|
170
|
+
responses.post(f"{BASE}/v1/speech", status=503, body="Service Unavailable", headers={"X-Request-Id": "gw-1"})
|
|
171
|
+
with pytest.raises(InternalServerError) as e:
|
|
172
|
+
Namu(api_key=KEY, max_retries=0).speech("x")
|
|
173
|
+
assert e.value.type == "http_error" and e.value.request_id == "gw-1"
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
@responses.activate
|
|
177
|
+
def test_network_errors(client):
|
|
178
|
+
responses.post(f"{BASE}/v1/speech", body=requests.ConnectionError("down"))
|
|
179
|
+
with pytest.raises(APIConnectionError):
|
|
180
|
+
Namu(api_key=KEY, max_retries=1).speech("x")
|
|
181
|
+
assert len(responses.calls) == 2
|
|
182
|
+
responses.reset()
|
|
183
|
+
responses.post(f"{BASE}/v1/speech", body=requests.Timeout("slow"))
|
|
184
|
+
with pytest.raises(APITimeoutError):
|
|
185
|
+
Namu(api_key=KEY, max_retries=0).speech("x")
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def test_context_manager_closes_its_session():
|
|
189
|
+
with Namu(api_key=KEY) as c:
|
|
190
|
+
assert repr(c) == "Namu(base_url='https://api.namuai-lab.com')"
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Against the real API, only the endpoints and errors that cost nothing: run with NAMU_LIVE=1 pytest -m live."""
|
|
2
|
+
import os
|
|
3
|
+
|
|
4
|
+
import pytest
|
|
5
|
+
|
|
6
|
+
from namu import AuthenticationError, Namu
|
|
7
|
+
|
|
8
|
+
pytestmark = [pytest.mark.live, pytest.mark.skipif(os.environ.get("NAMU_LIVE") != "1", reason="set NAMU_LIVE=1")]
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def test_voices_and_models():
|
|
12
|
+
c = Namu(api_key="")
|
|
13
|
+
assert {"nadia", "mouhamad", "fr"} <= {v["id"] for v in c.voices()}
|
|
14
|
+
models = {m["id"]: m for m in c.models()}
|
|
15
|
+
assert set(models) == {"speech-recognition", "speech-synthesis", "translation", "voice-agent"}
|
|
16
|
+
assert set(models["speech-recognition"]["languages"]) == {"ha", "dje", "fr"}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def test_unknown_key_is_refused_with_a_request_id():
|
|
20
|
+
with pytest.raises(AuthenticationError) as e:
|
|
21
|
+
Namu(api_key="namu_sk_" + "0" * 43, max_retries=0).speech("Sannu")
|
|
22
|
+
assert e.value.type == "invalid_api_key" and e.value.request_id
|