Skip to content

Commit

Permalink
[translation] release prep (Azure#19139)
Browse files Browse the repository at this point in the history
* fix type hint

* run black formatting

* docs sweep

* update changelog date

* update date again
  • Loading branch information
kristapratico authored Jun 7, 2021
1 parent 2df1266 commit f24a2a6
Show file tree
Hide file tree
Showing 16 changed files with 421 additions and 293 deletions.
2 changes: 1 addition & 1 deletion sdk/translation/azure-ai-translation-document/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Release History

## 1.0.0b2 (Unreleased)
## 1.0.0b2 (2021-06-08)

This version of the SDK defaults to the latest supported service version, which currently is v1.0

Expand Down
12 changes: 5 additions & 7 deletions sdk/translation/azure-ai-translation-document/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,11 +137,9 @@ The client provides operations for:

### Translation Input

To begin translating your documents, pass a list of `DocumentTranslationInput` into the `begin_translation` client method.
Constructing a `DocumentTranslationInput` requires that you pass the SAS URLs to your source and target containers (or files)
and the target language(s) for translation.
Input to the `begin_translation` client method can be provided in two different ways:

A single source container with documents can be translated to a different language:
1) A single source container with documents can be translated to a different language:

```python
from azure.core.credentials import AzureKeyCredential
Expand All @@ -151,7 +149,7 @@ document_translation_client = DocumentTranslationClient("<endpoint>", AzureKeyCr
poller = document_translation_client.begin_translation("<sas_url_to_source>", "<sas_url_to_target>", "<target_language_code>")
```

Or multiple different sources can be provided each with their own targets.
2) Or multiple different sources can be provided each with their own targets.

```python
from azure.core.credentials import AzureKeyCredential
Expand Down Expand Up @@ -240,7 +238,7 @@ for document in result:
if document.status == "Succeeded":
print("Source document location: {}".format(document.source_document_url))
print("Translated document location: {}".format(document.translated_document_url))
print("Translated to language: {}\n".format(document.translate_to))
print("Translated to language: {}\n".format(document.translated_to))
else:
print("Error Code: {}, Message: {}\n".format(document.error.code, document.error.message))
```
Expand Down Expand Up @@ -308,7 +306,7 @@ document_translation_client = DocumentTranslationClient(endpoint, credential)
operations = document_translation_client.list_all_translation_statuses() # type: ItemPaged[TranslationStatusResult]

for operation in operations:
print("ID: {}".format(operation.id))
print("\nID: {}".format(operation.id))
print("Status: {}".format(operation.status))
print("Created on: {}".format(operation.created_on))
print("Last updated on: {}".format(operation.last_updated_on))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
DocumentTranslationError,
TranslationGlossary,
DocumentTranslationInput,
FileFormat
FileFormat,
)

__VERSION__ = VERSION
Expand All @@ -35,5 +35,5 @@
"TranslationStatusResult",
"DocumentStatusResult",
"DocumentTranslationError",
"DocumentTranslationLROPoller"
"DocumentTranslationLROPoller",
]
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,6 @@ def validate_api_version(api_version):
except ValueError:
raise ValueError(
"Unsupported API version '{}'. Please select from:\n{}".format(
api_version, ", ".join(v.value for v in DocumentTranslationApiVersion))
api_version, ", ".join(v.value for v in DocumentTranslationApiVersion)
)
)
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@
import json
from typing import Any, TYPE_CHECKING, List, Union, overload
from azure.core.tracing.decorator import distributed_trace
from ._generated import BatchDocumentTranslationClient as _BatchDocumentTranslationClient
from ._generated import (
BatchDocumentTranslationClient as _BatchDocumentTranslationClient,
)
from ._models import (
TranslationStatusResult,
DocumentStatusResult,
DocumentTranslationInput,
FileFormat
FileFormat,
)
from ._user_agent import USER_AGENT
from ._polling import TranslationPolling, DocumentTranslationLROPollingMethod
Expand All @@ -21,16 +23,16 @@
convert_datetime,
get_authentication_policy,
get_translation_input,
POLLING_INTERVAL
POLLING_INTERVAL,
)

