Skip to content

Commit 0e3ce67

Browse files
Add Translator.translate_document_wait_until_done()
1 parent 50dd6b9 commit 0e3ce67

2 files changed

Lines changed: 27 additions & 11 deletions

File tree

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1212
Note: older library versions also support the new languages, this update only adds new code constants.
1313
* Add `limit_reached` and `any_limit_reached` properties to `Usage` object
1414
returned by `get_usage()`.
15+
* Add `Translator.translate_document_wait_until_done()` to poll translation
16+
status until translation is complete or fails.
1517
### Changed
1618
### Deprecated
1719
* Deprecate `limit_exceeded` and `any_limit_exceeded` properties of `Usage`

deepl/translator.py

Lines changed: 25 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -884,17 +884,7 @@ def translate_document(
884884
)
885885

886886
try:
887-
status = self.translate_document_get_status(handle)
888-
while status.ok and not status.done:
889-
secs = (status.seconds_remaining or 0) / 2.0 + 1.0
890-
secs = max(1.0, min(secs, 60.0))
891-
util.log_info(
892-
f"Rechecking document translation status "
893-
f"after sleeping for {secs:.3f} seconds."
894-
)
895-
time.sleep(secs)
896-
status = self.translate_document_get_status(handle)
897-
887+
status = self.translate_document_wait_until_done(handle)
898888
if status.ok:
899889
self.translate_document_download(handle, output_document)
900890
except Exception as e:
@@ -982,6 +972,30 @@ def translate_document_get_status(
982972
status, seconds_remaining, billed_characters, error_message
983973
)
984974

975+
def translate_document_wait_until_done(
976+
self, handle: DocumentHandle
977+
) -> DocumentStatus:
978+
"""
979+
Continually polls the status of the document translation associated
980+
with the given handle, sleeping in between requests, and returns the
981+
final status when the translation completes (whether successful or
982+
not).
983+
984+
:param handle: DocumentHandle to the document translation to wait on.
985+
:return: DocumentStatus containing the status when completed.
986+
"""
987+
status = self.translate_document_get_status(handle)
988+
while status.ok and not status.done:
989+
secs = (status.seconds_remaining or 0) / 2.0 + 1.0
990+
secs = max(1.0, min(secs, 60.0))
991+
util.log_info(
992+
f"Rechecking document translation status "
993+
f"after sleeping for {secs:.3f} seconds."
994+
)
995+
time.sleep(secs)
996+
status = self.translate_document_get_status(handle)
997+
return status
998+
985999
def translate_document_download(
9861000
self,
9871001
handle: DocumentHandle,

0 commit comments

Comments
 (0)