graphcore-audio 0.4.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.
- graphcore_audio-0.4.0/LICENSE +202 -0
- graphcore_audio-0.4.0/NOTICE +2 -0
- graphcore_audio-0.4.0/PKG-INFO +12 -0
- graphcore_audio-0.4.0/audio/__init__.py +0 -0
- graphcore_audio-0.4.0/audio/apps.py +14 -0
- graphcore_audio-0.4.0/audio/authorization.py +13 -0
- graphcore_audio-0.4.0/audio/conf.py +27 -0
- graphcore_audio-0.4.0/audio/entities/__init__.py +11 -0
- graphcore_audio-0.4.0/audio/entities/recording.py +10 -0
- graphcore_audio-0.4.0/audio/migrations/0001_initial.py +26 -0
- graphcore_audio-0.4.0/audio/migrations/__init__.py +0 -0
- graphcore_audio-0.4.0/audio/models.py +9 -0
- graphcore_audio-0.4.0/audio/persistence.py +6 -0
- graphcore_audio-0.4.0/audio/providers/__init__.py +0 -0
- graphcore_audio-0.4.0/audio/providers/fake.py +35 -0
- graphcore_audio-0.4.0/audio/providers/openai.py +50 -0
- graphcore_audio-0.4.0/audio/providers/port.py +31 -0
- graphcore_audio-0.4.0/audio/providers/registry.py +31 -0
- graphcore_audio-0.4.0/audio/specs/__init__.py +3 -0
- graphcore_audio-0.4.0/audio/specs/dsl.py +120 -0
- graphcore_audio-0.4.0/audio/specs/test_clients.py +20 -0
- graphcore_audio-0.4.0/audio/specs/test_dictation.py +87 -0
- graphcore_audio-0.4.0/audio/specs/test_privacy.py +45 -0
- graphcore_audio-0.4.0/audio/specs/test_vendor.py +59 -0
- graphcore_audio-0.4.0/audio/strategies/__init__.py +11 -0
- graphcore_audio-0.4.0/audio/strategies/recordings.py +88 -0
- graphcore_audio-0.4.0/audio/test_settings.py +6 -0
- graphcore_audio-0.4.0/audio/tests/__init__.py +0 -0
- graphcore_audio-0.4.0/audio/tests/test_openai_adapter.py +65 -0
- graphcore_audio-0.4.0/audio/tests/test_recordings.py +139 -0
- graphcore_audio-0.4.0/audio_agent_frontend/__init__.py +3 -0
- graphcore_audio-0.4.0/audio_agent_frontend/agent_views.py +11 -0
- graphcore_audio-0.4.0/graphcore_audio.egg-info/PKG-INFO +12 -0
- graphcore_audio-0.4.0/graphcore_audio.egg-info/SOURCES.txt +38 -0
- graphcore_audio-0.4.0/graphcore_audio.egg-info/dependency_links.txt +1 -0
- graphcore_audio-0.4.0/graphcore_audio.egg-info/entry_points.txt +5 -0
- graphcore_audio-0.4.0/graphcore_audio.egg-info/requires.txt +2 -0
- graphcore_audio-0.4.0/graphcore_audio.egg-info/top_level.txt +2 -0
- graphcore_audio-0.4.0/pyproject.toml +23 -0
- graphcore_audio-0.4.0/setup.cfg +4 -0
|
@@ -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.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: graphcore-audio
|
|
3
|
+
Version: 0.4.0
|
|
4
|
+
Summary: GraphCore app: audio
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Project-URL: Repository, https://github.com/graphcore-org/graphcore
|
|
7
|
+
Requires-Python: >=3.13
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
License-File: NOTICE
|
|
10
|
+
Requires-Dist: graphcore-kernel==0.4.0
|
|
11
|
+
Requires-Dist: openai<3,>=2
|
|
12
|
+
Dynamic: license-file
|
|
File without changes
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from graphcore.public.apps import GraphCoreAppConfig
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class AudioConfig(GraphCoreAppConfig):
|
|
5
|
+
# Django picks this config for the app package.
|
|
6
|
+
default = True
|
|
7
|
+
name = 'audio'
|
|
8
|
+
# Django app label. Must be unique across the deployment.
|
|
9
|
+
label = 'audio'
|
|
10
|
+
# Stable graphcore identity: namespaces this app's entity type ids and keys
|
|
11
|
+
# its per-user mount folder. Safe to move the package; never change this.
|
|
12
|
+
graphcore_app_id = 'audio'
|
|
13
|
+
graphcore_authorization = 'audio.authorization.configure'
|
|
14
|
+
graphcore_persistence = 'audio.persistence.configure'
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Authorization policy for the audio app: a recording is its
|
|
2
|
+
owner's alone, and anyone signed in may open one of their own."""
|
|
3
|
+
from graphcore.public.auth.perms import Create, Write
|
|
4
|
+
from graphcore.public.auth.policy import AccessPolicy
|
|
5
|
+
from graphcore.public.entities import Deployment
|
|
6
|
+
|
|
7
|
+
from audio.entities.recording import Recording
|
|
8
|
+
from audio.strategies.recordings import OpenRecording, Transcribe
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def configure(policy: AccessPolicy) -> None:
|
|
12
|
+
policy.define(Recording, shareable=False, can_contain=[], strategies={Transcribe: Write()})
|
|
13
|
+
policy.extend(Deployment, strategies={OpenRecording: Create()})
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""The app's settings, read at call time so a test may override them."""
|
|
2
|
+
import os
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
from django.conf import settings
|
|
6
|
+
|
|
7
|
+
DEFAULT_MODEL = 'openai/gpt-4o-mini-transcribe'
|
|
8
|
+
# Base64 in a strategy call adds a third; this keeps the message under the
|
|
9
|
+
# web server's 16 MB WebSocket limit.
|
|
10
|
+
DEFAULT_MAX_AUDIO_BYTES = 8 * 1024 * 1024
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def model() -> str:
|
|
14
|
+
return getattr(settings, 'AUDIO_TRANSCRIPTION_MODEL', DEFAULT_MODEL)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def max_audio_bytes() -> int:
|
|
18
|
+
return int(getattr(settings, 'AUDIO_MAX_UPLOAD_BYTES', DEFAULT_MAX_AUDIO_BYTES))
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def provider_key(provider: str) -> Optional[str]:
|
|
22
|
+
name = f'{provider.upper()}_API_KEY'
|
|
23
|
+
return getattr(settings, name, None) or os.environ.get(name) or None
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def provider_read_timeout() -> float:
|
|
27
|
+
return float(getattr(settings, 'AUDIO_PROVIDER_READ_TIMEOUT', 60))
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Entity types for the audio app. Every module in this package is
|
|
2
|
+
# imported at startup, so decorated classes register themselves.
|
|
3
|
+
#
|
|
4
|
+
# from graphcore.public.entities import Entity, register_entity
|
|
5
|
+
#
|
|
6
|
+
# @register_entity()
|
|
7
|
+
# class Board(Entity):
|
|
8
|
+
# pass
|
|
9
|
+
#
|
|
10
|
+
# Registers as 'audio.Board' — namespaced by this app's
|
|
11
|
+
# graphcore_app_id, so it cannot collide with another app's Board.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
from graphcore.public.entities import Entity, register_entity
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
@register_entity()
|
|
5
|
+
class Recording(Entity):
|
|
6
|
+
"""What one person dictated somewhere: the text of the latest take. The
|
|
7
|
+
audio is never kept."""
|
|
8
|
+
purpose: str = ''
|
|
9
|
+
text: str = ''
|
|
10
|
+
take: int = 0
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# Generated by Django 5.2.19 on 2026-11-16 13:29
|
|
2
|
+
|
|
3
|
+
import django.db.models.deletion
|
|
4
|
+
from django.db import migrations, models
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class Migration(migrations.Migration):
|
|
8
|
+
|
|
9
|
+
initial = True
|
|
10
|
+
|
|
11
|
+
dependencies = [
|
|
12
|
+
('graphcore', '0003_entity_key'),
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
operations = [
|
|
16
|
+
migrations.CreateModel(
|
|
17
|
+
name='RecordingModel',
|
|
18
|
+
fields=[
|
|
19
|
+
('entitymodel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='graphcore.entitymodel')),
|
|
20
|
+
('purpose', models.CharField(blank=True, db_index=True, default='', max_length=255)),
|
|
21
|
+
('text', models.TextField(blank=True, default='')),
|
|
22
|
+
('take', models.IntegerField(default=0)),
|
|
23
|
+
],
|
|
24
|
+
bases=('graphcore.entitymodel',),
|
|
25
|
+
),
|
|
26
|
+
]
|
|
File without changes
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
from django.db import models
|
|
2
|
+
|
|
3
|
+
from graphcore.public.persistence.django import EntityModel
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class RecordingModel(EntityModel):
|
|
7
|
+
purpose = models.CharField(max_length=255, default='', blank=True, db_index=True)
|
|
8
|
+
text = models.TextField(default='', blank=True)
|
|
9
|
+
take = models.IntegerField(default=0)
|
|
File without changes
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""A transcriber that plays scripted texts and records what it was sent."""
|
|
2
|
+
from collections import deque
|
|
3
|
+
from typing import ClassVar, Optional
|
|
4
|
+
|
|
5
|
+
from audio.providers.port import Transcriber
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
async def scripted_text(model: str, audio: bytes, mime_type: str, language: Optional[str]) -> str | Exception:
|
|
9
|
+
"""The next reply a test queued, else 'ok'. Spec tests patch it in the stack's processes."""
|
|
10
|
+
return FakeTranscriber.replies.popleft() if FakeTranscriber.replies else 'ok'
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class FakeTranscriber(Transcriber):
|
|
14
|
+
name = 'fake'
|
|
15
|
+
needs_key = False
|
|
16
|
+
|
|
17
|
+
replies: ClassVar[deque] = deque()
|
|
18
|
+
requests: ClassVar[list[dict]] = []
|
|
19
|
+
|
|
20
|
+
@classmethod
|
|
21
|
+
def reset(cls) -> None:
|
|
22
|
+
cls.replies.clear()
|
|
23
|
+
cls.requests.clear()
|
|
24
|
+
|
|
25
|
+
@classmethod
|
|
26
|
+
def play(cls, *replies) -> None:
|
|
27
|
+
"""Queue one reply per call: a text, or an exception to raise."""
|
|
28
|
+
cls.replies.extend(replies)
|
|
29
|
+
|
|
30
|
+
async def transcribe(self, model: str, audio: bytes, mime_type: str, language: Optional[str] = None) -> str:
|
|
31
|
+
self.requests.append({'model': model, 'audio': audio, 'mime_type': mime_type, 'language': language})
|
|
32
|
+
reply = await scripted_text(model, audio, mime_type, language)
|
|
33
|
+
if isinstance(reply, Exception):
|
|
34
|
+
raise reply
|
|
35
|
+
return reply
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""OpenAI's transcription endpoint behind the port."""
|
|
2
|
+
from typing import Optional
|
|
3
|
+
|
|
4
|
+
import openai
|
|
5
|
+
|
|
6
|
+
from audio.providers.port import ProviderError, Transcriber
|
|
7
|
+
|
|
8
|
+
_EXTENSIONS = {
|
|
9
|
+
'audio/webm': 'webm', 'audio/mp4': 'mp4', 'audio/ogg': 'ogg', 'audio/wav': 'wav',
|
|
10
|
+
'audio/x-wav': 'wav', 'audio/mpeg': 'mp3', 'audio/flac': 'flac', 'audio/x-m4a': 'm4a',
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class OpenAITranscriber(Transcriber):
|
|
15
|
+
name = 'openai'
|
|
16
|
+
|
|
17
|
+
def __init__(self, api_key: Optional[str], read_timeout: float, http_client=None):
|
|
18
|
+
super().__init__(api_key, read_timeout)
|
|
19
|
+
# Retries are the executor's.
|
|
20
|
+
self._client = openai.AsyncOpenAI(
|
|
21
|
+
api_key=api_key, max_retries=0, http_client=http_client,
|
|
22
|
+
timeout=openai.Timeout(read_timeout, connect=10.0),
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
async def transcribe(self, model: str, audio: bytes, mime_type: str, language: Optional[str] = None) -> str:
|
|
26
|
+
# The endpoint tells the format from the file name.
|
|
27
|
+
extension = _EXTENSIONS.get(mime_type.partition(';')[0].strip().lower())
|
|
28
|
+
if extension is None:
|
|
29
|
+
raise ProviderError('unsupported_audio', f"Cannot transcribe {mime_type or 'audio of an unknown type'}",
|
|
30
|
+
retryable=False)
|
|
31
|
+
params = {'model': model, 'file': (f'audio.{extension}', audio, mime_type), 'response_format': 'json'}
|
|
32
|
+
if language:
|
|
33
|
+
params['language'] = language
|
|
34
|
+
try:
|
|
35
|
+
result = await self._client.audio.transcriptions.create(**params)
|
|
36
|
+
except openai.APIError as exc:
|
|
37
|
+
raise _provider_error(exc) from exc
|
|
38
|
+
return result.text.strip()
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _provider_error(exc: openai.APIError) -> ProviderError:
|
|
42
|
+
if isinstance(exc, (openai.APITimeoutError, openai.APIConnectionError)):
|
|
43
|
+
return ProviderError('unreachable', str(exc), retryable=True)
|
|
44
|
+
if isinstance(exc, openai.RateLimitError):
|
|
45
|
+
return ProviderError('rate_limit', exc.message, retryable=True)
|
|
46
|
+
if isinstance(exc, openai.InternalServerError):
|
|
47
|
+
return ProviderError('server_error', exc.message, retryable=True)
|
|
48
|
+
if isinstance(exc, (openai.AuthenticationError, openai.PermissionDeniedError)):
|
|
49
|
+
return ProviderError('auth', exc.message, retryable=False)
|
|
50
|
+
return ProviderError('bad_request', exc.message, retryable=False)
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""What the app needs from a speech-to-text vendor."""
|
|
2
|
+
from abc import ABC, abstractmethod
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class ProviderError(Exception):
|
|
7
|
+
def __init__(self, code: str, message: str, *, retryable: bool):
|
|
8
|
+
super().__init__(f"{code}: {message}")
|
|
9
|
+
self.code = code
|
|
10
|
+
self.message = message
|
|
11
|
+
self.retryable = retryable
|
|
12
|
+
|
|
13
|
+
def __reduce__(self):
|
|
14
|
+
return _provider_error, (type(self), self.code, self.message, self.retryable)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _provider_error(cls, code: str, message: str, retryable: bool) -> 'ProviderError':
|
|
18
|
+
return cls(code, message, retryable=retryable)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Transcriber(ABC):
|
|
22
|
+
name: str
|
|
23
|
+
needs_key = True
|
|
24
|
+
|
|
25
|
+
def __init__(self, api_key: Optional[str], read_timeout: float):
|
|
26
|
+
self.api_key = api_key
|
|
27
|
+
self.read_timeout = read_timeout
|
|
28
|
+
|
|
29
|
+
@abstractmethod
|
|
30
|
+
async def transcribe(self, model: str, audio: bytes, mime_type: str, language: Optional[str] = None) -> str:
|
|
31
|
+
"""The words spoken in `audio`. `language` is an ISO-639-1 hint."""
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
from importlib import import_module
|
|
2
|
+
|
|
3
|
+
from audio import conf
|
|
4
|
+
from audio.providers.port import ProviderError, Transcriber
|
|
5
|
+
|
|
6
|
+
_ADAPTERS = {
|
|
7
|
+
'fake': 'audio.providers.fake.FakeTranscriber',
|
|
8
|
+
'openai': 'audio.providers.openai.OpenAITranscriber',
|
|
9
|
+
}
|
|
10
|
+
_built: dict[str, Transcriber] = {}
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def transcriber_for(model_id: str) -> tuple[Transcriber, str]:
|
|
14
|
+
"""The transcriber serving `model_id`, built once per process, and the
|
|
15
|
+
model name to send it."""
|
|
16
|
+
name, _, model = model_id.partition('/')
|
|
17
|
+
if name not in _built:
|
|
18
|
+
path = _ADAPTERS.get(name)
|
|
19
|
+
if path is None:
|
|
20
|
+
raise ProviderError('unknown_model', f"No transcription provider named {name!r}", retryable=False)
|
|
21
|
+
module, _, cls_name = path.rpartition('.')
|
|
22
|
+
transcriber_cls = getattr(import_module(module), cls_name)
|
|
23
|
+
key = conf.provider_key(name)
|
|
24
|
+
if transcriber_cls.needs_key and not key:
|
|
25
|
+
raise ProviderError('no_key', f"{name.upper()}_API_KEY is not set", retryable=False)
|
|
26
|
+
_built[name] = transcriber_cls(key, conf.provider_read_timeout())
|
|
27
|
+
return _built[name], model
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def reset() -> None:
|
|
31
|
+
_built.clear()
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""The audio app's vocabulary: people open a recording for a purpose,
|
|
2
|
+
dictate takes into it, and read back the words. The only module that names
|
|
3
|
+
the app's strategies, types and the vendor seam."""
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import base64
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import Optional
|
|
9
|
+
|
|
10
|
+
from graphcore.public.live_testing import Actor, Dsl, HttpError, strategy
|
|
11
|
+
|
|
12
|
+
from audio.providers.port import ProviderError
|
|
13
|
+
|
|
14
|
+
RECORDING = 'audio.Recording'
|
|
15
|
+
TRANSCRIPTION_MODEL = 'audio.conf.model'
|
|
16
|
+
MAX_AUDIO_BYTES = 'audio.conf.max_audio_bytes'
|
|
17
|
+
VENDOR = 'audio.providers.fake.scripted_text'
|
|
18
|
+
SCRIPTED_MODEL = 'fake/scribe'
|
|
19
|
+
SPEECH = b'RIFF....WAVEfmt speech'
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class Take:
|
|
24
|
+
"""What a person was told about one dictated take."""
|
|
25
|
+
status: str
|
|
26
|
+
request_id: Optional[str]
|
|
27
|
+
text: Optional[str] = None
|
|
28
|
+
take: Optional[int] = None
|
|
29
|
+
error: Optional[str] = None
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def succeeded(self) -> bool:
|
|
33
|
+
return self.status == 'succeeded'
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _take(outcome: dict) -> Take:
|
|
37
|
+
ret = outcome.get('ret_val') or {}
|
|
38
|
+
return Take(outcome['status'], outcome.get('strategy_request_id'), ret.get('text'), ret.get('take'),
|
|
39
|
+
outcome.get('error'))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class Speaker(Actor):
|
|
43
|
+
async def opens_a_recording(self, purpose: str = 'notes.editor') -> str:
|
|
44
|
+
outcome = await self.execute_one(strategy('OpenRecording', purpose=purpose))
|
|
45
|
+
assert outcome['status'] == 'succeeded', outcome
|
|
46
|
+
return outcome['ret_val']['recording_id']
|
|
47
|
+
|
|
48
|
+
async def dictates(self, recording: str, audio: bytes = SPEECH, mime_type: str = 'audio/webm',
|
|
49
|
+
language: Optional[str] = None, wait: bool = True) -> Take:
|
|
50
|
+
params = {'audio': base64.b64encode(audio).decode(), 'mime_type': mime_type}
|
|
51
|
+
if language:
|
|
52
|
+
params['language'] = language
|
|
53
|
+
return _take(await self.execute_one(strategy('Transcribe', recording, **params), wait=wait))
|
|
54
|
+
|
|
55
|
+
async def sends_text_as_audio(self, recording: str, text: str) -> Take:
|
|
56
|
+
return _take(await self.execute_one(strategy('Transcribe', recording, audio=text, mime_type='audio/webm')))
|
|
57
|
+
|
|
58
|
+
async def shares(self, recording: str, with_: 'Speaker') -> dict:
|
|
59
|
+
return await self.execute_one(strategy('CreateGrant', recording, subject_id=await with_.entity_id(),
|
|
60
|
+
role_name='viewer'))
|
|
61
|
+
|
|
62
|
+
async def words_in(self, recording: str) -> str:
|
|
63
|
+
return (await self.get(recording))['text']
|
|
64
|
+
|
|
65
|
+
async def takes_of(self, recording: str) -> int:
|
|
66
|
+
return (await self.get(recording))['take']
|
|
67
|
+
|
|
68
|
+
async def can_read(self, recording: str) -> bool:
|
|
69
|
+
try:
|
|
70
|
+
await self.get(recording)
|
|
71
|
+
return True
|
|
72
|
+
except HttpError:
|
|
73
|
+
return False
|
|
74
|
+
|
|
75
|
+
async def recordings(self) -> list[dict]:
|
|
76
|
+
return await self.find(RECORDING)
|
|
77
|
+
|
|
78
|
+
async def finished(self, take: Take) -> Take:
|
|
79
|
+
request = await super().finished(take.request_id)
|
|
80
|
+
return _take({**request, 'strategy_request_id': take.request_id})
|
|
81
|
+
|
|
82
|
+
async def request(self, take: Take) -> dict:
|
|
83
|
+
return await self.get(take.request_id)
|
|
84
|
+
|
|
85
|
+
async def opens_over_mcp(self, recording: str) -> str:
|
|
86
|
+
result = await self.mcp_tool('open', at=recording)
|
|
87
|
+
return result['content'][0]['text']
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class AudioDsl(Dsl):
|
|
91
|
+
actor_class = Speaker
|
|
92
|
+
|
|
93
|
+
def as_(self, name: str) -> Speaker:
|
|
94
|
+
return super().as_(name)
|
|
95
|
+
|
|
96
|
+
def _on_the_scripted_model(self) -> None:
|
|
97
|
+
if not getattr(self, '_scripted', False):
|
|
98
|
+
self._scripted = True
|
|
99
|
+
self.patch(TRANSCRIPTION_MODEL, return_value=SCRIPTED_MODEL).start()
|
|
100
|
+
|
|
101
|
+
def the_vendor_hears(self, *texts: str, hold: bool = False):
|
|
102
|
+
"""Each transcription in turn answers with the next text."""
|
|
103
|
+
self._on_the_scripted_model()
|
|
104
|
+
return self.patch(VENDOR, side_effect=list(texts), hold=hold)
|
|
105
|
+
|
|
106
|
+
def the_vendor_fails(self, code: str, message: str, retryable: bool = False):
|
|
107
|
+
self._on_the_scripted_model()
|
|
108
|
+
return self.patch(VENDOR, side_effect=ProviderError(code, message, retryable=retryable))
|
|
109
|
+
|
|
110
|
+
def the_vendor_is_busy_once_then_hears(self, text: str):
|
|
111
|
+
self._on_the_scripted_model()
|
|
112
|
+
return self.patch(VENDOR, side_effect=[ProviderError('overloaded', 'try again', retryable=True), text])
|
|
113
|
+
|
|
114
|
+
def uploads_are_limited_to(self, size: int):
|
|
115
|
+
return self.patch(MAX_AUDIO_BYTES, return_value=size)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def heard(vendor) -> list[dict]:
|
|
119
|
+
"""What the vendor was sent, one entry per call."""
|
|
120
|
+
return [dict(zip(('model', 'audio', 'mime_type', 'language'), call.args)) for call in vendor.call_args_list]
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""The same recording through an agent connected over MCP."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from graphcore.public.live_testing import scenario
|
|
5
|
+
|
|
6
|
+
from audio.specs.dsl import AudioDsl
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@scenario('Clients', 'An agent over MCP reads the words of a recording, and only its owner\'s')
|
|
10
|
+
async def _(a: AudioDsl):
|
|
11
|
+
ana, ben = a.as_('Ana'), a.as_('Ben')
|
|
12
|
+
recording = await ana.opens_a_recording('notes.editor')
|
|
13
|
+
with a.the_vendor_hears('Call the florist.'):
|
|
14
|
+
await ana.dictates(recording)
|
|
15
|
+
|
|
16
|
+
place = await ana.opens_over_mcp(recording)
|
|
17
|
+
refused = await ben.opens_over_mcp(recording)
|
|
18
|
+
|
|
19
|
+
assert 'Call the florist.' in place and 'take 1' in place, place
|
|
20
|
+
assert 'Call the florist.' not in refused, refused
|