-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathapi_data.py
More file actions
1676 lines (1401 loc) · 52.8 KB
/
Copy pathapi_data.py
File metadata and controls
1676 lines (1401 loc) · 52.8 KB
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
# Copyright 2023 DeepL SE (https://www.deepl.com)
# Use of this source code is governed by an MIT
# license that can be found in the LICENSE file.
import datetime
from enum import Enum
from typing import Dict, List, Optional, Tuple, Union
from deepl.util import get_int_safe, parse_timestamp
class TextResult:
"""Holds the result of a text translation request."""
def __init__(
self,
text: str,
detected_source_lang: str,
billed_characters: int,
model_type_used: Optional[str] = None,
):
self.text = text
self.detected_source_lang = detected_source_lang
self.billed_characters = billed_characters
self.model_type_used = model_type_used
def __str__(self):
return self.text
class WriteResult:
"""Holds the result of a text improvement request."""
def __init__(
self, text: str, detected_source_language: str, target_language: str
):
self.text = text
self.detected_source_language = detected_source_language
self.target_language = target_language
def __str__(self):
return self.text
class DocumentHandle:
"""Handle to an in-progress document translation.
:param document_id: ID of associated document request.
:param document_key: Key of associated document request.
"""
def __init__(self, document_id: str, document_key: str):
self._document_id = document_id
self._document_key = document_key
def __str__(self):
return f"Document ID: {self.document_id}, key: {self.document_key}"
@property
def document_id(self) -> str:
return self._document_id
@property
def document_key(self) -> str:
return self._document_key
class DocumentStatus:
"""Status of a document translation request.
:param status: One of the Status enum values below.
:param seconds_remaining: Estimated time until document translation
completes in seconds, or None if unknown.
:param billed_characters: Number of characters billed for this document, or
None if unknown or before translation is complete.
:param error_message: A short description of the error, or None if no error
has occurred.
"""
class Status(Enum):
QUEUED = "queued"
TRANSLATING = "translating"
DONE = "done"
DOWNLOADED = "downloaded"
ERROR = "error"
def __init__(
self,
status: Status,
seconds_remaining=None,
billed_characters=None,
error_message=None,
):
self._status = self.Status(status)
self._seconds_remaining = seconds_remaining
self._billed_characters = billed_characters
self._error_message = error_message
def __str__(self) -> str:
return self.status.value
@property
def ok(self) -> bool:
return self._status != self.Status.ERROR
@property
def done(self) -> bool:
return self._status == self.Status.DONE
@property
def status(self) -> Status:
return self._status
@property
def seconds_remaining(self) -> Optional[int]:
return self._seconds_remaining
@property
def billed_characters(self) -> Optional[int]:
return self._billed_characters
@property
def error_message(self) -> Optional[int]:
return self._error_message
class Usage:
"""Holds the result of a usage request.
The character, document and team_document properties provide details about
each corresponding usage type. These properties allow each usage type to be
checked individually.
The any_limit_reached property checks if for any usage type the amount used
has reached the allowed amount.
"""
class Detail:
def __init__(self, json: Optional[dict], prefix: str):
self._count = get_int_safe(json, f"{prefix}_count")
self._limit = get_int_safe(json, f"{prefix}_limit")
@property
def count(self) -> Optional[int]:
"""Returns the amount used for this usage type, may be None."""
return self._count
@property
def limit(self) -> Optional[int]:
"""Returns the maximum amount for this usage type, may be None."""
return self._limit
@property
def valid(self) -> bool:
"""True iff both the count and limit are set for this usage
type."""
return self._count is not None and self._limit is not None
@property
def limit_reached(self) -> bool:
"""True if this limit is valid and the amount used is greater than
or equal to the amount allowed, otherwise False."""
return self.valid and self.count >= self.limit # type: ignore[operator] # noqa: E501
@property
def limit_exceeded(self) -> bool:
"""Deprecated, use limit_reached instead."""
import warnings
warnings.warn(
"limit_reached is deprecated", DeprecationWarning, stacklevel=2
)
return self.limit_reached
def __str__(self) -> str:
return f"{self.count} of {self.limit}" if self.valid else "Unknown"
def __init__(self, json: Optional[dict]):
self._character = self.Detail(json, "character")
self._document = self.Detail(json, "document")
self._team_document = self.Detail(json, "team_document")
@property
def any_limit_reached(self) -> bool:
"""True if for any API usage type, the amount used is greater than or
equal to the amount allowed, otherwise False."""
return (
self.character.limit_reached
or self.document.limit_reached
or self.team_document.limit_reached
)
@property
def any_limit_exceeded(self) -> bool:
"""Deprecated, use any_limit_reached instead."""
import warnings
warnings.warn(
"any_limit_reached is deprecated", DeprecationWarning, stacklevel=2
)
return self.any_limit_reached
@property
def character(self) -> Detail:
"""Returns usage details for characters, primarily associated with the
translate_text (/translate) function."""
return self._character
@property
def document(self) -> Detail:
"""Returns usage details for documents."""
return self._document
@property
def team_document(self) -> Detail:
"""Returns usage details for documents shared among your team."""
return self._team_document
def __str__(self) -> str:
details: List[Tuple[str, Usage.Detail]] = [
("Characters", self.character),
("Documents", self.document),
("Team documents", self.team_document),
]
return "Usage this billing period:\n" + "\n".join(
[f"{label}: {detail}" for label, detail in details if detail.valid]
)
class Language:
"""Information about a language supported by DeepL translator.
:param code: Language code according to ISO 639-1, for example "EN".
Some target languages also include the regional variant according to
ISO 3166-1, for example "EN-US".
:param name: Name of the language in English.
:param supports_formality: (Optional) Specifies whether the formality
option is available for this language; target languages only.
"""
def __init__(
self, code: str, name: str, supports_formality: Optional[bool] = None
):
self.code = code
self.name = name
self.supports_formality = supports_formality
def __str__(self):
return self.code
@staticmethod
def remove_regional_variant(language: Union[str, "Language"]) -> str:
"""Removes the regional variant from a language, e.g. EN-US gives EN"""
dash_index = str(language).find("-")
if dash_index != -1:
return str(language).upper()[0:dash_index]
else:
return str(language).upper()
ACEHNESE = "ace"
AFRIKAANS = "af"
ARAGONESE = "an"
ARABIC = "ar"
ASSAMESE = "as"
AYMARA = "ay"
AZERBAIJANI = "az"
BASHKIR = "ba"
BELARUSIAN = "be"
BULGARIAN = "bg"
BHOJPURI = "bho"
BENGALI = "bn"
BRETON = "br"
BOSNIAN = "bs"
CATALAN = "ca"
CEBUANO = "ceb"
KURDISH_SORANI = "ckb"
CZECH = "cs"
WELSH = "cy"
DANISH = "da"
GERMAN = "de"
GREEK = "el"
ENGLISH = "en" # Only usable as a source language
ENGLISH_BRITISH = "en-GB" # Only usable as a target language
ENGLISH_AMERICAN = "en-US" # Only usable as a target language
ESPERANTO = "eo"
SPANISH = "es"
SPANISH_LATIN_AMERICAN = "es-419" # Only usable as a target language
ESTONIAN = "et"
BASQUE = "eu"
PERSIAN = "fa"
FINNISH = "fi"
FRENCH = "fr"
IRISH = "ga"
GALICIAN = "gl"
GUARANI = "gn"
KONKANI = "gom"
GUJARATI = "gu"
HAUSA = "ha"
HEBREW = "he"
HINDI = "hi"
CROATIAN = "hr"
HAITIAN_CREOLE = "ht"
HUNGARIAN = "hu"
ARMENIAN = "hy"
INDONESIAN = "id"
IGBO = "ig"
ICELANDIC = "is"
ITALIAN = "it"
JAPANESE = "ja"
JAVANESE = "jv"
GEORGIAN = "ka"
KAZAKH = "kk"
KURDISH_KURMANJI = "kmr"
KOREAN = "ko"
KYRGYZ = "ky"
LATIN = "la"
LUXEMBOURGISH = "lb"
LOMBARD = "lmo"
LINGALA = "ln"
LITHUANIAN = "lt"
LATVIAN = "lv"
MAITHILI = "mai"
MALAGASY = "mg"
MAORI = "mi"
MACEDONIAN = "mk"
MALAYALAM = "ml"
MONGOLIAN = "mn"
MARATHI = "mr"
MALAY = "ms"
MALTESE = "mt"
BURMESE = "my"
NORWEGIAN = "nb"
NEPALI = "ne"
DUTCH = "nl"
OCCITAN = "oc"
OROMO = "om"
PUNJABI = "pa"
PANGASINAN = "pag"
KAPAMPANGAN = "pam"
POLISH = "pl"
DARI = "prs"
PASHTO = "ps"
PORTUGUESE = "pt" # Only usable as a source language
PORTUGUESE_BRAZILIAN = "pt-BR" # Only usable as a target language
PORTUGUESE_EUROPEAN = "pt-PT" # Only usable as a target language
QUECHUA = "qu"
ROMANIAN = "ro"
RUSSIAN = "ru"
SANSKRIT = "sa"
SICILIAN = "scn"
SLOVAK = "sk"
SLOVENIAN = "sl"
ALBANIAN = "sq"
SERBIAN = "sr"
SESOTHO = "st"
SUNDANESE = "su"
SWEDISH = "sv"
SWAHILI = "sw"
TAMIL = "ta"
TELUGU = "te"
TAJIK = "tg"
THAI = "th"
TURKMEN = "tk"
TAGALOG = "tl"
TSWANA = "tn"
TURKISH = "tr"
TSONGA = "ts"
TATAR = "tt"
UKRAINIAN = "uk"
URDU = "ur"
UZBEK = "uz"
VIETNAMESE = "vi"
WOLOF = "wo"
XHOSA = "xh"
YIDDISH = "yi"
CANTONESE = "yue"
CHINESE = "zh"
CHINESE_SIMPLIFIED = "zh-Hans" # Only usable as a target language
CHINESE_TRADITIONAL = "zh-Hant" # Only usable as a target language
ZULU = "zu"
class GlossaryLanguagePair:
"""Information about a pair of languages supported for DeepL glossaries.
:param source_lang: The code of the source language.
:param target_lang: The code of the target language.
"""
def __init__(self, source_lang: str, target_lang: str):
self._source_lang = source_lang
self._target_lang = target_lang
@property
def source_lang(self) -> str:
"""Returns the code of the source language."""
return self._source_lang
@property
def target_lang(self) -> str:
"""Returns the code of the target language."""
return self._target_lang
class MultilingualGlossaryDictionaryEntries:
def __init__(
self,
source_lang: str,
target_lang: str,
entries: Dict[str, str],
):
self._source_lang = source_lang
self._target_lang = target_lang
self._entries = entries
def __str__(self) -> str:
return (
"MultilingualGlossaryDictionaryEntries: Source Language "
f"{self._source_lang}, Target Language {self._target_lang} "
f"Contents: {self._entries}"
)
@staticmethod
def from_json(json) -> "MultilingualGlossaryDictionaryEntries":
"""Create MultilingualGlossaryDictionaryEntries from the given
API JSON object.
"""
return MultilingualGlossaryDictionaryEntries(
str(json["source_lang"]),
str(json["target_lang"]),
json["entries"],
)
def to_json(self):
"""Create API JSON object from
MultilingualGlossaryDictionaryEntries
"""
return {
"source_lang": self._source_lang,
"target_lang": self._target_lang,
"entries": self._entries,
}
@property
def source_lang(self) -> str:
return self._source_lang
@property
def target_lang(self) -> str:
return self._target_lang
@property
def entries(self) -> Dict[str, str]:
return self._entries
class MultilingualGlossaryDictionaryEntriesResponse:
def __init__(
self, dictionaries: List[MultilingualGlossaryDictionaryEntries]
):
self._dictionaries = dictionaries
def __str__(self) -> str:
return (
"MultilingualGlossaryDictionaryEntriesResponse: "
f"Contents {self._dictionaries}"
)
@staticmethod
def from_json(json) -> "MultilingualGlossaryDictionaryEntriesResponse":
"""Create MultilingualGlossaryDictionaryEntriesResponse from the given
API JSON object.
"""
glossary_dicts = list(json["dictionaries"])
serialized_dicts = list(
map(
lambda glossary_dict: MultilingualGlossaryDictionaryEntries.from_json( # noqa: E501
glossary_dict
),
glossary_dicts,
)
)
return MultilingualGlossaryDictionaryEntriesResponse(serialized_dicts)
@property
def dictionaries(self) -> List[MultilingualGlossaryDictionaryEntries]:
return self._dictionaries
class MultilingualGlossaryDictionaryInfo:
def __init__(self, source_lang: str, target_lang: str, entry_count: int):
self._source_lang = source_lang
self._target_lang = target_lang
self._entry_count = entry_count
@staticmethod
def from_json(json) -> "MultilingualGlossaryDictionaryInfo":
"""Create MultilingualGlossaryDictionaryInfo from the given API JSON
object."""
return MultilingualGlossaryDictionaryInfo(
str(json["source_lang"]).upper(),
str(json["target_lang"]).upper(),
int(json["entry_count"]),
)
@property
def source_lang(self) -> str:
return self._source_lang
@property
def target_lang(self) -> str:
return self._target_lang
@property
def entry_count(self) -> int:
return self._entry_count
class MultilingualGlossaryInfo:
"""Information about a multilingual glossary, excluding the entry list.
Used by the /v3/glossaries API endpoints
:param glossary_id: Unique ID assigned to the glossary.
:param name: User-defined name assigned to the glossary.
:param creation_time: Timestamp when the glossary was created.
:param dictionaries: Dictionaries contained in this glossary. Each
dictionary contains its language pair and the number of entries.
"""
def __init__(
self,
glossary_id: str,
name: str,
creation_time: datetime.datetime,
dictionaries: List[MultilingualGlossaryDictionaryInfo],
):
self._glossary_id = glossary_id
self._name = name
self._creation_time = creation_time
self._dictionaries = dictionaries
def __str__(self) -> str:
return f'MultilingualGlossary "{self.name}" ({self.glossary_id})'
@staticmethod
def from_json(json) -> "MultilingualGlossaryInfo":
"""Create MultilingualGlossaryInfo from the given API JSON object."""
return MultilingualGlossaryInfo(
json["glossary_id"],
json["name"],
parse_timestamp(json["creation_time"]),
list(
map(
lambda entry: MultilingualGlossaryDictionaryInfo.from_json(
entry
),
json["dictionaries"],
)
),
)
@staticmethod
def to_json(self) -> dict:
"""Create API JSON object from MultilingualGlossaryInfo."""
return {
"glossary_id": self._glossary_id,
"name": self._name,
"creation_time": self._creation_time,
"dictionaries": self._dictionaries,
}
@property
def glossary_id(self) -> str:
return self._glossary_id
@property
def name(self) -> str:
return self._name
@property
def dictionaries(self) -> List[MultilingualGlossaryDictionaryInfo]:
return self._dictionaries
@property
def creation_time(self) -> datetime.datetime:
return self._creation_time
class GlossaryInfo:
"""Information about a glossary, excluding the entry list. GlossaryInfo
is compatible with the /v2 glossary endpoints and can only support
mono-lingual glossaries (e.g. a glossary with only one source and
target language defined).
:param glossary_id: Unique ID assigned to the glossary.
:param name: User-defined name assigned to the glossary.
:param ready: True iff the glossary may be used for translations.
:param source_lang: Source language code of the glossary.
:param target_lang: Target language code of the glossary.
:param creation_time: Timestamp when the glossary was created.
:param entry_count: The number of entries contained in the glossary.
"""
def __init__(
self,
glossary_id: str,
name: str,
ready: bool,
source_lang: str,
target_lang: str,
creation_time: datetime.datetime,
entry_count: int,
):
self._glossary_id = glossary_id
self._name = name
self._ready = ready
self._source_lang = source_lang
self._target_lang = target_lang
self._creation_time = creation_time
self._entry_count = entry_count
def __str__(self) -> str:
return f'Glossary "{self.name}" ({self.glossary_id})'
@staticmethod
def from_json(json) -> "GlossaryInfo":
"""Create GlossaryInfo from the given API JSON object."""
return GlossaryInfo(
json["glossary_id"],
json["name"],
bool(json["ready"]),
str(json["source_lang"]).upper(),
str(json["target_lang"]).upper(),
parse_timestamp(json["creation_time"]),
int(json["entry_count"]),
)
@property
def glossary_id(self) -> str:
return self._glossary_id
@property
def name(self) -> str:
return self._name
@property
def ready(self) -> bool:
return self._ready
@property
def source_lang(self) -> str:
return self._source_lang
@property
def target_lang(self) -> str:
return self._target_lang
@property
def creation_time(self) -> datetime.datetime:
return self._creation_time
@property
def entry_count(self) -> int:
return self._entry_count
class Formality(Enum):
"""Options for formality parameter."""
LESS = "less"
"""Translate using informal language."""
DEFAULT = "default"
"""Translate using the default formality."""
MORE = "more"
"""Translate using formal language."""
PREFER_MORE = "prefer_more"
"""Translate using formal language if the target language supports
formality, otherwise use default formality."""
PREFER_LESS = "prefer_less"
"""Translate using informal language if the target language supports
formality, otherwise use default formality."""
def __str__(self):
return self.value
class SplitSentences(Enum):
"""Options for split_sentences parameter.
Sets whether the translation engine should first split the input into
sentences. This is enabled by default. Possible values are:
- OFF: no splitting at all, whole input is treated as one sentence. Use
this option if the input text is already split into sentences, to
prevent the engine from splitting the sentence unintentionally.
- ALL: (default) splits on punctuation and on newlines.
- NO_NEWLINES: splits on punctuation only, ignoring newlines.
"""
OFF = "0"
ALL = "1"
NO_NEWLINES = "nonewlines"
DEFAULT = ALL
def __str__(self):
return self.value
class ModelType(Enum):
"""Options for model_type parameter.
Sets whether the translation engine should use a newer model type that
offers higher quality translations at the cost of translation time.
"""
QUALITY_OPTIMIZED = "quality_optimized"
LATENCY_OPTIMIZED = "latency_optimized"
PREFER_QUALITY_OPTIMIZED = "prefer_quality_optimized"
def __str__(self):
return self.value
class WritingStyle(Enum):
"""Options for the `style` parameter of the Write API.
Sets the style the improved text should be in. Note that currently, only
a style OR a tone is supported.
When using a style starting with `prefer_`, the style will only be used
if the chosen or detected language supports it.
"""
ACADEMIC = "academic"
BUSINESS = "business"
CASUAL = "casual"
DEFAULT = "default"
PREFER_ACADEMIC = "prefer_academic"
PREFER_BUSINESS = "prefer_business"
PREFER_CASUAL = "prefer_casual"
PREFER_SIMPLE = "prefer_simple"
SIMPLE = "simple"
def __str__(self):
return self.value
class WritingTone(Enum):
"""Options for the `tone` parameter of the Write API.
Sets the tone the improved text should be in. Note that currently, only
a style OR a tone is supported.
When using a tone starting with `prefer_`, the tone will only be used
if the chosen or detected language supports it.
"""
CONFIDENT = "confident"
DEFAULT = "default"
DIPLOMATIC = "diplomatic"
ENTHUSIASTIC = "enthusiastic"
FRIENDLY = "friendly"
PREFER_CONFIDENT = "prefer_confident"
PREFER_DIPLOMATIC = "prefer_diplomatic"
PREFER_ENTHUSIASTIC = "prefer_enthusiastic"
PREFER_FRIENDLY = "prefer_friendly"
def __str__(self):
return self.value
class ConfiguredRules:
"""Configuration rules for a style rule list.
:param dates_and_times: Date and time formatting rules.
:param formatting: Text formatting rules.
:param numbers: Number formatting rules.
:param punctuation: Punctuation rules.
:param spelling_and_grammar: Spelling and grammar rules.
:param style_and_tone: Style and tone rules.
:param vocabulary: Vocabulary rules.
"""
def __init__(
self,
dates_and_times: Optional[Dict[str, str]] = None,
formatting: Optional[Dict[str, str]] = None,
numbers: Optional[Dict[str, str]] = None,
punctuation: Optional[Dict[str, str]] = None,
spelling_and_grammar: Optional[Dict[str, str]] = None,
style_and_tone: Optional[Dict[str, str]] = None,
vocabulary: Optional[Dict[str, str]] = None,
):
self._dates_and_times = dates_and_times or {}
self._formatting = formatting or {}
self._numbers = numbers or {}
self._punctuation = punctuation or {}
self._spelling_and_grammar = spelling_and_grammar or {}
self._style_and_tone = style_and_tone or {}
self._vocabulary = vocabulary or {}
@staticmethod
def from_json(json) -> "ConfiguredRules":
"""Create ConfiguredRules from the given API JSON object."""
if not json:
return ConfiguredRules()
return ConfiguredRules(
dates_and_times=json.get("dates_and_times"),
formatting=json.get("formatting"),
numbers=json.get("numbers"),
punctuation=json.get("punctuation"),
spelling_and_grammar=json.get("spelling_and_grammar"),
style_and_tone=json.get("style_and_tone"),
vocabulary=json.get("vocabulary"),
)
@property
def dates_and_times(self) -> Dict[str, str]:
"""Returns date and time formatting rules."""
return self._dates_and_times
@property
def formatting(self) -> Dict[str, str]:
"""Returns text formatting rules."""
return self._formatting
@property
def numbers(self) -> Dict[str, str]:
"""Returns number formatting rules."""
return self._numbers
@property
def punctuation(self) -> Dict[str, str]:
"""Returns punctuation rules."""
return self._punctuation
@property
def spelling_and_grammar(self) -> Dict[str, str]:
"""Returns spelling and grammar rules."""
return self._spelling_and_grammar
@property
def style_and_tone(self) -> Dict[str, str]:
"""Returns style and tone rules."""
return self._style_and_tone
@property
def vocabulary(self) -> Dict[str, str]:
"""Returns vocabulary rules."""
return self._vocabulary
class CustomInstruction:
"""Custom instruction for a style rule.
:param label: Label for the custom instruction.
:param prompt: Prompt text for the custom instruction.
:param source_language: Optional source language code for the custom
instruction.
"""
def __init__(
self,
label: str,
prompt: str,
source_language: Optional[str] = None,
id: Optional[str] = None,
):
self._label = label
self._prompt = prompt
self._source_language = source_language
self._id = id
@staticmethod
def from_json(json) -> "CustomInstruction":
"""Create CustomInstruction from the given API JSON object."""
return CustomInstruction(
label=json["label"],
prompt=json["prompt"],
source_language=json.get("source_language"),
id=json.get("id"),
)
@property
def id(self) -> Optional[str]:
"""Returns the unique ID of the custom instruction."""
return self._id
@property
def label(self) -> str:
"""Returns the label of the custom instruction."""
return self._label
@property
def prompt(self) -> str:
"""Returns the prompt text of the custom instruction."""
return self._prompt
@property
def source_language(self) -> Optional[str]:
"""Returns the source language code, if specified."""
return self._source_language
class StyleRuleInfo:
"""Information about a style rule list.
:param style_id: Unique ID assigned to the style rule list.
:param name: User-defined name assigned to the style rule list.
:param creation_time: Timestamp when the style rule list was created.
:param updated_time: Timestamp when the style rule list was last updated.
:param language: Language code for the style rule list.
:param version: Version number of the style rule list.
:param configured_rules: The predefined rules that have been enabled.
:param custom_instructions: Optional list of custom instructions.
"""
def __init__(
self,
style_id: str,
name: str,
creation_time: datetime.datetime,
updated_time: datetime.datetime,
language: str,
version: int,
configured_rules: Optional[ConfiguredRules] = None,
custom_instructions: Optional[List[CustomInstruction]] = None,
):
self._style_id = style_id
self._name = name
self._creation_time = creation_time
self._updated_time = updated_time
self._language = language
self._version = version
self._configured_rules = configured_rules
self._custom_instructions = custom_instructions
def __str__(self) -> str:
return f'StyleRule "{self.name}" ({self.style_id})'
@staticmethod
def from_json(json) -> "StyleRuleInfo":
"""Create StyleRuleInfo from the given API JSON object."""
configured_rules_data = json.get("configured_rules")
configured_rules = None
if configured_rules_data:
configured_rules = ConfiguredRules.from_json(configured_rules_data)
custom_instructions_data = json.get("custom_instructions")
custom_instructions = None
if custom_instructions_data:
custom_instructions = [
CustomInstruction.from_json(instruction)
for instruction in custom_instructions_data
]
return StyleRuleInfo(
style_id=json["style_id"],
name=json["name"],
creation_time=parse_timestamp(json["creation_time"]),
updated_time=parse_timestamp(json["updated_time"]),
language=json["language"],
version=json["version"],
configured_rules=configured_rules,
custom_instructions=custom_instructions,
)
@property
def style_id(self) -> str:
"""Returns the unique ID of the style rule set."""
return self._style_id
@property
def name(self) -> str:
"""Returns the name of the style rule set."""
return self._name
@property
def creation_time(self) -> datetime.datetime:
"""Returns the creation timestamp."""
return self._creation_time
@property
def updated_time(self) -> datetime.datetime:
"""Returns the last update timestamp."""
return self._updated_time
@property
def language(self) -> str:
"""Returns the language code."""
return self._language
@property
def version(self) -> int:
"""Returns the version number."""
return self._version
@property
def configured_rules(self) -> Optional[ConfiguredRules]: