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
|
import re
from datetime import datetime, timedelta
from typing import Any, Optional
from moto.core.base_backend import BackendDict, BaseBackend
from moto.core.common_models import BaseModel
from moto.moto_api._internal import mock_random
from moto.moto_api._internal.managed_state_model import ManagedState
from .exceptions import BadRequestException, ConflictException
class BaseObject(BaseModel):
def camelCase(self, key: str) -> str:
words = []
for word in key.split("_"):
words.append(word.title())
return "".join(words)
def gen_response_object(self) -> dict[str, Any]:
response_object: dict[str, Any] = {}
for key, value in self.__dict__.items():
if "_" in key:
response_object[self.camelCase(key)] = value
else:
response_object[key[0].upper() + key[1:]] = value
return response_object
@property
def response_object(self) -> dict[str, Any]: # type: ignore[misc]
return self.gen_response_object()
class FakeTranscriptionJob(BaseObject, ManagedState):
def __init__(
self,
account_id: str,
region_name: str,
transcription_job_name: str,
language_code: Optional[str],
media_sample_rate_hertz: Optional[int],
media_format: Optional[str],
media: dict[str, str],
output_bucket_name: Optional[str],
output_key: Optional[str],
output_encryption_kms_key_id: Optional[str],
settings: Optional[dict[str, Any]],
model_settings: Optional[dict[str, Optional[str]]],
job_execution_settings: Optional[dict[str, Any]],
content_redaction: Optional[dict[str, Any]],
identify_language: Optional[bool],
identify_multiple_languages: Optional[bool],
language_options: Optional[list[str]],
subtitles: Optional[dict[str, Any]],
):
ManagedState.__init__(
self,
"transcribe::transcriptionjob",
transitions=[
(None, "QUEUED"),
("QUEUED", "IN_PROGRESS"),
("IN_PROGRESS", "COMPLETED"),
],
)
self._account_id = account_id
self._region_name = region_name
self.transcription_job_name = transcription_job_name
self.language_code = language_code
self.language_codes: Optional[list[dict[str, Any]]] = None
self.media_sample_rate_hertz = media_sample_rate_hertz
self.media_format = media_format
self.media = media
self.transcript: Optional[dict[str, str]] = None
self.start_time: Optional[str] = None
self.completion_time: Optional[str] = None
self.creation_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
self.failure_reason = None
self.settings = settings or {
"ChannelIdentification": False,
"ShowAlternatives": False,
"ShowSpeakerLabels": False,
}
self.model_settings = model_settings or {"LanguageModelName": None}
self.job_execution_settings = job_execution_settings or {
"AllowDeferredExecution": False,
"DataAccessRoleArn": None,
}
self.content_redaction = content_redaction or {
"RedactionType": None,
"RedactionOutput": None,
}
self.identify_language = identify_language
self.identify_multiple_languages = identify_multiple_languages
self.language_options = language_options
self.identified_language_score: Optional[float] = None
self._output_bucket_name = output_bucket_name
self.output_key = output_key
self._output_encryption_kms_key_id = output_encryption_kms_key_id
self.output_location_type = (
"CUSTOMER_BUCKET" if self._output_bucket_name else "SERVICE_BUCKET"
)
self.subtitles = subtitles or {"Formats": [], "OutputStartIndex": 0}
def response_object(self, response_type: str) -> dict[str, Any]: # type: ignore
response_field_dict = {
"CREATE": [
"TranscriptionJobName",
"TranscriptionJobStatus",
"LanguageCode",
"LanguageCodes",
"MediaFormat",
"Media",
"Settings",
"StartTime",
"CreationTime",
"IdentifyLanguage",
"IdentifyMultipleLanguages",
"LanguageOptions",
"JobExecutionSettings",
"Subtitles",
],
"GET": [
"TranscriptionJobName",
"TranscriptionJobStatus",
"LanguageCode",
"LanguageCodes",
"MediaSampleRateHertz",
"MediaFormat",
"Media",
"Settings",
"Transcript",
"StartTime",
"CreationTime",
"CompletionTime",
"IdentifyLanguage",
"IdentifyMultipleLanguages",
"LanguageOptions",
"IdentifiedLanguageScore",
"Subtitles",
],
"LIST": [
"TranscriptionJobName",
"CreationTime",
"StartTime",
"CompletionTime",
"LanguageCode",
"LanguageCodes",
"TranscriptionJobStatus",
"FailureReason",
"IdentifyLanguage",
"IdentifyMultipleLanguages",
"IdentifiedLanguageScore",
"OutputLocationType",
],
}
response_fields = response_field_dict[response_type]
response_object = self.gen_response_object()
response_object["TranscriptionJobStatus"] = self.status
if response_type != "LIST":
return {
"TranscriptionJob": {
k: v
for k, v in response_object.items()
if k in response_fields and v is not None and v != [None]
}
}
else:
return {
k: v
for k, v in response_object.items()
if k in response_fields and v is not None and v != [None]
}
def advance(self) -> None:
old_status = self.status
super().advance()
new_status = self.status
if old_status == new_status:
return
if new_status == "IN_PROGRESS":
self.start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
if not self.media_sample_rate_hertz:
self.media_sample_rate_hertz = 44100
if not self.media_format:
file_ext = self.media["MediaFileUri"].split(".")[-1].lower()
self.media_format = (
file_ext if file_ext in ["mp3", "mp4", "wav", "flac"] else "mp3"
)
if self.identify_language:
self.identified_language_score = 0.999645948
# Simply identify first language passed in language_options
# If none is set, default to "en-US"
if self.language_options is not None and len(self.language_options) > 0:
self.language_code = self.language_options[0]
else:
self.language_code = "en-US"
if self.identify_multiple_languages:
self.identified_language_score = 0.999645948
# Identify first two languages passed in language_options
# If none is set, default to "en-US"
self.language_codes: list[dict[str, Any]] = [] # type: ignore[no-redef]
if self.language_options is None or len(self.language_options) == 0:
self.language_codes.append(
{"LanguageCode": "en-US", "DurationInSeconds": 123.0}
)
else:
self.language_codes.append(
{
"LanguageCode": self.language_options[0],
"DurationInSeconds": 123.0,
}
)
if len(self.language_options) > 1:
self.language_codes.append(
{
"LanguageCode": self.language_options[1],
"DurationInSeconds": 321.0,
}
)
elif new_status == "COMPLETED":
self.completion_time = (datetime.now() + timedelta(seconds=10)).strftime(
"%Y-%m-%d %H:%M:%S"
)
if self._output_bucket_name:
remove_json_extension = re.compile("\\.json$")
transcript_file_prefix = (
f"https://s3.{self._region_name}.amazonaws.com/"
f"{self._output_bucket_name}/"
f"{remove_json_extension.sub('', self.output_key or self.transcription_job_name)}"
)
self.output_location_type = "CUSTOMER_BUCKET"
else:
transcript_file_prefix = (
f"https://s3.{self._region_name}.amazonaws.com/"
f"aws-transcribe-{self._region_name}-prod/"
f"{self._account_id}/"
f"{self.transcription_job_name}/"
f"{mock_random.uuid4()}/"
"asrOutput"
)
self.output_location_type = "SERVICE_BUCKET"
self.transcript = {"TranscriptFileUri": f"{transcript_file_prefix}.json"}
self.subtitles["SubtitleFileUris"] = [
f"{transcript_file_prefix}.{format}"
for format in self.subtitles["Formats"]
]
class FakeVocabulary(BaseObject, ManagedState):
def __init__(
self,
account_id: str,
region_name: str,
vocabulary_name: str,
language_code: str,
phrases: Optional[list[str]],
vocabulary_file_uri: Optional[str],
):
# Configured ManagedState
super().__init__(
"transcribe::vocabulary",
transitions=[(None, "PENDING"), ("PENDING", "READY")],
)
# Configure internal properties
self._region_name = region_name
self.vocabulary_name = vocabulary_name
self.language_code = language_code
self.phrases = phrases
self.vocabulary_file_uri = vocabulary_file_uri
self.last_modified_time: Optional[str] = None
self.failure_reason = None
self.download_uri = f"https://s3.{region_name}.amazonaws.com/aws-transcribe-dictionary-model-{region_name}-prod/{account_id}/{vocabulary_name}/{mock_random.uuid4()}/input.txt"
def response_object(self, response_type: str) -> dict[str, Any]: # type: ignore
response_field_dict = {
"CREATE": [
"VocabularyName",
"LanguageCode",
"VocabularyState",
"LastModifiedTime",
"FailureReason",
],
"GET": [
"VocabularyName",
"LanguageCode",
"VocabularyState",
"LastModifiedTime",
"FailureReason",
"DownloadUri",
],
"LIST": [
"VocabularyName",
"LanguageCode",
"LastModifiedTime",
"VocabularyState",
],
}
response_fields = response_field_dict[response_type]
response_object = self.gen_response_object()
response_object["VocabularyState"] = self.status
return {
k: v
for k, v in response_object.items()
if k in response_fields and v is not None and v != [None]
}
def advance(self) -> None:
old_status = self.status
super().advance()
new_status = self.status
if old_status != new_status:
self.last_modified_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
class FakeMedicalTranscriptionJob(BaseObject, ManagedState):
def __init__(
self,
region_name: str,
medical_transcription_job_name: str,
language_code: str,
media_sample_rate_hertz: Optional[int],
media_format: Optional[str],
media: dict[str, str],
output_bucket_name: str,
output_encryption_kms_key_id: Optional[str],
settings: Optional[dict[str, Any]],
specialty: str,
job_type: str,
):
ManagedState.__init__(
self,
"transcribe::medicaltranscriptionjob",
transitions=[
(None, "QUEUED"),
("QUEUED", "IN_PROGRESS"),
("IN_PROGRESS", "COMPLETED"),
],
)
self._region_name = region_name
self.medical_transcription_job_name = medical_transcription_job_name
self.language_code = language_code
self.media_sample_rate_hertz = media_sample_rate_hertz
self.media_format = media_format
self.media = media
self.transcript: Optional[dict[str, str]] = None
self.start_time: Optional[str] = None
self.completion_time: Optional[str] = None
self.creation_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
self.failure_reason = None
self.settings = settings or {
"ChannelIdentification": False,
"ShowAlternatives": False,
}
self.specialty = specialty
self.type = job_type
self._output_bucket_name = output_bucket_name
self._output_encryption_kms_key_id = output_encryption_kms_key_id
self.output_location_type = "CUSTOMER_BUCKET"
def response_object(self, response_type: str) -> dict[str, Any]: # type: ignore
response_field_dict = {
"CREATE": [
"MedicalTranscriptionJobName",
"TranscriptionJobStatus",
"LanguageCode",
"MediaFormat",
"Media",
"StartTime",
"CreationTime",
"Specialty",
"Type",
],
"GET": [
"MedicalTranscriptionJobName",
"TranscriptionJobStatus",
"LanguageCode",
"MediaSampleRateHertz",
"MediaFormat",
"Media",
"Transcript",
"StartTime",
"CreationTime",
"CompletionTime",
"Settings",
"Specialty",
"Type",
],
"LIST": [
"MedicalTranscriptionJobName",
"CreationTime",
"StartTime",
"CompletionTime",
"LanguageCode",
"TranscriptionJobStatus",
"FailureReason",
"OutputLocationType",
"Specialty",
"Type",
],
}
response_fields = response_field_dict[response_type]
response_object = self.gen_response_object()
response_object["TranscriptionJobStatus"] = self.status
if response_type != "LIST":
return {
"MedicalTranscriptionJob": {
k: v
for k, v in response_object.items()
if k in response_fields and v is not None and v != [None]
}
}
else:
return {
k: v
for k, v in response_object.items()
if k in response_fields and v is not None and v != [None]
}
def advance(self) -> None:
old_status = self.status
super().advance()
new_status = self.status
if old_status == new_status:
return
if new_status == "IN_PROGRESS":
self.start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
if not self.media_sample_rate_hertz:
self.media_sample_rate_hertz = 44100
if not self.media_format:
file_ext = self.media["MediaFileUri"].split(".")[-1].lower()
self.media_format = (
file_ext if file_ext in ["mp3", "mp4", "wav", "flac"] else "mp3"
)
elif new_status == "COMPLETED":
self.completion_time = (datetime.now() + timedelta(seconds=10)).strftime(
"%Y-%m-%d %H:%M:%S"
)
self.transcript = {
"TranscriptFileUri": f"https://s3.{self._region_name}.amazonaws.com/{self._output_bucket_name}/medical/{self.medical_transcription_job_name}.json"
}
class FakeMedicalVocabulary(FakeVocabulary):
def __init__(
self,
account_id: str,
region_name: str,
vocabulary_name: str,
language_code: str,
vocabulary_file_uri: Optional[str],
):
super().__init__(
account_id,
region_name,
vocabulary_name,
language_code=language_code,
phrases=None,
vocabulary_file_uri=vocabulary_file_uri,
)
self.model_name = "transcribe::medicalvocabulary"
self._region_name = region_name
self.vocabulary_name = vocabulary_name
self.language_code = language_code
self.vocabulary_file_uri = vocabulary_file_uri
self.last_modified_time = None
self.failure_reason = None
self.download_uri = f"https://s3.us-east-1.amazonaws.com/aws-transcribe-dictionary-model-{region_name}-prod/{account_id}/medical/{self.vocabulary_name}/{mock_random.uuid4()}/input.txt"
class TranscribeBackend(BaseBackend):
def __init__(self, region_name: str, account_id: str):
super().__init__(region_name, account_id)
self.medical_transcriptions: dict[str, FakeMedicalTranscriptionJob] = {}
self.transcriptions: dict[str, FakeTranscriptionJob] = {}
self.medical_vocabularies: dict[str, FakeMedicalVocabulary] = {}
self.vocabularies: dict[str, FakeVocabulary] = {}
def start_transcription_job(
self,
transcription_job_name: str,
language_code: Optional[str],
media_sample_rate_hertz: Optional[int],
media_format: Optional[str],
media: dict[str, str],
output_bucket_name: Optional[str],
output_key: Optional[str],
output_encryption_kms_key_id: Optional[str],
settings: Optional[dict[str, Any]],
model_settings: Optional[dict[str, Optional[str]]],
job_execution_settings: Optional[dict[str, Any]],
content_redaction: Optional[dict[str, Any]],
identify_language: Optional[bool],
identify_multiple_languages: Optional[bool],
language_options: Optional[list[str]],
subtitles: Optional[dict[str, Any]],
) -> dict[str, Any]:
if transcription_job_name in self.transcriptions:
raise ConflictException(
message="The requested job name already exists. Use a different job name."
)
vocabulary_name = settings.get("VocabularyName") if settings else None
if vocabulary_name and vocabulary_name not in self.vocabularies:
raise BadRequestException(
message="The requested vocabulary couldn't be found. "
"Check the vocabulary name and try your request again."
)
transcription_job_object = FakeTranscriptionJob(
account_id=self.account_id,
region_name=self.region_name,
transcription_job_name=transcription_job_name,
language_code=language_code,
media_sample_rate_hertz=media_sample_rate_hertz,
media_format=media_format,
media=media,
output_bucket_name=output_bucket_name,
output_key=output_key,
output_encryption_kms_key_id=output_encryption_kms_key_id,
settings=settings,
model_settings=model_settings,
job_execution_settings=job_execution_settings,
content_redaction=content_redaction,
identify_language=identify_language,
identify_multiple_languages=identify_multiple_languages,
language_options=language_options,
subtitles=subtitles,
)
self.transcriptions[transcription_job_name] = transcription_job_object
return transcription_job_object.response_object("CREATE")
def start_medical_transcription_job(
self,
medical_transcription_job_name: str,
language_code: str,
media_sample_rate_hertz: Optional[int],
media_format: Optional[str],
media: dict[str, str],
output_bucket_name: str,
output_encryption_kms_key_id: Optional[str],
settings: Optional[dict[str, Any]],
specialty: str,
type_: str,
) -> dict[str, Any]:
if medical_transcription_job_name in self.medical_transcriptions:
raise ConflictException(
message="The requested job name already exists. Use a different job name."
)
vocabulary_name = settings.get("VocabularyName") if settings else None
if vocabulary_name and vocabulary_name not in self.medical_vocabularies:
raise BadRequestException(
message="The requested vocabulary couldn't be found. "
"Check the vocabulary name and try your request again."
)
transcription_job_object = FakeMedicalTranscriptionJob(
region_name=self.region_name,
medical_transcription_job_name=medical_transcription_job_name,
language_code=language_code,
media_sample_rate_hertz=media_sample_rate_hertz,
media_format=media_format,
media=media,
output_bucket_name=output_bucket_name,
output_encryption_kms_key_id=output_encryption_kms_key_id,
settings=settings,
specialty=specialty,
job_type=type_,
)
self.medical_transcriptions[medical_transcription_job_name] = (
transcription_job_object
)
return transcription_job_object.response_object("CREATE")
def get_transcription_job(self, transcription_job_name: str) -> dict[str, Any]:
try:
job = self.transcriptions[transcription_job_name]
job.advance() # Fakes advancement through statuses.
return job.response_object("GET")
except KeyError:
raise BadRequestException(
message="The requested job couldn't be found. "
"Check the job name and try your request again."
)
def get_medical_transcription_job(
self, medical_transcription_job_name: str
) -> dict[str, Any]:
try:
job = self.medical_transcriptions[medical_transcription_job_name]
job.advance() # Fakes advancement through statuses.
return job.response_object("GET")
except KeyError:
raise BadRequestException(
message="The requested job couldn't be found. "
"Check the job name and try your request again."
)
def delete_transcription_job(self, transcription_job_name: str) -> None:
try:
del self.transcriptions[transcription_job_name]
except KeyError:
raise BadRequestException(
message="The requested job couldn't be found. "
"Check the job name and try your request again."
)
def delete_medical_transcription_job(
self, medical_transcription_job_name: str
) -> None:
try:
del self.medical_transcriptions[medical_transcription_job_name]
except KeyError:
raise BadRequestException(
message="The requested job couldn't be found. "
"Check the job name and try your request again."
)
def list_transcription_jobs(
self,
state_equals: str,
job_name_contains: str,
next_token: str,
max_results: int,
) -> dict[str, Any]:
jobs = list(self.transcriptions.values())
if state_equals:
jobs = [job for job in jobs if job.status == state_equals]
if job_name_contains:
jobs = [
job for job in jobs if job_name_contains in job.transcription_job_name
]
start_offset = int(next_token) if next_token else 0
end_offset = start_offset + (
max_results if max_results else 100
) # Arbitrarily selected...
jobs_paginated = jobs[start_offset:end_offset]
response: dict[str, Any] = {
"TranscriptionJobSummaries": [
job.response_object("LIST") for job in jobs_paginated
]
}
if end_offset < len(jobs):
response["NextToken"] = str(end_offset)
if state_equals:
response["Status"] = state_equals
return response
def list_medical_transcription_jobs(
self, status: str, job_name_contains: str, next_token: str, max_results: int
) -> dict[str, Any]:
jobs = list(self.medical_transcriptions.values())
if status:
jobs = [job for job in jobs if job.status == status]
if job_name_contains:
jobs = [
job
for job in jobs
if job_name_contains in job.medical_transcription_job_name
]
start_offset = int(next_token) if next_token else 0
end_offset = start_offset + (
max_results if max_results else 100
) # Arbitrarily selected...
jobs_paginated = jobs[start_offset:end_offset]
response: dict[str, Any] = {
"MedicalTranscriptionJobSummaries": [
job.response_object("LIST") for job in jobs_paginated
]
}
if end_offset < len(jobs):
response["NextToken"] = str(end_offset)
if status:
response["Status"] = status
return response
def create_vocabulary(
self,
vocabulary_name: str,
language_code: str,
phrases: Optional[list[str]],
vocabulary_file_uri: Optional[str],
) -> dict[str, Any]:
if (
phrases is not None
and vocabulary_file_uri is not None
or phrases is None
and vocabulary_file_uri is None
):
raise BadRequestException(
message="Either Phrases or VocabularyFileUri field should be provided."
)
if phrases is not None and len(phrases) < 1:
raise BadRequestException(
message="1 validation error detected: Value '[]' at 'phrases' failed to "
"satisfy constraint: Member must have length greater than or "
"equal to 1"
)
if vocabulary_name in self.vocabularies:
raise ConflictException(
message="The requested vocabulary name already exists. "
"Use a different vocabulary name."
)
vocabulary_object = FakeVocabulary(
account_id=self.account_id,
region_name=self.region_name,
vocabulary_name=vocabulary_name,
language_code=language_code,
phrases=phrases,
vocabulary_file_uri=vocabulary_file_uri,
)
self.vocabularies[vocabulary_name] = vocabulary_object
return vocabulary_object.response_object("CREATE")
def create_medical_vocabulary(
self,
vocabulary_name: str,
language_code: str,
vocabulary_file_uri: Optional[str],
) -> dict[str, Any]:
if vocabulary_name in self.medical_vocabularies:
raise ConflictException(
message="The requested vocabulary name already exists. "
"Use a different vocabulary name."
)
medical_vocabulary_object = FakeMedicalVocabulary(
account_id=self.account_id,
region_name=self.region_name,
vocabulary_name=vocabulary_name,
language_code=language_code,
vocabulary_file_uri=vocabulary_file_uri,
)
self.medical_vocabularies[vocabulary_name] = medical_vocabulary_object
return medical_vocabulary_object.response_object("CREATE")
def get_vocabulary(self, vocabulary_name: str) -> dict[str, Any]:
try:
job = self.vocabularies[vocabulary_name]
job.advance() # Fakes advancement through statuses.
return job.response_object("GET")
except KeyError:
raise BadRequestException(
message="The requested vocabulary couldn't be found. "
"Check the vocabulary name and try your request again."
)
def get_medical_vocabulary(self, vocabulary_name: str) -> dict[str, Any]:
try:
job = self.medical_vocabularies[vocabulary_name]
job.advance() # Fakes advancement through statuses.
return job.response_object("GET")
except KeyError:
raise BadRequestException(
message="The requested vocabulary couldn't be found. "
"Check the vocabulary name and try your request again."
)
def delete_vocabulary(self, vocabulary_name: str) -> None:
try:
del self.vocabularies[vocabulary_name]
except KeyError:
raise BadRequestException(
message="The requested vocabulary couldn't be found. Check the vocabulary name and try your request again."
)
def delete_medical_vocabulary(self, vocabulary_name: str) -> None:
try:
del self.medical_vocabularies[vocabulary_name]
except KeyError:
raise BadRequestException(
message="The requested vocabulary couldn't be found. Check the vocabulary name and try your request again."
)
def list_vocabularies(
self, state_equals: str, name_contains: str, next_token: str, max_results: int
) -> dict[str, Any]:
vocabularies = list(self.vocabularies.values())
if state_equals:
vocabularies = [
vocabulary
for vocabulary in vocabularies
if vocabulary.status == state_equals
]
if name_contains:
vocabularies = [
vocabulary
for vocabulary in vocabularies
if name_contains in vocabulary.vocabulary_name
]
start_offset = int(next_token) if next_token else 0
end_offset = start_offset + (
max_results if max_results else 100
) # Arbitrarily selected...
vocabularies_paginated = vocabularies[start_offset:end_offset]
response: dict[str, Any] = {
"Vocabularies": [
vocabulary.response_object("LIST")
for vocabulary in vocabularies_paginated
]
}
if end_offset < len(vocabularies):
response["NextToken"] = str(end_offset)
if state_equals:
response["Status"] = state_equals
return response
def list_medical_vocabularies(
self, state_equals: str, name_contains: str, next_token: str, max_results: int
) -> dict[str, Any]:
vocabularies = list(self.medical_vocabularies.values())
if state_equals:
vocabularies = [
vocabulary
for vocabulary in vocabularies
if vocabulary.status == state_equals
]
if name_contains:
vocabularies = [
vocabulary
for vocabulary in vocabularies
if name_contains in vocabulary.vocabulary_name
]
start_offset = int(next_token) if next_token else 0
end_offset = start_offset + (
max_results if max_results else 100
) # Arbitrarily selected...
vocabularies_paginated = vocabularies[start_offset:end_offset]
response: dict[str, Any] = {
"Vocabularies": [
vocabulary.response_object("LIST")
for vocabulary in vocabularies_paginated
]
}
if end_offset < len(vocabularies):
response["NextToken"] = str(end_offset)
if state_equals:
response["Status"] = state_equals
return response
transcribe_backends = BackendDict(TranscribeBackend, "transcribe")
|