Official Python library for the DeepL language translation API.
Repo DeepL/deepl-python, read from GitHub 14 h ago. DeepL has not joined Take My Repo.
TL;DR: new APIs in this release: the Admin API, spoken terms and style profiles.
Translation memories, style rules and multilingual glossaries gained many options and fixes.
Read Changed and Deprecated before upgrading; no public API is removed in this release.
headers option to the Translator, DeepLClient andDeepLAdminClient constructors: extra HTTP headers sent with every requestUser-Agent and Authorization; Content-Type,Content-Length, Transfer-Encoding, Host and an Accept the libraryUser-Agent.app_info option, an AppInfo(app_name, app_version), to theTranslator, DeepLClient and DeepLAdminClient constructors, the same asset_app_info().NotFoundException, raised for HTTP 404 on every endpoint.GlossaryNotFoundException is now its subclass.is_free_account_auth_key(), which replaces auth_key_is_free_account().extra_body_parameters option to create_style_rule(),update_style_rule_name(), update_style_rule_configured_rules(),create_style_rule_custom_instruction() andupdate_style_rule_custom_instruction().get_style_rule_custom_instruction(),update_style_rule_custom_instruction() anddelete_style_rule_custom_instruction() accept a CustomInstruction objectinstruction_id, as well as an ID string.max_retries and timeout_s options to the Translator,DeepLClient and DeepLAdminClient constructors, to set the maximum numberstyle_profile option to translate_text() and the documenttranslate_document(),translate_document_from_filepath(), translate_document_upload()) toStyleProfile--style-profile-id.DeepLAdminClient class for the Admin API. It must be created withcreate_developer_key(), list_developer_keys(),deactivate_developer_key(), rename_developer_key(),set_developer_key_usage_limits()) and retrieving usage analyticsget_usage_analytics(), get_custom_tag_usage_analytics()) withDeveloperKey, DeveloperKeyUsageLimits,AdminUsageReport, AdminUsageBreakdown, KeyUsage, CustomTagUsageReport,CustomTagUsage and CustomTagUsageBreakdown, and the request optionsDeveloperKeyUsageLimitsUpdate, AdminUsageGroupBy andCustomTagUsageAggregateBy.extra_body_parameters.create_developer_key() is retried only when the request was not sent:AdminUsageReport.total_usage,AdminUsageBreakdown.speech_to_speech_minutes andCustomTagUsageBreakdown.speech_to_speech_minutes are None when theusage_report orcustom_tag_usage_report raises DeepLException.get_languages_for_resource() method to the DeepLClient class to/v3/languages endpoint. Resources are given asLanguageResourceName values or strings; results are LanguageSupportDeepLException.get_language_resources() method to the DeepLClient class to/v3/languages/resources endpoint. Results are returned asLanguageResource and ResourceFeature objects; needs_source_supportneeds_target_support are False when the API omits them.Language constants for the target variants de-CH, de-DE,es-ES, fr-CA, and fr-FR.enable_watermark option to translate_document(),translate_document_upload() and translate_document_from_filepath(). SetTrue to add a "Translated by DeepL" watermark to docx and pdfUsage: api_key_character,speech_to_text_minutes and speech_to_speech_minutes (asOptional[Usage.Detail]), start_time and end_time (the billing period),products, a list of Usage.Product objects with per-product usage.None when the response does not contain them; products entries/v3/spoken-terms) to the DeepLClient class:create_spoken_terms(), list_spoken_terms(), get_spoken_terms(),update_spoken_terms(), get_spoken_terms_entries(),replace_spoken_terms_list(), delete_spoken_terms() anddelete_spoken_terms_list(), with the SpokenTerms, SpokenTermsList andSpokenTermsEntries types. create_spoken_terms(), update_spoken_terms()replace_spoken_terms_list() accept extra_body_parameters. CollectionDeepLException./v3/style_profiles) to the DeepLClientlist_style_profiles(), create_style_profile(),get_style_profile(), update_style_profile() anddelete_style_profile(), with the StyleProfile type. The glossary_ids,style_rule_ids and translation_memory_ids options ofcreate_style_profile() and update_style_profile() accept IDs orGlossaryInfo, MultilingualGlossaryInfo, StyleRuleInfo andTranslationMemoryInfo objects, and both functions acceptextra_body_parameters. A style profile response that is not a JSON object,style_profile_id, name, creation_time orupdated_time, raises DeepLException.TagHandlingMode (HTML, XML) and TagHandlingVersion (V1,V2) enums. The tag_handling and tag_handling_version options oftranslate_text() accept them as well as strings.tag_handling_version to TextResult: the tag handling version theNone when the response does not contain it.translate_text() accepts source_lang and target_lang positionally aftertranslate_text("Hello", None, "DE"). Keyword use istarget_lang still raises TypeError.document_id property to DocumentStatus, read from the statustranslate_document_get_status() (falling back to the handle'stranslate_document(), translate_document_from_filepath() andtranslate_document_upload() now also accept source_lang andtarget_lang as positional arguments after the input (and output)translate_document_upload(file, "EN", "DE").writing_style and extra_body_parameters options torephrase_text(), and the extra_body_parameters option tocorrect_text(). writing_style and tone accept a WritingStyle orWritingTone member or a string.update_multilingual_glossary() to the DeepLClient class to rename aget_multilingual_glossary_dictionary_entries() to the DeepLClientMultilingualGlossaryDictionaryEntries of one dictionaryGlossaryNotFoundException if the glossary has none for theextra_body_parameters option to create_multilingual_glossary(),create_multilingual_glossary_from_csv(),update_multilingual_glossary_name(),update_multilingual_glossary_dictionary(),update_multilingual_glossary_dictionary_from_csv(),replace_multilingual_glossary_dictionary() andreplace_multilingual_glossary_dictionary_from_csv().get_multilingual_glossary() accepts a MultilingualGlossaryInfo object, asglossary, besides a glossary ID.dictionaries (create_multilingual_glossary()),dictionary (update_multilingual_glossary_dictionary(),replace_multilingual_glossary_dictionary()), csv (the*_multilingual_glossary*_from_csv() functions) and glossaryget_multilingual_glossary()).MultilingualGlossaryInfo, MultilingualGlossaryDictionaryInfo andMultilingualGlossaryDictionaryEntries are exported from the deepl package.MultilingualGlossaryDictionaryInfo.to_json().content_type and extra_body_parameters options toimport_translation_memory_from_filepath(), and the extra_body_parameterscreate_translation_memory_import(). content_type is declaredTranslationMemoryJobStatus enum. TranslationMemoryJob.statusTranslationMemoryJobResult.status now return its members for theawaiting_input, processing, completed, failed andexpired, and the plain string for any other value. Members are stringsTranslationMemoryJobResult.STATUS_* constants keep working.content parameter name to upload_translation_memory_file()input_file. Positional calls areDocumentTranslationException accepts should_retry andhttp_status_code. translate_document() andtranslate_document_from_filepath() copy both from the underlyingDeepLException; before they were always False and None.timeout_s, wait_until_translation_memory_job_done() now cuts itsimport_translation_memory_from_filepath() now reads the file andexport_translation_memory_to_filepath() now checks the output path beforeOSErrors are raised without creating a job;translate_text() now accepts glossary and glossary_ids withoutsource_lang, and DeepL uses the glossary dictionary for the detectedValueError. Document translation with asource_lang.server_url is now kept; previously the last path segment wasAuthorizationException; previouslyDeepLException.Translator now emits a DeprecationWarning; previously it didNotFoundException instead of DeepLExceptionGlossaryNotFoundException, now aNotFoundException).User-Agent platform information now ends with python/<version>;requests version.EN and PT are now sent to the API, which translates themEN-US and PT-PT; previously they were rejected client-side.get_source_languages(), get_target_languages(), andget_glossary_languages() now use the /v3/languages endpoint/v2/languages and/v2/glossary-language-pairs endpoints. Public signatures and returnchunk_size of translate_document_download() anddownload_translation_memory_export() is now 64 KiB instead of 1 byte, sooutput_file no longer write one byte per call. The writtenchunk_size still applies.DocumentStatus.status is now typed Union[DocumentStatus.Status, str]: aValueError. Type-checked code that readsstatus.status.value may need an isinstance(..., DocumentStatus.Status)str(status) returns the status string in both cases.Translator is deprecated in favour of DeepLClient, which supports all itsGlossaryNotFoundException is deprecated, catch NotFoundException instead.auth_key_is_free_account() is deprecated, use is_free_account_auth_key().DeprecationWarning.deepl.http_client.user_agent is deprecated inUser-Agent entry in the headers option, and will be removed inDeprecationWarning.translate_document_download() ordownload_translation_memory_export() without output_file now emits aDeprecationWarning. It still returns the streaming requests.Response; inoutput_file will be required and both methods willNone.skip_language_check to Translator() or DeepLClient(), orskip_cache to get_source_languages() or get_target_languages(), nowDeprecationWarning. Both parameters have no effect and will beFalse toNone; passing False explicitly also warns.deepl.http_client.max_network_retries anddeepl.http_client.min_connection_timeout are deprecated in favour of themax_retries and timeout_s client options, and will be removed in theDeprecationWarning.Language (Language.GERMAN,Language.ENGLISH_AMERICAN, ...) are deprecated and will be removed in the"de", orget_source_languages() andget_target_languages(). The constants keep working and emit no warning.style keyword of rephrase_text() is deprecated in favour ofwriting_style and emits a DeprecationWarning. It keeps working; if bothwriting_style is used.get_multilingual_glossary_entries() is deprecated, useget_multilingual_glossary_dictionary_entries().glossary_dicts, glossary_dict, csv_data andglossary_id of the multilingual glossary functions are deprecated, usedictionaries, dictionary, csv and glossary.input_file keyword of upload_translation_memory_file() iscontent and will be removed in the next majorDeprecationWarning.SplitSentences.DEFAULT is deprecated, use SplitSentences.ALL, which it istranslate_text_with_glossary() is deprecated, use translate_text() withglossary parameter. Calling it emits a DeprecationWarning.ValueError namingIndexError (it is still an IndexError).ConnectionException with should_retry True once retries are used up.create_developer_key() is still not retried after it.translate_document_download() now streams the translated document tooutput_file in chunks, instead of first reading the whole document intotranslate_document_download() ordownload_translation_memory_export() reads the downloaded file now raisesConnectionException, instead of a requests exception.Location) now raise DeepLException withhttp_status_code, instead of being parsed as a successful response.ConnectionExceptionshould_retry False.%20 instead of +.should_retry as [secure] for HTTP 429 and 5xx, and dropping theexport_translation_memory_to_filepath() no longer leaves aDeepLException.should_retry is now True for every HTTP 5xx error. It wasFalse for all of them except 503, although they are retried.message or detail is not a string (a number,null) no longer raises TypeError; the value is included asnull is left out.:fx check that selects the API Free server. AValueError.translate_text() raising TypeError when a translation in thebilled_characters. TextResult.billed_characters is nowNone in that case.translate_text() raising IndexError when the response holds fewerDeepLException.translate_document_get_status() raising ValueError andtranslate_document_wait_until_done() stopping when the API returns aDocumentStatus.status keepstranslate_document() and translate_document_from_filepath()formality=default when formality was not set. It is now senttranslate_document_get_status() and translate_document_download()translate_document_upload() returning an empty DocumentHandle whendocument_id or document_key, and raisingAttributeError when the response body is not a JSON object. Both nowDeepLException.DocumentStatus.error_message, which is a/, ? or # addressed a different resource.KeyError, ValueError,TypeError or AttributeError on a malformed StyleRuleInfo orCustomInstruction response. They now raise DeepLException.DeprecationWarning messages of Usage.Detail.limit_exceeded andUsage.any_limit_exceeded, which named the replacement instead of theLanguage.ENGLISH and Language.PORTUGUESE comments thatcreate_glossary_from_csv() failing with "Object of type bytes is notrephrase CLI command always failing with an unexpected keyword--show-detected-source now prints the detected sourcetranslate CLI alias of the text command failing with'action_translate'.extra_body_parameters documentation, which claimed that entriesMultilingualGlossaryInfo.to_json() raising TypeError when called onrephrase_text() and correct_text() failing with "Object of typetarget_lang is a Language object orWritingStyle or WritingTone member. The value isrephrase_text() and correct_text() now raise DeepLException when theimprovements list, fewer improvements than input texts, ortext. Before, this raised IndexError orAttributeError, or silently returned a shorter list.get_source_languages() and get_target_languages() now raiseDeepLException when the response is not a list (they returned an emptyKeyError, AttributeError or TypeError). A null features field is/v3/glossaries request paths, and theget_multilingual_glossary_entries() anddelete_multilingual_glossary_dictionary() is URL-encoded.delete_multilingual_glossary_dictionary() now also strips regional variantsEN-GB becomes EN), like the other multilingual glossary functions.DeepLException instead ofKeyError, TypeError or ValueError.MultilingualGlossaryInfo.to_json() returns a JSON-serialisable dictionary:creation_time as an ISO 8601 string and dictionaries as dictionaries./, ? or spaces no longer change the requested URL.KeyError,TypeError or AttributeError when the API returns a malformed response.DeepLException. list_translation_memories() also raisesDeepLException for a non-JSON response instead of returning an empty list.get_usage() returning a Usage with every value invalid when theDeepLException.translate_document_download() now raises errors with the API's errorcontent: <file>.translate_document_wait_until_done() (and translate_document() withtimeout_s) shortens its last wait to the timeout, so it no longer runs uptimeout_s.glossary_ids parametertranslate_text(), translate_document(),translate_document_upload(), and translate_document_from_filepath().style_ruletranslate_document(), translate_document_upload(), andtranslate_document_from_filepath().translation_memory and translation_memory_threshold parameters intranslate_document(), translate_document_upload(), andtranslate_document_from_filepath().--glossary-ids CLI argument for the text and document commands,--style-id, --translation-memory-id, and--translation-memory-threshold CLI arguments to the document command.get_translation_memory(), list_translation_memory_segments(),delete_translation_memory(), create_translation_memory_import(),upload_translation_memory_file(), create_translation_memory_export(),get_translation_memory_job(),wait_until_translation_memory_job_done(), anddownload_translation_memory_export(), along with theimport_translation_memory_from_filepath() andexport_translation_memory_to_filepath() convenience functions that createawaiting_input for a while after the upload; the wait loop polls throughtimeout_s to bound the wait.TranslationMemorySegments, TranslationMemorySegment,TranslationMemoryTargetSegment, TranslationMemoryImport,TranslationMemoryExport, TranslationMemoryJob, andTranslationMemoryJobResult types.creation_time and updated_time properties toTranslationMemoryInfo.translation-memory CLI command with the list, get,segments, import, export, job, and delete subcommands.translation_memory and translation_memory_threshold parameters intranslate_text().list_translation_memories() method to the DeepLClient class for--translation-memory-id and --translation-memory-threshold CLI$HOME from the global image.DeepLClient class:create_style_rule(), get_style_rule(), update_style_rule_name(),update_style_rule_configured_rules(), and delete_style_rule().DeepLClient class: create_style_rule_custom_instruction(),get_style_rule_custom_instruction(),update_style_rule_custom_instruction(), anddelete_style_rule_custom_instruction().NotFoundException error message by removing the misleading "check server_url" suggestion.tag_handling_version parameter to translate_text() to specify which versionv1 and v2.