if TYPE_CHECKING:
from azure.core.paging import ItemPaged
from azure.core.credentials import TokenCredential, AzureKeyCredential
from ._polling import DocumentTranslationLROPoller


class DocumentTranslationClient(object): # pylint: disable=r0205

def __init__(self, endpoint, credential, **kwargs):
# type: (str, Union[AzureKeyCredential, TokenCredential], Any) -> None
"""DocumentTranslationClient is your interface to the Document Translation service.
Expand Down Expand Up @@ -67,7 +69,7 @@ def __init__(self, endpoint, credential, **kwargs):
"""
self._endpoint = endpoint
self._credential = credential
self._api_version = kwargs.pop('api_version', None)
self._api_version = kwargs.pop("api_version", None)

authentication_policy = get_authentication_policy(credential)
polling_interval = kwargs.pop("polling_interval", POLLING_INTERVAL)
Expand Down Expand Up @@ -98,19 +100,22 @@ def close(self):

@overload
def begin_translation(self, source_url, target_url, target_language_code, **kwargs):
# type: (str, str, str, **Any) -> DocumentTranslationPoller[ItemPaged[DocumentStatusResult]]
# type: (str, str, str, **Any) -> DocumentTranslationLROPoller[ItemPaged[DocumentStatusResult]]
pass

@overload
def begin_translation(self, inputs, **kwargs):
# type: (List[DocumentTranslationInput], **Any) -> DocumentTranslationLROPoller[ItemPaged[DocumentStatusResult]]
pass

def begin_translation(self, *args, **kwargs): # pylint: disable=client-method-missing-type-annotations
def begin_translation(
self, *args, **kwargs
): # pylint: disable=client-method-missing-type-annotations
"""Begin translating the document(s) in your source container to your target container
in the given language. To perform a single translation from source to target, pass the `source_url`,
`target_url`, and `target_language_code` parameters. To pass multiple inputs for translation, including
other translation options, pass the `inputs` parameter as a list of DocumentTranslationInput.
other translation options, pass the `inputs` parameter as a list of
:class:`~azure.ai.translation.document.DocumentTranslationInput`.
For supported languages and document formats, see the service documentation:
https://docs.microsoft.com/azure/cognitive-services/translator/document-translation/overview
Expand Down Expand Up @@ -153,7 +158,8 @@ def deserialization_callback(
return self.list_all_document_statuses(translation_status["id"])

polling_interval = kwargs.pop(
"polling_interval", self._client._config.polling_interval # pylint: disable=protected-access
"polling_interval",
self._client._config.polling_interval, # pylint: disable=protected-access
)

pipeline_response = None
Expand All @@ -168,11 +174,10 @@ def deserialization_callback(
inputs=inputs if not continuation_token else None,
polling=DocumentTranslationLROPollingMethod(
timeout=polling_interval,
lro_algorithms=[
TranslationPolling()
],
lro_algorithms=[TranslationPolling()],
cont_token_response=pipeline_response,
**kwargs),
**kwargs
),
cls=callback,
continuation_token=continuation_token,
**kwargs
Expand All @@ -192,8 +197,12 @@ def get_translation_status(self, translation_id, **kwargs):
:raises ~azure.core.exceptions.HttpResponseError or ~azure.core.exceptions.ResourceNotFoundError:
"""

translation_status = self._client.document_translation.get_translation_status(translation_id, **kwargs)
return TranslationStatusResult._from_generated(translation_status) # pylint: disable=protected-access
translation_status = self._client.document_translation.get_translation_status(
translation_id, **kwargs
)
return TranslationStatusResult._from_generated( # pylint: disable=protected-access
translation_status
)

