graphcore-apps 0.5.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agents/__init__.py +0 -0
- agents/apps.py +15 -0
- agents/authorization.py +62 -0
- agents/conf.py +78 -0
- agents/delegation.py +218 -0
- agents/entities/__init__.py +0 -0
- agents/entities/agent.py +16 -0
- agents/entities/conversation.py +23 -0
- agents/entities/instruction.py +7 -0
- agents/entities/message.py +30 -0
- agents/entities/profile.py +14 -0
- agents/entities/skill.py +8 -0
- agents/migrations/0001_initial.py +88 -0
- agents/migrations/0002_message_context_versions.py +16 -0
- agents/migrations/0003_compaction_threshold.py +21 -0
- agents/migrations/0004_agent_debug_context.py +16 -0
- agents/migrations/0005_conversation_last_active_at.py +34 -0
- agents/migrations/0006_tasks.py +21 -0
- agents/migrations/0007_agent_start_address.py +16 -0
- agents/migrations/__init__.py +0 -0
- agents/models.py +64 -0
- agents/persistence.py +18 -0
- agents/providers/__init__.py +0 -0
- agents/providers/anthropic.py +142 -0
- agents/providers/fake.py +51 -0
- agents/providers/google.py +186 -0
- agents/providers/openai.py +177 -0
- agents/providers/port.py +101 -0
- agents/providers/registry.py +40 -0
- agents/routes.py +5 -0
- agents/runtime/__init__.py +0 -0
- agents/runtime/compaction.py +29 -0
- agents/runtime/context.py +78 -0
- agents/runtime/dispatch.py +76 -0
- agents/runtime/effective_agent.py +70 -0
- agents/runtime/loop.py +454 -0
- agents/runtime/prompt.py +183 -0
- agents/runtime/resume.py +30 -0
- agents/runtime/tools.py +35 -0
- agents/specs/__init__.py +3 -0
- agents/specs/dsl.py +310 -0
- agents/specs/test_r01_agents.py +74 -0
- agents/specs/test_r02_conversations.py +146 -0
- agents/specs/test_r03_acts_as_the_sender.py +60 -0
- agents/specs/test_r04_context.py +63 -0
- agents/specs/test_r05_personal_configuration.py +86 -0
- agents/specs/test_r06_delegation.py +70 -0
- agents/specs/test_r07_sharing.py +103 -0
- agents/specs/test_r08_embedding.py +40 -0
- agents/specs/test_r09_finding.py +41 -0
- agents/specs/test_r10_clients.py +41 -0
- agents/strategies/__init__.py +0 -0
- agents/strategies/_schema.py +16 -0
- agents/strategies/agents.py +93 -0
- agents/strategies/context.py +45 -0
- agents/strategies/conversations.py +65 -0
- agents/strategies/instructions.py +62 -0
- agents/strategies/messages.py +56 -0
- agents/strategies/models.py +27 -0
- agents/strategies/profiles.py +43 -0
- agents/strategies/skills.py +47 -0
- agents/strategies/turn.py +47 -0
- agents/test_settings.py +6 -0
- agents/tests/__init__.py +0 -0
- agents/tests/support.py +94 -0
- agents/tests/test_agent_views.py +181 -0
- agents/tests/test_agents.py +166 -0
- agents/tests/test_anthropic_adapter.py +221 -0
- agents/tests/test_context.py +231 -0
- agents/tests/test_control.py +162 -0
- agents/tests/test_conversations.py +158 -0
- agents/tests/test_delegation.py +392 -0
- agents/tests/test_google_adapter.py +208 -0
- agents/tests/test_inspect.py +59 -0
- agents/tests/test_live_providers.py +69 -0
- agents/tests/test_openai_adapter.py +259 -0
- agents/tests/test_profiles.py +92 -0
- agents/tests/test_resumption.py +150 -0
- agents/tests/test_turns.py +230 -0
- agents/validation.py +48 -0
- agents_agent_frontend/__init__.py +3 -0
- agents_agent_frontend/agent_views.py +286 -0
- audio/__init__.py +0 -0
- audio/apps.py +14 -0
- audio/authorization.py +13 -0
- audio/conf.py +27 -0
- audio/entities/__init__.py +11 -0
- audio/entities/recording.py +10 -0
- audio/migrations/0001_initial.py +26 -0
- audio/migrations/__init__.py +0 -0
- audio/models.py +9 -0
- audio/persistence.py +6 -0
- audio/providers/__init__.py +0 -0
- audio/providers/fake.py +35 -0
- audio/providers/openai.py +50 -0
- audio/providers/port.py +31 -0
- audio/providers/registry.py +31 -0
- audio/specs/__init__.py +3 -0
- audio/specs/dsl.py +120 -0
- audio/specs/test_clients.py +20 -0
- audio/specs/test_dictation.py +87 -0
- audio/specs/test_privacy.py +45 -0
- audio/specs/test_vendor.py +59 -0
- audio/strategies/__init__.py +11 -0
- audio/strategies/recordings.py +88 -0
- audio/test_settings.py +6 -0
- audio/tests/__init__.py +0 -0
- audio/tests/test_openai_adapter.py +65 -0
- audio/tests/test_recordings.py +139 -0
- audio_agent_frontend/__init__.py +3 -0
- audio_agent_frontend/agent_views.py +11 -0
- graphcore_apps-0.5.0.dist-info/METADATA +14 -0
- graphcore_apps-0.5.0.dist-info/RECORD +118 -0
- graphcore_apps-0.5.0.dist-info/WHEEL +5 -0
- graphcore_apps-0.5.0.dist-info/entry_points.txt +7 -0
- graphcore_apps-0.5.0.dist-info/licenses/LICENSE +202 -0
- graphcore_apps-0.5.0.dist-info/licenses/NOTICE +2 -0
- graphcore_apps-0.5.0.dist-info/top_level.txt +4 -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
|
audio/models.py
ADDED
|
@@ -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)
|
audio/persistence.py
ADDED
|
File without changes
|
audio/providers/fake.py
ADDED
|
@@ -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)
|
audio/providers/port.py
ADDED
|
@@ -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()
|
audio/specs/__init__.py
ADDED
audio/specs/dsl.py
ADDED
|
@@ -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
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Dictating into a recording: each take's words become the recording's text."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from graphcore.public.live_testing import scenario
|
|
5
|
+
|
|
6
|
+
from audio.specs.dsl import SCRIPTED_MODEL, AudioDsl, heard
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@scenario('Recordings', 'A person has one recording per purpose, the same one every time they open it')
|
|
10
|
+
async def _(a: AudioDsl):
|
|
11
|
+
ana = a.as_('Ana')
|
|
12
|
+
|
|
13
|
+
composer = await ana.opens_a_recording('agents.composer')
|
|
14
|
+
again = await ana.opens_a_recording('agents.composer')
|
|
15
|
+
notes = await ana.opens_a_recording('notes.editor')
|
|
16
|
+
|
|
17
|
+
assert composer == again and composer != notes
|
|
18
|
+
assert await ana.words_in(composer) == '' and await ana.takes_of(composer) == 0
|
|
19
|
+
assert sorted(r['purpose'] for r in await ana.recordings()) == ['agents.composer', 'notes.editor']
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@scenario('Recordings', "Two people opening the same purpose get recordings of their own")
|
|
23
|
+
async def _(a: AudioDsl):
|
|
24
|
+
ana, ben = a.as_('Ana'), a.as_('Ben')
|
|
25
|
+
|
|
26
|
+
hers = await ana.opens_a_recording('agents.composer')
|
|
27
|
+
his = await ben.opens_a_recording('agents.composer')
|
|
28
|
+
|
|
29
|
+
assert hers != his
|
|
30
|
+
assert [r['entity_id'] for r in await ben.recordings()] == [his]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@scenario('Dictation', 'The words of a take become the recording\'s text, and the take is counted')
|
|
34
|
+
async def _(a: AudioDsl):
|
|
35
|
+
ana = a.as_('Ana')
|
|
36
|
+
recording = await ana.opens_a_recording()
|
|
37
|
+
|
|
38
|
+
with a.the_vendor_hears('Book the venue for June.') as vendor:
|
|
39
|
+
take = await ana.dictates(recording, mime_type='audio/webm', language='en')
|
|
40
|
+
|
|
41
|
+
assert take.succeeded and (take.text, take.take) == ('Book the venue for June.', 1), take
|
|
42
|
+
assert await ana.words_in(recording) == 'Book the venue for June.'
|
|
43
|
+
assert heard(vendor) == [{'model': SCRIPTED_MODEL.split('/')[1], 'audio': b'RIFF....WAVEfmt speech',
|
|
44
|
+
'mime_type': 'audio/webm', 'language': 'en'}]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@scenario('Dictation', 'A second take replaces the text and counts two')
|
|
48
|
+
async def _(a: AudioDsl):
|
|
49
|
+
ana = a.as_('Ana')
|
|
50
|
+
recording = await ana.opens_a_recording()
|
|
51
|
+
|
|
52
|
+
with a.the_vendor_hears('First thought.', 'Second thought.'):
|
|
53
|
+
await ana.dictates(recording)
|
|
54
|
+
take = await ana.dictates(recording)
|
|
55
|
+
|
|
56
|
+
assert (take.text, take.take) == ('Second thought.', 2), take
|
|
57
|
+
assert (await ana.words_in(recording), await ana.takes_of(recording)) == ('Second thought.', 2)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@scenario('Dictation', 'A watcher sees the words arrive over the live connection')
|
|
61
|
+
async def _(a: AudioDsl):
|
|
62
|
+
ana = a.as_('Ana')
|
|
63
|
+
recording = await ana.opens_a_recording()
|
|
64
|
+
connection = await ana.connects()
|
|
65
|
+
await connection.subscribe(recording)
|
|
66
|
+
|
|
67
|
+
with a.the_vendor_hears('Live words.'):
|
|
68
|
+
await ana.dictates(recording)
|
|
69
|
+
|
|
70
|
+
await connection.sees(recording, text='Live words.', take=1)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@scenario('Dictation', 'A take nobody waits for still lands, once the vendor answers')
|
|
74
|
+
async def _(a: AudioDsl):
|
|
75
|
+
ana = a.as_('Ana')
|
|
76
|
+
recording = await ana.opens_a_recording()
|
|
77
|
+
|
|
78
|
+
with a.the_vendor_hears('Slowly spoken.', hold=True) as vendor:
|
|
79
|
+
take = await ana.dictates(recording, wait=False)
|
|
80
|
+
await vendor.wait_for_calls(1)
|
|
81
|
+
assert (await ana.request(take))['status'] == 'running'
|
|
82
|
+
assert await ana.takes_of(recording) == 0
|
|
83
|
+
|
|
84
|
+
vendor.release()
|
|
85
|
+
|
|
86
|
+
assert (await ana.finished(take)).succeeded
|
|
87
|
+
assert await ana.words_in(recording) == 'Slowly spoken.'
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""A recording is its owner's alone, and the audio is never kept."""
|
|
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('Privacy', "Nobody else can read a person's recording or dictate into it")
|
|
10
|
+
async def _(a: AudioDsl):
|
|
11
|
+
ana, ben = a.as_('Ana'), a.as_('Ben')
|
|
12
|
+
recording = await ana.opens_a_recording()
|
|
13
|
+
with a.the_vendor_hears('Private words.', 'Not mine.') as vendor:
|
|
14
|
+
await ana.dictates(recording)
|
|
15
|
+
|
|
16
|
+
take = await ben.dictates(recording)
|
|
17
|
+
|
|
18
|
+
assert not take.succeeded, take
|
|
19
|
+
assert not await ben.can_read(recording)
|
|
20
|
+
assert await ana.words_in(recording) == 'Private words.'
|
|
21
|
+
assert vendor.call_count == 1
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@scenario('Privacy', 'A recording cannot be shared')
|
|
25
|
+
async def _(a: AudioDsl):
|
|
26
|
+
ana, ben = a.as_('Ana'), a.as_('Ben')
|
|
27
|
+
recording = await ana.opens_a_recording()
|
|
28
|
+
|
|
29
|
+
outcome = await ana.shares(recording, with_=ben)
|
|
30
|
+
|
|
31
|
+
assert outcome['status'] == 'failed', outcome
|
|
32
|
+
assert not await ben.can_read(recording)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@scenario('Privacy', 'The audio is not kept on the request once the take ends')
|
|
36
|
+
async def _(a: AudioDsl):
|
|
37
|
+
ana = a.as_('Ana')
|
|
38
|
+
recording = await ana.opens_a_recording()
|
|
39
|
+
|
|
40
|
+
with a.the_vendor_hears('Gone afterwards.'):
|
|
41
|
+
take = await ana.dictates(recording)
|
|
42
|
+
|
|
43
|
+
params = (await ana.request(take))['param_config']
|
|
44
|
+
assert params['mime_type'] == 'audio/webm'
|
|
45
|
+
assert 'UklGRi4uLi5XQVZFZm10IHNwZWVjaA' not in str(params), params
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""What a person is told when the speech-to-text vendor, or the audio, is not right."""
|
|
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('Vendor', "Without the vendor's key, a take fails naming the key and leaves the text alone")
|
|
10
|
+
async def _(a: AudioDsl):
|
|
11
|
+
ana = a.as_('Ana')
|
|
12
|
+
recording = await ana.opens_a_recording()
|
|
13
|
+
|
|
14
|
+
take = await ana.dictates(recording)
|
|
15
|
+
|
|
16
|
+
assert take.status == 'failed' and 'OPENAI_API_KEY' in take.error, take
|
|
17
|
+
assert (await ana.words_in(recording), await ana.takes_of(recording)) == ('', 0)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@scenario('Vendor', 'A vendor that refuses the audio fails the take and writes nothing')
|
|
21
|
+
async def _(a: AudioDsl):
|
|
22
|
+
ana = a.as_('Ana')
|
|
23
|
+
recording = await ana.opens_a_recording()
|
|
24
|
+
|
|
25
|
+
with a.the_vendor_fails('invalid_request', 'unsupported audio format'):
|
|
26
|
+
take = await ana.dictates(recording)
|
|
27
|
+
|
|
28
|
+
assert take.status == 'failed' and 'unsupported audio format' in take.error, take
|
|
29
|
+
assert await ana.takes_of(recording) == 0
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@scenario('Vendor', 'A busy vendor is asked again, and the second answer is kept')
|
|
33
|
+
async def _(a: AudioDsl):
|
|
34
|
+
ana = a.as_('Ana')
|
|
35
|
+
recording = await ana.opens_a_recording()
|
|
36
|
+
|
|
37
|
+
with a.the_vendor_is_busy_once_then_hears('Second time lucky.') as vendor:
|
|
38
|
+
take = await ana.dictates(recording)
|
|
39
|
+
|
|
40
|
+
assert take.succeeded, take
|
|
41
|
+
assert vendor.call_count == 2
|
|
42
|
+
assert (await ana.words_in(recording), await ana.takes_of(recording)) == ('Second time lucky.', 1)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@scenario('Limits', 'Audio that is not base64, empty, or too large is refused before the vendor hears it')
|
|
46
|
+
async def _(a: AudioDsl):
|
|
47
|
+
ana = a.as_('Ana')
|
|
48
|
+
recording = await ana.opens_a_recording()
|
|
49
|
+
|
|
50
|
+
with a.the_vendor_hears('never') as vendor, a.uploads_are_limited_to(8):
|
|
51
|
+
garbled = await ana.sends_text_as_audio(recording, 'not base64!')
|
|
52
|
+
empty = await ana.dictates(recording, audio=b'')
|
|
53
|
+
large = await ana.dictates(recording, audio=b'123456789')
|
|
54
|
+
|
|
55
|
+
assert 'not base64' in garbled.error, garbled
|
|
56
|
+
assert 'empty' in empty.error, empty
|
|
57
|
+
assert 'larger than 8 bytes' in large.error, large
|
|
58
|
+
assert vendor.call_count == 0
|
|
59
|
+
assert await ana.takes_of(recording) == 0
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Strategies for the audio app. Every module in this package is
|
|
2
|
+
# imported at startup, so decorated classes register themselves.
|
|
3
|
+
#
|
|
4
|
+
# from graphcore.public.strategies import Strategy, register_strategy
|
|
5
|
+
#
|
|
6
|
+
# from audio.entities.board import Board
|
|
7
|
+
#
|
|
8
|
+
# @register_strategy(Board)
|
|
9
|
+
# class ArchiveBoard(Strategy):
|
|
10
|
+
# async def apply(self):
|
|
11
|
+
# return self.strategy_request, self.entity
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
import binascii
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
from graphcore.public.entities import Entity
|
|
6
|
+
from graphcore.public.errors import InvalidRequest, StrategyFailed, TransientError
|
|
7
|
+
from graphcore.public.persistence import AllOf, EntityFilter, Equal
|
|
8
|
+
from graphcore.public.strategies import Strategy, StrategyRequestPayload, register_strategy
|
|
9
|
+
|
|
10
|
+
from audio import conf
|
|
11
|
+
from audio.entities.recording import Recording
|
|
12
|
+
from audio.providers.port import ProviderError
|
|
13
|
+
from audio.providers.registry import transcriber_for
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _params(properties: dict, required: tuple = ()) -> dict:
|
|
17
|
+
return {"type": "object", "properties": properties, "required": list(required), "additionalProperties": False}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@register_strategy(Entity)
|
|
21
|
+
class OpenRecording(Strategy):
|
|
22
|
+
strategy_description = "Returns the caller's recording for a purpose, creating it the first time"
|
|
23
|
+
param_schema = _params(
|
|
24
|
+
{"purpose": {"type": "string", "description": "Where the dictation goes, such as `agents.composer`"}},
|
|
25
|
+
required=('purpose',),
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
async def apply(self) -> tuple:
|
|
29
|
+
purpose = self.strategy_request.param_config['purpose']
|
|
30
|
+
# The first in listing order, so a duplicate left by a lost race never takes over.
|
|
31
|
+
page = await self.session.list(EntityFilter(
|
|
32
|
+
type_ids=frozenset({Recording.get_entity_type_id()}),
|
|
33
|
+
where=AllOf((Equal('owner', self.principal_entity_id), Equal('purpose', purpose))),
|
|
34
|
+
), limit=1)
|
|
35
|
+
recording = page.entities[0] if page.entities else await self.save_entity(
|
|
36
|
+
self.session.create(Recording, purpose=purpose),
|
|
37
|
+
)
|
|
38
|
+
self.strategy_request.ret_val['recording_id'] = recording.entity_id
|
|
39
|
+
return self.strategy_request, self.entity
|
|
40
|
+
|
|
41
|
+
@classmethod
|
|
42
|
+
def request_constructor(cls, purpose: str) -> StrategyRequestPayload:
|
|
43
|
+
return cls._build_request(target_entity_id=None, param_config={'purpose': purpose})
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@register_strategy(Recording)
|
|
47
|
+
class Transcribe(Strategy):
|
|
48
|
+
strategy_description = "Turns recorded speech into the recording's text and counts a new take"
|
|
49
|
+
timeout = 120
|
|
50
|
+
transient_params = frozenset({'audio'})
|
|
51
|
+
param_schema = _params(
|
|
52
|
+
{
|
|
53
|
+
"audio": {"type": "string", "description": "The audio file, base64-encoded"},
|
|
54
|
+
"mime_type": {"type": "string", "description": "The audio's type, such as `audio/webm`"},
|
|
55
|
+
"language": {"type": "string", "description": "ISO-639-1 code of the spoken language, when known"},
|
|
56
|
+
},
|
|
57
|
+
required=('audio', 'mime_type'),
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
async def apply(self) -> tuple:
|
|
61
|
+
given = self.strategy_request.param_config
|
|
62
|
+
try:
|
|
63
|
+
audio = base64.b64decode(given['audio'], validate=True)
|
|
64
|
+
except (binascii.Error, ValueError) as exc:
|
|
65
|
+
raise InvalidRequest("audio is not base64") from exc
|
|
66
|
+
if not audio:
|
|
67
|
+
raise InvalidRequest("audio is empty")
|
|
68
|
+
if len(audio) > conf.max_audio_bytes():
|
|
69
|
+
raise InvalidRequest(f"audio is larger than {conf.max_audio_bytes()} bytes")
|
|
70
|
+
try:
|
|
71
|
+
transcriber, model = transcriber_for(conf.model())
|
|
72
|
+
text = await transcriber.transcribe(model, audio, given['mime_type'], given.get('language'))
|
|
73
|
+
except ProviderError as exc:
|
|
74
|
+
if exc.retryable:
|
|
75
|
+
raise TransientError(str(exc)) from exc
|
|
76
|
+
raise StrategyFailed(str(exc)) from exc
|
|
77
|
+
self.entity.text = text
|
|
78
|
+
self.entity.take += 1
|
|
79
|
+
self.strategy_request.ret_val.update(text=text, take=self.entity.take)
|
|
80
|
+
return self.strategy_request, self.entity
|
|
81
|
+
|
|
82
|
+
@classmethod
|
|
83
|
+
def request_constructor(cls, target_entity_id: str, audio: str, mime_type: str,
|
|
84
|
+
language: Optional[str] = None) -> StrategyRequestPayload:
|
|
85
|
+
param_config = {'audio': audio, 'mime_type': mime_type}
|
|
86
|
+
if language:
|
|
87
|
+
param_config['language'] = language
|
|
88
|
+
return cls._build_request(target_entity_id=target_entity_id, param_config=param_config)
|
audio/test_settings.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
# Runs this app's tests without a project:
|
|
2
|
+
# python -m django test audio --settings=audio.test_settings
|
|
3
|
+
# Inside a project, `graphcore test` runs them with the project's settings.
|
|
4
|
+
from graphcore.public.test_settings import app_test_settings
|
|
5
|
+
|
|
6
|
+
globals().update(app_test_settings('audio'))
|
audio/tests/__init__.py
ADDED
|
File without changes
|