diff --git a/sdk/contentsafety/azure-ai-contentsafety/_meta.json b/sdk/contentsafety/azure-ai-contentsafety/_meta.json new file mode 100644 index 000000000000..4a797c5a713a --- /dev/null +++ b/sdk/contentsafety/azure-ai-contentsafety/_meta.json @@ -0,0 +1,6 @@ +{ + "commit": "ef76b5cbcee099bb7855792bd73173454ac51081", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "typespec_src": "specification/cognitiveservices/ContentSafety", + "@azure-tools/typespec-python": "0.15.14" +} \ No newline at end of file diff --git a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/__init__.py b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/__init__.py index b18f5528965f..7eee7d8f0096 100644 --- a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/__init__.py +++ b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/__init__.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from ._client import ContentSafetyClient +from ._client import BlocklistClient from ._version import VERSION __version__ = VERSION @@ -20,6 +21,7 @@ __all__ = [ "ContentSafetyClient", + "BlocklistClient", ] __all__.extend([p for p in _patch_all if p not in __all__]) diff --git a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_client.py b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_client.py index 5b7456fbba58..e2e1f2849fe6 100644 --- a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_client.py +++ b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_client.py @@ -7,33 +7,38 @@ # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any +from typing import Any, TYPE_CHECKING, Union from azure.core import PipelineClient from azure.core.credentials import AzureKeyCredential from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse -from ._configuration import ContentSafetyClientConfiguration -from ._operations import ContentSafetyClientOperationsMixin +from ._configuration import BlocklistClientConfiguration, ContentSafetyClientConfiguration +from ._operations import BlocklistClientOperationsMixin, ContentSafetyClientOperationsMixin from ._serialization import Deserializer, Serializer +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + class ContentSafetyClient(ContentSafetyClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword - """Analyze harmful content. + """ContentSafetyClient. :param endpoint: Supported Cognitive Services endpoints (protocol and hostname, for example: https://:code:``.cognitiveservices.azure.com). Required. :type endpoint: str - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.AzureKeyCredential - :keyword api_version: The API version to use for this operation. Default value is - "2023-04-30-preview". Note that overriding this default value may result in unsupported - behavior. + :param credential: Credential needed for the client to connect to Azure. Is either a + AzureKeyCredential type or a TokenCredential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials.TokenCredential + :keyword api_version: The API version to use for this operation. Default value is "2023-10-01". + Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__(self, endpoint: str, credential: AzureKeyCredential, **kwargs: Any) -> None: + def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, "TokenCredential"], **kwargs: Any) -> None: _endpoint = "{endpoint}/contentsafety" self._config = ContentSafetyClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) _policies = kwargs.pop("policies", None) @@ -59,7 +64,7 @@ def __init__(self, endpoint: str, credential: AzureKeyCredential, **kwargs: Any) self._deserialize = Deserializer() self._serialize.client_side_validation = False - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: + def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -83,7 +88,7 @@ def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: } request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, **kwargs) # type: ignore + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore def close(self) -> None: self._client.close() @@ -94,3 +99,81 @@ def __enter__(self) -> "ContentSafetyClient": def __exit__(self, *exc_details: Any) -> None: self._client.__exit__(*exc_details) + + +class BlocklistClient(BlocklistClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword + """BlocklistClient. + + :param endpoint: Supported Cognitive Services endpoints (protocol and hostname, for example: + https://:code:``.cognitiveservices.azure.com). Required. + :type endpoint: str + :param credential: Credential needed for the client to connect to Azure. Is either a + AzureKeyCredential type or a TokenCredential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials.TokenCredential + :keyword api_version: The API version to use for this operation. Default value is "2023-10-01". + Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, "TokenCredential"], **kwargs: Any) -> None: + _endpoint = "{endpoint}/contentsafety" + self._config = BlocklistClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + + def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> "BlocklistClient": + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_configuration.py b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_configuration.py index 2e06295ad2d3..9d9a723f0355 100644 --- a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_configuration.py +++ b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_configuration.py @@ -6,13 +6,17 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any +from typing import Any, TYPE_CHECKING, Union from azure.core.credentials import AzureKeyCredential from azure.core.pipeline import policies from ._version import VERSION +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + class ContentSafetyClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long """Configuration for ContentSafetyClient. @@ -23,16 +27,17 @@ class ContentSafetyClientConfiguration: # pylint: disable=too-many-instance-att :param endpoint: Supported Cognitive Services endpoints (protocol and hostname, for example: https://:code:``.cognitiveservices.azure.com). Required. :type endpoint: str - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.AzureKeyCredential - :keyword api_version: The API version to use for this operation. Default value is - "2023-04-30-preview". Note that overriding this default value may result in unsupported - behavior. + :param credential: Credential needed for the client to connect to Azure. Is either a + AzureKeyCredential type or a TokenCredential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials.TokenCredential + :keyword api_version: The API version to use for this operation. Default value is "2023-10-01". + Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__(self, endpoint: str, credential: AzureKeyCredential, **kwargs: Any) -> None: - api_version: str = kwargs.pop("api_version", "2023-04-30-preview") + def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, "TokenCredential"], **kwargs: Any) -> None: + api_version: str = kwargs.pop("api_version", "2023-10-01") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") @@ -42,21 +47,82 @@ def __init__(self, endpoint: str, credential: AzureKeyCredential, **kwargs: Any) self.endpoint = endpoint self.credential = credential self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://cognitiveservices.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "ai-contentsafety/{}".format(VERSION)) self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) + def _infer_policy(self, **kwargs): + if isinstance(self.credential, AzureKeyCredential): + return policies.AzureKeyCredentialPolicy(self.credential, "Ocp-Apim-Subscription-Key", **kwargs) + if hasattr(self.credential, "get_token"): + return policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + raise TypeError(f"Unsupported credential: {self.credential}") + def _configure(self, **kwargs: Any) -> None: self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = self._infer_policy(**kwargs) + + +class BlocklistClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long + """Configuration for BlocklistClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: Supported Cognitive Services endpoints (protocol and hostname, for example: + https://:code:``.cognitiveservices.azure.com). Required. + :type endpoint: str + :param credential: Credential needed for the client to connect to Azure. Is either a + AzureKeyCredential type or a TokenCredential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials.TokenCredential + :keyword api_version: The API version to use for this operation. Default value is "2023-10-01". + Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, "TokenCredential"], **kwargs: Any) -> None: + api_version: str = kwargs.pop("api_version", "2023-10-01") + + if endpoint is None: + raise ValueError("Parameter 'endpoint' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + + self.endpoint = endpoint + self.credential = credential + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://cognitiveservices.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "ai-contentsafety/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _infer_policy(self, **kwargs): + if isinstance(self.credential, AzureKeyCredential): + return policies.AzureKeyCredentialPolicy(self.credential, "Ocp-Apim-Subscription-Key", **kwargs) + if hasattr(self.credential, "get_token"): + return policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + raise TypeError(f"Unsupported credential: {self.credential}") + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.AzureKeyCredentialPolicy( - self.credential, "Ocp-Apim-Subscription-Key", **kwargs - ) + self.authentication_policy = self._infer_policy(**kwargs) diff --git a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_model_base.py b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_model_base.py index dd3b15748b79..aec056aba7b7 100644 --- a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_model_base.py +++ b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_model_base.py @@ -8,6 +8,7 @@ # pyright: reportGeneralTypeIssues=false import calendar +import decimal import functools import sys import logging @@ -31,7 +32,7 @@ _LOGGER = logging.getLogger(__name__) -__all__ = ["AzureJSONEncoder", "Model", "rest_field", "rest_discriminator"] +__all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] TZ_UTC = timezone.utc @@ -125,7 +126,7 @@ def _is_readonly(p): return False -class AzureJSONEncoder(JSONEncoder): +class SdkJSONEncoder(JSONEncoder): """A JSON encoder that's capable of serializing datetime objects and bytes.""" def __init__(self, *args, exclude_readonly: bool = False, format: typing.Optional[str] = None, **kwargs): @@ -140,10 +141,12 @@ def default(self, o): # pylint: disable=too-many-return-statements return {k: v for k, v in o.items() if k not in readonly_props} return dict(o.items()) try: - return super(AzureJSONEncoder, self).default(o) + return super(SdkJSONEncoder, self).default(o) except TypeError: if isinstance(o, _Null): return None + if isinstance(o, decimal.Decimal): + return float(o) if isinstance(o, (bytes, bytearray)): return _serialize_bytes(o, self.format) try: @@ -157,7 +160,7 @@ def default(self, o): # pylint: disable=too-many-return-statements except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass - return super(AzureJSONEncoder, self).default(o) + return super(SdkJSONEncoder, self).default(o) _VALID_DATE = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" + r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") @@ -275,6 +278,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_decimal(attr): + if isinstance(attr, decimal.Decimal): + return attr + return decimal.Decimal(str(attr)) + + _DESERIALIZE_MAPPING = { datetime: _deserialize_datetime, date: _deserialize_date, @@ -283,6 +292,7 @@ def _deserialize_duration(attr): bytearray: _deserialize_bytes, timedelta: _deserialize_duration, typing.Any: lambda x: x, + decimal.Decimal: _deserialize_decimal, } _DESERIALIZE_MAPPING_WITHFORMAT = { @@ -426,6 +436,8 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m return tuple(_serialize(x, format) for x in o) if isinstance(o, (bytes, bytearray)): return _serialize_bytes(o, format) + if isinstance(o, decimal.Decimal): + return float(o) try: # First try datetime.datetime return _serialize_datetime(o, format) @@ -642,24 +654,18 @@ def _deserialize_with_union(deserializers, obj): try: if annotation._name == "Dict": - key_deserializer = _get_deserialize_callable_from_annotation(annotation.__args__[0], module, rf) value_deserializer = _get_deserialize_callable_from_annotation(annotation.__args__[1], module, rf) def _deserialize_dict( - key_deserializer: typing.Optional[typing.Callable], value_deserializer: typing.Optional[typing.Callable], obj: typing.Dict[typing.Any, typing.Any], ): if obj is None: return obj - return { - _deserialize(key_deserializer, k, module): _deserialize(value_deserializer, v, module) - for k, v in obj.items() - } + return {k: _deserialize(value_deserializer, v, module) for k, v in obj.items()} return functools.partial( _deserialize_dict, - key_deserializer, value_deserializer, ) except (AttributeError, IndexError): @@ -698,19 +704,17 @@ def _deserialize_sequence( pass def _deserialize_default( - annotation, - deserializer_from_mapping, + deserializer, obj, ): if obj is None: return obj - try: - return _deserialize_with_callable(annotation, obj) - except Exception: - pass - return _deserialize_with_callable(deserializer_from_mapping, obj) + return _deserialize_with_callable(deserializer, obj) + + if get_deserializer(annotation, rf): + return functools.partial(_deserialize_default, get_deserializer(annotation, rf)) - return functools.partial(_deserialize_default, annotation, get_deserializer(annotation, rf)) + return functools.partial(_deserialize_default, annotation) def _deserialize_with_callable( @@ -718,7 +722,7 @@ def _deserialize_with_callable( value: typing.Any, ): try: - if value is None: + if value is None or isinstance(value, _Null): return None if deserializer is None: return value @@ -740,10 +744,14 @@ def _deserialize( value: typing.Any, module: typing.Optional[str] = None, rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, ) -> typing.Any: if isinstance(value, PipelineResponse): value = value.http_response.json() - deserializer = _get_deserialize_callable_from_annotation(deserializer, module, rf) + if rf is None and format: + rf = _RestField(format=format) + if not isinstance(deserializer, functools.partial): + deserializer = _get_deserialize_callable_from_annotation(deserializer, module, rf) return _deserialize_with_callable(deserializer, value) diff --git a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_operations/__init__.py b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_operations/__init__.py index c6de97557237..2f88364a4715 100644 --- a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_operations/__init__.py +++ b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_operations/__init__.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from ._operations import ContentSafetyClientOperationsMixin +from ._operations import BlocklistClientOperationsMixin from ._patch import __all__ as _patch_all from ._patch import * # pylint: disable=unused-wildcard-import @@ -14,6 +15,7 @@ __all__ = [ "ContentSafetyClientOperationsMixin", + "BlocklistClientOperationsMixin", ] __all__.extend([p for p in _patch_all if p not in __all__]) _patch_sdk() diff --git a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_operations/_operations.py b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_operations/_operations.py index 54fef8bb776b..70434f946a0d 100644 --- a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_operations/_operations.py +++ b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_operations/_operations.py @@ -27,9 +27,9 @@ from azure.core.utils import case_insensitive_dict from .. import models as _models -from .._model_base import AzureJSONEncoder, _deserialize +from .._model_base import SdkJSONEncoder, _deserialize from .._serialization import Serializer -from .._vendor import ContentSafetyClientMixinABC +from .._vendor import BlocklistClientMixinABC, ContentSafetyClientMixinABC if sys.version_info >= (3, 9): from collections.abc import MutableMapping @@ -48,7 +48,7 @@ def build_content_safety_analyze_text_request(**kwargs: Any) -> HttpRequest: # _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-30-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -70,7 +70,7 @@ def build_content_safety_analyze_image_request(**kwargs: Any) -> HttpRequest: # _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-30-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -87,17 +87,18 @@ def build_content_safety_analyze_image_request(**kwargs: Any) -> HttpRequest: # return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_content_safety_get_text_blocklist_request( # pylint: disable=name-too-long +def build_blocklist_add_or_update_blocklist_items_request( # pylint: disable=name-too-long blocklist_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-30-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/text/blocklists/{blocklistName}" + _url = "/text/blocklists/{blocklistName}:addOrUpdateBlocklistItems" path_format_arguments = { "blocklistName": _SERIALIZER.url("blocklist_name", blocklist_name, "str"), } @@ -109,18 +110,20 @@ def build_content_safety_get_text_blocklist_request( # pylint: disable=name-too # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_content_safety_create_or_update_text_blocklist_request( # pylint: disable=name-too-long +def build_blocklist_create_or_update_text_blocklist_request( # pylint: disable=name-too-long blocklist_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-30-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -142,12 +145,12 @@ def build_content_safety_create_or_update_text_blocklist_request( # pylint: dis return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) -def build_content_safety_delete_text_blocklist_request( # pylint: disable=name-too-long +def build_blocklist_delete_text_blocklist_request( # pylint: disable=name-too-long blocklist_name: str, **kwargs: Any ) -> HttpRequest: _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-30-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-01")) # Construct URL _url = "/text/blocklists/{blocklistName}" path_format_arguments = { @@ -162,15 +165,22 @@ def build_content_safety_delete_text_blocklist_request( # pylint: disable=name- return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) -def build_content_safety_list_text_blocklists_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long +def build_blocklist_get_text_blocklist_request( # pylint: disable=name-too-long + blocklist_name: str, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-30-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/text/blocklists" + _url = "/text/blocklists/{blocklistName}" + path_format_arguments = { + "blocklistName": _SERIALIZER.url("blocklist_name", blocklist_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -181,20 +191,20 @@ def build_content_safety_list_text_blocklists_request(**kwargs: Any) -> HttpRequ return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_content_safety_add_block_items_request( # pylint: disable=name-too-long - blocklist_name: str, **kwargs: Any +def build_blocklist_get_text_blocklist_item_request( # pylint: disable=name-too-long + blocklist_name: str, blocklist_item_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-30-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/text/blocklists/{blocklistName}:addBlockItems" + _url = "/text/blocklists/{blocklistName}/blocklistItems/{blocklistItemId}" path_format_arguments = { "blocklistName": _SERIALIZER.url("blocklist_name", blocklist_name, "str"), + "blocklistItemId": _SERIALIZER.url("blocklist_item_id", blocklist_item_id, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -204,22 +214,26 @@ def build_content_safety_add_block_items_request( # pylint: disable=name-too-lo # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_content_safety_remove_block_items_request( # pylint: disable=name-too-long - blocklist_name: str, **kwargs: Any +def build_blocklist_list_text_blocklist_items_request( # pylint: disable=name-too-long + blocklist_name: str, + *, + top: Optional[int] = None, + skip: Optional[int] = None, + maxpagesize: Optional[int] = None, + **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-30-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-01")) + accept = _headers.pop("Accept", "application/json") + # Construct URL - _url = "/text/blocklists/{blocklistName}:removeBlockItems" + _url = "/text/blocklists/{blocklistName}/blocklistItems" path_format_arguments = { "blocklistName": _SERIALIZER.url("blocklist_name", blocklist_name, "str"), } @@ -228,31 +242,28 @@ def build_content_safety_remove_block_items_request( # pylint: disable=name-too # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["top"] = _SERIALIZER.query("top", top, "int") + if skip is not None: + _params["skip"] = _SERIALIZER.query("skip", skip, "int") + if maxpagesize is not None: + _params["maxpagesize"] = _SERIALIZER.query("maxpagesize", maxpagesize, "int") # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_content_safety_get_text_blocklist_item_request( # pylint: disable=name-too-long - blocklist_name: str, block_item_id: str, **kwargs: Any -) -> HttpRequest: +def build_blocklist_list_text_blocklists_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-30-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/text/blocklists/{blocklistName}/blockItems/{blockItemId}" - path_format_arguments = { - "blocklistName": _SERIALIZER.url("blocklist_name", blocklist_name, "str"), - "blockItemId": _SERIALIZER.url("block_item_id", block_item_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore + _url = "/text/blocklists" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -263,22 +274,16 @@ def build_content_safety_get_text_blocklist_item_request( # pylint: disable=nam return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_content_safety_list_text_blocklist_items_request( # pylint: disable=name-too-long - blocklist_name: str, - *, - top: Optional[int] = None, - skip: Optional[int] = None, - maxpagesize: Optional[int] = None, - **kwargs: Any +def build_blocklist_remove_blocklist_items_request( # pylint: disable=name-too-long + blocklist_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-30-preview")) - accept = _headers.pop("Accept", "application/json") - + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-01")) # Construct URL - _url = "/text/blocklists/{blocklistName}/blockItems" + _url = "/text/blocklists/{blocklistName}:removeBlocklistItems" path_format_arguments = { "blocklistName": _SERIALIZER.url("blocklist_name", blocklist_name, "str"), } @@ -287,31 +292,26 @@ def build_content_safety_list_text_blocklist_items_request( # pylint: disable=n # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if top is not None: - _params["top"] = _SERIALIZER.query("top", top, "int") - if skip is not None: - _params["skip"] = _SERIALIZER.query("skip", skip, "int") - if maxpagesize is not None: - _params["maxpagesize"] = _SERIALIZER.query("maxpagesize", maxpagesize, "int") # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) class ContentSafetyClientOperationsMixin(ContentSafetyClientMixinABC): @overload def analyze_text( - self, body: _models.AnalyzeTextOptions, *, content_type: str = "application/json", **kwargs: Any + self, options: _models.AnalyzeTextOptions, *, content_type: str = "application/json", **kwargs: Any ) -> _models.AnalyzeTextResult: """Analyze Text. - A sync API for harmful content analysis for text. Currently, we support four categories: Hate, - SelfHarm, Sexual, Violence. + A synchronous API for the analysis of potentially harmful text content. Currently, it supports + four categories: Hate, SelfHarm, Sexual, and Violence. - :param body: The request of text analysis. Required. - :type body: ~azure.ai.contentsafety.models.AnalyzeTextOptions + :param options: The text analysis request. Required. + :type options: ~azure.ai.contentsafety.models.AnalyzeTextOptions :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -324,15 +324,15 @@ def analyze_text( @overload def analyze_text( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, options: JSON, *, content_type: str = "application/json", **kwargs: Any ) -> _models.AnalyzeTextResult: """Analyze Text. - A sync API for harmful content analysis for text. Currently, we support four categories: Hate, - SelfHarm, Sexual, Violence. + A synchronous API for the analysis of potentially harmful text content. Currently, it supports + four categories: Hate, SelfHarm, Sexual, and Violence. - :param body: The request of text analysis. Required. - :type body: JSON + :param options: The text analysis request. Required. + :type options: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -345,15 +345,15 @@ def analyze_text( @overload def analyze_text( - self, body: IO, *, content_type: str = "application/json", **kwargs: Any + self, options: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.AnalyzeTextResult: """Analyze Text. - A sync API for harmful content analysis for text. Currently, we support four categories: Hate, - SelfHarm, Sexual, Violence. + A synchronous API for the analysis of potentially harmful text content. Currently, it supports + four categories: Hate, SelfHarm, Sexual, and Violence. - :param body: The request of text analysis. Required. - :type body: IO + :param options: The text analysis request. Required. + :type options: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str @@ -366,16 +366,16 @@ def analyze_text( @distributed_trace def analyze_text( - self, body: Union[_models.AnalyzeTextOptions, JSON, IO], **kwargs: Any + self, options: Union[_models.AnalyzeTextOptions, JSON, IO], **kwargs: Any ) -> _models.AnalyzeTextResult: """Analyze Text. - A sync API for harmful content analysis for text. Currently, we support four categories: Hate, - SelfHarm, Sexual, Violence. + A synchronous API for the analysis of potentially harmful text content. Currently, it supports + four categories: Hate, SelfHarm, Sexual, and Violence. - :param body: The request of text analysis. Is one of the following types: AnalyzeTextOptions, + :param options: The text analysis request. Is one of the following types: AnalyzeTextOptions, JSON, IO Required. - :type body: ~azure.ai.contentsafety.models.AnalyzeTextOptions or JSON or IO + :type options: ~azure.ai.contentsafety.models.AnalyzeTextOptions or JSON or IO :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default value is None. :paramtype content_type: str @@ -401,10 +401,10 @@ def analyze_text( content_type = content_type or "application/json" _content = None - if isinstance(body, (IOBase, bytes)): - _content = body + if isinstance(options, (IOBase, bytes)): + _content = options else: - _content = json.dumps(body, cls=AzureJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_content_safety_analyze_text_request( content_type=content_type, @@ -443,15 +443,15 @@ def analyze_text( @overload def analyze_image( - self, body: _models.AnalyzeImageOptions, *, content_type: str = "application/json", **kwargs: Any + self, options: _models.AnalyzeImageOptions, *, content_type: str = "application/json", **kwargs: Any ) -> _models.AnalyzeImageResult: """Analyze Image. - A sync API for harmful content analysis for image. Currently, we support four categories: Hate, - SelfHarm, Sexual, Violence. + A synchronous API for the analysis of potentially harmful image content. Currently, it supports + four categories: Hate, SelfHarm, Sexual, and Violence. - :param body: The analysis request of the image. Required. - :type body: ~azure.ai.contentsafety.models.AnalyzeImageOptions + :param options: The image analysis request. Required. + :type options: ~azure.ai.contentsafety.models.AnalyzeImageOptions :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -464,15 +464,15 @@ def analyze_image( @overload def analyze_image( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, options: JSON, *, content_type: str = "application/json", **kwargs: Any ) -> _models.AnalyzeImageResult: """Analyze Image. - A sync API for harmful content analysis for image. Currently, we support four categories: Hate, - SelfHarm, Sexual, Violence. + A synchronous API for the analysis of potentially harmful image content. Currently, it supports + four categories: Hate, SelfHarm, Sexual, and Violence. - :param body: The analysis request of the image. Required. - :type body: JSON + :param options: The image analysis request. Required. + :type options: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -485,15 +485,15 @@ def analyze_image( @overload def analyze_image( - self, body: IO, *, content_type: str = "application/json", **kwargs: Any + self, options: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.AnalyzeImageResult: """Analyze Image. - A sync API for harmful content analysis for image. Currently, we support four categories: Hate, - SelfHarm, Sexual, Violence. + A synchronous API for the analysis of potentially harmful image content. Currently, it supports + four categories: Hate, SelfHarm, Sexual, and Violence. - :param body: The analysis request of the image. Required. - :type body: IO + :param options: The image analysis request. Required. + :type options: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str @@ -506,16 +506,16 @@ def analyze_image( @distributed_trace def analyze_image( - self, body: Union[_models.AnalyzeImageOptions, JSON, IO], **kwargs: Any + self, options: Union[_models.AnalyzeImageOptions, JSON, IO], **kwargs: Any ) -> _models.AnalyzeImageResult: """Analyze Image. - A sync API for harmful content analysis for image. Currently, we support four categories: Hate, - SelfHarm, Sexual, Violence. + A synchronous API for the analysis of potentially harmful image content. Currently, it supports + four categories: Hate, SelfHarm, Sexual, and Violence. - :param body: The analysis request of the image. Is one of the following types: - AnalyzeImageOptions, JSON, IO Required. - :type body: ~azure.ai.contentsafety.models.AnalyzeImageOptions or JSON or IO + :param options: The image analysis request. Is one of the following types: AnalyzeImageOptions, + JSON, IO Required. + :type options: ~azure.ai.contentsafety.models.AnalyzeImageOptions or JSON or IO :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default value is None. :paramtype content_type: str @@ -541,10 +541,10 @@ def analyze_image( content_type = content_type or "application/json" _content = None - if isinstance(body, (IOBase, bytes)): - _content = body + if isinstance(options, (IOBase, bytes)): + _content = options else: - _content = json.dumps(body, cls=AzureJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_content_safety_analyze_image_request( content_type=content_type, @@ -581,18 +581,108 @@ def analyze_image( return deserialized # type: ignore + +class BlocklistClientOperationsMixin(BlocklistClientMixinABC): + @overload + def add_or_update_blocklist_items( + self, + blocklist_name: str, + options: _models.AddOrUpdateTextBlocklistItemsOptions, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AddOrUpdateTextBlocklistItemsResult: + """Add or update BlocklistItems To Text Blocklist. + + Add or update blocklistItems to a text blocklist. You can add or update at most 100 + blocklistItems in one request. + + :param blocklist_name: Text blocklist name. Required. + :type blocklist_name: str + :param options: Options for adding or updating blocklist items. Required. + :type options: ~azure.ai.contentsafety.models.AddOrUpdateTextBlocklistItemsOptions + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. + :return: AddOrUpdateTextBlocklistItemsResult. The AddOrUpdateTextBlocklistItemsResult is + compatible with MutableMapping + :rtype: ~azure.ai.contentsafety.models.AddOrUpdateTextBlocklistItemsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def add_or_update_blocklist_items( + self, blocklist_name: str, options: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AddOrUpdateTextBlocklistItemsResult: + """Add or update BlocklistItems To Text Blocklist. + + Add or update blocklistItems to a text blocklist. You can add or update at most 100 + blocklistItems in one request. + + :param blocklist_name: Text blocklist name. Required. + :type blocklist_name: str + :param options: Options for adding or updating blocklist items. Required. + :type options: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. + :return: AddOrUpdateTextBlocklistItemsResult. The AddOrUpdateTextBlocklistItemsResult is + compatible with MutableMapping + :rtype: ~azure.ai.contentsafety.models.AddOrUpdateTextBlocklistItemsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def add_or_update_blocklist_items( + self, blocklist_name: str, options: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AddOrUpdateTextBlocklistItemsResult: + """Add or update BlocklistItems To Text Blocklist. + + Add or update blocklistItems to a text blocklist. You can add or update at most 100 + blocklistItems in one request. + + :param blocklist_name: Text blocklist name. Required. + :type blocklist_name: str + :param options: Options for adding or updating blocklist items. Required. + :type options: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. + :return: AddOrUpdateTextBlocklistItemsResult. The AddOrUpdateTextBlocklistItemsResult is + compatible with MutableMapping + :rtype: ~azure.ai.contentsafety.models.AddOrUpdateTextBlocklistItemsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + @distributed_trace - def get_text_blocklist(self, blocklist_name: str, **kwargs: Any) -> _models.TextBlocklist: - """Get Text Blocklist By blocklistName. + def add_or_update_blocklist_items( + self, blocklist_name: str, options: Union[_models.AddOrUpdateTextBlocklistItemsOptions, JSON, IO], **kwargs: Any + ) -> _models.AddOrUpdateTextBlocklistItemsResult: + """Add or update BlocklistItems To Text Blocklist. - Returns text blocklist details. + Add or update blocklistItems to a text blocklist. You can add or update at most 100 + blocklistItems in one request. :param blocklist_name: Text blocklist name. Required. :type blocklist_name: str + :param options: Options for adding or updating blocklist items. Is one of the following types: + AddOrUpdateTextBlocklistItemsOptions, JSON, IO Required. + :type options: ~azure.ai.contentsafety.models.AddOrUpdateTextBlocklistItemsOptions or JSON or + IO + :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default + value is None. + :paramtype content_type: str :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You will have to context manage the returned stream. - :return: TextBlocklist. The TextBlocklist is compatible with MutableMapping - :rtype: ~azure.ai.contentsafety.models.TextBlocklist + :return: AddOrUpdateTextBlocklistItemsResult. The AddOrUpdateTextBlocklistItemsResult is + compatible with MutableMapping + :rtype: ~azure.ai.contentsafety.models.AddOrUpdateTextBlocklistItemsResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { @@ -603,14 +693,24 @@ def get_text_blocklist(self, blocklist_name: str, **kwargs: Any) -> _models.Text } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.TextBlocklist] = kwargs.pop("cls", None) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.AddOrUpdateTextBlocklistItemsResult] = kwargs.pop("cls", None) - _request = build_content_safety_get_text_blocklist_request( + content_type = content_type or "application/json" + _content = None + if isinstance(options, (IOBase, bytes)): + _content = options + else: + _content = json.dumps(options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_blocklist_add_or_update_blocklist_items_request( blocklist_name=blocklist_name, + content_type=content_type, api_version=self._config.api_version, + content=_content, headers=_headers, params=_params, ) @@ -635,7 +735,7 @@ def get_text_blocklist(self, blocklist_name: str, **kwargs: Any) -> _models.Text if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models.TextBlocklist, response.json()) + deserialized = _deserialize(_models.AddOrUpdateTextBlocklistItemsResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -646,19 +746,19 @@ def get_text_blocklist(self, blocklist_name: str, **kwargs: Any) -> _models.Text def create_or_update_text_blocklist( self, blocklist_name: str, - resource: _models.TextBlocklist, + options: _models.TextBlocklist, *, content_type: str = "application/merge-patch+json", **kwargs: Any ) -> _models.TextBlocklist: """Create Or Update Text Blocklist. - Updates a text blocklist, if blocklistName does not exist, create a new blocklist. + Updates a text blocklist. If the blocklistName does not exist, a new blocklist will be created. :param blocklist_name: Text blocklist name. Required. :type blocklist_name: str - :param resource: The resource instance. Required. - :type resource: ~azure.ai.contentsafety.models.TextBlocklist + :param options: The resource instance. Required. + :type options: ~azure.ai.contentsafety.models.TextBlocklist :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -671,16 +771,16 @@ def create_or_update_text_blocklist( @overload def create_or_update_text_blocklist( - self, blocklist_name: str, resource: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, blocklist_name: str, options: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any ) -> _models.TextBlocklist: """Create Or Update Text Blocklist. - Updates a text blocklist, if blocklistName does not exist, create a new blocklist. + Updates a text blocklist. If the blocklistName does not exist, a new blocklist will be created. :param blocklist_name: Text blocklist name. Required. :type blocklist_name: str - :param resource: The resource instance. Required. - :type resource: JSON + :param options: The resource instance. Required. + :type options: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -693,16 +793,16 @@ def create_or_update_text_blocklist( @overload def create_or_update_text_blocklist( - self, blocklist_name: str, resource: IO, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, blocklist_name: str, options: IO, *, content_type: str = "application/merge-patch+json", **kwargs: Any ) -> _models.TextBlocklist: """Create Or Update Text Blocklist. - Updates a text blocklist, if blocklistName does not exist, create a new blocklist. + Updates a text blocklist. If the blocklistName does not exist, a new blocklist will be created. :param blocklist_name: Text blocklist name. Required. :type blocklist_name: str - :param resource: The resource instance. Required. - :type resource: IO + :param options: The resource instance. Required. + :type options: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -715,17 +815,17 @@ def create_or_update_text_blocklist( @distributed_trace def create_or_update_text_blocklist( - self, blocklist_name: str, resource: Union[_models.TextBlocklist, JSON, IO], **kwargs: Any + self, blocklist_name: str, options: Union[_models.TextBlocklist, JSON, IO], **kwargs: Any ) -> _models.TextBlocklist: """Create Or Update Text Blocklist. - Updates a text blocklist, if blocklistName does not exist, create a new blocklist. + Updates a text blocklist. If the blocklistName does not exist, a new blocklist will be created. :param blocklist_name: Text blocklist name. Required. :type blocklist_name: str - :param resource: The resource instance. Is one of the following types: TextBlocklist, JSON, IO + :param options: The resource instance. Is one of the following types: TextBlocklist, JSON, IO Required. - :type resource: ~azure.ai.contentsafety.models.TextBlocklist or JSON or IO + :type options: ~azure.ai.contentsafety.models.TextBlocklist or JSON or IO :keyword content_type: This request has a JSON Merge Patch body. Default value is None. :paramtype content_type: str :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You @@ -750,12 +850,12 @@ def create_or_update_text_blocklist( content_type = content_type or "application/merge-patch+json" _content = None - if isinstance(resource, (IOBase, bytes)): - _content = resource + if isinstance(options, (IOBase, bytes)): + _content = options else: - _content = json.dumps(resource, cls=AzureJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_content_safety_create_or_update_text_blocklist_request( + _request = build_blocklist_create_or_update_text_blocklist_request( blocklist_name=blocklist_name, content_type=content_type, api_version=self._config.api_version, @@ -808,8 +908,6 @@ def delete_text_blocklist( # pylint: disable=inconsistent-return-statements :param blocklist_name: Text blocklist name. Required. :type blocklist_name: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -827,7 +925,7 @@ def delete_text_blocklist( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_content_safety_delete_text_blocklist_request( + _request = build_blocklist_delete_text_blocklist_request( blocklist_name=blocklist_name, api_version=self._config.api_version, headers=_headers, @@ -838,7 +936,7 @@ def delete_text_blocklist( # pylint: disable=inconsistent-return-statements } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = kwargs.pop("stream", False) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -855,20 +953,19 @@ def delete_text_blocklist( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, {}) # type: ignore @distributed_trace - def list_text_blocklists(self, **kwargs: Any) -> Iterable["_models.TextBlocklist"]: - """Get All Text Blocklists. + def get_text_blocklist(self, blocklist_name: str, **kwargs: Any) -> _models.TextBlocklist: + """Get Text Blocklist By blocklistName. - Get all text blocklists details. + Returns text blocklist details. - :return: An iterator like instance of TextBlocklist - :rtype: ~azure.core.paging.ItemPaged[~azure.ai.contentsafety.models.TextBlocklist] + :param blocklist_name: Text blocklist name. Required. + :type blocklist_name: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. + :return: TextBlocklist. The TextBlocklist is compatible with MutableMapping + :rtype: ~azure.ai.contentsafety.models.TextBlocklist :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[List[_models.TextBlocklist]] = kwargs.pop("cls", None) - error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -877,159 +974,62 @@ def list_text_blocklists(self, **kwargs: Any) -> Iterable["_models.TextBlocklist } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: - - _request = build_content_safety_list_text_blocklists_request( - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + cls: ClsType[_models.TextBlocklist] = kwargs.pop("cls", None) - return _request + _request = build_blocklist_get_text_blocklist_request( + blocklist_name=blocklist_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.TextBlocklist], deserialized["value"]) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.get("nextLink") or None, iter(list_of_elem) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) - def get_next(next_link=None): - _request = prepare_request(next_link) + response = pipeline_response.http_response - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response + if response.status_code not in [200]: + if _stream: + response.read() # Load the body in memory and close the socket + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) - if response.status_code not in [200]: - if _stream: - response.read() # Load the body in memory and close the socket - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.TextBlocklist, response.json()) - return pipeline_response + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore - return ItemPaged(get_next, extract_data) + return deserialized # type: ignore - @overload - def add_block_items( - self, - blocklist_name: str, - body: _models.AddBlockItemsOptions, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.AddBlockItemsResult: - """Add BlockItems To Text Blocklist. + @distributed_trace + def get_text_blocklist_item( + self, blocklist_name: str, blocklist_item_id: str, **kwargs: Any + ) -> _models.TextBlocklistItem: + """Get BlocklistItem By blocklistName And blocklistItemId. - Add blockItems to a text blocklist. You can add at most 100 BlockItems in one request. + Get blocklistItem by blocklistName and blocklistItemId from a text blocklist. :param blocklist_name: Text blocklist name. Required. :type blocklist_name: str - :param body: Required. - :type body: ~azure.ai.contentsafety.models.AddBlockItemsOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str + :param blocklist_item_id: The service will generate a BlocklistItemId, which will be a UUID. + Required. + :type blocklist_item_id: str :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You will have to context manage the returned stream. - :return: AddBlockItemsResult. The AddBlockItemsResult is compatible with MutableMapping - :rtype: ~azure.ai.contentsafety.models.AddBlockItemsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def add_block_items( - self, blocklist_name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AddBlockItemsResult: - """Add BlockItems To Text Blocklist. - - Add blockItems to a text blocklist. You can add at most 100 BlockItems in one request. - - :param blocklist_name: Text blocklist name. Required. - :type blocklist_name: str - :param body: Required. - :type body: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: AddBlockItemsResult. The AddBlockItemsResult is compatible with MutableMapping - :rtype: ~azure.ai.contentsafety.models.AddBlockItemsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def add_block_items( - self, blocklist_name: str, body: IO, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AddBlockItemsResult: - """Add BlockItems To Text Blocklist. - - Add blockItems to a text blocklist. You can add at most 100 BlockItems in one request. - - :param blocklist_name: Text blocklist name. Required. - :type blocklist_name: str - :param body: Required. - :type body: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: AddBlockItemsResult. The AddBlockItemsResult is compatible with MutableMapping - :rtype: ~azure.ai.contentsafety.models.AddBlockItemsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def add_block_items( - self, blocklist_name: str, body: Union[_models.AddBlockItemsOptions, JSON, IO], **kwargs: Any - ) -> _models.AddBlockItemsResult: - """Add BlockItems To Text Blocklist. - - Add blockItems to a text blocklist. You can add at most 100 BlockItems in one request. - - :param blocklist_name: Text blocklist name. Required. - :type blocklist_name: str - :param body: Is one of the following types: AddBlockItemsOptions, JSON, IO Required. - :type body: ~azure.ai.contentsafety.models.AddBlockItemsOptions or JSON or IO - :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default - value is None. - :paramtype content_type: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: AddBlockItemsResult. The AddBlockItemsResult is compatible with MutableMapping - :rtype: ~azure.ai.contentsafety.models.AddBlockItemsResult + :return: TextBlocklistItem. The TextBlocklistItem is compatible with MutableMapping + :rtype: ~azure.ai.contentsafety.models.TextBlocklistItem :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { @@ -1040,24 +1040,15 @@ def add_block_items( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.AddBlockItemsResult] = kwargs.pop("cls", None) + cls: ClsType[_models.TextBlocklistItem] = kwargs.pop("cls", None) - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=AzureJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_content_safety_add_block_items_request( + _request = build_blocklist_get_text_blocklist_item_request( blocklist_name=blocklist_name, - content_type=content_type, + blocklist_item_id=blocklist_item_id, api_version=self._config.api_version, - content=_content, headers=_headers, params=_params, ) @@ -1082,171 +1073,37 @@ def add_block_items( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models.AddBlockItemsResult, response.json()) + deserialized = _deserialize(_models.TextBlocklistItem, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - @overload - def remove_block_items( # pylint: disable=inconsistent-return-statements - self, - blocklist_name: str, - body: _models.RemoveBlockItemsOptions, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Remove BlockItems From Text Blocklist. - - Remove blockItems from a text blocklist. You can remove at most 100 BlockItems in one request. - - :param blocklist_name: Text blocklist name. Required. - :type blocklist_name: str - :param body: Required. - :type body: ~azure.ai.contentsafety.models.RemoveBlockItemsOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def remove_block_items( # pylint: disable=inconsistent-return-statements - self, blocklist_name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> None: - """Remove BlockItems From Text Blocklist. - - Remove blockItems from a text blocklist. You can remove at most 100 BlockItems in one request. - - :param blocklist_name: Text blocklist name. Required. - :type blocklist_name: str - :param body: Required. - :type body: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def remove_block_items( # pylint: disable=inconsistent-return-statements - self, blocklist_name: str, body: IO, *, content_type: str = "application/json", **kwargs: Any - ) -> None: - """Remove BlockItems From Text Blocklist. - - Remove blockItems from a text blocklist. You can remove at most 100 BlockItems in one request. - - :param blocklist_name: Text blocklist name. Required. - :type blocklist_name: str - :param body: Required. - :type body: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - @distributed_trace - def remove_block_items( # pylint: disable=inconsistent-return-statements - self, blocklist_name: str, body: Union[_models.RemoveBlockItemsOptions, JSON, IO], **kwargs: Any - ) -> None: - """Remove BlockItems From Text Blocklist. + def list_text_blocklist_items( + self, blocklist_name: str, *, top: Optional[int] = None, skip: Optional[int] = None, **kwargs: Any + ) -> Iterable["_models.TextBlocklistItem"]: + """Get All BlocklistItems By blocklistName. - Remove blockItems from a text blocklist. You can remove at most 100 BlockItems in one request. + Get all blocklistItems in a text blocklist. :param blocklist_name: Text blocklist name. Required. :type blocklist_name: str - :param body: Is one of the following types: RemoveBlockItemsOptions, JSON, IO Required. - :type body: ~azure.ai.contentsafety.models.RemoveBlockItemsOptions or JSON or IO - :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default - value is None. - :paramtype content_type: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: None - :rtype: None + :keyword top: The number of result items to return. Default value is None. + :paramtype top: int + :keyword skip: The number of result items to skip. Default value is None. + :paramtype skip: int + :return: An iterator like instance of TextBlocklistItem + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.contentsafety.models.TextBlocklistItem] :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[None] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=AzureJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_content_safety_remove_block_items_request( - blocklist_name=blocklist_name, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - if _stream: - response.read() # Load the body in memory and close the socket - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace - def get_text_blocklist_item(self, blocklist_name: str, block_item_id: str, **kwargs: Any) -> _models.TextBlockItem: - """Get BlockItem By blocklistName And blockItemId. - - Get blockItem By blockItemId from a text blocklist. + maxpagesize = kwargs.pop("maxpagesize", None) + cls: ClsType[List[_models.TextBlocklistItem]] = kwargs.pop("cls", None) - :param blocklist_name: Text blocklist name. Required. - :type blocklist_name: str - :param block_item_id: Block Item Id. It will be uuid. Required. - :type block_item_id: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: TextBlockItem. The TextBlockItem is compatible with MutableMapping - :rtype: ~azure.ai.contentsafety.models.TextBlockItem - :raises ~azure.core.exceptions.HttpResponseError: - """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -1255,69 +1112,87 @@ def get_text_blocklist_item(self, blocklist_name: str, block_item_id: str, **kwa } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} + def prepare_request(next_link=None): + if not next_link: - cls: ClsType[_models.TextBlockItem] = kwargs.pop("cls", None) + _request = build_blocklist_list_text_blocklist_items_request( + blocklist_name=blocklist_name, + top=top, + skip=skip, + maxpagesize=maxpagesize, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request = build_content_safety_get_text_blocklist_item_request( - blocklist_name=blocklist_name, - block_item_id=block_item_id, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) + return _request - response = pipeline_response.http_response + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(List[_models.TextBlocklistItem], deserialized["value"]) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) - if response.status_code not in [200]: - if _stream: - response.read() # Load the body in memory and close the socket - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + def get_next(next_link=None): + _request = prepare_request(next_link) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.TextBlockItem, response.json()) + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + if response.status_code not in [200]: + if _stream: + response.read() # Load the body in memory and close the socket + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) - return deserialized # type: ignore + return pipeline_response + + return ItemPaged(get_next, extract_data) @distributed_trace - def list_text_blocklist_items( - self, blocklist_name: str, *, top: Optional[int] = None, skip: Optional[int] = None, **kwargs: Any - ) -> Iterable["_models.TextBlockItem"]: - """Get All BlockItems By blocklistName. + def list_text_blocklists(self, **kwargs: Any) -> Iterable["_models.TextBlocklist"]: + """Get All Text Blocklists. - Get all blockItems in a text blocklist. + Get all text blocklists details. - :param blocklist_name: Text blocklist name. Required. - :type blocklist_name: str - :keyword top: The number of result items to return. Default value is None. - :paramtype top: int - :keyword skip: The number of result items to skip. Default value is None. - :paramtype skip: int - :return: An iterator like instance of TextBlockItem - :rtype: ~azure.core.paging.ItemPaged[~azure.ai.contentsafety.models.TextBlockItem] + :return: An iterator like instance of TextBlocklist + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.contentsafety.models.TextBlocklist] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - maxpagesize = kwargs.pop("maxpagesize", None) - cls: ClsType[List[_models.TextBlockItem]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.TextBlocklist]] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, @@ -1330,11 +1205,7 @@ def list_text_blocklist_items( def prepare_request(next_link=None): if not next_link: - _request = build_content_safety_list_text_blocklist_items_request( - blocklist_name=blocklist_name, - top=top, - skip=skip, - maxpagesize=maxpagesize, + _request = build_blocklist_list_text_blocklists_request( api_version=self._config.api_version, headers=_headers, params=_params, @@ -1370,7 +1241,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.TextBlockItem], deserialized["value"]) + list_of_elem = _deserialize(List[_models.TextBlocklist], deserialized["value"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -1393,3 +1264,142 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) + + @overload + def remove_blocklist_items( # pylint: disable=inconsistent-return-statements + self, + blocklist_name: str, + options: _models.RemoveTextBlocklistItemsOptions, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Remove BlocklistItems From Text Blocklist. + + Remove blocklistItems from a text blocklist. You can remove at most 100 BlocklistItems in one + request. + + :param blocklist_name: Text blocklist name. Required. + :type blocklist_name: str + :param options: Options for removing blocklist items. Required. + :type options: ~azure.ai.contentsafety.models.RemoveTextBlocklistItemsOptions + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def remove_blocklist_items( # pylint: disable=inconsistent-return-statements + self, blocklist_name: str, options: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Remove BlocklistItems From Text Blocklist. + + Remove blocklistItems from a text blocklist. You can remove at most 100 BlocklistItems in one + request. + + :param blocklist_name: Text blocklist name. Required. + :type blocklist_name: str + :param options: Options for removing blocklist items. Required. + :type options: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def remove_blocklist_items( # pylint: disable=inconsistent-return-statements + self, blocklist_name: str, options: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Remove BlocklistItems From Text Blocklist. + + Remove blocklistItems from a text blocklist. You can remove at most 100 BlocklistItems in one + request. + + :param blocklist_name: Text blocklist name. Required. + :type blocklist_name: str + :param options: Options for removing blocklist items. Required. + :type options: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def remove_blocklist_items( # pylint: disable=inconsistent-return-statements + self, blocklist_name: str, options: Union[_models.RemoveTextBlocklistItemsOptions, JSON, IO], **kwargs: Any + ) -> None: + """Remove BlocklistItems From Text Blocklist. + + Remove blocklistItems from a text blocklist. You can remove at most 100 BlocklistItems in one + request. + + :param blocklist_name: Text blocklist name. Required. + :type blocklist_name: str + :param options: Options for removing blocklist items. Is one of the following types: + RemoveTextBlocklistItemsOptions, JSON, IO Required. + :type options: ~azure.ai.contentsafety.models.RemoveTextBlocklistItemsOptions or JSON or IO + :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default + value is None. + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(options, (IOBase, bytes)): + _content = options + else: + _content = json.dumps(options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_blocklist_remove_blocklist_items_request( + blocklist_name=blocklist_name, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + if _stream: + response.read() # Load the body in memory and close the socket + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_serialization.py b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_serialization.py index 7bed5532429d..baa661cb82d2 100644 --- a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_serialization.py +++ b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_serialization.py @@ -63,8 +63,8 @@ import isodate # type: ignore -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback -from azure.core.serialization import NULL as AzureCoreNull +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull _BOM = codecs.BOM_UTF8.decode(encoding="utf-8") @@ -124,7 +124,7 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: pass return ET.fromstring(data_as_str) # nosec - except ET.ParseError: + except ET.ParseError as err: # It might be because the server has an issue, and returned JSON with # content-type XML.... # So let's try a JSON load, and if it's still broken @@ -143,7 +143,7 @@ def _json_attemp(data): # The function hack is because Py2.7 messes up with exception # context otherwise. _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") + raise DeserializationError("XML is invalid") from err raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) @classmethod @@ -340,7 +340,7 @@ def _create_xml_node(cls): return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: - """Return the JSON that would be sent to azure from this model. + """Return the JSON that would be sent to server from this model. This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. @@ -668,7 +668,7 @@ def _serialize(self, target_obj, data_type=None, **kwargs): except (AttributeError, KeyError, TypeError) as err: msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) + raise SerializationError(msg) from err else: return serialized @@ -710,7 +710,7 @@ def body(self, data, data_type, **kwargs): ] data = deserializer._deserialize(data_type, data) except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) + raise SerializationError("Unable to build a model: " + str(err)) from err return self._serialize(data, data_type, **kwargs) @@ -730,7 +730,6 @@ def url(self, name, data, data_type, **kwargs): if kwargs.get("skip_quote") is True: output = str(output) - # https://github.com/Azure/autorest.python/issues/2063 output = output.replace("{", quote("{")).replace("}", quote("}")) else: output = quote(str(output), safe="") @@ -746,7 +745,7 @@ def query(self, name, data, data_type, **kwargs): :param str data_type: The type to be serialized from. :keyword bool skip_quote: Whether to skip quote the serialized result. Defaults to False. - :rtype: str + :rtype: str, list :raises: TypeError if serialization fails. :raises: ValueError if data is None """ @@ -806,7 +805,7 @@ def serialize_data(self, data, data_type, **kwargs): raise ValueError("No value for given attribute") try: - if data is AzureCoreNull: + if data is CoreNull: return None if data_type in self.basic_types.values(): return self.serialize_basic(data, data_type, **kwargs) @@ -826,7 +825,7 @@ def serialize_data(self, data, data_type, **kwargs): except (ValueError, TypeError) as err: msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) + raise SerializationError(msg.format(data, data_type)) from err else: return self._serialize(data, **kwargs) @@ -1172,10 +1171,10 @@ def serialize_iso(attr, **kwargs): return date + microseconds + "Z" except (ValueError, OverflowError) as err: msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) + raise SerializationError(msg) from err except AttributeError as err: msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) + raise TypeError(msg) from err @staticmethod def serialize_unix(attr, **kwargs): @@ -1211,7 +1210,6 @@ def rest_key_extractor(attr, attr_desc, data): if working_data is None: # If at any point while following flatten JSON path see None, it means # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 return None key = ".".join(dict_keys[1:]) @@ -1232,7 +1230,6 @@ def rest_key_case_insensitive_extractor(attr, attr_desc, data): if working_data is None: # If at any point while following flatten JSON path see None, it means # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 return None key = ".".join(dict_keys[1:]) @@ -1483,7 +1480,7 @@ def _deserialize(self, target_obj, data): d_attrs[attr] = value except (AttributeError, TypeError, KeyError) as err: msg = "Unable to deserialize to object: " + class_name # type: ignore - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err else: additional_properties = self._build_additional_properties(attributes, data) return self._instantiate_model(response, d_attrs, additional_properties) @@ -1654,7 +1651,7 @@ def deserialize_data(self, data, data_type): except (ValueError, TypeError, AttributeError) as err: msg = "Unable to deserialize response data." msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err else: return self._deserialize(obj_type, data) @@ -1810,7 +1807,6 @@ def deserialize_enum(data, enum_obj): data = data.value if isinstance(data, int): # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 try: return list(enum_obj.__members__.values())[data] except IndexError: @@ -1864,10 +1860,10 @@ def deserialize_decimal(attr): if isinstance(attr, ET.Element): attr = attr.text try: - return decimal.Decimal(attr) # type: ignore + return decimal.Decimal(str(attr)) # type: ignore except decimal.DecimalException as err: msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err @staticmethod def deserialize_long(attr): @@ -1895,7 +1891,7 @@ def deserialize_duration(attr): duration = isodate.parse_duration(attr) except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err else: return duration @@ -1947,7 +1943,7 @@ def deserialize_rfc(attr): date_obj = date_obj.astimezone(tz=TZ_UTC) except ValueError as err: msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err else: return date_obj @@ -1984,7 +1980,7 @@ def deserialize_iso(attr): raise OverflowError("Hit max or min date") except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err else: return date_obj @@ -2000,9 +1996,10 @@ def deserialize_unix(attr): if isinstance(attr, ET.Element): attr = int(attr.text) # type: ignore try: + attr = int(attr) date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) except ValueError as err: msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err else: return date_obj diff --git a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_vendor.py b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_vendor.py index 80b9ac2054b8..3a907524ca0c 100644 --- a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_vendor.py +++ b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_vendor.py @@ -8,7 +8,7 @@ from abc import ABC from typing import TYPE_CHECKING -from ._configuration import ContentSafetyClientConfiguration +from ._configuration import BlocklistClientConfiguration, ContentSafetyClientConfiguration if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports @@ -24,3 +24,12 @@ class ContentSafetyClientMixinABC(ABC): _config: ContentSafetyClientConfiguration _serialize: "Serializer" _deserialize: "Deserializer" + + +class BlocklistClientMixinABC(ABC): + """DO NOT use this class. It is for internal typing use only.""" + + _client: "PipelineClient" + _config: BlocklistClientConfiguration + _serialize: "Serializer" + _deserialize: "Deserializer" diff --git a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_version.py b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_version.py index bbcd28b4aa67..0ec13ea52bbf 100644 --- a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_version.py +++ b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "1.0.0b2" +VERSION = "1.0.0" diff --git a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/aio/__init__.py b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/aio/__init__.py index a8a7dd09fe23..93236600dc7b 100644 --- a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/aio/__init__.py +++ b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/aio/__init__.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from ._client import ContentSafetyClient +from ._client import BlocklistClient try: from ._patch import __all__ as _patch_all @@ -17,6 +18,7 @@ __all__ = [ "ContentSafetyClient", + "BlocklistClient", ] __all__.extend([p for p in _patch_all if p not in __all__]) diff --git a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/aio/_client.py b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/aio/_client.py index 20a25b33b77e..5b3f2b75f678 100644 --- a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/aio/_client.py +++ b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/aio/_client.py @@ -7,7 +7,7 @@ # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, Awaitable +from typing import Any, Awaitable, TYPE_CHECKING, Union from azure.core import AsyncPipelineClient from azure.core.credentials import AzureKeyCredential @@ -15,25 +15,32 @@ from azure.core.rest import AsyncHttpResponse, HttpRequest from .._serialization import Deserializer, Serializer -from ._configuration import ContentSafetyClientConfiguration -from ._operations import ContentSafetyClientOperationsMixin +from ._configuration import BlocklistClientConfiguration, ContentSafetyClientConfiguration +from ._operations import BlocklistClientOperationsMixin, ContentSafetyClientOperationsMixin + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential class ContentSafetyClient(ContentSafetyClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword - """Analyze harmful content. + """ContentSafetyClient. :param endpoint: Supported Cognitive Services endpoints (protocol and hostname, for example: https://:code:``.cognitiveservices.azure.com). Required. :type endpoint: str - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.AzureKeyCredential - :keyword api_version: The API version to use for this operation. Default value is - "2023-04-30-preview". Note that overriding this default value may result in unsupported - behavior. + :param credential: Credential needed for the client to connect to Azure. Is either a + AzureKeyCredential type or a TokenCredential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials_async.AsyncTokenCredential + :keyword api_version: The API version to use for this operation. Default value is "2023-10-01". + Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__(self, endpoint: str, credential: AzureKeyCredential, **kwargs: Any) -> None: + def __init__( + self, endpoint: str, credential: Union[AzureKeyCredential, "AsyncTokenCredential"], **kwargs: Any + ) -> None: _endpoint = "{endpoint}/contentsafety" self._config = ContentSafetyClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) _policies = kwargs.pop("policies", None) @@ -59,7 +66,9 @@ def __init__(self, endpoint: str, credential: AzureKeyCredential, **kwargs: Any) self._deserialize = Deserializer() self._serialize.client_side_validation = False - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: + def send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -83,7 +92,7 @@ def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHt } request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, **kwargs) # type: ignore + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore async def close(self) -> None: await self._client.close() @@ -94,3 +103,85 @@ async def __aenter__(self) -> "ContentSafetyClient": async def __aexit__(self, *exc_details: Any) -> None: await self._client.__aexit__(*exc_details) + + +class BlocklistClient(BlocklistClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword + """BlocklistClient. + + :param endpoint: Supported Cognitive Services endpoints (protocol and hostname, for example: + https://:code:``.cognitiveservices.azure.com). Required. + :type endpoint: str + :param credential: Credential needed for the client to connect to Azure. Is either a + AzureKeyCredential type or a TokenCredential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials_async.AsyncTokenCredential + :keyword api_version: The API version to use for this operation. Default value is "2023-10-01". + Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, endpoint: str, credential: Union[AzureKeyCredential, "AsyncTokenCredential"], **kwargs: Any + ) -> None: + _endpoint = "{endpoint}/contentsafety" + self._config = BlocklistClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + + def send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "BlocklistClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/aio/_configuration.py b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/aio/_configuration.py index 868397d6bf09..c19698582c6d 100644 --- a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/aio/_configuration.py +++ b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/aio/_configuration.py @@ -6,13 +6,17 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any +from typing import Any, TYPE_CHECKING, Union from azure.core.credentials import AzureKeyCredential from azure.core.pipeline import policies from .._version import VERSION +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + class ContentSafetyClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long """Configuration for ContentSafetyClient. @@ -23,16 +27,19 @@ class ContentSafetyClientConfiguration: # pylint: disable=too-many-instance-att :param endpoint: Supported Cognitive Services endpoints (protocol and hostname, for example: https://:code:``.cognitiveservices.azure.com). Required. :type endpoint: str - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.AzureKeyCredential - :keyword api_version: The API version to use for this operation. Default value is - "2023-04-30-preview". Note that overriding this default value may result in unsupported - behavior. + :param credential: Credential needed for the client to connect to Azure. Is either a + AzureKeyCredential type or a TokenCredential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials_async.AsyncTokenCredential + :keyword api_version: The API version to use for this operation. Default value is "2023-10-01". + Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__(self, endpoint: str, credential: AzureKeyCredential, **kwargs: Any) -> None: - api_version: str = kwargs.pop("api_version", "2023-04-30-preview") + def __init__( + self, endpoint: str, credential: Union[AzureKeyCredential, "AsyncTokenCredential"], **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2023-10-01") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") @@ -42,21 +49,84 @@ def __init__(self, endpoint: str, credential: AzureKeyCredential, **kwargs: Any) self.endpoint = endpoint self.credential = credential self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://cognitiveservices.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "ai-contentsafety/{}".format(VERSION)) self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) + def _infer_policy(self, **kwargs): + if isinstance(self.credential, AzureKeyCredential): + return policies.AzureKeyCredentialPolicy(self.credential, "Ocp-Apim-Subscription-Key", **kwargs) + if hasattr(self.credential, "get_token"): + return policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + raise TypeError(f"Unsupported credential: {self.credential}") + def _configure(self, **kwargs: Any) -> None: self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = self._infer_policy(**kwargs) + + +class BlocklistClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long + """Configuration for BlocklistClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: Supported Cognitive Services endpoints (protocol and hostname, for example: + https://:code:``.cognitiveservices.azure.com). Required. + :type endpoint: str + :param credential: Credential needed for the client to connect to Azure. Is either a + AzureKeyCredential type or a TokenCredential type. Required. + :type credential: ~azure.core.credentials.AzureKeyCredential or + ~azure.core.credentials_async.AsyncTokenCredential + :keyword api_version: The API version to use for this operation. Default value is "2023-10-01". + Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, endpoint: str, credential: Union[AzureKeyCredential, "AsyncTokenCredential"], **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2023-10-01") + + if endpoint is None: + raise ValueError("Parameter 'endpoint' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + + self.endpoint = endpoint + self.credential = credential + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://cognitiveservices.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "ai-contentsafety/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _infer_policy(self, **kwargs): + if isinstance(self.credential, AzureKeyCredential): + return policies.AzureKeyCredentialPolicy(self.credential, "Ocp-Apim-Subscription-Key", **kwargs) + if hasattr(self.credential, "get_token"): + return policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + raise TypeError(f"Unsupported credential: {self.credential}") + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.AzureKeyCredentialPolicy( - self.credential, "Ocp-Apim-Subscription-Key", **kwargs - ) + self.authentication_policy = self._infer_policy(**kwargs) diff --git a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/aio/_operations/__init__.py b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/aio/_operations/__init__.py index c6de97557237..2f88364a4715 100644 --- a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/aio/_operations/__init__.py +++ b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/aio/_operations/__init__.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from ._operations import ContentSafetyClientOperationsMixin +from ._operations import BlocklistClientOperationsMixin from ._patch import __all__ as _patch_all from ._patch import * # pylint: disable=unused-wildcard-import @@ -14,6 +15,7 @@ __all__ = [ "ContentSafetyClientOperationsMixin", + "BlocklistClientOperationsMixin", ] __all__.extend([p for p in _patch_all if p not in __all__]) _patch_sdk() diff --git a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/aio/_operations/_operations.py b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/aio/_operations/_operations.py index 8255e3fa378e..16739cf4c97f 100644 --- a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/aio/_operations/_operations.py +++ b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/aio/_operations/_operations.py @@ -28,20 +28,20 @@ from azure.core.utils import case_insensitive_dict from ... import models as _models -from ..._model_base import AzureJSONEncoder, _deserialize +from ..._model_base import SdkJSONEncoder, _deserialize from ..._operations._operations import ( - build_content_safety_add_block_items_request, + build_blocklist_add_or_update_blocklist_items_request, + build_blocklist_create_or_update_text_blocklist_request, + build_blocklist_delete_text_blocklist_request, + build_blocklist_get_text_blocklist_item_request, + build_blocklist_get_text_blocklist_request, + build_blocklist_list_text_blocklist_items_request, + build_blocklist_list_text_blocklists_request, + build_blocklist_remove_blocklist_items_request, build_content_safety_analyze_image_request, build_content_safety_analyze_text_request, - build_content_safety_create_or_update_text_blocklist_request, - build_content_safety_delete_text_blocklist_request, - build_content_safety_get_text_blocklist_item_request, - build_content_safety_get_text_blocklist_request, - build_content_safety_list_text_blocklist_items_request, - build_content_safety_list_text_blocklists_request, - build_content_safety_remove_block_items_request, ) -from .._vendor import ContentSafetyClientMixinABC +from .._vendor import BlocklistClientMixinABC, ContentSafetyClientMixinABC if sys.version_info >= (3, 9): from collections.abc import MutableMapping @@ -55,15 +55,15 @@ class ContentSafetyClientOperationsMixin(ContentSafetyClientMixinABC): @overload async def analyze_text( - self, body: _models.AnalyzeTextOptions, *, content_type: str = "application/json", **kwargs: Any + self, options: _models.AnalyzeTextOptions, *, content_type: str = "application/json", **kwargs: Any ) -> _models.AnalyzeTextResult: """Analyze Text. - A sync API for harmful content analysis for text. Currently, we support four categories: Hate, - SelfHarm, Sexual, Violence. + A synchronous API for the analysis of potentially harmful text content. Currently, it supports + four categories: Hate, SelfHarm, Sexual, and Violence. - :param body: The request of text analysis. Required. - :type body: ~azure.ai.contentsafety.models.AnalyzeTextOptions + :param options: The text analysis request. Required. + :type options: ~azure.ai.contentsafety.models.AnalyzeTextOptions :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -76,15 +76,15 @@ async def analyze_text( @overload async def analyze_text( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, options: JSON, *, content_type: str = "application/json", **kwargs: Any ) -> _models.AnalyzeTextResult: """Analyze Text. - A sync API for harmful content analysis for text. Currently, we support four categories: Hate, - SelfHarm, Sexual, Violence. + A synchronous API for the analysis of potentially harmful text content. Currently, it supports + four categories: Hate, SelfHarm, Sexual, and Violence. - :param body: The request of text analysis. Required. - :type body: JSON + :param options: The text analysis request. Required. + :type options: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -97,15 +97,15 @@ async def analyze_text( @overload async def analyze_text( - self, body: IO, *, content_type: str = "application/json", **kwargs: Any + self, options: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.AnalyzeTextResult: """Analyze Text. - A sync API for harmful content analysis for text. Currently, we support four categories: Hate, - SelfHarm, Sexual, Violence. + A synchronous API for the analysis of potentially harmful text content. Currently, it supports + four categories: Hate, SelfHarm, Sexual, and Violence. - :param body: The request of text analysis. Required. - :type body: IO + :param options: The text analysis request. Required. + :type options: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str @@ -118,16 +118,16 @@ async def analyze_text( @distributed_trace_async async def analyze_text( - self, body: Union[_models.AnalyzeTextOptions, JSON, IO], **kwargs: Any + self, options: Union[_models.AnalyzeTextOptions, JSON, IO], **kwargs: Any ) -> _models.AnalyzeTextResult: """Analyze Text. - A sync API for harmful content analysis for text. Currently, we support four categories: Hate, - SelfHarm, Sexual, Violence. + A synchronous API for the analysis of potentially harmful text content. Currently, it supports + four categories: Hate, SelfHarm, Sexual, and Violence. - :param body: The request of text analysis. Is one of the following types: AnalyzeTextOptions, + :param options: The text analysis request. Is one of the following types: AnalyzeTextOptions, JSON, IO Required. - :type body: ~azure.ai.contentsafety.models.AnalyzeTextOptions or JSON or IO + :type options: ~azure.ai.contentsafety.models.AnalyzeTextOptions or JSON or IO :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default value is None. :paramtype content_type: str @@ -153,10 +153,10 @@ async def analyze_text( content_type = content_type or "application/json" _content = None - if isinstance(body, (IOBase, bytes)): - _content = body + if isinstance(options, (IOBase, bytes)): + _content = options else: - _content = json.dumps(body, cls=AzureJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_content_safety_analyze_text_request( content_type=content_type, @@ -195,15 +195,15 @@ async def analyze_text( @overload async def analyze_image( - self, body: _models.AnalyzeImageOptions, *, content_type: str = "application/json", **kwargs: Any + self, options: _models.AnalyzeImageOptions, *, content_type: str = "application/json", **kwargs: Any ) -> _models.AnalyzeImageResult: """Analyze Image. - A sync API for harmful content analysis for image. Currently, we support four categories: Hate, - SelfHarm, Sexual, Violence. + A synchronous API for the analysis of potentially harmful image content. Currently, it supports + four categories: Hate, SelfHarm, Sexual, and Violence. - :param body: The analysis request of the image. Required. - :type body: ~azure.ai.contentsafety.models.AnalyzeImageOptions + :param options: The image analysis request. Required. + :type options: ~azure.ai.contentsafety.models.AnalyzeImageOptions :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -216,15 +216,15 @@ async def analyze_image( @overload async def analyze_image( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, options: JSON, *, content_type: str = "application/json", **kwargs: Any ) -> _models.AnalyzeImageResult: """Analyze Image. - A sync API for harmful content analysis for image. Currently, we support four categories: Hate, - SelfHarm, Sexual, Violence. + A synchronous API for the analysis of potentially harmful image content. Currently, it supports + four categories: Hate, SelfHarm, Sexual, and Violence. - :param body: The analysis request of the image. Required. - :type body: JSON + :param options: The image analysis request. Required. + :type options: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -237,15 +237,15 @@ async def analyze_image( @overload async def analyze_image( - self, body: IO, *, content_type: str = "application/json", **kwargs: Any + self, options: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.AnalyzeImageResult: """Analyze Image. - A sync API for harmful content analysis for image. Currently, we support four categories: Hate, - SelfHarm, Sexual, Violence. + A synchronous API for the analysis of potentially harmful image content. Currently, it supports + four categories: Hate, SelfHarm, Sexual, and Violence. - :param body: The analysis request of the image. Required. - :type body: IO + :param options: The image analysis request. Required. + :type options: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str @@ -258,16 +258,16 @@ async def analyze_image( @distributed_trace_async async def analyze_image( - self, body: Union[_models.AnalyzeImageOptions, JSON, IO], **kwargs: Any + self, options: Union[_models.AnalyzeImageOptions, JSON, IO], **kwargs: Any ) -> _models.AnalyzeImageResult: """Analyze Image. - A sync API for harmful content analysis for image. Currently, we support four categories: Hate, - SelfHarm, Sexual, Violence. + A synchronous API for the analysis of potentially harmful image content. Currently, it supports + four categories: Hate, SelfHarm, Sexual, and Violence. - :param body: The analysis request of the image. Is one of the following types: - AnalyzeImageOptions, JSON, IO Required. - :type body: ~azure.ai.contentsafety.models.AnalyzeImageOptions or JSON or IO + :param options: The image analysis request. Is one of the following types: AnalyzeImageOptions, + JSON, IO Required. + :type options: ~azure.ai.contentsafety.models.AnalyzeImageOptions or JSON or IO :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default value is None. :paramtype content_type: str @@ -293,10 +293,10 @@ async def analyze_image( content_type = content_type or "application/json" _content = None - if isinstance(body, (IOBase, bytes)): - _content = body + if isinstance(options, (IOBase, bytes)): + _content = options else: - _content = json.dumps(body, cls=AzureJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_content_safety_analyze_image_request( content_type=content_type, @@ -333,18 +333,108 @@ async def analyze_image( return deserialized # type: ignore + +class BlocklistClientOperationsMixin(BlocklistClientMixinABC): + @overload + async def add_or_update_blocklist_items( + self, + blocklist_name: str, + options: _models.AddOrUpdateTextBlocklistItemsOptions, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AddOrUpdateTextBlocklistItemsResult: + """Add or update BlocklistItems To Text Blocklist. + + Add or update blocklistItems to a text blocklist. You can add or update at most 100 + blocklistItems in one request. + + :param blocklist_name: Text blocklist name. Required. + :type blocklist_name: str + :param options: Options for adding or updating blocklist items. Required. + :type options: ~azure.ai.contentsafety.models.AddOrUpdateTextBlocklistItemsOptions + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. + :return: AddOrUpdateTextBlocklistItemsResult. The AddOrUpdateTextBlocklistItemsResult is + compatible with MutableMapping + :rtype: ~azure.ai.contentsafety.models.AddOrUpdateTextBlocklistItemsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def add_or_update_blocklist_items( + self, blocklist_name: str, options: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AddOrUpdateTextBlocklistItemsResult: + """Add or update BlocklistItems To Text Blocklist. + + Add or update blocklistItems to a text blocklist. You can add or update at most 100 + blocklistItems in one request. + + :param blocklist_name: Text blocklist name. Required. + :type blocklist_name: str + :param options: Options for adding or updating blocklist items. Required. + :type options: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. + :return: AddOrUpdateTextBlocklistItemsResult. The AddOrUpdateTextBlocklistItemsResult is + compatible with MutableMapping + :rtype: ~azure.ai.contentsafety.models.AddOrUpdateTextBlocklistItemsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def add_or_update_blocklist_items( + self, blocklist_name: str, options: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AddOrUpdateTextBlocklistItemsResult: + """Add or update BlocklistItems To Text Blocklist. + + Add or update blocklistItems to a text blocklist. You can add or update at most 100 + blocklistItems in one request. + + :param blocklist_name: Text blocklist name. Required. + :type blocklist_name: str + :param options: Options for adding or updating blocklist items. Required. + :type options: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. + :return: AddOrUpdateTextBlocklistItemsResult. The AddOrUpdateTextBlocklistItemsResult is + compatible with MutableMapping + :rtype: ~azure.ai.contentsafety.models.AddOrUpdateTextBlocklistItemsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + @distributed_trace_async - async def get_text_blocklist(self, blocklist_name: str, **kwargs: Any) -> _models.TextBlocklist: - """Get Text Blocklist By blocklistName. + async def add_or_update_blocklist_items( + self, blocklist_name: str, options: Union[_models.AddOrUpdateTextBlocklistItemsOptions, JSON, IO], **kwargs: Any + ) -> _models.AddOrUpdateTextBlocklistItemsResult: + """Add or update BlocklistItems To Text Blocklist. - Returns text blocklist details. + Add or update blocklistItems to a text blocklist. You can add or update at most 100 + blocklistItems in one request. :param blocklist_name: Text blocklist name. Required. :type blocklist_name: str + :param options: Options for adding or updating blocklist items. Is one of the following types: + AddOrUpdateTextBlocklistItemsOptions, JSON, IO Required. + :type options: ~azure.ai.contentsafety.models.AddOrUpdateTextBlocklistItemsOptions or JSON or + IO + :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default + value is None. + :paramtype content_type: str :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You will have to context manage the returned stream. - :return: TextBlocklist. The TextBlocklist is compatible with MutableMapping - :rtype: ~azure.ai.contentsafety.models.TextBlocklist + :return: AddOrUpdateTextBlocklistItemsResult. The AddOrUpdateTextBlocklistItemsResult is + compatible with MutableMapping + :rtype: ~azure.ai.contentsafety.models.AddOrUpdateTextBlocklistItemsResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { @@ -355,14 +445,24 @@ async def get_text_blocklist(self, blocklist_name: str, **kwargs: Any) -> _model } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.TextBlocklist] = kwargs.pop("cls", None) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.AddOrUpdateTextBlocklistItemsResult] = kwargs.pop("cls", None) - _request = build_content_safety_get_text_blocklist_request( + content_type = content_type or "application/json" + _content = None + if isinstance(options, (IOBase, bytes)): + _content = options + else: + _content = json.dumps(options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_blocklist_add_or_update_blocklist_items_request( blocklist_name=blocklist_name, + content_type=content_type, api_version=self._config.api_version, + content=_content, headers=_headers, params=_params, ) @@ -387,7 +487,7 @@ async def get_text_blocklist(self, blocklist_name: str, **kwargs: Any) -> _model if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models.TextBlocklist, response.json()) + deserialized = _deserialize(_models.AddOrUpdateTextBlocklistItemsResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -398,19 +498,19 @@ async def get_text_blocklist(self, blocklist_name: str, **kwargs: Any) -> _model async def create_or_update_text_blocklist( self, blocklist_name: str, - resource: _models.TextBlocklist, + options: _models.TextBlocklist, *, content_type: str = "application/merge-patch+json", **kwargs: Any ) -> _models.TextBlocklist: """Create Or Update Text Blocklist. - Updates a text blocklist, if blocklistName does not exist, create a new blocklist. + Updates a text blocklist. If the blocklistName does not exist, a new blocklist will be created. :param blocklist_name: Text blocklist name. Required. :type blocklist_name: str - :param resource: The resource instance. Required. - :type resource: ~azure.ai.contentsafety.models.TextBlocklist + :param options: The resource instance. Required. + :type options: ~azure.ai.contentsafety.models.TextBlocklist :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -423,16 +523,16 @@ async def create_or_update_text_blocklist( @overload async def create_or_update_text_blocklist( - self, blocklist_name: str, resource: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, blocklist_name: str, options: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any ) -> _models.TextBlocklist: """Create Or Update Text Blocklist. - Updates a text blocklist, if blocklistName does not exist, create a new blocklist. + Updates a text blocklist. If the blocklistName does not exist, a new blocklist will be created. :param blocklist_name: Text blocklist name. Required. :type blocklist_name: str - :param resource: The resource instance. Required. - :type resource: JSON + :param options: The resource instance. Required. + :type options: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -445,16 +545,16 @@ async def create_or_update_text_blocklist( @overload async def create_or_update_text_blocklist( - self, blocklist_name: str, resource: IO, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, blocklist_name: str, options: IO, *, content_type: str = "application/merge-patch+json", **kwargs: Any ) -> _models.TextBlocklist: """Create Or Update Text Blocklist. - Updates a text blocklist, if blocklistName does not exist, create a new blocklist. + Updates a text blocklist. If the blocklistName does not exist, a new blocklist will be created. :param blocklist_name: Text blocklist name. Required. :type blocklist_name: str - :param resource: The resource instance. Required. - :type resource: IO + :param options: The resource instance. Required. + :type options: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -467,17 +567,17 @@ async def create_or_update_text_blocklist( @distributed_trace_async async def create_or_update_text_blocklist( - self, blocklist_name: str, resource: Union[_models.TextBlocklist, JSON, IO], **kwargs: Any + self, blocklist_name: str, options: Union[_models.TextBlocklist, JSON, IO], **kwargs: Any ) -> _models.TextBlocklist: """Create Or Update Text Blocklist. - Updates a text blocklist, if blocklistName does not exist, create a new blocklist. + Updates a text blocklist. If the blocklistName does not exist, a new blocklist will be created. :param blocklist_name: Text blocklist name. Required. :type blocklist_name: str - :param resource: The resource instance. Is one of the following types: TextBlocklist, JSON, IO + :param options: The resource instance. Is one of the following types: TextBlocklist, JSON, IO Required. - :type resource: ~azure.ai.contentsafety.models.TextBlocklist or JSON or IO + :type options: ~azure.ai.contentsafety.models.TextBlocklist or JSON or IO :keyword content_type: This request has a JSON Merge Patch body. Default value is None. :paramtype content_type: str :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You @@ -502,12 +602,12 @@ async def create_or_update_text_blocklist( content_type = content_type or "application/merge-patch+json" _content = None - if isinstance(resource, (IOBase, bytes)): - _content = resource + if isinstance(options, (IOBase, bytes)): + _content = options else: - _content = json.dumps(resource, cls=AzureJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_content_safety_create_or_update_text_blocklist_request( + _request = build_blocklist_create_or_update_text_blocklist_request( blocklist_name=blocklist_name, content_type=content_type, api_version=self._config.api_version, @@ -560,8 +660,6 @@ async def delete_text_blocklist( # pylint: disable=inconsistent-return-statemen :param blocklist_name: Text blocklist name. Required. :type blocklist_name: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -579,7 +677,7 @@ async def delete_text_blocklist( # pylint: disable=inconsistent-return-statemen cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_content_safety_delete_text_blocklist_request( + _request = build_blocklist_delete_text_blocklist_request( blocklist_name=blocklist_name, api_version=self._config.api_version, headers=_headers, @@ -590,7 +688,7 @@ async def delete_text_blocklist( # pylint: disable=inconsistent-return-statemen } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = kwargs.pop("stream", False) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -606,20 +704,158 @@ async def delete_text_blocklist( # pylint: disable=inconsistent-return-statemen if cls: return cls(pipeline_response, None, {}) # type: ignore + @distributed_trace_async + async def get_text_blocklist(self, blocklist_name: str, **kwargs: Any) -> _models.TextBlocklist: + """Get Text Blocklist By blocklistName. + + Returns text blocklist details. + + :param blocklist_name: Text blocklist name. Required. + :type blocklist_name: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. + :return: TextBlocklist. The TextBlocklist is compatible with MutableMapping + :rtype: ~azure.ai.contentsafety.models.TextBlocklist + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.TextBlocklist] = kwargs.pop("cls", None) + + _request = build_blocklist_get_text_blocklist_request( + blocklist_name=blocklist_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + await response.read() # Load the body in memory and close the socket + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.TextBlocklist, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_text_blocklist_item( + self, blocklist_name: str, blocklist_item_id: str, **kwargs: Any + ) -> _models.TextBlocklistItem: + """Get BlocklistItem By blocklistName And blocklistItemId. + + Get blocklistItem by blocklistName and blocklistItemId from a text blocklist. + + :param blocklist_name: Text blocklist name. Required. + :type blocklist_name: str + :param blocklist_item_id: The service will generate a BlocklistItemId, which will be a UUID. + Required. + :type blocklist_item_id: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. + :return: TextBlocklistItem. The TextBlocklistItem is compatible with MutableMapping + :rtype: ~azure.ai.contentsafety.models.TextBlocklistItem + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.TextBlocklistItem] = kwargs.pop("cls", None) + + _request = build_blocklist_get_text_blocklist_item_request( + blocklist_name=blocklist_name, + blocklist_item_id=blocklist_item_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + await response.read() # Load the body in memory and close the socket + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.TextBlocklistItem, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + @distributed_trace - def list_text_blocklists(self, **kwargs: Any) -> AsyncIterable["_models.TextBlocklist"]: - """Get All Text Blocklists. + def list_text_blocklist_items( + self, blocklist_name: str, *, top: Optional[int] = None, skip: Optional[int] = None, **kwargs: Any + ) -> AsyncIterable["_models.TextBlocklistItem"]: + """Get All BlocklistItems By blocklistName. - Get all text blocklists details. + Get all blocklistItems in a text blocklist. - :return: An iterator like instance of TextBlocklist - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.contentsafety.models.TextBlocklist] + :param blocklist_name: Text blocklist name. Required. + :type blocklist_name: str + :keyword top: The number of result items to return. Default value is None. + :paramtype top: int + :keyword skip: The number of result items to skip. Default value is None. + :paramtype skip: int + :return: An iterator like instance of TextBlocklistItem + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.ai.contentsafety.models.TextBlocklistItem] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.TextBlocklist]] = kwargs.pop("cls", None) + maxpagesize = kwargs.pop("maxpagesize", None) + cls: ClsType[List[_models.TextBlocklistItem]] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, @@ -632,7 +868,11 @@ def list_text_blocklists(self, **kwargs: Any) -> AsyncIterable["_models.TextBloc def prepare_request(next_link=None): if not next_link: - _request = build_content_safety_list_text_blocklists_request( + _request = build_blocklist_list_text_blocklist_items_request( + blocklist_name=blocklist_name, + top=top, + skip=skip, + maxpagesize=maxpagesize, api_version=self._config.api_version, headers=_headers, params=_params, @@ -668,7 +908,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.TextBlocklist], deserialized["value"]) + list_of_elem = _deserialize(List[_models.TextBlocklistItem], deserialized["value"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -692,98 +932,21 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - @overload - async def add_block_items( - self, - blocklist_name: str, - body: _models.AddBlockItemsOptions, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.AddBlockItemsResult: - """Add BlockItems To Text Blocklist. - - Add blockItems to a text blocklist. You can add at most 100 BlockItems in one request. - - :param blocklist_name: Text blocklist name. Required. - :type blocklist_name: str - :param body: Required. - :type body: ~azure.ai.contentsafety.models.AddBlockItemsOptions - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: AddBlockItemsResult. The AddBlockItemsResult is compatible with MutableMapping - :rtype: ~azure.ai.contentsafety.models.AddBlockItemsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def add_block_items( - self, blocklist_name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AddBlockItemsResult: - """Add BlockItems To Text Blocklist. - - Add blockItems to a text blocklist. You can add at most 100 BlockItems in one request. - - :param blocklist_name: Text blocklist name. Required. - :type blocklist_name: str - :param body: Required. - :type body: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: AddBlockItemsResult. The AddBlockItemsResult is compatible with MutableMapping - :rtype: ~azure.ai.contentsafety.models.AddBlockItemsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def add_block_items( - self, blocklist_name: str, body: IO, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AddBlockItemsResult: - """Add BlockItems To Text Blocklist. + @distributed_trace + def list_text_blocklists(self, **kwargs: Any) -> AsyncIterable["_models.TextBlocklist"]: + """Get All Text Blocklists. - Add blockItems to a text blocklist. You can add at most 100 BlockItems in one request. + Get all text blocklists details. - :param blocklist_name: Text blocklist name. Required. - :type blocklist_name: str - :param body: Required. - :type body: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: AddBlockItemsResult. The AddBlockItemsResult is compatible with MutableMapping - :rtype: ~azure.ai.contentsafety.models.AddBlockItemsResult + :return: An iterator like instance of TextBlocklist + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.contentsafety.models.TextBlocklist] :raises ~azure.core.exceptions.HttpResponseError: """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} - @distributed_trace_async - async def add_block_items( - self, blocklist_name: str, body: Union[_models.AddBlockItemsOptions, JSON, IO], **kwargs: Any - ) -> _models.AddBlockItemsResult: - """Add BlockItems To Text Blocklist. - - Add blockItems to a text blocklist. You can add at most 100 BlockItems in one request. + cls: ClsType[List[_models.TextBlocklist]] = kwargs.pop("cls", None) - :param blocklist_name: Text blocklist name. Required. - :type blocklist_name: str - :param body: Is one of the following types: AddBlockItemsOptions, JSON, IO Required. - :type body: ~azure.ai.contentsafety.models.AddBlockItemsOptions or JSON or IO - :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default - value is None. - :paramtype content_type: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: AddBlockItemsResult. The AddBlockItemsResult is compatible with MutableMapping - :rtype: ~azure.ai.contentsafety.models.AddBlockItemsResult - :raises ~azure.core.exceptions.HttpResponseError: - """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -792,143 +955,154 @@ async def add_block_items( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} + def prepare_request(next_link=None): + if not next_link: - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.AddBlockItemsResult] = kwargs.pop("cls", None) + _request = build_blocklist_list_text_blocklists_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=AzureJSONEncoder, exclude_readonly=True) # type: ignore + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - _request = build_content_safety_add_block_items_request( - blocklist_name=blocklist_name, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + return _request - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(List[_models.TextBlocklist], deserialized["value"]) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) - response = pipeline_response.http_response + async def get_next(next_link=None): + _request = prepare_request(next_link) - if response.status_code not in [200]: - if _stream: - await response.read() # Load the body in memory and close the socket - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.AddBlockItemsResult, response.json()) + if response.status_code not in [200]: + if _stream: + await response.read() # Load the body in memory and close the socket + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return pipeline_response - return deserialized # type: ignore + return AsyncItemPaged(get_next, extract_data) @overload - async def remove_block_items( # pylint: disable=inconsistent-return-statements + async def remove_blocklist_items( # pylint: disable=inconsistent-return-statements self, blocklist_name: str, - body: _models.RemoveBlockItemsOptions, + options: _models.RemoveTextBlocklistItemsOptions, *, content_type: str = "application/json", **kwargs: Any ) -> None: - """Remove BlockItems From Text Blocklist. + """Remove BlocklistItems From Text Blocklist. - Remove blockItems from a text blocklist. You can remove at most 100 BlockItems in one request. + Remove blocklistItems from a text blocklist. You can remove at most 100 BlocklistItems in one + request. :param blocklist_name: Text blocklist name. Required. :type blocklist_name: str - :param body: Required. - :type body: ~azure.ai.contentsafety.models.RemoveBlockItemsOptions + :param options: Options for removing blocklist items. Required. + :type options: ~azure.ai.contentsafety.models.RemoveTextBlocklistItemsOptions :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def remove_block_items( # pylint: disable=inconsistent-return-statements - self, blocklist_name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + async def remove_blocklist_items( # pylint: disable=inconsistent-return-statements + self, blocklist_name: str, options: JSON, *, content_type: str = "application/json", **kwargs: Any ) -> None: - """Remove BlockItems From Text Blocklist. + """Remove BlocklistItems From Text Blocklist. - Remove blockItems from a text blocklist. You can remove at most 100 BlockItems in one request. + Remove blocklistItems from a text blocklist. You can remove at most 100 BlocklistItems in one + request. :param blocklist_name: Text blocklist name. Required. :type blocklist_name: str - :param body: Required. - :type body: JSON + :param options: Options for removing blocklist items. Required. + :type options: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def remove_block_items( # pylint: disable=inconsistent-return-statements - self, blocklist_name: str, body: IO, *, content_type: str = "application/json", **kwargs: Any + async def remove_blocklist_items( # pylint: disable=inconsistent-return-statements + self, blocklist_name: str, options: IO, *, content_type: str = "application/json", **kwargs: Any ) -> None: - """Remove BlockItems From Text Blocklist. + """Remove BlocklistItems From Text Blocklist. - Remove blockItems from a text blocklist. You can remove at most 100 BlockItems in one request. + Remove blocklistItems from a text blocklist. You can remove at most 100 BlocklistItems in one + request. :param blocklist_name: Text blocklist name. Required. :type blocklist_name: str - :param body: Required. - :type body: IO + :param options: Options for removing blocklist items. Required. + :type options: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def remove_block_items( # pylint: disable=inconsistent-return-statements - self, blocklist_name: str, body: Union[_models.RemoveBlockItemsOptions, JSON, IO], **kwargs: Any + async def remove_blocklist_items( # pylint: disable=inconsistent-return-statements + self, blocklist_name: str, options: Union[_models.RemoveTextBlocklistItemsOptions, JSON, IO], **kwargs: Any ) -> None: - """Remove BlockItems From Text Blocklist. + """Remove BlocklistItems From Text Blocklist. - Remove blockItems from a text blocklist. You can remove at most 100 BlockItems in one request. + Remove blocklistItems from a text blocklist. You can remove at most 100 BlocklistItems in one + request. :param blocklist_name: Text blocklist name. Required. :type blocklist_name: str - :param body: Is one of the following types: RemoveBlockItemsOptions, JSON, IO Required. - :type body: ~azure.ai.contentsafety.models.RemoveBlockItemsOptions or JSON or IO + :param options: Options for removing blocklist items. Is one of the following types: + RemoveTextBlocklistItemsOptions, JSON, IO Required. + :type options: ~azure.ai.contentsafety.models.RemoveTextBlocklistItemsOptions or JSON or IO :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default value is None. :paramtype content_type: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -949,12 +1123,12 @@ async def remove_block_items( # pylint: disable=inconsistent-return-statements content_type = content_type or "application/json" _content = None - if isinstance(body, (IOBase, bytes)): - _content = body + if isinstance(options, (IOBase, bytes)): + _content = options else: - _content = json.dumps(body, cls=AzureJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_content_safety_remove_block_items_request( + _request = build_blocklist_remove_blocklist_items_request( blocklist_name=blocklist_name, content_type=content_type, api_version=self._config.api_version, @@ -967,7 +1141,7 @@ async def remove_block_items( # pylint: disable=inconsistent-return-statements } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = kwargs.pop("stream", False) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -982,168 +1156,3 @@ async def remove_block_items( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) # type: ignore - - @distributed_trace_async - async def get_text_blocklist_item( - self, blocklist_name: str, block_item_id: str, **kwargs: Any - ) -> _models.TextBlockItem: - """Get BlockItem By blocklistName And blockItemId. - - Get blockItem By blockItemId from a text blocklist. - - :param blocklist_name: Text blocklist name. Required. - :type blocklist_name: str - :param block_item_id: Block Item Id. It will be uuid. Required. - :type block_item_id: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: TextBlockItem. The TextBlockItem is compatible with MutableMapping - :rtype: ~azure.ai.contentsafety.models.TextBlockItem - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models.TextBlockItem] = kwargs.pop("cls", None) - - _request = build_content_safety_get_text_blocklist_item_request( - blocklist_name=blocklist_name, - block_item_id=block_item_id, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - await response.read() # Load the body in memory and close the socket - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.TextBlockItem, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_text_blocklist_items( - self, blocklist_name: str, *, top: Optional[int] = None, skip: Optional[int] = None, **kwargs: Any - ) -> AsyncIterable["_models.TextBlockItem"]: - """Get All BlockItems By blocklistName. - - Get all blockItems in a text blocklist. - - :param blocklist_name: Text blocklist name. Required. - :type blocklist_name: str - :keyword top: The number of result items to return. Default value is None. - :paramtype top: int - :keyword skip: The number of result items to skip. Default value is None. - :paramtype skip: int - :return: An iterator like instance of TextBlockItem - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.contentsafety.models.TextBlockItem] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - maxpagesize = kwargs.pop("maxpagesize", None) - cls: ClsType[List[_models.TextBlockItem]] = kwargs.pop("cls", None) - - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_content_safety_list_text_blocklist_items_request( - blocklist_name=blocklist_name, - top=top, - skip=skip, - maxpagesize=maxpagesize, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - return _request - - async def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.TextBlockItem], deserialized["value"]) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.get("nextLink") or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - await response.read() # Load the body in memory and close the socket - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) diff --git a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/aio/_vendor.py b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/aio/_vendor.py index d0609967e945..aaf8f213e731 100644 --- a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/aio/_vendor.py +++ b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/aio/_vendor.py @@ -8,7 +8,7 @@ from abc import ABC from typing import TYPE_CHECKING -from ._configuration import ContentSafetyClientConfiguration +from ._configuration import BlocklistClientConfiguration, ContentSafetyClientConfiguration if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports @@ -24,3 +24,12 @@ class ContentSafetyClientMixinABC(ABC): _config: ContentSafetyClientConfiguration _serialize: "Serializer" _deserialize: "Deserializer" + + +class BlocklistClientMixinABC(ABC): + """DO NOT use this class. It is for internal typing use only.""" + + _client: "AsyncPipelineClient" + _config: BlocklistClientConfiguration + _serialize: "Serializer" + _deserialize: "Deserializer" diff --git a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/models/__init__.py b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/models/__init__.py index 48eb2421985e..a4cd06fb66cf 100644 --- a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/models/__init__.py +++ b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/models/__init__.py @@ -6,21 +6,22 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from ._models import AddBlockItemsOptions -from ._models import AddBlockItemsResult +from ._models import AddOrUpdateTextBlocklistItemsOptions +from ._models import AddOrUpdateTextBlocklistItemsResult from ._models import AnalyzeImageOptions from ._models import AnalyzeImageResult from ._models import AnalyzeTextOptions from ._models import AnalyzeTextResult -from ._models import ImageAnalyzeSeverityResult +from ._models import ImageCategoriesAnalysis from ._models import ImageData -from ._models import RemoveBlockItemsOptions -from ._models import TextAnalyzeSeverityResult -from ._models import TextBlockItem -from ._models import TextBlockItemInfo +from ._models import RemoveTextBlocklistItemsOptions from ._models import TextBlocklist -from ._models import TextBlocklistMatchResult +from ._models import TextBlocklistItem +from ._models import TextBlocklistMatch +from ._models import TextCategoriesAnalysis +from ._enums import AnalyzeImageOutputType +from ._enums import AnalyzeTextOutputType from ._enums import ImageCategory from ._enums import TextCategory from ._patch import __all__ as _patch_all @@ -28,20 +29,21 @@ from ._patch import patch_sdk as _patch_sdk __all__ = [ - "AddBlockItemsOptions", - "AddBlockItemsResult", + "AddOrUpdateTextBlocklistItemsOptions", + "AddOrUpdateTextBlocklistItemsResult", "AnalyzeImageOptions", "AnalyzeImageResult", "AnalyzeTextOptions", "AnalyzeTextResult", - "ImageAnalyzeSeverityResult", + "ImageCategoriesAnalysis", "ImageData", - "RemoveBlockItemsOptions", - "TextAnalyzeSeverityResult", - "TextBlockItem", - "TextBlockItemInfo", + "RemoveTextBlocklistItemsOptions", "TextBlocklist", - "TextBlocklistMatchResult", + "TextBlocklistItem", + "TextBlocklistMatch", + "TextCategoriesAnalysis", + "AnalyzeImageOutputType", + "AnalyzeTextOutputType", "ImageCategory", "TextCategory", ] diff --git a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/models/_enums.py b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/models/_enums.py index f0c6baf1f648..6e91fad1a406 100644 --- a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/models/_enums.py +++ b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/models/_enums.py @@ -10,6 +10,22 @@ from azure.core import CaseInsensitiveEnumMeta +class AnalyzeImageOutputType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of image analysis output.""" + + FOUR_SEVERITY_LEVELS = "FourSeverityLevels" + """Output severities in four levels, the value could be 0,2,4,6.""" + + +class AnalyzeTextOutputType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of text analysis output.""" + + FOUR_SEVERITY_LEVELS = "FourSeverityLevels" + """Output severities in four levels, the value could be 0,2,4,6.""" + EIGHT_SEVERITY_LEVELS = "EightSeverityLevels" + """Output severities in eight levels, the value could be 0,1,2,3,4,5,6,7.""" + + class ImageCategory(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Image analyze category.""" diff --git a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/models/_models.py b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/models/_models.py index f73a30b99f56..cf0403b1cd4c 100644 --- a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/models/_models.py +++ b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/models/_models.py @@ -17,23 +17,23 @@ from .. import models as _models -class AddBlockItemsOptions(_model_base.Model): - """The request of adding blockItems to text blocklist. +class AddOrUpdateTextBlocklistItemsOptions(_model_base.Model): + """The request to add blocklistItems to a text blocklist. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. - :ivar block_items: Array of blockItemInfo to add. Required. - :vartype block_items: list[~azure.ai.contentsafety.models.TextBlockItemInfo] + :ivar blocklist_items: Array of blocklistItems to add. Required. + :vartype blocklist_items: list[~azure.ai.contentsafety.models.TextBlocklistItem] """ - block_items: List["_models.TextBlockItemInfo"] = rest_field(name="blockItems") - """Array of blockItemInfo to add. Required.""" + blocklist_items: List["_models.TextBlocklistItem"] = rest_field(name="blocklistItems") + """Array of blocklistItems to add. Required.""" @overload def __init__( self, *, - block_items: List["_models.TextBlockItemInfo"], + blocklist_items: List["_models.TextBlocklistItem"], ): ... @@ -48,21 +48,23 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useles super().__init__(*args, **kwargs) -class AddBlockItemsResult(_model_base.Model): - """The response of adding blockItems to text blocklist. +class AddOrUpdateTextBlocklistItemsResult(_model_base.Model): + """The response of adding blocklistItems to the text blocklist. - :ivar value: Array of blockItems added. - :vartype value: list[~azure.ai.contentsafety.models.TextBlockItem] + All required parameters must be populated in order to send to server. + + :ivar blocklist_items: Array of blocklistItems have been added. Required. + :vartype blocklist_items: list[~azure.ai.contentsafety.models.TextBlocklistItem] """ - value: Optional[List["_models.TextBlockItem"]] = rest_field() - """Array of blockItems added.""" + blocklist_items: List["_models.TextBlocklistItem"] = rest_field(name="blocklistItems") + """Array of blocklistItems have been added. Required.""" @overload def __init__( self, *, - value: Optional[List["_models.TextBlockItem"]] = None, + blocklist_items: List["_models.TextBlocklistItem"], ): ... @@ -78,22 +80,28 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useles class AnalyzeImageOptions(_model_base.Model): - """The analysis request of the image. + """The image analysis request. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar image: The image needs to be analyzed. Required. :vartype image: ~azure.ai.contentsafety.models.ImageData - :ivar categories: The categories will be analyzed. If not assigned, a default set of the - categories' analysis results will be returned. + :ivar categories: The categories will be analyzed. If they are not assigned, a default set of + analysis results for the categories will be returned. :vartype categories: list[str or ~azure.ai.contentsafety.models.ImageCategory] + :ivar output_type: This refers to the type of image analysis output. If no value is assigned, + the default value will be "FourSeverityLevels". "FourSeverityLevels" + :vartype output_type: str or ~azure.ai.contentsafety.models.AnalyzeImageOutputType """ image: "_models.ImageData" = rest_field() """The image needs to be analyzed. Required.""" categories: Optional[List[Union[str, "_models.ImageCategory"]]] = rest_field() - """The categories will be analyzed. If not assigned, a default set of the categories' analysis - results will be returned.""" + """The categories will be analyzed. If they are not assigned, a default set of analysis results + for the categories will be returned.""" + output_type: Optional[Union[str, "_models.AnalyzeImageOutputType"]] = rest_field(name="outputType") + """This refers to the type of image analysis output. If no value is assigned, the default value + will be \"FourSeverityLevels\". \"FourSeverityLevels\"""" @overload def __init__( @@ -101,6 +109,7 @@ def __init__( *, image: "_models.ImageData", categories: Optional[List[Union[str, "_models.ImageCategory"]]] = None, + output_type: Optional[Union[str, "_models.AnalyzeImageOutputType"]] = None, ): ... @@ -116,35 +125,22 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useles class AnalyzeImageResult(_model_base.Model): - """The analysis response of the image. - - :ivar hate_result: Analysis result for Hate category. - :vartype hate_result: ~azure.ai.contentsafety.models.ImageAnalyzeSeverityResult - :ivar self_harm_result: Analysis result for SelfHarm category. - :vartype self_harm_result: ~azure.ai.contentsafety.models.ImageAnalyzeSeverityResult - :ivar sexual_result: Analysis result for Sexual category. - :vartype sexual_result: ~azure.ai.contentsafety.models.ImageAnalyzeSeverityResult - :ivar violence_result: Analysis result for Violence category. - :vartype violence_result: ~azure.ai.contentsafety.models.ImageAnalyzeSeverityResult + """The image analysis response. + + All required parameters must be populated in order to send to server. + + :ivar categories_analysis: Analysis result for categories. Required. + :vartype categories_analysis: list[~azure.ai.contentsafety.models.ImageCategoriesAnalysis] """ - hate_result: Optional["_models.ImageAnalyzeSeverityResult"] = rest_field(name="hateResult") - """Analysis result for Hate category.""" - self_harm_result: Optional["_models.ImageAnalyzeSeverityResult"] = rest_field(name="selfHarmResult") - """Analysis result for SelfHarm category.""" - sexual_result: Optional["_models.ImageAnalyzeSeverityResult"] = rest_field(name="sexualResult") - """Analysis result for Sexual category.""" - violence_result: Optional["_models.ImageAnalyzeSeverityResult"] = rest_field(name="violenceResult") - """Analysis result for Violence category.""" + categories_analysis: List["_models.ImageCategoriesAnalysis"] = rest_field(name="categoriesAnalysis") + """Analysis result for categories. Required.""" @overload def __init__( self, *, - hate_result: Optional["_models.ImageAnalyzeSeverityResult"] = None, - self_harm_result: Optional["_models.ImageAnalyzeSeverityResult"] = None, - sexual_result: Optional["_models.ImageAnalyzeSeverityResult"] = None, - violence_result: Optional["_models.ImageAnalyzeSeverityResult"] = None, + categories_analysis: List["_models.ImageCategoriesAnalysis"], ): ... @@ -160,36 +156,44 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useles class AnalyzeTextOptions(_model_base.Model): - """The analysis request of the text. + """The text analysis request. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. - :ivar text: The text needs to be scanned. We support at most 1000 characters (unicode code - points) in text of one request. Required. + :ivar text: The text needs to be analyzed. We support a maximum of 10k Unicode characters + (Unicode code points) in the text of one request. Required. :vartype text: str - :ivar categories: The categories will be analyzed. If not assigned, a default set of the - categories' analysis results will be returned. + :ivar categories: The categories will be analyzed. If they are not assigned, a default set of + analysis results for the categories will be returned. :vartype categories: list[str or ~azure.ai.contentsafety.models.TextCategory] :ivar blocklist_names: The names of blocklists. :vartype blocklist_names: list[str] - :ivar break_by_blocklists: When set to true, further analyses of harmful content will not be + :ivar halt_on_blocklist_hit: When set to true, further analyses of harmful content will not be performed in cases where blocklists are hit. When set to false, all analyses of harmful content will be performed, whether or not blocklists are hit. - :vartype break_by_blocklists: bool + :vartype halt_on_blocklist_hit: bool + :ivar output_type: This refers to the type of text analysis output. If no value is assigned, + the default value will be "FourSeverityLevels". Known values are: "FourSeverityLevels" and + "EightSeverityLevels". + :vartype output_type: str or ~azure.ai.contentsafety.models.AnalyzeTextOutputType """ text: str = rest_field() - """The text needs to be scanned. We support at most 1000 characters (unicode code points) in text - of one request. Required.""" + """The text needs to be analyzed. We support a maximum of 10k Unicode characters (Unicode code + points) in the text of one request. Required.""" categories: Optional[List[Union[str, "_models.TextCategory"]]] = rest_field() - """The categories will be analyzed. If not assigned, a default set of the categories' analysis - results will be returned.""" + """The categories will be analyzed. If they are not assigned, a default set of analysis results + for the categories will be returned.""" blocklist_names: Optional[List[str]] = rest_field(name="blocklistNames") """The names of blocklists.""" - break_by_blocklists: Optional[bool] = rest_field(name="breakByBlocklists") + halt_on_blocklist_hit: Optional[bool] = rest_field(name="haltOnBlocklistHit") """When set to true, further analyses of harmful content will not be performed in cases where blocklists are hit. When set to false, all analyses of harmful content will be performed, whether or not blocklists are hit.""" + output_type: Optional[Union[str, "_models.AnalyzeTextOutputType"]] = rest_field(name="outputType") + """This refers to the type of text analysis output. If no value is assigned, the default value + will be \"FourSeverityLevels\". Known values are: \"FourSeverityLevels\" and + \"EightSeverityLevels\".""" @overload def __init__( @@ -198,7 +202,8 @@ def __init__( text: str, categories: Optional[List[Union[str, "_models.TextCategory"]]] = None, blocklist_names: Optional[List[str]] = None, - break_by_blocklists: Optional[bool] = None, + halt_on_blocklist_hit: Optional[bool] = None, + output_type: Optional[Union[str, "_models.AnalyzeTextOutputType"]] = None, ): ... @@ -214,43 +219,27 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useles class AnalyzeTextResult(_model_base.Model): - """The analysis response of the text. - - :ivar blocklists_match_results: The details of blocklist match. - :vartype blocklists_match_results: - list[~azure.ai.contentsafety.models.TextBlocklistMatchResult] - :ivar hate_result: Analysis result for Hate category. - :vartype hate_result: ~azure.ai.contentsafety.models.TextAnalyzeSeverityResult - :ivar self_harm_result: Analysis result for SelfHarm category. - :vartype self_harm_result: ~azure.ai.contentsafety.models.TextAnalyzeSeverityResult - :ivar sexual_result: Analysis result for Sexual category. - :vartype sexual_result: ~azure.ai.contentsafety.models.TextAnalyzeSeverityResult - :ivar violence_result: Analysis result for Violence category. - :vartype violence_result: ~azure.ai.contentsafety.models.TextAnalyzeSeverityResult + """The text analysis response. + + All required parameters must be populated in order to send to server. + + :ivar blocklists_match: The blocklist match details. + :vartype blocklists_match: list[~azure.ai.contentsafety.models.TextBlocklistMatch] + :ivar categories_analysis: Analysis result for categories. Required. + :vartype categories_analysis: list[~azure.ai.contentsafety.models.TextCategoriesAnalysis] """ - blocklists_match_results: Optional[List["_models.TextBlocklistMatchResult"]] = rest_field( - name="blocklistsMatchResults" - ) - """The details of blocklist match.""" - hate_result: Optional["_models.TextAnalyzeSeverityResult"] = rest_field(name="hateResult") - """Analysis result for Hate category.""" - self_harm_result: Optional["_models.TextAnalyzeSeverityResult"] = rest_field(name="selfHarmResult") - """Analysis result for SelfHarm category.""" - sexual_result: Optional["_models.TextAnalyzeSeverityResult"] = rest_field(name="sexualResult") - """Analysis result for Sexual category.""" - violence_result: Optional["_models.TextAnalyzeSeverityResult"] = rest_field(name="violenceResult") - """Analysis result for Violence category.""" + blocklists_match: Optional[List["_models.TextBlocklistMatch"]] = rest_field(name="blocklistsMatch") + """The blocklist match details.""" + categories_analysis: List["_models.TextCategoriesAnalysis"] = rest_field(name="categoriesAnalysis") + """Analysis result for categories. Required.""" @overload def __init__( self, *, - blocklists_match_results: Optional[List["_models.TextBlocklistMatchResult"]] = None, - hate_result: Optional["_models.TextAnalyzeSeverityResult"] = None, - self_harm_result: Optional["_models.TextAnalyzeSeverityResult"] = None, - sexual_result: Optional["_models.TextAnalyzeSeverityResult"] = None, - violence_result: Optional["_models.TextAnalyzeSeverityResult"] = None, + categories_analysis: List["_models.TextCategoriesAnalysis"], + blocklists_match: Optional[List["_models.TextBlocklistMatch"]] = None, ): ... @@ -265,32 +254,34 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useles super().__init__(*args, **kwargs) -class ImageAnalyzeSeverityResult(_model_base.Model): +class ImageCategoriesAnalysis(_model_base.Model): """Image analysis result. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. - :ivar category: The image category. Required. Known values are: "Hate", "SelfHarm", "Sexual", - and "Violence". + :ivar category: The image analysis category. Required. Known values are: "Hate", "SelfHarm", + "Sexual", and "Violence". :vartype category: str or ~azure.ai.contentsafety.models.ImageCategory - :ivar severity: The higher the severity of input content, the larger this value, currently its - value could be: 0,2,4,6. Required. + :ivar severity: The value increases with the severity of the input content. The value of this + field is determined by the output type specified in the request. The output type could be + ‘FourSeverityLevels’, and the output value can be 0, 2, 4, 6. :vartype severity: int """ category: Union[str, "_models.ImageCategory"] = rest_field() - """The image category. Required. Known values are: \"Hate\", \"SelfHarm\", \"Sexual\", and - \"Violence\".""" - severity: int = rest_field() - """The higher the severity of input content, the larger this value, currently its value could be: - 0,2,4,6. Required.""" + """The image analysis category. Required. Known values are: \"Hate\", \"SelfHarm\", \"Sexual\", + and \"Violence\".""" + severity: Optional[int] = rest_field() + """The value increases with the severity of the input content. The value of this field is + determined by the output type specified in the request. The output type could be + ‘FourSeverityLevels’, and the output value can be 0, 2, 4, 6.""" @overload def __init__( self, *, category: Union[str, "_models.ImageCategory"], - severity: int, + severity: Optional[int] = None, ): ... @@ -306,20 +297,20 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useles class ImageData(_model_base.Model): - """The content or blob url of image, could be base64 encoding bytes or blob url. If both are - given, the request will be refused. The maximum size of image is 2048 pixels * 2048 pixels, no - larger than 4MB at the same time. The minimum size of image is 50 pixels * 50 pixels. + """The image can be either base64 encoded bytes or a blob URL. You can choose only one of these + options. If both are provided, the request will be refused. The maximum image size is 2048 x + 2048 pixels and should not exceed 4 MB, while the minimum image size is 50 x 50 pixels. - :ivar content: Base64 encoding of image. + :ivar content: The Base64 encoding of the image. :vartype content: bytes - :ivar blob_url: The blob url of image. + :ivar blob_url: The blob url of the image. :vartype blob_url: str """ content: Optional[bytes] = rest_field(format="base64") - """Base64 encoding of image.""" + """The Base64 encoding of the image.""" blob_url: Optional[str] = rest_field(name="blobUrl") - """The blob url of image.""" + """The blob url of the image.""" @overload def __init__( @@ -341,63 +332,23 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useles super().__init__(*args, **kwargs) -class RemoveBlockItemsOptions(_model_base.Model): - """The request of removing blockItems from text blocklist. +class RemoveTextBlocklistItemsOptions(_model_base.Model): + """The request to remove blocklistItems from a text blocklist. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. - :ivar block_item_ids: Array of blockItemIds to remove. Required. - :vartype block_item_ids: list[str] + :ivar blocklist_item_ids: Array of blocklistItemIds to remove. Required. + :vartype blocklist_item_ids: list[str] """ - block_item_ids: List[str] = rest_field(name="blockItemIds") - """Array of blockItemIds to remove. Required.""" + blocklist_item_ids: List[str] = rest_field(name="blocklistItemIds") + """Array of blocklistItemIds to remove. Required.""" @overload def __init__( self, *, - block_item_ids: List[str], - ): - ... - - @overload - def __init__(self, mapping: Mapping[str, Any]): - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation - super().__init__(*args, **kwargs) - - -class TextAnalyzeSeverityResult(_model_base.Model): - """Text analysis result. - - All required parameters must be populated in order to send to Azure. - - :ivar category: The text category. Required. Known values are: "Hate", "SelfHarm", "Sexual", - and "Violence". - :vartype category: str or ~azure.ai.contentsafety.models.TextCategory - :ivar severity: The higher the severity of input content, the larger this value is. The values - could be: 0,2,4,6. Required. - :vartype severity: int - """ - - category: Union[str, "_models.TextCategory"] = rest_field() - """The text category. Required. Known values are: \"Hate\", \"SelfHarm\", \"Sexual\", and - \"Violence\".""" - severity: int = rest_field() - """The higher the severity of input content, the larger this value is. The values could be: - 0,2,4,6. Required.""" - - @overload - def __init__( - self, - *, - category: Union[str, "_models.TextCategory"], - severity: int, + blocklist_item_ids: List[str], ): ... @@ -412,32 +363,27 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useles super().__init__(*args, **kwargs) -class TextBlockItem(_model_base.Model): - """Item in TextBlocklist. +class TextBlocklist(_model_base.Model): + """Text Blocklist. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. - :ivar block_item_id: Block Item Id. It will be uuid. Required. - :vartype block_item_id: str - :ivar description: Block item description. + :ivar blocklist_name: Text blocklist name. Required. + :vartype blocklist_name: str + :ivar description: Text blocklist description. :vartype description: str - :ivar text: Block item content. Required. - :vartype text: str """ - block_item_id: str = rest_field(name="blockItemId", visibility=["read", "create", "query"]) - """Block Item Id. It will be uuid. Required.""" + blocklist_name: str = rest_field(name="blocklistName", visibility=["read", "create", "query"]) + """Text blocklist name. Required.""" description: Optional[str] = rest_field() - """Block item description.""" - text: str = rest_field() - """Block item content. Required.""" + """Text blocklist description.""" @overload def __init__( self, *, - block_item_id: str, - text: str, + blocklist_name: str, description: Optional[str] = None, ): ... @@ -453,21 +399,28 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useles super().__init__(*args, **kwargs) -class TextBlockItemInfo(_model_base.Model): - """Block item info in text blocklist. +class TextBlocklistItem(_model_base.Model): + """Item in a TextBlocklist. - All required parameters must be populated in order to send to Azure. + Readonly variables are only populated by the server, and will be ignored when sending a request. - :ivar description: Block item description. + All required parameters must be populated in order to send to server. + + :ivar blocklist_item_id: The service will generate a BlocklistItemId, which will be a UUID. + Required. + :vartype blocklist_item_id: str + :ivar description: BlocklistItem description. :vartype description: str - :ivar text: Block item content. Required. + :ivar text: BlocklistItem content. Required. :vartype text: str """ + blocklist_item_id: str = rest_field(name="blocklistItemId", visibility=["read"]) + """The service will generate a BlocklistItemId, which will be a UUID. Required.""" description: Optional[str] = rest_field() - """Block item description.""" + """BlocklistItem description.""" text: str = rest_field() - """Block item content. Required.""" + """BlocklistItem content. Required.""" @overload def __init__( @@ -489,28 +442,33 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useles super().__init__(*args, **kwargs) -class TextBlocklist(_model_base.Model): - """Text Blocklist. +class TextBlocklistMatch(_model_base.Model): + """The result of blocklist match. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. - :ivar blocklist_name: Text blocklist name. Required. + :ivar blocklist_name: The name of the matched blocklist. Required. :vartype blocklist_name: str - :ivar description: Text blocklist description. - :vartype description: str + :ivar blocklist_item_id: The ID of the matched item. Required. + :vartype blocklist_item_id: str + :ivar blocklist_item_text: The content of the matched item. Required. + :vartype blocklist_item_text: str """ - blocklist_name: str = rest_field(name="blocklistName", visibility=["read", "create", "query"]) - """Text blocklist name. Required.""" - description: Optional[str] = rest_field() - """Text blocklist description.""" + blocklist_name: str = rest_field(name="blocklistName") + """The name of the matched blocklist. Required.""" + blocklist_item_id: str = rest_field(name="blocklistItemId") + """The ID of the matched item. Required.""" + blocklist_item_text: str = rest_field(name="blocklistItemText") + """The content of the matched item. Required.""" @overload def __init__( self, *, blocklist_name: str, - description: Optional[str] = None, + blocklist_item_id: str, + blocklist_item_text: str, ): ... @@ -525,43 +483,36 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useles super().__init__(*args, **kwargs) -class TextBlocklistMatchResult(_model_base.Model): - """The result of blocklist match. +class TextCategoriesAnalysis(_model_base.Model): + """Text analysis result. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. - :ivar blocklist_name: The name of matched blocklist. Required. - :vartype blocklist_name: str - :ivar block_item_id: The id of matched item. Required. - :vartype block_item_id: str - :ivar block_item_text: The content of matched item. Required. - :vartype block_item_text: str - :ivar offset: The character offset of matched text in original input. Required. - :vartype offset: int - :ivar length: The length of matched text in original input. Required. - :vartype length: int + :ivar category: The text analysis category. Required. Known values are: "Hate", "SelfHarm", + "Sexual", and "Violence". + :vartype category: str or ~azure.ai.contentsafety.models.TextCategory + :ivar severity: The value increases with the severity of the input content. The value of this + field is determined by the output type specified in the request. The output type could be + ‘FourSeverityLevels’ or ‘EightSeverity Levels’, and the output value can be 0, 2, 4, 6 or 0, 1, + 2, 3, 4, 5, 6, or 7. + :vartype severity: int """ - blocklist_name: str = rest_field(name="blocklistName") - """The name of matched blocklist. Required.""" - block_item_id: str = rest_field(name="blockItemId") - """The id of matched item. Required.""" - block_item_text: str = rest_field(name="blockItemText") - """The content of matched item. Required.""" - offset: int = rest_field() - """The character offset of matched text in original input. Required.""" - length: int = rest_field() - """The length of matched text in original input. Required.""" + category: Union[str, "_models.TextCategory"] = rest_field() + """The text analysis category. Required. Known values are: \"Hate\", \"SelfHarm\", \"Sexual\", and + \"Violence\".""" + severity: Optional[int] = rest_field() + """The value increases with the severity of the input content. The value of this field is + determined by the output type specified in the request. The output type could be + ‘FourSeverityLevels’ or ‘EightSeverity Levels’, and the output value can be 0, 2, 4, 6 or 0, 1, + 2, 3, 4, 5, 6, or 7.""" @overload def __init__( self, *, - blocklist_name: str, - block_item_id: str, - block_item_text: str, - offset: int, - length: int, + category: Union[str, "_models.TextCategory"], + severity: Optional[int] = None, ): ... diff --git a/sdk/contentsafety/azure-ai-contentsafety/samples/sample_analyze_image.py b/sdk/contentsafety/azure-ai-contentsafety/samples/sample_analyze_image.py index 2901b3a63d47..f3f52c8e3f81 100644 --- a/sdk/contentsafety/azure-ai-contentsafety/samples/sample_analyze_image.py +++ b/sdk/contentsafety/azure-ai-contentsafety/samples/sample_analyze_image.py @@ -6,9 +6,10 @@ # license information. # -------------------------------------------------------------------------- + def analyze_image(): # [START analyze_image] - + import os from azure.ai.contentsafety import ContentSafetyClient from azure.core.credentials import AzureKeyCredential @@ -51,4 +52,4 @@ def analyze_image(): if __name__ == "__main__": - analyze_image() \ No newline at end of file + analyze_image() diff --git a/sdk/contentsafety/azure-ai-contentsafety/samples/sample_analyze_image_async.py b/sdk/contentsafety/azure-ai-contentsafety/samples/sample_analyze_image_async.py index c53674fae41e..14c3ca7cc5e1 100644 --- a/sdk/contentsafety/azure-ai-contentsafety/samples/sample_analyze_image_async.py +++ b/sdk/contentsafety/azure-ai-contentsafety/samples/sample_analyze_image_async.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- import asyncio + async def analyze_image_async(): # [START analyze_image_async] @@ -51,9 +52,11 @@ async def analyze_image_async(): # [END analyze_image_async] + async def main(): await analyze_image_async() + if __name__ == "__main__": loop = asyncio.get_event_loop() - loop.run_until_complete(main()) \ No newline at end of file + loop.run_until_complete(main()) diff --git a/sdk/contentsafety/azure-ai-contentsafety/samples/sample_analyze_text.py b/sdk/contentsafety/azure-ai-contentsafety/samples/sample_analyze_text.py index bfc0717c4fac..1d1e38c37e78 100644 --- a/sdk/contentsafety/azure-ai-contentsafety/samples/sample_analyze_text.py +++ b/sdk/contentsafety/azure-ai-contentsafety/samples/sample_analyze_text.py @@ -48,5 +48,6 @@ def analyze_text(): # [END analyze_text] + if __name__ == "__main__": - analyze_text() \ No newline at end of file + analyze_text() diff --git a/sdk/contentsafety/azure-ai-contentsafety/samples/sample_analyze_text_async.py b/sdk/contentsafety/azure-ai-contentsafety/samples/sample_analyze_text_async.py index 445d9bde8308..c79d18dcb03d 100644 --- a/sdk/contentsafety/azure-ai-contentsafety/samples/sample_analyze_text_async.py +++ b/sdk/contentsafety/azure-ai-contentsafety/samples/sample_analyze_text_async.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- import asyncio + async def analyze_text_async(): # [START analyze_text_async] @@ -49,9 +50,11 @@ async def analyze_text_async(): # [END analyze_text_async] + async def main(): await analyze_text_async() + if __name__ == "__main__": loop = asyncio.get_event_loop() - loop.run_until_complete(main()) \ No newline at end of file + loop.run_until_complete(main()) diff --git a/sdk/contentsafety/azure-ai-contentsafety/samples/sample_manage_blocklist.py b/sdk/contentsafety/azure-ai-contentsafety/samples/sample_manage_blocklist.py index 1e8a108de823..2888cf16578c 100644 --- a/sdk/contentsafety/azure-ai-contentsafety/samples/sample_manage_blocklist.py +++ b/sdk/contentsafety/azure-ai-contentsafety/samples/sample_manage_blocklist.py @@ -6,6 +6,7 @@ # license information. # -------------------------------------------------------------------------- + def create_or_update_text_blocklist(): # [START create_or_update_text_blocklist] @@ -24,7 +25,9 @@ def create_or_update_text_blocklist(): blocklist_description = "Test blocklist management." try: - blocklist = client.create_or_update_text_blocklist(blocklist_name=blocklist_name, resource={"description": blocklist_description}) + blocklist = client.create_or_update_text_blocklist( + blocklist_name=blocklist_name, resource={"description": blocklist_description} + ) if blocklist: print("\nBlocklist created or updated: ") print(f"Name: {blocklist.blocklist_name}, Description: {blocklist.description}") @@ -39,16 +42,14 @@ def create_or_update_text_blocklist(): # [END create_or_update_text_blocklist] + def add_block_items(): # [START add_block_items] import os from azure.ai.contentsafety import ContentSafetyClient from azure.core.credentials import AzureKeyCredential - from azure.ai.contentsafety.models import ( - TextBlockItemInfo, - AddBlockItemsOptions - ) + from azure.ai.contentsafety.models import TextBlockItemInfo, AddBlockItemsOptions from azure.core.exceptions import HttpResponseError key = os.environ["CONTENT_SAFETY_KEY"] @@ -70,7 +71,9 @@ def add_block_items(): if result and result.value: print("\nBlock items added: ") for block_item in result.value: - print(f"BlockItemId: {block_item.block_item_id}, Text: {block_item.text}, Description: {block_item.description}") + print( + f"BlockItemId: {block_item.block_item_id}, Text: {block_item.text}, Description: {block_item.description}" + ) except HttpResponseError as e: print("\nAdd block items failed: ") if e.error: @@ -82,6 +85,7 @@ def add_block_items(): # [END add_block_items] + def analyze_text_with_blocklists(): # [START analyze_text_with_blocklists] @@ -102,12 +106,16 @@ def analyze_text_with_blocklists(): try: # After you edit your blocklist, it usually takes effect in 5 minutes, please wait some time before analyzing with blocklist after editing. - analysis_result = client.analyze_text(AnalyzeTextOptions(text=input_text, blocklist_names=[blocklist_name], break_by_blocklists=False)) + analysis_result = client.analyze_text( + AnalyzeTextOptions(text=input_text, blocklist_names=[blocklist_name], break_by_blocklists=False) + ) if analysis_result and analysis_result.blocklists_match_results: print("\nBlocklist match results: ") for match_result in analysis_result.blocklists_match_results: print(f"Block item was hit in text, Offset={match_result.offset}, Length={match_result.length}.") - print(f"BlocklistName: {match_result.blocklist_name}, BlockItemId: {match_result.block_item_id}, BlockItemText: {match_result.block_item_text}") + print( + f"BlocklistName: {match_result.blocklist_name}, BlockItemId: {match_result.block_item_id}, BlockItemText: {match_result.block_item_text}" + ) except HttpResponseError as e: print("\nAnalyze text failed: ") if e.error: @@ -119,6 +127,7 @@ def analyze_text_with_blocklists(): # [END analyze_text_with_blocklists] + def list_text_blocklists(): # [START list_text_blocklists] @@ -150,6 +159,7 @@ def list_text_blocklists(): # [END list_text_blocklists] + def get_text_blocklist(): # [START get_text_blocklist] @@ -182,6 +192,7 @@ def get_text_blocklist(): # [END get_text_blocklist] + def list_block_items(): # [START list_block_items] @@ -203,7 +214,9 @@ def list_block_items(): if block_items: print("\nList block items: ") for block_item in block_items: - print(f"BlockItemId: {block_item.block_item_id}, Text: {block_item.text}, Description: {block_item.description}") + print( + f"BlockItemId: {block_item.block_item_id}, Text: {block_item.text}, Description: {block_item.description}" + ) except HttpResponseError as e: print("\nList block items failed: ") if e.error: @@ -215,6 +228,7 @@ def list_block_items(): # [END list_block_items] + def get_block_item(): # [START get_block_item] @@ -244,12 +258,11 @@ def get_block_item(): block_item_id = add_result.value[0].block_item_id # Get this blockItem by blockItemId - block_item = client.get_text_blocklist_item( - blocklist_name=blocklist_name, - block_item_id= block_item_id - ) + block_item = client.get_text_blocklist_item(blocklist_name=blocklist_name, block_item_id=block_item_id) print("\nGet blockitem: ") - print(f"BlockItemId: {block_item.block_item_id}, Text: {block_item.text}, Description: {block_item.description}") + print( + f"BlockItemId: {block_item.block_item_id}, Text: {block_item.text}, Description: {block_item.description}" + ) except HttpResponseError as e: print("\nGet block item failed: ") if e.error: @@ -261,17 +274,14 @@ def get_block_item(): # [END get_block_item] + def remove_block_items(): # [START remove_block_items] import os from azure.ai.contentsafety import ContentSafetyClient from azure.core.credentials import AzureKeyCredential - from azure.ai.contentsafety.models import ( - TextBlockItemInfo, - AddBlockItemsOptions, - RemoveBlockItemsOptions - ) + from azure.ai.contentsafety.models import TextBlockItemInfo, AddBlockItemsOptions, RemoveBlockItemsOptions from azure.core.exceptions import HttpResponseError key = os.environ["CONTENT_SAFETY_KEY"] @@ -295,8 +305,7 @@ def remove_block_items(): # Remove this blockItem by blockItemId client.remove_block_items( - blocklist_name=blocklist_name, - body=RemoveBlockItemsOptions(block_item_ids=[block_item_id]) + blocklist_name=blocklist_name, body=RemoveBlockItemsOptions(block_item_ids=[block_item_id]) ) print(f"\nRemoved blockItem: {add_result.value[0].block_item_id}") except HttpResponseError as e: @@ -310,6 +319,7 @@ def remove_block_items(): # [END remove_block_items] + def delete_blocklist(): # [START delete_blocklist] @@ -340,6 +350,7 @@ def delete_blocklist(): # [END delete_blocklist] + if __name__ == "__main__": create_or_update_text_blocklist() add_block_items() @@ -349,4 +360,4 @@ def delete_blocklist(): list_block_items() get_block_item() remove_block_items() - delete_blocklist() \ No newline at end of file + delete_blocklist() diff --git a/sdk/contentsafety/azure-ai-contentsafety/setup.py b/sdk/contentsafety/azure-ai-contentsafety/setup.py index 2141e17a7ae0..400df3265fd4 100644 --- a/sdk/contentsafety/azure-ai-contentsafety/setup.py +++ b/sdk/contentsafety/azure-ai-contentsafety/setup.py @@ -13,7 +13,7 @@ PACKAGE_NAME = "azure-ai-contentsafety" -PACKAGE_PPRINT_NAME = "Azure AI Content Safety" +PACKAGE_PPRINT_NAME = "Azure Ai Contentsafety" # a-b-c => a/b/c package_folder_path = PACKAGE_NAME.replace("-", "/") @@ -38,7 +38,7 @@ url="https://github.com/Azure/azure-sdk-for-python/tree/main/sdk", keywords="azure, azure sdk", classifiers=[ - "Development Status :: 4 - Beta", + "Development Status :: 5 - Production/Stable", "Programming Language :: Python", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3", diff --git a/sdk/contentsafety/azure-ai-contentsafety/tests/test_content_safety.py b/sdk/contentsafety/azure-ai-contentsafety/tests/test_content_safety.py index 9c6e83685afa..bb152ddc8c88 100644 --- a/sdk/contentsafety/azure-ai-contentsafety/tests/test_content_safety.py +++ b/sdk/contentsafety/azure-ai-contentsafety/tests/test_content_safety.py @@ -33,7 +33,9 @@ def test_analyze_text(self, content_safety_endpoint, content_safety_key): client = self.create_client(content_safety_endpoint, content_safety_key) assert client is not None - text_path = os.path.abspath(os.path.join(os.path.abspath(__file__), "..", "..", "./samples/sample_data/text.txt")) + text_path = os.path.abspath( + os.path.join(os.path.abspath(__file__), "..", "..", "./samples/sample_data/text.txt") + ) with open(text_path) as f: request = AnalyzeTextOptions(text=f.readline(), categories=[]) response = client.analyze_text(request) @@ -51,7 +53,9 @@ def test_analyze_image(self, content_safety_endpoint, content_safety_key): client = self.create_client(content_safety_endpoint, content_safety_key) assert client is not None - image_path = os.path.abspath(os.path.join(os.path.abspath(__file__), "..", "..", "./samples/sample_data/image.jpg")) + image_path = os.path.abspath( + os.path.join(os.path.abspath(__file__), "..", "..", "./samples/sample_data/image.jpg") + ) with open(image_path, "rb") as file: request = AnalyzeImageOptions(image=ImageData(content=file.read())) response = client.analyze_image(request) diff --git a/sdk/contentsafety/azure-ai-contentsafety/tsp-location.yaml b/sdk/contentsafety/azure-ai-contentsafety/tsp-location.yaml index 03b2e7251c2c..3fa1fd4ead83 100644 --- a/sdk/contentsafety/azure-ai-contentsafety/tsp-location.yaml +++ b/sdk/contentsafety/azure-ai-contentsafety/tsp-location.yaml @@ -1,3 +1,5 @@ +additionalDirectories: [] +commit: ef76b5cbcee099bb7855792bd73173454ac51081 directory: specification/cognitiveservices/ContentSafety -commit: 17c41d0c4a96294bf563b009c9c72093963b529f repo: Azure/azure-rest-api-specs +