@distributed_trace
def cancel_translation(self, translation_id, **kwargs):
Expand Down Expand Up @@ -223,13 +232,15 @@ def list_all_translation_statuses(self, **kwargs):
:keyword int results_per_page: is the number of operations returned per page.
:keyword list[str] translation_ids: translation operations ids to filter by.
:keyword list[str] statuses: translation operation statuses to filter by.
:keyword Union[str, datetime.datetime] created_after: get operations created after certain datetime.
:keyword Union[str, datetime.datetime] created_before: get operations created before certain datetime.
:keyword created_after: get operations created after certain datetime.
:paramtype created_after: Union[str, datetime.datetime]
:keyword created_before: get operations created before certain datetime.
:paramtype created_before: Union[str, datetime.datetime]
:keyword list[str] order_by: the sorting query for the operations returned.
format: ["parm1 asc/desc", "parm2 asc/desc", ...]
(ex: 'createdDateTimeUtc asc', 'createdDateTimeUtc desc').
:return: ~azure.core.paging.ItemPaged[:class:`~azure.ai.translation.document.TranslationStatusResult`]
:rtype: ~azure.core.paging.ItemPaged[:class:`~azure.ai.translation.document.TranslationStatusResult`]
:return: A pageable of TranslationStatusResult.
:rtype: ~azure.core.paging.ItemPaged[TranslationStatusResult]
:raises ~azure.core.exceptions.HttpResponseError:
.. admonition:: Example:
Expand All @@ -248,14 +259,19 @@ def list_all_translation_statuses(self, **kwargs):
results_per_page = kwargs.pop("results_per_page", None)
translation_ids = kwargs.pop("translation_ids", None)

def _convert_from_generated_model(generated_model): # pylint: disable=protected-access
return TranslationStatusResult._from_generated(generated_model) # pylint: disable=protected-access
def _convert_from_generated_model(
generated_model,
): # pylint: disable=protected-access
return TranslationStatusResult._from_generated(
generated_model
) # pylint: disable=protected-access

model_conversion_function = kwargs.pop(
"cls",
lambda translation_statuses: [
_convert_from_generated_model(status) for status in translation_statuses
])
],
)

return self._client.document_translation.get_translations_status(
cls=model_conversion_function,
Expand All @@ -278,13 +294,15 @@ def list_all_document_statuses(self, translation_id, **kwargs):
:keyword int results_per_page: is the number of documents returned per page.
:keyword list[str] document_ids: document IDs to filter by.
:keyword list[str] statuses: document statuses to filter by.
:keyword Union[str, datetime.datetime] translated_after: get document translated after certain datetime.
:keyword Union[str, datetime.datetime] translated_before: get document translated before certain datetime.
:keyword translated_after: get document translated after certain datetime.
:paramtype translated_after: Union[str, datetime.datetime]
:keyword translated_before: get document translated before certain datetime.
:paramtype translated_before: Union[str, datetime.datetime]
:keyword list[str] order_by: the sorting query for the documents.
format: ["parm1 asc/desc", "parm2 asc/desc", ...]
(ex: 'createdDateTimeUtc asc', 'createdDateTimeUtc desc').
:return: ~azure.core.paging.ItemPaged[:class:`~azure.ai.translation.document.DocumentStatusResult`]
:rtype: ~azure.core.paging.ItemPaged[:class:`~azure.ai.translation.document.DocumentStatusResult`]
:return: A pageable of DocumentStatusResult.
:rtype: ~azure.core.paging.ItemPaged[DocumentStatusResult]
:raises ~azure.core.exceptions.HttpResponseError:
.. admonition:: Example:
Expand All @@ -298,20 +316,26 @@ def list_all_document_statuses(self, translation_id, **kwargs):
"""
translated_after = kwargs.pop("translated_after", None)
translated_before = kwargs.pop("translated_before", None)
translated_after = convert_datetime(translated_after) if translated_after else None
translated_before = convert_datetime(translated_before) if translated_before else None
translated_after = (
convert_datetime(translated_after) if translated_after else None
)
translated_before = (
convert_datetime(translated_before) if translated_before else None
)
results_per_page = kwargs.pop("results_per_page", None)
document_ids = kwargs.pop("document_ids", None)


def _convert_from_generated_model(generated_model):
return DocumentStatusResult._from_generated(generated_model) # pylint: disable=protected-access
return DocumentStatusResult._from_generated( # pylint: disable=protected-access
generated_model
)

model_conversion_function = kwargs.pop(
"cls",
lambda doc_statuses: [
_convert_from_generated_model(doc_status) for doc_status in doc_statuses
])
],
)

return self._client.document_translation.get_documents_status(
id=translation_id,
Expand All @@ -336,10 +360,11 @@ def get_document_status(self, translation_id, document_id, **kwargs):
"""

document_status = self._client.document_translation.get_document_status(
translation_id,
document_id,
**kwargs)
return DocumentStatusResult._from_generated(document_status) # pylint: disable=protected-access
translation_id, document_id, **kwargs
)
return DocumentStatusResult._from_generated( # pylint: disable=protected-access
document_status
)

