Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions sdk/translation/azure-ai-translation-text/_meta.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"commit": "4637adf8aac277915fad37135dc4d11d34e166b9",
"repository_url": "https://github.com/Azure/azure-rest-api-specs",
"typespec_src": "specification/translation/Azure.AI.TextTranslation",
"@azure-tools/typespec-python": {
"version": "0.8.2",
"resolved": "https://registry.npmjs.org/@azure-tools/typespec-python/-/typespec-python-0.8.2.tgz",
"dependencies": {
"@autorest/python": {
"version": "6.4.9",
"resolved": "https://registry.npmjs.org/@autorest/python/-/python-6.4.9.tgz"
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------

from ._patch import TextTranslationClient
from ._client import TextTranslationClient
from ._version import VERSION

__version__ = VERSION
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ class TextTranslationClient(TextTranslationClientOperationsMixin): # pylint: di
:param endpoint: Supported Text Translation endpoints (protocol and hostname, for example:
https://api.cognitive.microsofttranslator.com). Required.
:type endpoint: str
:keyword api_version: Default value is "3.0". Note that overriding this default value may
result in unsupported behavior.
:keyword api_version: Mandatory API version parameter. Default value is "3.0". Note that
overriding this default value may result in unsupported behavior.
:paramtype api_version: str
"""

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,13 @@
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------

import sys
from typing import Any

from azure.core.configuration import Configuration
from azure.core.pipeline import policies

from ._version import VERSION

if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports


class TextTranslationClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes
"""Configuration for TextTranslationClient.
Expand All @@ -29,14 +23,14 @@ class TextTranslationClientConfiguration(Configuration): # pylint: disable=too-
:param endpoint: Supported Text Translation endpoints (protocol and hostname, for example:
https://api.cognitive.microsofttranslator.com). Required.
:type endpoint: str
:keyword api_version: Default value is "3.0". Note that overriding this default value may
result in unsupported behavior.
:keyword api_version: Mandatory API version parameter. Default value is "3.0". Note that
overriding this default value may result in unsupported behavior.
:paramtype api_version: str
"""

def __init__(self, endpoint: str, **kwargs: Any) -> None:
super(TextTranslationClientConfiguration, self).__init__(**kwargs)
api_version: Literal["3.0"] = kwargs.pop("api_version", "3.0")
api_version: str = kwargs.pop("api_version", "3.0")

if endpoint is None:
raise ValueError("Parameter 'endpoint' must not be None.")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -425,7 +425,9 @@ def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:
if non_attr_kwargs:
# actual type errors only throw the first wrong keyword arg they see, so following that.
raise TypeError(f"{class_name}.__init__() got an unexpected keyword argument '{non_attr_kwargs[0]}'")
dict_to_pass.update({self._attr_to_rest_field[k]._rest_name: _serialize(v) for k, v in kwargs.items()})
dict_to_pass.update(
{self._attr_to_rest_field[k]._rest_name: _serialize(v) for k, v in kwargs.items() if v is not None}
)
super().__init__(dict_to_pass)

def copy(self) -> "Model":
Expand Down

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,16 @@
# Licensed under the MIT License.
# ------------------------------------

from typing import ( Union, Optional )
from typing import Union, Optional
from azure.core.pipeline import PipelineRequest
from azure.core.pipeline.policies import ( SansIOHTTPPolicy, BearerTokenCredentialPolicy, AzureKeyCredentialPolicy )
from azure.core.credentials import ( TokenCredential, AzureKeyCredential )
from azure.core.pipeline.policies import SansIOHTTPPolicy, BearerTokenCredentialPolicy, AzureKeyCredentialPolicy
from azure.core.credentials import TokenCredential, AzureKeyCredential

from ._client import TextTranslationClient as ServiceClientGenerated

DEFAULT_TOKEN_SCOPE = "https://api.microsofttranslator.com/"


def patch_sdk():
"""Do not remove from this file.

Expand All @@ -20,9 +21,10 @@ def patch_sdk():
https://aka.ms/azsdk/python/dpcodegen/python/customize
"""


class TranslatorCredential:
""" Credential for Translator Service. It is using combination of Resource key and region.
"""
"""Credential for Translator Service. It is using combination of Resource key and region."""

def __init__(self, key: str, region: str) -> None:
self.key = key
self.region = region
Expand All @@ -40,18 +42,21 @@ def update(self, key: str) -> None:
raise TypeError("The key used for updating must be a string.")
self.key = key


class TranslatorAuthenticationPolicy(SansIOHTTPPolicy):
""" Translator Authentication Policy. Adds both authentication headers that are required.
"""Translator Authentication Policy. Adds both authentication headers that are required.
Ocp-Apim-Subscription-Region header contains region of the Translator resource.
Ocp-Apim-Subscription-Key header contains API key of the Translator resource.
"""

def __init__(self, credential: TranslatorCredential):
self.credential = credential

def on_request(self, request: PipelineRequest) -> None:
request.http_request.headers["Ocp-Apim-Subscription-Key"] = self.credential.key
request.http_request.headers["Ocp-Apim-Subscription-Region"] = self.credential.region


def get_translation_endpoint(endpoint, api_version):
if not endpoint:
endpoint = "https://api.cognitive.microsofttranslator.com"
Expand All @@ -64,17 +69,22 @@ def get_translation_endpoint(endpoint, api_version):

return translator_endpoint


def set_authentication_policy(credential, kwargs):
if isinstance(credential, TranslatorCredential):
if not kwargs.get("authentication_policy"):
kwargs["authentication_policy"] = TranslatorAuthenticationPolicy(credential)
elif isinstance(credential, AzureKeyCredential):
if not kwargs.get("authentication_policy"):
kwargs["authentication_policy"] = AzureKeyCredentialPolicy(
name="Ocp-Apim-Subscription-Key", credential=credential)
name="Ocp-Apim-Subscription-Key", credential=credential
)
elif hasattr(credential, "get_token"):
if not kwargs.get("authentication_policy"):
kwargs["authentication_policy"] = BearerTokenCredentialPolicy(credential, *kwargs.pop("credential_scopes", [DEFAULT_TOKEN_SCOPE]), kwargs)
kwargs["authentication_policy"] = BearerTokenCredentialPolicy(
credential, *kwargs.pop("credential_scopes", [DEFAULT_TOKEN_SCOPE]), kwargs
)


class TextTranslationClient(ServiceClientGenerated):
"""Text translation is a cloud-based REST API feature of the Translator service that uses neural
Expand Down Expand Up @@ -117,22 +127,21 @@ class TextTranslationClient(ServiceClientGenerated):
result in unsupported behavior.
:paramtype api_version: str
"""

def __init__(
self,
credential: Union[AzureKeyCredential , TokenCredential , TranslatorCredential],
*,
endpoint: Optional[str] = None,
api_version = "3.0",
**kwargs):
self,
credential: Union[AzureKeyCredential, TokenCredential, TranslatorCredential],
*,
endpoint: Optional[str] = None,
api_version="3.0",
**kwargs
):

set_authentication_policy(credential, kwargs)

translation_endpoint = get_translation_endpoint(endpoint, api_version)

super().__init__(
endpoint=translation_endpoint,
api_version=api_version,
**kwargs
)
super().__init__(endpoint=translation_endpoint, api_version=api_version, **kwargs)


__all__ = ["TextTranslationClient", "TranslatorCredential"]
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ class TextTranslationClient(TextTranslationClientOperationsMixin): # pylint: di
:param endpoint: Supported Text Translation endpoints (protocol and hostname, for example:
https://api.cognitive.microsofttranslator.com). Required.
:type endpoint: str
:keyword api_version: Default value is "3.0". Note that overriding this default value may
result in unsupported behavior.
:keyword api_version: Mandatory API version parameter. Default value is "3.0". Note that
overriding this default value may result in unsupported behavior.
:paramtype api_version: str
"""

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,13 @@
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------

import sys
from typing import Any

from azure.core.configuration import Configuration
from azure.core.pipeline import policies

from .._version import VERSION

if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports


class TextTranslationClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes
"""Configuration for TextTranslationClient.
Expand All @@ -29,14 +23,14 @@ class TextTranslationClientConfiguration(Configuration): # pylint: disable=too-
:param endpoint: Supported Text Translation endpoints (protocol and hostname, for example:
https://api.cognitive.microsofttranslator.com). Required.
:type endpoint: str
:keyword api_version: Default value is "3.0". Note that overriding this default value may
result in unsupported behavior.
:keyword api_version: Mandatory API version parameter. Default value is "3.0". Note that
overriding this default value may result in unsupported behavior.
:paramtype api_version: str
"""

def __init__(self, endpoint: str, **kwargs: Any) -> None:
super(TextTranslationClientConfiguration, self).__init__(**kwargs)
api_version: Literal["3.0"] = kwargs.pop("api_version", "3.0")
api_version: str = kwargs.pop("api_version", "3.0")

if endpoint is None:
raise ValueError("Parameter 'endpoint' must not be None.")
Expand Down
Loading