-
Notifications
You must be signed in to change notification settings - Fork 12
/
transcriber.py
1244 lines (999 loc) · 36.4 KB
/
transcriber.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import base64
import concurrent.futures
import functools
import json
import os
import queue
import threading
import time
from typing import (
Any,
Callable,
Dict,
Generator,
Iterable,
Iterator,
List,
Optional,
Union,
)
from urllib.parse import urlencode, urlparse
import httpx
import websockets
import websockets.exceptions
from typing_extensions import Self
from websockets.sync.client import connect as websocket_connect
from . import api
from . import client as _client
from . import lemur, types
class _TranscriptImpl:
def __init__(
self,
*,
client: _client.Client,
transcript_id: Optional[str],
) -> None:
self._client = client
self.transcript_id = transcript_id
self.transcript: Optional[types.TranscriptResponse] = None
@property
def config(self) -> types.TranscriptionConfig:
"Returns the configuration from the internal Transcript object"
return types.TranscriptionConfig(
**self.transcript.dict(
include=set(types.RawTranscriptionConfig.__fields__),
exclude_none=True,
)
)
@classmethod
def from_response(
cls,
*,
client: _client.Client,
response: types.TranscriptResponse,
) -> Self:
self = cls(
client=client,
transcript_id=response.id,
)
self.transcript = response
return self
def wait_for_completion(self) -> Self:
"""
polls the given transcript until we have a status other than `processing` or `queued`
"""
while True:
try:
self.transcript = api.get_transcript(
self._client.http_client,
self.transcript_id,
)
except Exception as exc:
self.transcript = types.TranscriptResponse(
**self.transcript.dict(
exclude_none=True, exclude={"status", "error"}
),
status=types.TranscriptStatus.error,
error=str(exc),
)
if self.transcript.status in (
types.TranscriptStatus.completed,
types.TranscriptStatus.error,
):
break
time.sleep(self._client.settings.polling_interval)
return self
def export_subtitles_srt(
self,
*,
chars_per_caption: Optional[int],
) -> str:
return api.export_subtitles_srt(
client=self._client.http_client,
transcript_id=self.transcript.id,
chars_per_caption=chars_per_caption,
)
def export_subtitles_vtt(
self,
*,
chars_per_caption: Optional[int],
) -> str:
return api.export_subtitles_vtt(
client=self._client.http_client,
transcript_id=self.transcript.id,
chars_per_caption=chars_per_caption,
)
def word_search(
self,
*,
words: List[str],
) -> List[types.WordSearchMatch]:
response = api.word_search(
client=self._client.http_client,
transcript_id=self.transcript.id,
words=words,
)
return response.matches
def get_sentences(self) -> List[types.Sentence]:
response = api.get_sentences(
client=self._client.http_client,
transcript_id=self.transcript.id,
)
return response.sentences
def get_paragraphs(self) -> List[types.Paragraph]:
response = api.get_paragraphs(
client=self._client.http_client,
transcript_id=self.transcript.id,
)
return response.paragraphs
@functools.lru_cache
def get_redacted_audio_url(self) -> str:
"""
Retrieve the URL for the PII-redacted audio file, if `redact_pii_audio` was enabled on the `TranscriptionConfig`.
Subsequent calls will return cached URL rather than requesting it from the API again.
Returns: The URL of the redacted audio file.
"""
if not self.config.redact_pii or not self.config.redact_pii_audio:
raise ValueError(
"Redacted audio is only available when `redact_pii` and `redact_pii_audio` are set to `True`."
)
while True:
try:
return api.get_redacted_audio(
client=self._client.http_client,
transcript_id=self.transcript_id,
).redacted_audio_url
except types.RedactedAudioIncompleteError:
time.sleep(self._client.settings.polling_interval)
def save_redacted_audio(self, filepath: str):
"""
Retrieve the PII-redacted audio file, if `redact_pii_audio` was enabled on the `TranscriptionConfig`
Args:
filepath: The path to save the redacted audio file to.
"""
with httpx.stream(method="GET", url=self.get_redacted_audio_url()) as response:
if response.status_code not in (httpx.codes.OK, httpx.codes.NOT_MODIFIED):
raise types.RedactedAudioUnavailableError(
f"Fetching redacted audio failed with status code {response.status_code}"
)
with open(filepath, "wb") as f:
for chunk in response.iter_bytes():
f.write(chunk)
class Transcript(types.Sourcable):
"""
Transcript object to perform operations on the actual transcript.
"""
def __init__(
self,
transcript_id: Optional[str],
client: Optional[_client.Client] = None,
) -> None:
self._client = client or _client.Client.get_default()
self._impl = _TranscriptImpl(
client=self._client,
transcript_id=transcript_id,
)
self._executor = concurrent.futures.ThreadPoolExecutor()
def wait_for_completion(self) -> Self:
self._impl.wait_for_completion()
return self
def wait_for_completion_async(
self,
) -> concurrent.futures.Future[Self]:
return self._executor.submit(self.wait_for_completion)
@classmethod
def from_response(
cls,
*,
client: _client.Client,
response: types.TranscriptResponse,
) -> Self:
_impl = _TranscriptImpl.from_response(client=client, response=response)
self = cls(
client=client,
transcript_id=response.id,
)
self._impl = _impl
return self
@classmethod
def get_by_id(cls, transcript_id: str) -> Self:
"""Fetch an existing transcript. Blocks until the transcript is completed.
Args:
transcript_id: the id of the transcript to fetch
Returns:
The transcript object identified by the given id.
"""
return cls(transcript_id=transcript_id).wait_for_completion()
@classmethod
def get_by_id_async(cls, transcript_id: str) -> concurrent.futures.Future[Self]:
"""Fetch an existing transcript asynchronously.
Args:
transcript_id: the id of the transcript to fetch
Returns:
A future that will resolve to the transcript object identified by the given id.
"""
return cls(transcript_id=transcript_id).wait_for_completion_async()
@property
def id(self) -> Optional[str]:
"The unique identifier of your transcription"
return self._impl.transcript_id
@property
def config(self) -> types.TranscriptionConfig:
"Return the corresponding configurations for the given transcript."
return self._impl.config
@property
def json_response(self) -> Optional[dict]:
"The full JSON response associated with the transcript."
return self._impl.transcript.dict()
@property
def audio_url(self) -> str:
"The corresponding audio url"
return self._impl.transcript.audio_url
@property
def text(self) -> Optional[str]:
"The text transcription of your media file"
return self._impl.transcript.text
@property
def summary(self) -> Optional[str]:
"The summarization of the transcript"
return self._impl.transcript.summary
@property
def chapters(self) -> Optional[List[types.Chapter]]:
"The list of auto-chapters results"
return self._impl.transcript.chapters
@property
def content_safety(self) -> Optional[types.ContentSafetyResponse]:
"The results from the content safety analysis"
return self._impl.transcript.content_safety_labels
@property
def sentiment_analysis(self) -> Optional[List[types.Sentiment]]:
"The list of sentiment analysis results"
return self._impl.transcript.sentiment_analysis_results
@property
def entities(self) -> Optional[List[types.Entity]]:
"The list of entity detection results"
return self._impl.transcript.entities
@property
def iab_categories(self) -> Optional[types.IABResponse]:
"The results from the IAB category detection"
return self._impl.transcript.iab_categories_result
@property
def auto_highlights(self) -> Optional[types.AutohighlightResponse]:
"The results from the auto-highlights model"
return self._impl.transcript.auto_highlights_result
@property
def status(self) -> types.TranscriptStatus:
"The current status of the transcript"
return self._impl.transcript.status
@property
def error(self) -> Optional[str]:
"The error message in case the transcription fails"
return self._impl.transcript.error
@property
def words(self) -> Optional[List[types.Word]]:
"The list of words in the transcript"
return self._impl.transcript.words
@property
def utterances(self) -> Optional[List[types.Utterance]]:
"""
When `dual_channel` or `speaker_labels` is enabled,
a list of utterances in the transcript.
"""
return self._impl.transcript.utterances
@property
def confidence(self) -> Optional[float]:
"The confidence our model has in the transcribed text, between 0 and 1"
return self._impl.transcript.confidence
@property
def audio_duration(self) -> Optional[float]:
"The duration of the audio in seconds"
return self._impl.transcript.audio_duration
@property
def webhook_status_code(self) -> Optional[int]:
"The status code we received from your server when delivering your webhook"
return self._impl.transcript.webhook_status_code
@property
def webhook_auth(self) -> Optional[bool]:
"Whether the webhook was sent with an HTTP authentication header"
return self._impl.transcript.webhook_auth
@property
def lemur(self) -> lemur.Lemur:
"""
Access AssemblyAI's LeMUR features.
"""
return lemur.Lemur(
client=self._client,
sources=[types.LemurSource(self)],
)
def export_subtitles_srt(
self,
chars_per_caption: Optional[int] = None,
) -> str:
"""
You can export your complete transcripts in SRT format,
to be plugged into a video player for subtitles and closed captions.
Args:
chars_per_caption: To control the maximum number of characters per caption
Returns: A string containing the all subtitles in SRT format.
"""
return self._impl.export_subtitles_srt(
chars_per_caption=chars_per_caption,
)
def export_subtitles_vtt(
self,
chars_per_caption: Optional[int] = None,
) -> str:
"""
You can export your complete transcripts in VTT format,
to be plugged into a video player for subtitles and closed captions.
Args:
chars_per_caption: To control the maximum number of characters per caption
Returns: A string containing the all subtitles in VTT format.
"""
return self._impl.export_subtitles_vtt(
chars_per_caption=chars_per_caption,
)
def word_search(
self,
words: List[str],
) -> List[types.WordSearchMatch]:
"""
Once a transcript has been completed, you can search through the transcript for a specific set of keywords.
You can search for individual words, numbers, or phrases containing up to five words or numbers.
Args:
words: A list of words, numbers, or phrases (containing up to five words or numbers)
Returns: A list of matches
"""
return self._impl.word_search(
words=words,
)
def get_sentences(
self,
) -> List[types.Sentence]:
"""
Semantically segment your transcript into sentences to create more reader-friendly transcripts.
Returns: A list of sentence objects.
"""
return self._impl.get_sentences()
def get_paragraphs(
self,
) -> List[types.Paragraph]:
"""
Semantically segment your transcript into paragraphs to create more reader-friendly transcripts.
Returns: A list of paragraph objects.
"""
return self._impl.get_paragraphs()
def get_redacted_audio_url(self) -> str:
"""
Retrieve the URL for the PII-redacted audio file, if `redact_pii_audio` was enabled on the `TranscriptionConfig`.
Subsequent calls will return cached URL rather than requesting it from the API again.
Returns: The URL of the redacted audio file.
"""
return self._impl.get_redacted_audio_url()
def save_redacted_audio(self, filepath: str):
"""
Retrieve the PII-redacted audio file, if `redact_pii_audio` was enabled on the `TranscriptionConfig`
Args:
filepath: The path to save the redacted audio file to.
"""
return self._impl.save_redacted_audio(filepath=filepath)
class _TranscriptGroupImpl:
def __init__(
self,
*,
transcript_ids: List[str],
client: _client.Client,
) -> None:
self._client = client
self.transcripts: List[Transcript] = []
for transcript_id in transcript_ids:
self.add_transcript(transcript_id)
@property
def transcript_ids(self) -> List[str]:
return [t.id for t in self.transcripts]
def add_transcript(self, transcript: Union[Transcript, str]) -> None:
if isinstance(transcript, Transcript):
self.transcripts.append(transcript)
elif isinstance(transcript, str):
self.transcripts.append(
Transcript(
client=self._client,
transcript_id=transcript,
)
)
else:
raise TypeError("Unsupported type for `transcript`")
return self
def wait_for_completion(self) -> None:
transcripts: List[Transcript] = []
future_transcripts: Dict[concurrent.futures.Future[Transcript], str] = {}
for transcript in self.transcripts:
future = transcript.wait_for_completion_async()
future_transcripts[future] = transcript
finished_futures, _ = concurrent.futures.wait(future_transcripts)
for future in finished_futures:
transcripts.append(future.result())
self.transcripts = transcripts
class TranscriptGroup:
"""
A group of transcripts.
Used when transcribing multiple transcripts at once.
"""
def __init__(
self,
transcript_ids: List[str] = [],
client: Optional[_client.Client] = None,
) -> None:
self._client = client or _client.Client.get_default()
self._impl = _TranscriptGroupImpl(
transcript_ids=transcript_ids,
client=self._client,
)
self._executor = concurrent.futures.ThreadPoolExecutor()
@property
def transcripts(self) -> List[Transcript]:
"""
Returns the list of the transcripts within the `TranscriptGroup`
"""
return self._impl.transcripts
def __iter__(self) -> Iterator[Transcript]:
"""
Iterate over the transcripts within the `TranscriptGroup`
"""
return iter(self.transcripts)
@classmethod
def get_by_ids(cls, transcript_ids: List[str]) -> Self:
return cls(transcript_ids=transcript_ids).wait_for_completion()
@classmethod
def get_by_ids_async(
cls, transcript_ids: List[str]
) -> concurrent.futures.Future[Self]:
return cls(transcript_ids=transcript_ids).wait_for_completion_async()
@property
def status(self) -> types.TranscriptStatus:
"""
Return the status of the `TranscriptGroup`.
e.g. if any of the transcripts is in `error` status, the whole `TranscriptGroup` will be in `error` status.
"""
all_status = {t.status for t in self.transcripts}
if any(s == types.TranscriptStatus.error for s in all_status):
return types.TranscriptStatus.error
elif any(s == types.TranscriptStatus.queued for s in all_status):
return types.TranscriptStatus.queued
elif any(s == types.TranscriptStatus.processing for s in all_status):
return types.TranscriptStatus.processing
elif all(s == types.TranscriptStatus.completed for s in all_status):
return types.TranscriptStatus.completed
@property
def lemur(self) -> lemur.Lemur:
"""
Access AssemblyAI's LeMUR functionality.
"""
return lemur.Lemur(
client=self._impl._client,
sources=[types.LemurSource(t) for t in self.transcripts],
)
def add_transcript(
self,
transcript: Union[Transcript, str],
) -> Self:
"""
Adds a transcript to the given `TranscriptGroup`
Args:
transcript: A `Transcript` object or the ID as a `str`
"""
self._impl.add_transcript(transcript)
return self
def wait_for_completion(self) -> Self:
"""
Polls each transcript within the `TranscriptGroup`.
"""
self._impl.wait_for_completion()
return self
def wait_for_completion_async(
self,
) -> concurrent.futures.Future[Self]:
return self._executor.submit(self.wait_for_completion)
class _TranscriberImpl:
"""
Implementation of the Transcriber class.
"""
def __init__(
self,
*,
client: _client.Client,
config: types.TranscriptionConfig,
) -> None:
self._client = client
self.config = config
def transcribe_url(
self,
*,
url: str,
config: types.TranscriptionConfig,
poll: bool,
) -> Transcript:
transcript_request = types.TranscriptRequest(
audio_url=url,
**config.raw.dict(exclude_none=True),
)
try:
transcript = Transcript.from_response(
client=self._client,
response=api.create_transcript(
client=self._client.http_client,
request=transcript_request,
),
)
except Exception as exc:
return Transcript.from_response(
client=self._client,
response=types.TranscriptResponse(
audio_url=url,
**config.raw.dict(exclude_none=True),
status=types.TranscriptStatus.error,
error=str(exc),
),
)
if poll:
return transcript.wait_for_completion()
return transcript
def transcribe_file(
self,
*,
path: str,
config: types.TranscriptionConfig,
poll: bool,
) -> Transcript:
with open(path, "rb") as audio_file:
try:
audio_url = api.upload_file(
client=self._client.http_client,
audio_file=audio_file,
)
except Exception as exc:
return Transcript.from_response(
client=self._client,
response=types.TranscriptResponse(
audio_url=path,
**config.raw.dict(exclude_none=True),
status=types.TranscriptStatus.error,
error=str(exc),
),
)
return self.transcribe_url(
url=audio_url,
config=config,
poll=poll,
)
def transcribe(
self,
data: str,
config: Optional[types.TranscriptionConfig],
poll: bool,
) -> Transcript:
if config is None:
config = self.config
if urlparse(data).scheme in {"http", "https"}:
return self.transcribe_url(
url=data,
config=config,
poll=poll,
)
return self.transcribe_file(
path=data,
config=config,
poll=poll,
)
def transcribe_group(
self,
*,
data: List[str],
config: Optional[types.TranscriptionConfig],
poll: bool,
) -> TranscriptGroup:
if config is None:
config = self.config
executor = concurrent.futures.ThreadPoolExecutor(max_workers=8)
future_transcripts: Dict[concurrent.futures.Future[Transcript], str] = {}
for d in data:
transcript_future = executor.submit(
self.transcribe,
data=d,
config=config,
poll=False,
)
future_transcripts[transcript_future] = d
finished_futures, _ = concurrent.futures.wait(future_transcripts)
transcript_group = TranscriptGroup(
client=self._client,
)
for future in finished_futures:
transcript_group.add_transcript(future.result())
if poll:
return transcript_group.wait_for_completion()
return transcript_group
class Transcriber:
"""
A transcriber used for transcribing URLs or local audio files.
"""
def __init__(
self,
*,
client: Optional[_client.Client] = None,
config: Optional[types.TranscriptionConfig] = None,
max_workers: Optional[int] = None,
) -> None:
"""
Initializes the `Transcriber` with the given parameters.
Args:
`client`: The `Client` to use for the `Transcriber`. If `None` is given, the
default settings for the `Client` will be used.
`config`: The default configuration for the `Transcriber`. If `None` is given,
the default configuration of a `TranscriptionConfig` will be used.
`max_workers`: The maximum number of parallel jobs when using the `_async`
methods on the `Transcriber`. By default it uses `os.cpu_count() - 1`
Example:
To use the `Transcriber` with the default settings, you can simply do:
```
transcriber = aai.Transcriber()
```
To use the `Transcriber` with a custom configuration, you can do:
```
config = aai.TranscriptionConfig(punctuate=False, format_text=False)
transcriber = aai.Transcriber(config=config)
```
"""
self._client = client or _client.Client.get_default()
self._impl = _TranscriberImpl(
client=self._client,
config=config or types.TranscriptionConfig(),
)
if not max_workers:
max_workers = max(1, os.cpu_count() - 1)
self._executor = concurrent.futures.ThreadPoolExecutor(
max_workers=max_workers,
)
@property
def config(self) -> types.TranscriptionConfig:
"""
Returns the default configuration of the `Transcriber`.
"""
return self._impl.config
@config.setter
def config(self, config: types.TranscriptionConfig) -> None:
"""
Sets the default configuration of the `Transcriber`.
Args:
`config`: The new default configuration.
"""
self._impl.config = config
def submit(
self,
data: str,
config: Optional[types.TranscriptionConfig] = None,
) -> Transcript:
"""
Submits a transcription job without waiting for its completion.
Args:
data: An URL or a local file (as path)
config: Transcription options and features. If `None` is given, the Transcriber's
default configuration will be used.
"""
return self._impl.transcribe(
data=data,
config=config,
poll=False,
)
def submit_group(
self,
data: List[str],
config: Optional[types.TranscriptionConfig] = None,
) -> TranscriptGroup:
"""
Submits multiple transcription jobs without waiting for their completion.
Args:
data: A list of paths or URLs (can be mixed)
config: Transcription options and features. If `None` is given, the Transcriber's
default configuration will be used.
"""
return self._impl.transcribe_group(
data=data,
config=config,
poll=False,
)
def transcribe(
self,
data: str,
config: Optional[types.TranscriptionConfig] = None,
) -> Transcript:
"""
Transcribes an audio file whose location can be specified via a URL or file path.
Args:
data: An URL or a local file (as path)
config: Transcription options and features. If `None` is given, the Transcriber's
default configuration will be used.
"""
return self._impl.transcribe(
data=data,
config=config,
poll=True,
)
def transcribe_async(
self,
data: str,
config: Optional[types.TranscriptionConfig] = None,
) -> concurrent.futures.Future[Transcript]:
"""
Transcribes an audio file whose location can be specified via a URL or file path.
Args:
data: An URL or a local file (as path)
config: Transcription options and features. If `None` is given, the Transcriber's
default configuration will be used.
"""
return self._executor.submit(
self._impl.transcribe,
data=data,
config=config,
poll=True,
)
def transcribe_group(
self,
data: List[str],
config: Optional[types.TranscriptionConfig] = None,
) -> TranscriptGroup:
"""
Transcribes a list of files (as paths) or URLs with the given configs.
Args:
data: A list of paths or URLs (can be mixed)
config: Transcription options and features. If `None` is given, the Transcriber's
default configuration will be used.
"""
return self._impl.transcribe_group(
data=data,
config=config,
poll=True,
)
def transcribe_group_async(
self,
data: List[str],
config: Optional[types.TranscriptionConfig] = None,
) -> concurrent.futures.Future[TranscriptGroup]:
"""
Transcribes a list of files (as paths) or URLs with the given configs asynchronously
by returning a `concurrent.futures.Future[TranscriptGroup]` object.
Args:
data: A list of paths or URLs (can be mixed)
config: Transcription options and features. If `None` is given, the Transcriber's
default configuration will be used.
"""
return self._executor.submit(
self._impl.transcribe_group,
data=data,
config=config,
poll=True,
)
class _RealtimeTranscriberImpl:
def __init__(
self,
*,
on_data: Callable[[types.RealtimeTranscript], None],
on_error: Callable[[types.RealtimeError], None],
on_open: Optional[Callable[[types.RealtimeSessionOpened], None]],
on_close: Optional[Callable[[], None]],
sample_rate: int,
word_boost: List[str],
client: _client.Client,
) -> None:
self._client = client
self._websocket: Optional[websockets_client.ClientConnection] = None
self._on_open = on_open
self._on_data = on_data
self._on_error = on_error
self._on_close = on_close
self._sample_rate = sample_rate
self._word_boost = word_boost
self._write_queue: queue.Queue[bytes] = queue.Queue()
self._write_thread = threading.Thread(target=self._write)
self._read_thread = threading.Thread(target=self._read)
self._stop_event = threading.Event()
def connect(