@distributed_trace
def get_glossary_formats(self, **kwargs):
Expand All @@ -351,8 +376,12 @@ def get_glossary_formats(self, **kwargs):
:raises ~azure.core.exceptions.HttpResponseError:
"""

glossary_formats = self._client.document_translation.get_supported_glossary_formats(**kwargs)
return FileFormat._from_generated_list(glossary_formats.value) # pylint: disable=protected-access
glossary_formats = (
self._client.document_translation.get_supported_glossary_formats(**kwargs)
)
return FileFormat._from_generated_list( # pylint: disable=protected-access
glossary_formats.value
)

@distributed_trace
def get_document_formats(self, **kwargs):
Expand All @@ -364,5 +393,9 @@ def get_document_formats(self, **kwargs):
:raises ~azure.core.exceptions.HttpResponseError:
"""

document_formats = self._client.document_translation.get_supported_document_formats(**kwargs)
return FileFormat._from_generated_list(document_formats.value) # pylint: disable=protected-access
document_formats = (
self._client.document_translation.get_supported_document_formats(**kwargs)
)
return FileFormat._from_generated_list( # pylint: disable=protected-access
document_formats.value
)
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,24 @@
TargetInput as _TargetInput,
)
from ._models import DocumentTranslationInput

COGNITIVE_KEY_HEADER = "Ocp-Apim-Subscription-Key"
POLLING_INTERVAL = 1


def get_translation_input(args, kwargs, continuation_token):
try:
inputs = kwargs.pop('inputs', None)
inputs = kwargs.pop("inputs", None)
if not inputs:
inputs = args[0]
request = DocumentTranslationInput._to_generated_list(inputs) \
if not continuation_token else None # pylint: disable=protected-access
request = (
DocumentTranslationInput._to_generated_list(inputs) # pylint: disable=protected-access
if not continuation_token
else None
)
except (AttributeError, TypeError, IndexError):
try:
source_url = kwargs.pop('source_url', None)
source_url = kwargs.pop("source_url", None)
if not source_url:
source_url = args[0]
target_url = kwargs.pop("target_url", None)
Expand All @@ -40,18 +44,19 @@ def get_translation_input(args, kwargs, continuation_token):
target_language_code = args[2]
request = [
_BatchRequest(
source=_SourceInput(
source_url=source_url
),
targets=[_TargetInput(
target_url=target_url,
language=target_language_code
)]
source=_SourceInput(source_url=source_url),
targets=[
_TargetInput(
target_url=target_url, language=target_language_code
)
],
)
]
except (AttributeError, TypeError, IndexError):
raise ValueError("Pass 'inputs' for multiple inputs or 'source_url', 'target_url', "
"and 'target_language_code' for a single input.")
raise ValueError(
"Pass 'inputs' for multiple inputs or 'source_url', 'target_url', "
"and 'target_language_code' for a single input."
)

return request

Expand Down Expand Up @@ -85,7 +90,7 @@ def get_http_logging_policy(**kwargs):
"Set-Cookie",
"X-Powered-By",
"Strict-Transport-Security",
"x-content-type-options"
"x-content-type-options",
}
)
http_logging_policy.allowed_query_params.update(
Expand All @@ -97,7 +102,7 @@ def get_http_logging_policy(**kwargs):
"statuses",
"createdDateTimeUtcStart",
"createdDateTimeUtcEnd",
"$orderBy"
"$orderBy",
}
)
return http_logging_policy
Expand Down
Loading

0 comments on commit f24a2a6

Please sign in to comment.