Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix/azure region #19

Merged
merged 2 commits into from
Jun 1, 2024
Merged
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
26 changes: 18 additions & 8 deletions src/easytl/easytl.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,14 +75,15 @@ def set_credentials(api_type:typing.Literal["deepl", "gemini", "openai", "google
##-------------------start-of-test_credentials()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------

@staticmethod
def test_credentials(api_type:typing.Literal["deepl", "gemini", "openai", "google translate", "anthropic", "azure"]) -> typing.Tuple[bool, typing.Optional[Exception]]:
def test_credentials(api_type:typing.Literal["deepl", "gemini", "openai", "google translate", "anthropic", "azure"], azure_region:str = "westus") -> typing.Tuple[bool, typing.Optional[Exception]]:

"""

Tests the validity of the credentials for the specified API type.

Parameters:
api_type (literal["deepl", "gemini", "openai", "google translate", "anthropic", "azure"]) : The API type to test the credentials for.
azure_region (string) : The Azure region to test the credentials for. Default is 'westus'.

Returns:
(bool) : Whether the credentials are valid.
Expand All @@ -96,18 +97,26 @@ def test_credentials(api_type:typing.Literal["deepl", "gemini", "openai", "googl
"openai": {"service": OpenAIService, "exception": OpenAIError, "test_func": OpenAIService._test_api_key_validity},
"google translate": {"service": GoogleTLService, "exception": GoogleAPIError, "test_func": GoogleTLService._test_credentials},
"anthropic": {"service": AnthropicService, "exception": AnthropicError, "test_func": AnthropicService._test_api_key_validity},
"azure": {"service": AzureService, "exception": RequestException, "test_func": AzureService._test_credentials}
"azure":{"test_func":None} # We kind of not need it, it's just for the assertion.
}

assert api_type in api_services, InvalidAPITypeException("Invalid API type specified. Supported types are 'deepl', 'gemini', 'openai', 'google translate', 'anthropic' and 'azure'.")

_is_valid, _e = api_services[api_type]["test_func"]()
if(api_type == "azure"):
_is_valid, _e = AzureService._test_credentials(azure_region)
else:
_is_valid, _e = api_services[api_type]["test_func"]()

if _e is not None:
raise _e

if(not _is_valid):
## Done to make sure the exception is due to the specified API type and not the fault of EasyTL
assert isinstance(_e, api_services[api_type]["exception"]), _e
return False, _e
# Temporally commented. We think that an exception should be raised if the credentials are invalid, instead of soft-handling it.
# if(not _is_valid):
# ## Done to make sure the exception is due to the specified API type and not the fault of EasyTL
# assert isinstance(_e, api_services[api_type]["exception"]), _e
# return False, _e

# If the exception gets raised it would not make sense to return it, it already 'goes back' through exception handling.
return True, None

##-------------------start-of-googletl_translate()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Expand Down Expand Up @@ -1246,7 +1255,8 @@ def azure_translate(text: typing.Union[str, typing.Iterable[str]],

assert response_type in ["text", "json"], InvalidResponseFormatException("Invalid response type specified. Must be 'text' or 'json'.")

EasyTL.test_credentials("azure")

EasyTL.test_credentials("azure", azure_region=azure_region)

if(override_previous_settings == True):
AzureService._set_attributes(target_language=target_lang,
Expand Down
7 changes: 6 additions & 1 deletion src/easytl/services/azure_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,9 @@ def _translate_text(text:str) -> typing.Union[typing.List[typing.Any], typing.An
request = requests.post(url, params=params, headers=headers, json=body)
response = request.json()

if 'error' in response:
raise Exception(f"{response['error']['message']}\n\nTip: Double check API key, region and endpoint :)") # Should we use a custom exception?

return response

except Exception as _e:
Expand Down Expand Up @@ -185,7 +188,7 @@ async def _translate_text_async(text:str) -> typing.Union[typing.List[typing.Any
##-------------------start-of-_test_credentials()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------

@staticmethod
def _test_credentials() -> typing.Tuple[bool, typing.Union[Exception, None]]:
def _test_credentials(azure_region: str) -> typing.Tuple[bool, typing.Union[Exception, None]]:

"""

Expand All @@ -197,6 +200,8 @@ def _test_credentials() -> typing.Tuple[bool, typing.Union[Exception, None]]:

"""

AzureService._set_attributes(azure_region=azure_region)

try:
AzureService._translate_text('Hola')
return True, None
Expand Down