From 1bc47254599c7eb0dd1bec8fd497b1cbcc2e012e Mon Sep 17 00:00:00 2001 From: SDKAuto Date: Mon, 12 Feb 2024 08:30:40 +0000 Subject: [PATCH] CodeGen from PR 27353 in Azure/azure-rest-api-specs Merge e54dd6efb59574eaa60af9ec1d4060711a823258 into 87e46c2a10b8a6d54ac45522659ec0bc9197de39 --- .../azure-ai-contentsafety/_meta.json | 6 + .../azure/ai/contentsafety/_client.py | 10 +- .../azure/ai/contentsafety/_configuration.py | 14 +- .../azure/ai/contentsafety/_model_base.py | 98 +- .../contentsafety/_operations/_operations.py | 1090 ++++++++++++++++- .../azure/ai/contentsafety/_serialization.py | 29 +- .../azure/ai/contentsafety/_validation.py | 50 + .../azure/ai/contentsafety/aio/_client.py | 10 +- .../ai/contentsafety/aio/_configuration.py | 14 +- .../aio/_operations/_operations.py | 1012 ++++++++++++++- .../azure/ai/contentsafety/models/__init__.py | 16 + .../azure/ai/contentsafety/models/_models.py | 289 +++++ .../azure-ai-contentsafety/setup.py | 8 +- .../azure-ai-contentsafety/tsp-location.yaml | 5 +- 14 files changed, 2455 insertions(+), 196 deletions(-) create mode 100644 sdk/contentsafety/azure-ai-contentsafety/_meta.json create mode 100644 sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_validation.py diff --git a/sdk/contentsafety/azure-ai-contentsafety/_meta.json b/sdk/contentsafety/azure-ai-contentsafety/_meta.json new file mode 100644 index 000000000000..18a622966ccb --- /dev/null +++ b/sdk/contentsafety/azure-ai-contentsafety/_meta.json @@ -0,0 +1,6 @@ +{ + "commit": "983ef3efcf3bf10eb4867009ee160eec742c2459", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "typespec_src": "specification/cognitiveservices/ContentSafety", + "@azure-tools/typespec-python": "0.20.0" +} \ No newline at end of file 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 e2e1f2849fe6..f6832f3ca921 100644 --- a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_client.py +++ b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_client.py @@ -33,8 +33,9 @@ class ContentSafetyClient(ContentSafetyClientOperationsMixin): # pylint: disabl 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. + :keyword api_version: The API version to use for this operation. Default value is + "2023-10-30-preview". Note that overriding this default value may result in unsupported + behavior. :paramtype api_version: str """ @@ -111,8 +112,9 @@ class BlocklistClient(BlocklistClientOperationsMixin): # pylint: disable=client 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. + :keyword api_version: The API version to use for this operation. Default value is + "2023-10-30-preview". Note that overriding this default value may result in unsupported + behavior. :paramtype api_version: str """ 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 9d9a723f0355..fd4e121e5a1e 100644 --- a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_configuration.py +++ b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_configuration.py @@ -31,13 +31,14 @@ class ContentSafetyClientConfiguration: # pylint: disable=too-many-instance-att 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. + :keyword api_version: The API version to use for this operation. Default value is + "2023-10-30-preview". 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") + api_version: str = kwargs.pop("api_version", "2023-10-30-preview") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") @@ -86,13 +87,14 @@ class BlocklistClientConfiguration: # pylint: disable=too-many-instance-attribu 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. + :keyword api_version: The API version to use for this operation. Default value is + "2023-10-30-preview". 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") + api_version: str = kwargs.pop("api_version", "2023-10-30-preview") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") 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 aec056aba7b7..c0abb9546acf 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 @@ -5,7 +5,6 @@ # license information. # -------------------------------------------------------------------------- # pylint: disable=protected-access, arguments-differ, signature-differs, broad-except -# pyright: reportGeneralTypeIssues=false import calendar import decimal @@ -16,9 +15,10 @@ import re import copy import typing -import email +import email.utils from datetime import datetime, date, time, timedelta, timezone from json import JSONEncoder +from typing_extensions import Self import isodate from azure.core.exceptions import DeserializationError from azure.core import CaseInsensitiveEnumMeta @@ -35,6 +35,7 @@ __all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] TZ_UTC = timezone.utc +_T = typing.TypeVar("_T") def _timedelta_as_isostr(td: timedelta) -> str: @@ -242,7 +243,7 @@ def _deserialize_date(attr: typing.Union[str, date]) -> date: # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. if isinstance(attr, date): return attr - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) + return isodate.parse_date(attr, defaultmonth=None, defaultday=None) # type: ignore def _deserialize_time(attr: typing.Union[str, time]) -> time: @@ -375,8 +376,12 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: except KeyError: return default - @typing.overload # type: ignore - def pop(self, key: str) -> typing.Any: # pylint: disable=no-member + @typing.overload + def pop(self, key: str) -> typing.Any: + ... + + @typing.overload + def pop(self, key: str, default: _T) -> _T: ... @typing.overload @@ -397,8 +402,8 @@ def clear(self) -> None: def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: self._data.update(*args, **kwargs) - @typing.overload # type: ignore - def setdefault(self, key: str) -> typing.Any: + @typing.overload + def setdefault(self, key: str, default: None = None) -> None: ... @typing.overload @@ -462,7 +467,13 @@ def _get_rest_field( def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typing.Any: - return _deserialize(rf._type, value) if (rf and rf._is_model) else _serialize(value, rf._format if rf else None) + if not rf: + return _serialize(value, None) + if rf._is_multipart_file_input: + return value + if rf._is_model: + return _deserialize(rf._type, value) + return _serialize(value, rf._format) class Model(_MyMutableMapping): @@ -498,7 +509,7 @@ def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: def copy(self) -> "Model": return Model(self.__dict__) - def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> "Model": # pylint: disable=unused-argument + def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: # pylint: disable=unused-argument # we know the last three classes in mro are going to be 'Model', 'dict', and 'object' mros = cls.__mro__[:-3][::-1] # ignore model, dict, and object parents, and reverse the mro order attr_to_rest_field: typing.Dict[str, _RestField] = { # map attribute name to rest_field property @@ -540,7 +551,7 @@ def _deserialize(cls, data, exist_discriminators): return cls(data) discriminator = cls._get_discriminator(exist_discriminators) exist_discriminators.append(discriminator) - mapped_cls = cls.__mapping__.get(data.get(discriminator), cls) # pylint: disable=no-member + mapped_cls = cls.__mapping__.get(data.get(discriminator), cls) # pyright: ignore # pylint: disable=no-member if mapped_cls == cls: return cls(data) return mapped_cls._deserialize(data, exist_discriminators) # pylint: disable=protected-access @@ -557,9 +568,16 @@ def as_dict(self, *, exclude_readonly: bool = False) -> typing.Dict[str, typing. if exclude_readonly: readonly_props = [p._rest_name for p in self._attr_to_rest_field.values() if _is_readonly(p)] for k, v in self.items(): - if exclude_readonly and k in readonly_props: # pyright: ignore[reportUnboundVariable] + if exclude_readonly and k in readonly_props: # pyright: ignore continue - result[k] = Model._as_dict_value(v, exclude_readonly=exclude_readonly) + is_multipart_file_input = False + try: + is_multipart_file_input = next( + rf for rf in self._attr_to_rest_field.values() if rf._rest_name == k + )._is_multipart_file_input + except StopIteration: + pass + result[k] = v if is_multipart_file_input else Model._as_dict_value(v, exclude_readonly=exclude_readonly) return result @staticmethod @@ -567,7 +585,7 @@ def _as_dict_value(v: typing.Any, exclude_readonly: bool = False) -> typing.Any: if v is None or isinstance(v, _Null): return None if isinstance(v, (list, tuple, set)): - return [Model._as_dict_value(x, exclude_readonly=exclude_readonly) for x in v] + return type(v)(Model._as_dict_value(x, exclude_readonly=exclude_readonly) for x in v) if isinstance(v, dict): return {dk: Model._as_dict_value(dv, exclude_readonly=exclude_readonly) for dk, dv in v.items()} return v.as_dict(exclude_readonly=exclude_readonly) if hasattr(v, "as_dict") else v @@ -605,29 +623,22 @@ def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj return obj return _deserialize(model_deserializer, obj) - return functools.partial(_deserialize_model, annotation) + return functools.partial(_deserialize_model, annotation) # pyright: ignore except Exception: pass # is it a literal? try: - if sys.version_info >= (3, 8): - from typing import ( - Literal, - ) # pylint: disable=no-name-in-module, ungrouped-imports - else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports - - if annotation.__origin__ == Literal: + if annotation.__origin__ is typing.Literal: # pyright: ignore return None except AttributeError: pass # is it optional? try: - if any(a for a in annotation.__args__ if a == type(None)): + if any(a for a in annotation.__args__ if a == type(None)): # pyright: ignore if_obj_deserializer = _get_deserialize_callable_from_annotation( - next(a for a in annotation.__args__ if a != type(None)), module, rf + next(a for a in annotation.__args__ if a != type(None)), module, rf # pyright: ignore ) def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Callable], obj): @@ -640,7 +651,9 @@ def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Calla pass if getattr(annotation, "__origin__", None) is typing.Union: - deserializers = [_get_deserialize_callable_from_annotation(arg, module, rf) for arg in annotation.__args__] + deserializers = [ + _get_deserialize_callable_from_annotation(arg, module, rf) for arg in annotation.__args__ # pyright: ignore + ] def _deserialize_with_union(deserializers, obj): for deserializer in deserializers: @@ -653,8 +666,10 @@ def _deserialize_with_union(deserializers, obj): return functools.partial(_deserialize_with_union, deserializers) try: - if annotation._name == "Dict": - value_deserializer = _get_deserialize_callable_from_annotation(annotation.__args__[1], module, rf) + if annotation._name == "Dict": # pyright: ignore + value_deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[1], module, rf # pyright: ignore + ) def _deserialize_dict( value_deserializer: typing.Optional[typing.Callable], @@ -671,8 +686,8 @@ def _deserialize_dict( except (AttributeError, IndexError): pass try: - if annotation._name in ["List", "Set", "Tuple", "Sequence"]: - if len(annotation.__args__) > 1: + if annotation._name in ["List", "Set", "Tuple", "Sequence"]: # pyright: ignore + if len(annotation.__args__) > 1: # pyright: ignore def _deserialize_multiple_sequence( entry_deserializers: typing.List[typing.Optional[typing.Callable]], @@ -686,10 +701,13 @@ def _deserialize_multiple_sequence( ) entry_deserializers = [ - _get_deserialize_callable_from_annotation(dt, module, rf) for dt in annotation.__args__ + _get_deserialize_callable_from_annotation(dt, module, rf) + for dt in annotation.__args__ # pyright: ignore ] return functools.partial(_deserialize_multiple_sequence, entry_deserializers) - deserializer = _get_deserialize_callable_from_annotation(annotation.__args__[0], module, rf) + deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[0], module, rf # pyright: ignore + ) def _deserialize_sequence( deserializer: typing.Optional[typing.Callable], @@ -709,7 +727,11 @@ def _deserialize_default( ): if obj is None: return obj - return _deserialize_with_callable(deserializer, obj) + try: + return _deserialize_with_callable(deserializer, obj) + except Exception: + pass + return obj if get_deserializer(annotation, rf): return functools.partial(_deserialize_default, get_deserializer(annotation, rf)) @@ -765,6 +787,7 @@ def __init__( visibility: typing.Optional[typing.List[str]] = None, default: typing.Any = _UNSET, format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, ): self._type = type self._rest_name_input = name @@ -774,6 +797,7 @@ def __init__( self._is_model = False self._default = default self._format = format + self._is_multipart_file_input = is_multipart_file_input @property def _rest_name(self) -> str: @@ -819,8 +843,16 @@ def rest_field( visibility: typing.Optional[typing.List[str]] = None, default: typing.Any = _UNSET, format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, ) -> typing.Any: - return _RestField(name=name, type=type, visibility=visibility, default=default, format=format) + return _RestField( + name=name, + type=type, + visibility=visibility, + default=default, + format=format, + is_multipart_file_input=is_multipart_file_input, + ) def rest_discriminator( 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 175bc5ca04d6..25c67bf57db9 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 @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -29,6 +29,7 @@ from .. import models as _models from .._model_base import SdkJSONEncoder, _deserialize from .._serialization import Serializer +from .._validation import api_version_validation from .._vendor import BlocklistClientMixinABC, ContentSafetyClientMixinABC if sys.version_info >= (3, 9): @@ -48,7 +49,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-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-30-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -70,7 +71,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-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-30-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -87,6 +88,52 @@ 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_detect_text_jailbreak_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 {}) + + 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-30-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/text:detectJailbreak" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # 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) + + +def build_content_safety_detect_text_protected_material_request( # pylint: disable=name-too-long + **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-10-30-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/text:detectProtectedMaterial" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # 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) + + def build_blocklist_add_or_update_blocklist_items_request( # pylint: disable=name-too-long blocklist_name: str, **kwargs: Any ) -> HttpRequest: @@ -94,7 +141,7 @@ def build_blocklist_add_or_update_blocklist_items_request( # pylint: disable=na _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-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-30-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -123,7 +170,7 @@ def build_blocklist_create_or_update_text_blocklist_request( # pylint: disable= _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-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-30-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -150,7 +197,7 @@ def build_blocklist_delete_text_blocklist_request( # pylint: disable=name-too-l ) -> HttpRequest: _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-30-preview")) # Construct URL _url = "/text/blocklists/{blocklistName}" path_format_arguments = { @@ -171,7 +218,7 @@ def build_blocklist_get_text_blocklist_request( # 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-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-30-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -197,7 +244,7 @@ def build_blocklist_get_text_blocklist_item_request( # pylint: disable=name-too _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-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-30-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -224,12 +271,12 @@ def build_blocklist_list_text_blocklist_items_request( # pylint: disable=name-t top: Optional[int] = None, skip: Optional[int] = None, maxpagesize: Optional[int] = None, - **kwargs: Any + **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-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-30-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -259,7 +306,7 @@ def build_blocklist_list_text_blocklists_request(**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-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-30-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -281,7 +328,7 @@ def build_blocklist_remove_blocklist_items_request( # pylint: disable=name-too- _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-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-30-preview")) # Construct URL _url = "/text/blocklists/{blocklistName}:removeBlocklistItems" path_format_arguments = { @@ -305,6 +352,7 @@ class ContentSafetyClientOperationsMixin(ContentSafetyClientMixinABC): def analyze_text( self, options: _models.AnalyzeTextOptions, *, content_type: str = "application/json", **kwargs: Any ) -> _models.AnalyzeTextResult: + # pylint: disable=line-too-long """Analyze Text. A synchronous API for the analysis of potentially harmful text content. Currently, it supports @@ -315,17 +363,84 @@ def analyze_text( :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: AnalyzeTextResult. The AnalyzeTextResult is compatible with MutableMapping :rtype: ~azure.ai.contentsafety.models.AnalyzeTextResult :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + options = { + "text": "str", # The text needs to be analyzed. We support a maximum of 10k + Unicode characters (Unicode code points) in the text of one request. Required. + "blocklistNames": [ + "str" # Optional. The names of blocklists. + ], + "categories": [ + "str" # Optional. The categories will be analyzed. If they are not + assigned, a default set of analysis results for the categories will be + returned. + ], + "haltOnBlocklistHit": bool, # Optional. 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. + "incidents": { + "haltOnIncidentHit": bool, # Optional. When set to true, further + analyses of harmful content will not be performed in cases where incidents + are hit. When set to false, all analyses of harmful content will be + performed, whether or not incidents are hit. + "incidentNames": [ + "str" # Optional. The accept decision made by service. + ] + }, + "outputType": "str" # Optional. 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". + } + + # response body for status code(s): 200 + response == { + "categoriesAnalysis": [ + { + "category": "str", # The text analysis category. Required. + Known values are: "Hate", "SelfHarm", "Sexual", and "Violence". + "severity": 0 # Optional. 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 + "u2018FourSeverityLevels"u2019 or "u2018EightSeverity Levels"u2019, and + the output value can be 0, 2, 4, 6 or 0, 1, 2, 3, 4, 5, 6, or 7. + } + ], + "blocklistsMatch": [ + { + "blocklistItemId": "str", # The ID of the matched item. + Required. + "blocklistItemText": "str", # The content of the matched + item. Required. + "blocklistName": "str" # The name of the matched blocklist. + Required. + } + ], + "citation": [ + "str" # Optional. Chunks in the original text detected as harmful + content. Analysis result and scores are caused by these. + ], + "incidentMatches": [ + { + "incidentName": "str" # The name of the matched incident. + Required. + } + ] + } """ @overload def analyze_text( self, options: JSON, *, content_type: str = "application/json", **kwargs: Any ) -> _models.AnalyzeTextResult: + # pylint: disable=line-too-long """Analyze Text. A synchronous API for the analysis of potentially harmful text content. Currently, it supports @@ -336,17 +451,54 @@ def analyze_text( :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: AnalyzeTextResult. The AnalyzeTextResult is compatible with MutableMapping :rtype: ~azure.ai.contentsafety.models.AnalyzeTextResult :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "categoriesAnalysis": [ + { + "category": "str", # The text analysis category. Required. + Known values are: "Hate", "SelfHarm", "Sexual", and "Violence". + "severity": 0 # Optional. 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 + "u2018FourSeverityLevels"u2019 or "u2018EightSeverity Levels"u2019, and + the output value can be 0, 2, 4, 6 or 0, 1, 2, 3, 4, 5, 6, or 7. + } + ], + "blocklistsMatch": [ + { + "blocklistItemId": "str", # The ID of the matched item. + Required. + "blocklistItemText": "str", # The content of the matched + item. Required. + "blocklistName": "str" # The name of the matched blocklist. + Required. + } + ], + "citation": [ + "str" # Optional. Chunks in the original text detected as harmful + content. Analysis result and scores are caused by these. + ], + "incidentMatches": [ + { + "incidentName": "str" # The name of the matched incident. + Required. + } + ] + } """ @overload def analyze_text( self, options: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> _models.AnalyzeTextResult: + # pylint: disable=line-too-long """Analyze Text. A synchronous API for the analysis of potentially harmful text content. Currently, it supports @@ -357,17 +509,54 @@ def analyze_text( :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: AnalyzeTextResult. The AnalyzeTextResult is compatible with MutableMapping :rtype: ~azure.ai.contentsafety.models.AnalyzeTextResult :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "categoriesAnalysis": [ + { + "category": "str", # The text analysis category. Required. + Known values are: "Hate", "SelfHarm", "Sexual", and "Violence". + "severity": 0 # Optional. 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 + "u2018FourSeverityLevels"u2019 or "u2018EightSeverity Levels"u2019, and + the output value can be 0, 2, 4, 6 or 0, 1, 2, 3, 4, 5, 6, or 7. + } + ], + "blocklistsMatch": [ + { + "blocklistItemId": "str", # The ID of the matched item. + Required. + "blocklistItemText": "str", # The content of the matched + item. Required. + "blocklistName": "str" # The name of the matched blocklist. + Required. + } + ], + "citation": [ + "str" # Optional. Chunks in the original text detected as harmful + content. Analysis result and scores are caused by these. + ], + "incidentMatches": [ + { + "incidentName": "str" # The name of the matched incident. + Required. + } + ] + } """ @distributed_trace def analyze_text( self, options: Union[_models.AnalyzeTextOptions, JSON, IO[bytes]], **kwargs: Any ) -> _models.AnalyzeTextResult: + # pylint: disable=line-too-long """Analyze Text. A synchronous API for the analysis of potentially harmful text content. Currently, it supports @@ -376,14 +565,77 @@ def analyze_text( :param options: The text analysis request. Is one of the following types: AnalyzeTextOptions, JSON, IO[bytes] Required. :type options: ~azure.ai.contentsafety.models.AnalyzeTextOptions or JSON or IO[bytes] - :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: AnalyzeTextResult. The AnalyzeTextResult is compatible with MutableMapping :rtype: ~azure.ai.contentsafety.models.AnalyzeTextResult :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + options = { + "text": "str", # The text needs to be analyzed. We support a maximum of 10k + Unicode characters (Unicode code points) in the text of one request. Required. + "blocklistNames": [ + "str" # Optional. The names of blocklists. + ], + "categories": [ + "str" # Optional. The categories will be analyzed. If they are not + assigned, a default set of analysis results for the categories will be + returned. + ], + "haltOnBlocklistHit": bool, # Optional. 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. + "incidents": { + "haltOnIncidentHit": bool, # Optional. When set to true, further + analyses of harmful content will not be performed in cases where incidents + are hit. When set to false, all analyses of harmful content will be + performed, whether or not incidents are hit. + "incidentNames": [ + "str" # Optional. The accept decision made by service. + ] + }, + "outputType": "str" # Optional. 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". + } + + # response body for status code(s): 200 + response == { + "categoriesAnalysis": [ + { + "category": "str", # The text analysis category. Required. + Known values are: "Hate", "SelfHarm", "Sexual", and "Violence". + "severity": 0 # Optional. 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 + "u2018FourSeverityLevels"u2019 or "u2018EightSeverity Levels"u2019, and + the output value can be 0, 2, 4, 6 or 0, 1, 2, 3, 4, 5, 6, or 7. + } + ], + "blocklistsMatch": [ + { + "blocklistItemId": "str", # The ID of the matched item. + Required. + "blocklistItemText": "str", # The content of the matched + item. Required. + "blocklistName": "str" # The name of the matched blocklist. + Required. + } + ], + "citation": [ + "str" # Optional. Chunks in the original text detected as harmful + content. Analysis result and scores are caused by these. + ], + "incidentMatches": [ + { + "incidentName": "str" # The name of the matched incident. + Required. + } + ] + } """ error_map = { 401: ClientAuthenticationError, @@ -445,6 +697,7 @@ def analyze_text( def analyze_image( self, options: _models.AnalyzeImageOptions, *, content_type: str = "application/json", **kwargs: Any ) -> _models.AnalyzeImageResult: + # pylint: disable=line-too-long """Analyze Image. A synchronous API for the analysis of potentially harmful image content. Currently, it supports @@ -455,17 +708,65 @@ def analyze_image( :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: AnalyzeImageResult. The AnalyzeImageResult is compatible with MutableMapping :rtype: ~azure.ai.contentsafety.models.AnalyzeImageResult :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + options = { + "image": { + "blobUrl": "str", # Optional. The blob url of the image. + "content": bytes("bytes", encoding="utf-8") # Optional. The Base64 + encoding of the image. + }, + "categories": [ + "str" # Optional. The categories will be analyzed. If they are not + assigned, a default set of analysis results for the categories will be + returned. + ], + "incidents": { + "haltOnIncidentHit": bool, # Optional. When set to true, further + analyses of harmful content will not be performed in cases where incidents + are hit. When set to false, all analyses of harmful content will be + performed, whether or not incidents are hit. + "incidentNames": [ + "str" # Optional. The accept decision made by service. + ] + }, + "outputType": "str" # Optional. This refers to the type of image analysis + output. If no value is assigned, the default value will be "FourSeverityLevels". + "FourSeverityLevels" + } + + # response body for status code(s): 200 + response == { + "categoriesAnalysis": [ + { + "category": "str", # The image analysis category. Required. + Known values are: "Hate", "SelfHarm", "Sexual", and "Violence". + "severity": 0 # Optional. 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 + "u2018FourSeverityLevels"u2019, and the output value can be 0, 2, 4, 6. + } + ], + "incidentMatches": [ + { + "incidentName": "str" # The name of the matched incident. + Required. + } + ] + } """ @overload def analyze_image( self, options: JSON, *, content_type: str = "application/json", **kwargs: Any ) -> _models.AnalyzeImageResult: + # pylint: disable=line-too-long """Analyze Image. A synchronous API for the analysis of potentially harmful image content. Currently, it supports @@ -476,17 +777,39 @@ def analyze_image( :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: AnalyzeImageResult. The AnalyzeImageResult is compatible with MutableMapping :rtype: ~azure.ai.contentsafety.models.AnalyzeImageResult :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "categoriesAnalysis": [ + { + "category": "str", # The image analysis category. Required. + Known values are: "Hate", "SelfHarm", "Sexual", and "Violence". + "severity": 0 # Optional. 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 + "u2018FourSeverityLevels"u2019, and the output value can be 0, 2, 4, 6. + } + ], + "incidentMatches": [ + { + "incidentName": "str" # The name of the matched incident. + Required. + } + ] + } """ @overload def analyze_image( self, options: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> _models.AnalyzeImageResult: + # pylint: disable=line-too-long """Analyze Image. A synchronous API for the analysis of potentially harmful image content. Currently, it supports @@ -497,17 +820,39 @@ def analyze_image( :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: AnalyzeImageResult. The AnalyzeImageResult is compatible with MutableMapping :rtype: ~azure.ai.contentsafety.models.AnalyzeImageResult :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "categoriesAnalysis": [ + { + "category": "str", # The image analysis category. Required. + Known values are: "Hate", "SelfHarm", "Sexual", and "Violence". + "severity": 0 # Optional. 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 + "u2018FourSeverityLevels"u2019, and the output value can be 0, 2, 4, 6. + } + ], + "incidentMatches": [ + { + "incidentName": "str" # The name of the matched incident. + Required. + } + ] + } """ @distributed_trace def analyze_image( self, options: Union[_models.AnalyzeImageOptions, JSON, IO[bytes]], **kwargs: Any ) -> _models.AnalyzeImageResult: + # pylint: disable=line-too-long """Analyze Image. A synchronous API for the analysis of potentially harmful image content. Currently, it supports @@ -516,14 +861,58 @@ def analyze_image( :param options: The image analysis request. Is one of the following types: AnalyzeImageOptions, JSON, IO[bytes] Required. :type options: ~azure.ai.contentsafety.models.AnalyzeImageOptions or JSON or IO[bytes] - :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: AnalyzeImageResult. The AnalyzeImageResult is compatible with MutableMapping :rtype: ~azure.ai.contentsafety.models.AnalyzeImageResult :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + options = { + "image": { + "blobUrl": "str", # Optional. The blob url of the image. + "content": bytes("bytes", encoding="utf-8") # Optional. The Base64 + encoding of the image. + }, + "categories": [ + "str" # Optional. The categories will be analyzed. If they are not + assigned, a default set of analysis results for the categories will be + returned. + ], + "incidents": { + "haltOnIncidentHit": bool, # Optional. When set to true, further + analyses of harmful content will not be performed in cases where incidents + are hit. When set to false, all analyses of harmful content will be + performed, whether or not incidents are hit. + "incidentNames": [ + "str" # Optional. The accept decision made by service. + ] + }, + "outputType": "str" # Optional. This refers to the type of image analysis + output. If no value is assigned, the default value will be "FourSeverityLevels". + "FourSeverityLevels" + } + + # response body for status code(s): 200 + response == { + "categoriesAnalysis": [ + { + "category": "str", # The image analysis category. Required. + Known values are: "Hate", "SelfHarm", "Sexual", and "Violence". + "severity": 0 # Optional. 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 + "u2018FourSeverityLevels"u2019, and the output value can be 0, 2, 4, 6. + } + ], + "incidentMatches": [ + { + "incidentName": "str" # The name of the matched incident. + Required. + } + ] + } """ error_map = { 401: ClientAuthenticationError, @@ -581,6 +970,407 @@ def analyze_image( return deserialized # type: ignore + @overload + @api_version_validation( + method_added_on="2023-10-15-preview", + ) + def detect_text_jailbreak( + self, options: _models.AnalyzeTextJailbreakOptions, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AnalyzeTextJailbreakResult: + # pylint: disable=line-too-long + """Analyze Text Jailbreak. + + A synchronous API for the analysis of text jailbreak. + + :param options: The text jailbreak analysis request. Required. + :type options: ~azure.ai.contentsafety.models.AnalyzeTextJailbreakOptions + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: AnalyzeTextJailbreakResult. The AnalyzeTextJailbreakResult is compatible with + MutableMapping + :rtype: ~azure.ai.contentsafety.models.AnalyzeTextJailbreakResult + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + options = { + "text": "str" # The text needs to be analyzed if it attempt to jailbreak. We + support a maximum of 1k Unicode characters (Unicode code points) in the text of + one request. Required. + } + + # response body for status code(s): 200 + response == { + "jailbreakAnalysis": { + "detected": bool # Analysis result for jailbreak. Required. + } + } + """ + + @overload + @api_version_validation( + method_added_on="2023-10-15-preview", + ) + def detect_text_jailbreak( + self, options: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AnalyzeTextJailbreakResult: + """Analyze Text Jailbreak. + + A synchronous API for the analysis of text jailbreak. + + :param options: The text jailbreak 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 + :return: AnalyzeTextJailbreakResult. The AnalyzeTextJailbreakResult is compatible with + MutableMapping + :rtype: ~azure.ai.contentsafety.models.AnalyzeTextJailbreakResult + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "jailbreakAnalysis": { + "detected": bool # Analysis result for jailbreak. Required. + } + } + """ + + @overload + @api_version_validation( + method_added_on="2023-10-15-preview", + ) + def detect_text_jailbreak( + self, options: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AnalyzeTextJailbreakResult: + """Analyze Text Jailbreak. + + A synchronous API for the analysis of text jailbreak. + + :param options: The text jailbreak analysis request. Required. + :type options: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: AnalyzeTextJailbreakResult. The AnalyzeTextJailbreakResult is compatible with + MutableMapping + :rtype: ~azure.ai.contentsafety.models.AnalyzeTextJailbreakResult + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "jailbreakAnalysis": { + "detected": bool # Analysis result for jailbreak. Required. + } + } + """ + + @distributed_trace + @api_version_validation( + method_added_on="2023-10-15-preview", + ) + def detect_text_jailbreak( + self, options: Union[_models.AnalyzeTextJailbreakOptions, JSON, IO[bytes]], **kwargs: Any + ) -> _models.AnalyzeTextJailbreakResult: + # pylint: disable=line-too-long + """Analyze Text Jailbreak. + + A synchronous API for the analysis of text jailbreak. + + :param options: The text jailbreak analysis request. Is one of the following types: + AnalyzeTextJailbreakOptions, JSON, IO[bytes] Required. + :type options: ~azure.ai.contentsafety.models.AnalyzeTextJailbreakOptions or JSON or IO[bytes] + :return: AnalyzeTextJailbreakResult. The AnalyzeTextJailbreakResult is compatible with + MutableMapping + :rtype: ~azure.ai.contentsafety.models.AnalyzeTextJailbreakResult + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + options = { + "text": "str" # The text needs to be analyzed if it attempt to jailbreak. We + support a maximum of 1k Unicode characters (Unicode code points) in the text of + one request. Required. + } + + # response body for status code(s): 200 + response == { + "jailbreakAnalysis": { + "detected": bool # Analysis result for jailbreak. Required. + } + } + """ + 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[_models.AnalyzeTextJailbreakResult] = 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_content_safety_detect_text_jailbreak_request( + 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 [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.AnalyzeTextJailbreakResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + @api_version_validation( + method_added_on="2023-10-15-preview", + ) + def detect_text_protected_material( + self, + options: _models.AnalyzeTextProtectedMaterialOptions, + *, + content_type: str = "application/json", + **kwargs: Any, + ) -> _models.AnalyzeTextProtectedMaterialResult: + # pylint: disable=line-too-long + """Analyze Protected Material. + + A synchronous API for the analysis of protected material. + + :param options: The text protected material analysis request. Required. + :type options: ~azure.ai.contentsafety.models.AnalyzeTextProtectedMaterialOptions + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: AnalyzeTextProtectedMaterialResult. The AnalyzeTextProtectedMaterialResult is + compatible with MutableMapping + :rtype: ~azure.ai.contentsafety.models.AnalyzeTextProtectedMaterialResult + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + options = { + "text": "str" # The text needs to be analyzed. We support a maximum of 1k + Unicode characters (Unicode code points) in the text of one request. Required. + } + + # response body for status code(s): 200 + response == { + "protectedMaterialAnalysis": { + "detected": bool # Analysis result for protected material.. + Required. + } + } + """ + + @overload + @api_version_validation( + method_added_on="2023-10-15-preview", + ) + def detect_text_protected_material( + self, options: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AnalyzeTextProtectedMaterialResult: + """Analyze Protected Material. + + A synchronous API for the analysis of protected material. + + :param options: The text protected material 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 + :return: AnalyzeTextProtectedMaterialResult. The AnalyzeTextProtectedMaterialResult is + compatible with MutableMapping + :rtype: ~azure.ai.contentsafety.models.AnalyzeTextProtectedMaterialResult + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "protectedMaterialAnalysis": { + "detected": bool # Analysis result for protected material.. + Required. + } + } + """ + + @overload + @api_version_validation( + method_added_on="2023-10-15-preview", + ) + def detect_text_protected_material( + self, options: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AnalyzeTextProtectedMaterialResult: + """Analyze Protected Material. + + A synchronous API for the analysis of protected material. + + :param options: The text protected material analysis request. Required. + :type options: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: AnalyzeTextProtectedMaterialResult. The AnalyzeTextProtectedMaterialResult is + compatible with MutableMapping + :rtype: ~azure.ai.contentsafety.models.AnalyzeTextProtectedMaterialResult + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "protectedMaterialAnalysis": { + "detected": bool # Analysis result for protected material.. + Required. + } + } + """ + + @distributed_trace + @api_version_validation( + method_added_on="2023-10-15-preview", + ) + def detect_text_protected_material( + self, options: Union[_models.AnalyzeTextProtectedMaterialOptions, JSON, IO[bytes]], **kwargs: Any + ) -> _models.AnalyzeTextProtectedMaterialResult: + # pylint: disable=line-too-long + """Analyze Protected Material. + + A synchronous API for the analysis of protected material. + + :param options: The text protected material analysis request. Is one of the following types: + AnalyzeTextProtectedMaterialOptions, JSON, IO[bytes] Required. + :type options: ~azure.ai.contentsafety.models.AnalyzeTextProtectedMaterialOptions or JSON or + IO[bytes] + :return: AnalyzeTextProtectedMaterialResult. The AnalyzeTextProtectedMaterialResult is + compatible with MutableMapping + :rtype: ~azure.ai.contentsafety.models.AnalyzeTextProtectedMaterialResult + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + options = { + "text": "str" # The text needs to be analyzed. We support a maximum of 1k + Unicode characters (Unicode code points) in the text of one request. Required. + } + + # response body for status code(s): 200 + response == { + "protectedMaterialAnalysis": { + "detected": bool # Analysis result for protected material.. + Required. + } + } + """ + 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[_models.AnalyzeTextProtectedMaterialResult] = 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_content_safety_detect_text_protected_material_request( + 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 [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.AnalyzeTextProtectedMaterialResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + class BlocklistClientOperationsMixin(BlocklistClientMixinABC): @overload @@ -590,7 +1380,7 @@ def add_or_update_blocklist_items( options: _models.AddOrUpdateTextBlocklistItemsOptions, *, content_type: str = "application/json", - **kwargs: Any + **kwargs: Any, ) -> _models.AddOrUpdateTextBlocklistItemsResult: """Add or update BlocklistItems To Text Blocklist. @@ -604,12 +1394,37 @@ def add_or_update_blocklist_items( :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: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + options = { + "blocklistItems": [ + { + "blocklistItemId": "str", # The service will generate a + BlocklistItemId, which will be a UUID. Required. + "text": "str", # BlocklistItem content. Required. + "description": "str" # Optional. BlocklistItem description. + } + ] + } + + # response body for status code(s): 200 + response == { + "blocklistItems": [ + { + "blocklistItemId": "str", # The service will generate a + BlocklistItemId, which will be a UUID. Required. + "text": "str", # BlocklistItem content. Required. + "description": "str" # Optional. BlocklistItem description. + } + ] + } """ @overload @@ -628,12 +1443,25 @@ def add_or_update_blocklist_items( :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: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "blocklistItems": [ + { + "blocklistItemId": "str", # The service will generate a + BlocklistItemId, which will be a UUID. Required. + "text": "str", # BlocklistItem content. Required. + "description": "str" # Optional. BlocklistItem description. + } + ] + } """ @overload @@ -652,12 +1480,25 @@ def add_or_update_blocklist_items( :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: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "blocklistItems": [ + { + "blocklistItemId": "str", # The service will generate a + BlocklistItemId, which will be a UUID. Required. + "text": "str", # BlocklistItem content. Required. + "description": "str" # Optional. BlocklistItem description. + } + ] + } """ @distributed_trace @@ -665,7 +1506,7 @@ def add_or_update_blocklist_items( self, blocklist_name: str, options: Union[_models.AddOrUpdateTextBlocklistItemsOptions, JSON, IO[bytes]], - **kwargs: Any + **kwargs: Any, ) -> _models.AddOrUpdateTextBlocklistItemsResult: """Add or update BlocklistItems To Text Blocklist. @@ -678,15 +1519,37 @@ def add_or_update_blocklist_items( AddOrUpdateTextBlocklistItemsOptions, JSON, IO[bytes] Required. :type options: ~azure.ai.contentsafety.models.AddOrUpdateTextBlocklistItemsOptions or JSON or IO[bytes] - :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: AddOrUpdateTextBlocklistItemsResult. The AddOrUpdateTextBlocklistItemsResult is compatible with MutableMapping :rtype: ~azure.ai.contentsafety.models.AddOrUpdateTextBlocklistItemsResult :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + options = { + "blocklistItems": [ + { + "blocklistItemId": "str", # The service will generate a + BlocklistItemId, which will be a UUID. Required. + "text": "str", # BlocklistItem content. Required. + "description": "str" # Optional. BlocklistItem description. + } + ] + } + + # response body for status code(s): 200 + response == { + "blocklistItems": [ + { + "blocklistItemId": "str", # The service will generate a + BlocklistItemId, which will be a UUID. Required. + "text": "str", # BlocklistItem content. Required. + "description": "str" # Optional. BlocklistItem description. + } + ] + } """ error_map = { 401: ClientAuthenticationError, @@ -752,7 +1615,7 @@ def create_or_update_text_blocklist( options: _models.TextBlocklist, *, content_type: str = "application/merge-patch+json", - **kwargs: Any + **kwargs: Any, ) -> _models.TextBlocklist: """Create Or Update Text Blocklist. @@ -765,11 +1628,24 @@ def create_or_update_text_blocklist( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+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: TextBlocklist. The TextBlocklist is compatible with MutableMapping :rtype: ~azure.ai.contentsafety.models.TextBlocklist :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + options = { + "blocklistName": "str", # Text blocklist name. Required. + "description": "str" # Optional. Text blocklist description. + } + + # response body for status code(s): 201, 200 + response == { + "blocklistName": "str", # Text blocklist name. Required. + "description": "str" # Optional. Text blocklist description. + } """ @overload @@ -787,11 +1663,18 @@ def create_or_update_text_blocklist( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+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: TextBlocklist. The TextBlocklist is compatible with MutableMapping :rtype: ~azure.ai.contentsafety.models.TextBlocklist :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 201, 200 + response == { + "blocklistName": "str", # Text blocklist name. Required. + "description": "str" # Optional. Text blocklist description. + } """ @overload @@ -801,7 +1684,7 @@ def create_or_update_text_blocklist( options: IO[bytes], *, content_type: str = "application/merge-patch+json", - **kwargs: Any + **kwargs: Any, ) -> _models.TextBlocklist: """Create Or Update Text Blocklist. @@ -814,11 +1697,18 @@ def create_or_update_text_blocklist( :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/merge-patch+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: TextBlocklist. The TextBlocklist is compatible with MutableMapping :rtype: ~azure.ai.contentsafety.models.TextBlocklist :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 201, 200 + response == { + "blocklistName": "str", # Text blocklist name. Required. + "description": "str" # Optional. Text blocklist description. + } """ @distributed_trace @@ -834,13 +1724,24 @@ def create_or_update_text_blocklist( :param options: The resource instance. Is one of the following types: TextBlocklist, JSON, IO[bytes] Required. :type options: ~azure.ai.contentsafety.models.TextBlocklist or JSON or IO[bytes] - :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 - 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: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + options = { + "blocklistName": "str", # Text blocklist name. Required. + "description": "str" # Optional. Text blocklist description. + } + + # response body for status code(s): 201, 200 + response == { + "blocklistName": "str", # Text blocklist name. Required. + "description": "str" # Optional. Text blocklist description. + } """ error_map = { 401: ClientAuthenticationError, @@ -968,11 +1869,18 @@ def get_text_blocklist(self, blocklist_name: str, **kwargs: Any) -> _models.Text :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: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "blocklistName": "str", # Text blocklist name. Required. + "description": "str" # Optional. Text blocklist description. + } """ error_map = { 401: ClientAuthenticationError, @@ -1034,11 +1942,20 @@ def get_text_blocklist_item( :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: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "blocklistItemId": "str", # The service will generate a BlocklistItemId, + which will be a UUID. Required. + "text": "str", # BlocklistItem content. Required. + "description": "str" # Optional. BlocklistItem description. + } """ error_map = { 401: ClientAuthenticationError, @@ -1105,6 +2022,17 @@ def list_text_blocklist_items( :return: An iterator like instance of TextBlocklistItem :rtype: ~azure.core.paging.ItemPaged[~azure.ai.contentsafety.models.TextBlocklistItem] :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "blocklistItemId": "str", # The service will generate a BlocklistItemId, + which will be a UUID. Required. + "text": "str", # BlocklistItem content. Required. + "description": "str" # Optional. BlocklistItem description. + } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} @@ -1196,6 +2124,15 @@ def list_text_blocklists(self, **kwargs: Any) -> Iterable["_models.TextBlocklist :return: An iterator like instance of TextBlocklist :rtype: ~azure.core.paging.ItemPaged[~azure.ai.contentsafety.models.TextBlocklist] :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "blocklistName": "str", # Text blocklist name. Required. + "description": "str" # Optional. Text blocklist description. + } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} @@ -1280,7 +2217,7 @@ def remove_blocklist_items( # pylint: disable=inconsistent-return-statements options: _models.RemoveTextBlocklistItemsOptions, *, content_type: str = "application/json", - **kwargs: Any + **kwargs: Any, ) -> None: """Remove BlocklistItems From Text Blocklist. @@ -1297,6 +2234,16 @@ def remove_blocklist_items( # pylint: disable=inconsistent-return-statements :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + options = { + "blocklistItemIds": [ + "str" # Array of blocklistItemIds to remove. Required. + ] + } """ @overload @@ -1346,7 +2293,7 @@ def remove_blocklist_items( # pylint: disable=inconsistent-return-statements self, blocklist_name: str, options: Union[_models.RemoveTextBlocklistItemsOptions, JSON, IO[bytes]], - **kwargs: Any + **kwargs: Any, ) -> None: """Remove BlocklistItems From Text Blocklist. @@ -1359,12 +2306,19 @@ def remove_blocklist_items( # pylint: disable=inconsistent-return-statements RemoveTextBlocklistItemsOptions, JSON, IO[bytes] Required. :type options: ~azure.ai.contentsafety.models.RemoveTextBlocklistItemsOptions or JSON or IO[bytes] - :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: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + options = { + "blocklistItemIds": [ + "str" # Array of blocklistItemIds to remove. Required. + ] + } """ error_map = { 401: ClientAuthenticationError, 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 baa661cb82d2..930e875563c6 100644 --- a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_serialization.py +++ b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_serialization.py @@ -170,13 +170,6 @@ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], return None -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str - unicode_str = str - _LOGGER = logging.getLogger(__name__) try: @@ -545,7 +538,7 @@ class Serializer(object): "multiple": lambda x, y: x % y != 0, } - def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): + def __init__(self, classes: Optional[Mapping[str, type]] = None): self.serialize_type = { "iso-8601": Serializer.serialize_iso, "rfc-1123": Serializer.serialize_rfc, @@ -561,7 +554,7 @@ def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): "[]": self.serialize_iter, "{}": self.serialize_dict, } - self.dependencies: Dict[str, Type[ModelType]] = dict(classes) if classes else {} + self.dependencies: Dict[str, type] = dict(classes) if classes else {} self.key_transformer = full_restapi_key_transformer self.client_side_validation = True @@ -649,7 +642,7 @@ def _serialize(self, target_obj, data_type=None, **kwargs): else: # That's a basic type # Integrate namespace if necessary local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) + local_node.text = str(new_attr) serialized.append(local_node) # type: ignore else: # JSON for k in reversed(keys): # type: ignore @@ -994,7 +987,7 @@ def serialize_object(self, attr, **kwargs): return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) if obj_type is _long_type: return self.serialize_long(attr) - if obj_type is unicode_str: + if obj_type is str: return self.serialize_unicode(attr) if obj_type is datetime.datetime: return self.serialize_iso(attr) @@ -1370,7 +1363,7 @@ class Deserializer(object): 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}]?") - def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): + def __init__(self, classes: Optional[Mapping[str, type]] = None): self.deserialize_type = { "iso-8601": Deserializer.deserialize_iso, "rfc-1123": Deserializer.deserialize_rfc, @@ -1390,7 +1383,7 @@ def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): "duration": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } - self.dependencies: Dict[str, Type[ModelType]] = dict(classes) if classes else {} + self.dependencies: Dict[str, type] = dict(classes) if classes else {} self.key_extractors = [rest_key_extractor, xml_key_extractor] # Additional properties only works if the "rest_key_extractor" is used to # extract the keys. Making it to work whatever the key extractor is too much @@ -1443,7 +1436,7 @@ def _deserialize(self, target_obj, data): response, class_name = self._classify_target(target_obj, data) - if isinstance(response, basestring): + if isinstance(response, str): return self.deserialize_data(data, response) elif isinstance(response, type) and issubclass(response, Enum): return self.deserialize_enum(data, response) @@ -1514,7 +1507,7 @@ def _classify_target(self, target, data): if target is None: return None, None - if isinstance(target, basestring): + if isinstance(target, str): try: target = self.dependencies[target] except KeyError: @@ -1577,7 +1570,7 @@ def _unpack_content(raw_data, content_type=None): if hasattr(raw_data, "_content_consumed"): return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): + if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore return raw_data @@ -1699,7 +1692,7 @@ def deserialize_object(self, attr, **kwargs): if isinstance(attr, ET.Element): # Do no recurse on XML, just return the tree as-is return attr - if isinstance(attr, basestring): + if isinstance(attr, str): return self.deserialize_basic(attr, "str") obj_type = type(attr) if obj_type in self.basic_types: @@ -1756,7 +1749,7 @@ def deserialize_basic(self, attr, data_type): if data_type == "bool": if attr in [True, False, 1, 0]: return bool(attr) - elif isinstance(attr, basestring): + elif isinstance(attr, str): if attr.lower() in ["true", "1"]: return True elif attr.lower() in ["false", "0"]: diff --git a/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_validation.py b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_validation.py new file mode 100644 index 000000000000..752b2822f9d3 --- /dev/null +++ b/sdk/contentsafety/azure-ai-contentsafety/azure/ai/contentsafety/_validation.py @@ -0,0 +1,50 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools + + +def api_version_validation(**kwargs): + params_added_on = kwargs.pop("params_added_on", {}) + method_added_on = kwargs.pop("method_added_on", "") + + def decorator(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + try: + # this assumes the client has an _api_version attribute + client = args[0] + client_api_version = client._config.api_version # pylint: disable=protected-access + except AttributeError: + return func(*args, **kwargs) + + if method_added_on > client_api_version: + raise ValueError( + f"'{func.__name__}' is not available in API version " + f"{client_api_version}. Pass service API version {method_added_on} or newer to your client." + ) + + unsupported = { + parameter: api_version + for api_version, parameters in params_added_on.items() + for parameter in parameters + if parameter in kwargs and api_version > client_api_version + } + if unsupported: + raise ValueError( + "".join( + [ + f"'{param}' is not available in API version {client_api_version}. " + f"Use service API version {version} or newer.\n" + for param, version in unsupported.items() + ] + ) + ) + return func(*args, **kwargs) + + return wrapper + + return decorator 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 5b3f2b75f678..8ec81206db1e 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 @@ -33,8 +33,9 @@ class ContentSafetyClient(ContentSafetyClientOperationsMixin): # pylint: disabl 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. + :keyword api_version: The API version to use for this operation. Default value is + "2023-10-30-preview". Note that overriding this default value may result in unsupported + behavior. :paramtype api_version: str """ @@ -115,8 +116,9 @@ class BlocklistClient(BlocklistClientOperationsMixin): # pylint: disable=client 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. + :keyword api_version: The API version to use for this operation. Default value is + "2023-10-30-preview". Note that overriding this default value may result in unsupported + behavior. :paramtype api_version: str """ 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 c19698582c6d..28e33ed24651 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 @@ -31,15 +31,16 @@ class ContentSafetyClientConfiguration: # pylint: disable=too-many-instance-att 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. + :keyword api_version: The API version to use for this operation. Default value is + "2023-10-30-preview". 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") + api_version: str = kwargs.pop("api_version", "2023-10-30-preview") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") @@ -88,15 +89,16 @@ class BlocklistClientConfiguration: # pylint: disable=too-many-instance-attribu 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. + :keyword api_version: The API version to use for this operation. Default value is + "2023-10-30-preview". 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") + api_version: str = kwargs.pop("api_version", "2023-10-30-preview") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") 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 51040e157e2b..036bfc3a55f5 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 @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -40,7 +40,10 @@ build_blocklist_remove_blocklist_items_request, build_content_safety_analyze_image_request, build_content_safety_analyze_text_request, + build_content_safety_detect_text_jailbreak_request, + build_content_safety_detect_text_protected_material_request, ) +from ..._validation import api_version_validation from .._vendor import BlocklistClientMixinABC, ContentSafetyClientMixinABC if sys.version_info >= (3, 9): @@ -57,6 +60,7 @@ class ContentSafetyClientOperationsMixin(ContentSafetyClientMixinABC): async def analyze_text( self, options: _models.AnalyzeTextOptions, *, content_type: str = "application/json", **kwargs: Any ) -> _models.AnalyzeTextResult: + # pylint: disable=line-too-long """Analyze Text. A synchronous API for the analysis of potentially harmful text content. Currently, it supports @@ -67,17 +71,84 @@ async def analyze_text( :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: AnalyzeTextResult. The AnalyzeTextResult is compatible with MutableMapping :rtype: ~azure.ai.contentsafety.models.AnalyzeTextResult :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + options = { + "text": "str", # The text needs to be analyzed. We support a maximum of 10k + Unicode characters (Unicode code points) in the text of one request. Required. + "blocklistNames": [ + "str" # Optional. The names of blocklists. + ], + "categories": [ + "str" # Optional. The categories will be analyzed. If they are not + assigned, a default set of analysis results for the categories will be + returned. + ], + "haltOnBlocklistHit": bool, # Optional. 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. + "incidents": { + "haltOnIncidentHit": bool, # Optional. When set to true, further + analyses of harmful content will not be performed in cases where incidents + are hit. When set to false, all analyses of harmful content will be + performed, whether or not incidents are hit. + "incidentNames": [ + "str" # Optional. The accept decision made by service. + ] + }, + "outputType": "str" # Optional. 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". + } + + # response body for status code(s): 200 + response == { + "categoriesAnalysis": [ + { + "category": "str", # The text analysis category. Required. + Known values are: "Hate", "SelfHarm", "Sexual", and "Violence". + "severity": 0 # Optional. 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 + "u2018FourSeverityLevels"u2019 or "u2018EightSeverity Levels"u2019, and + the output value can be 0, 2, 4, 6 or 0, 1, 2, 3, 4, 5, 6, or 7. + } + ], + "blocklistsMatch": [ + { + "blocklistItemId": "str", # The ID of the matched item. + Required. + "blocklistItemText": "str", # The content of the matched + item. Required. + "blocklistName": "str" # The name of the matched blocklist. + Required. + } + ], + "citation": [ + "str" # Optional. Chunks in the original text detected as harmful + content. Analysis result and scores are caused by these. + ], + "incidentMatches": [ + { + "incidentName": "str" # The name of the matched incident. + Required. + } + ] + } """ @overload async def analyze_text( self, options: JSON, *, content_type: str = "application/json", **kwargs: Any ) -> _models.AnalyzeTextResult: + # pylint: disable=line-too-long """Analyze Text. A synchronous API for the analysis of potentially harmful text content. Currently, it supports @@ -88,17 +159,54 @@ async def analyze_text( :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: AnalyzeTextResult. The AnalyzeTextResult is compatible with MutableMapping :rtype: ~azure.ai.contentsafety.models.AnalyzeTextResult :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "categoriesAnalysis": [ + { + "category": "str", # The text analysis category. Required. + Known values are: "Hate", "SelfHarm", "Sexual", and "Violence". + "severity": 0 # Optional. 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 + "u2018FourSeverityLevels"u2019 or "u2018EightSeverity Levels"u2019, and + the output value can be 0, 2, 4, 6 or 0, 1, 2, 3, 4, 5, 6, or 7. + } + ], + "blocklistsMatch": [ + { + "blocklistItemId": "str", # The ID of the matched item. + Required. + "blocklistItemText": "str", # The content of the matched + item. Required. + "blocklistName": "str" # The name of the matched blocklist. + Required. + } + ], + "citation": [ + "str" # Optional. Chunks in the original text detected as harmful + content. Analysis result and scores are caused by these. + ], + "incidentMatches": [ + { + "incidentName": "str" # The name of the matched incident. + Required. + } + ] + } """ @overload async def analyze_text( self, options: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> _models.AnalyzeTextResult: + # pylint: disable=line-too-long """Analyze Text. A synchronous API for the analysis of potentially harmful text content. Currently, it supports @@ -109,17 +217,54 @@ async def analyze_text( :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: AnalyzeTextResult. The AnalyzeTextResult is compatible with MutableMapping :rtype: ~azure.ai.contentsafety.models.AnalyzeTextResult :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "categoriesAnalysis": [ + { + "category": "str", # The text analysis category. Required. + Known values are: "Hate", "SelfHarm", "Sexual", and "Violence". + "severity": 0 # Optional. 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 + "u2018FourSeverityLevels"u2019 or "u2018EightSeverity Levels"u2019, and + the output value can be 0, 2, 4, 6 or 0, 1, 2, 3, 4, 5, 6, or 7. + } + ], + "blocklistsMatch": [ + { + "blocklistItemId": "str", # The ID of the matched item. + Required. + "blocklistItemText": "str", # The content of the matched + item. Required. + "blocklistName": "str" # The name of the matched blocklist. + Required. + } + ], + "citation": [ + "str" # Optional. Chunks in the original text detected as harmful + content. Analysis result and scores are caused by these. + ], + "incidentMatches": [ + { + "incidentName": "str" # The name of the matched incident. + Required. + } + ] + } """ @distributed_trace_async async def analyze_text( self, options: Union[_models.AnalyzeTextOptions, JSON, IO[bytes]], **kwargs: Any ) -> _models.AnalyzeTextResult: + # pylint: disable=line-too-long """Analyze Text. A synchronous API for the analysis of potentially harmful text content. Currently, it supports @@ -128,14 +273,77 @@ async def analyze_text( :param options: The text analysis request. Is one of the following types: AnalyzeTextOptions, JSON, IO[bytes] Required. :type options: ~azure.ai.contentsafety.models.AnalyzeTextOptions or JSON or IO[bytes] - :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: AnalyzeTextResult. The AnalyzeTextResult is compatible with MutableMapping :rtype: ~azure.ai.contentsafety.models.AnalyzeTextResult :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + options = { + "text": "str", # The text needs to be analyzed. We support a maximum of 10k + Unicode characters (Unicode code points) in the text of one request. Required. + "blocklistNames": [ + "str" # Optional. The names of blocklists. + ], + "categories": [ + "str" # Optional. The categories will be analyzed. If they are not + assigned, a default set of analysis results for the categories will be + returned. + ], + "haltOnBlocklistHit": bool, # Optional. 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. + "incidents": { + "haltOnIncidentHit": bool, # Optional. When set to true, further + analyses of harmful content will not be performed in cases where incidents + are hit. When set to false, all analyses of harmful content will be + performed, whether or not incidents are hit. + "incidentNames": [ + "str" # Optional. The accept decision made by service. + ] + }, + "outputType": "str" # Optional. 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". + } + + # response body for status code(s): 200 + response == { + "categoriesAnalysis": [ + { + "category": "str", # The text analysis category. Required. + Known values are: "Hate", "SelfHarm", "Sexual", and "Violence". + "severity": 0 # Optional. 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 + "u2018FourSeverityLevels"u2019 or "u2018EightSeverity Levels"u2019, and + the output value can be 0, 2, 4, 6 or 0, 1, 2, 3, 4, 5, 6, or 7. + } + ], + "blocklistsMatch": [ + { + "blocklistItemId": "str", # The ID of the matched item. + Required. + "blocklistItemText": "str", # The content of the matched + item. Required. + "blocklistName": "str" # The name of the matched blocklist. + Required. + } + ], + "citation": [ + "str" # Optional. Chunks in the original text detected as harmful + content. Analysis result and scores are caused by these. + ], + "incidentMatches": [ + { + "incidentName": "str" # The name of the matched incident. + Required. + } + ] + } """ error_map = { 401: ClientAuthenticationError, @@ -197,6 +405,7 @@ async def analyze_text( async def analyze_image( self, options: _models.AnalyzeImageOptions, *, content_type: str = "application/json", **kwargs: Any ) -> _models.AnalyzeImageResult: + # pylint: disable=line-too-long """Analyze Image. A synchronous API for the analysis of potentially harmful image content. Currently, it supports @@ -207,17 +416,65 @@ async def analyze_image( :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: AnalyzeImageResult. The AnalyzeImageResult is compatible with MutableMapping :rtype: ~azure.ai.contentsafety.models.AnalyzeImageResult :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + options = { + "image": { + "blobUrl": "str", # Optional. The blob url of the image. + "content": bytes("bytes", encoding="utf-8") # Optional. The Base64 + encoding of the image. + }, + "categories": [ + "str" # Optional. The categories will be analyzed. If they are not + assigned, a default set of analysis results for the categories will be + returned. + ], + "incidents": { + "haltOnIncidentHit": bool, # Optional. When set to true, further + analyses of harmful content will not be performed in cases where incidents + are hit. When set to false, all analyses of harmful content will be + performed, whether or not incidents are hit. + "incidentNames": [ + "str" # Optional. The accept decision made by service. + ] + }, + "outputType": "str" # Optional. This refers to the type of image analysis + output. If no value is assigned, the default value will be "FourSeverityLevels". + "FourSeverityLevels" + } + + # response body for status code(s): 200 + response == { + "categoriesAnalysis": [ + { + "category": "str", # The image analysis category. Required. + Known values are: "Hate", "SelfHarm", "Sexual", and "Violence". + "severity": 0 # Optional. 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 + "u2018FourSeverityLevels"u2019, and the output value can be 0, 2, 4, 6. + } + ], + "incidentMatches": [ + { + "incidentName": "str" # The name of the matched incident. + Required. + } + ] + } """ @overload async def analyze_image( self, options: JSON, *, content_type: str = "application/json", **kwargs: Any ) -> _models.AnalyzeImageResult: + # pylint: disable=line-too-long """Analyze Image. A synchronous API for the analysis of potentially harmful image content. Currently, it supports @@ -228,17 +485,39 @@ async def analyze_image( :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: AnalyzeImageResult. The AnalyzeImageResult is compatible with MutableMapping :rtype: ~azure.ai.contentsafety.models.AnalyzeImageResult :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "categoriesAnalysis": [ + { + "category": "str", # The image analysis category. Required. + Known values are: "Hate", "SelfHarm", "Sexual", and "Violence". + "severity": 0 # Optional. 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 + "u2018FourSeverityLevels"u2019, and the output value can be 0, 2, 4, 6. + } + ], + "incidentMatches": [ + { + "incidentName": "str" # The name of the matched incident. + Required. + } + ] + } """ @overload async def analyze_image( self, options: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> _models.AnalyzeImageResult: + # pylint: disable=line-too-long """Analyze Image. A synchronous API for the analysis of potentially harmful image content. Currently, it supports @@ -249,17 +528,39 @@ async def analyze_image( :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: AnalyzeImageResult. The AnalyzeImageResult is compatible with MutableMapping :rtype: ~azure.ai.contentsafety.models.AnalyzeImageResult :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "categoriesAnalysis": [ + { + "category": "str", # The image analysis category. Required. + Known values are: "Hate", "SelfHarm", "Sexual", and "Violence". + "severity": 0 # Optional. 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 + "u2018FourSeverityLevels"u2019, and the output value can be 0, 2, 4, 6. + } + ], + "incidentMatches": [ + { + "incidentName": "str" # The name of the matched incident. + Required. + } + ] + } """ @distributed_trace_async async def analyze_image( self, options: Union[_models.AnalyzeImageOptions, JSON, IO[bytes]], **kwargs: Any ) -> _models.AnalyzeImageResult: + # pylint: disable=line-too-long """Analyze Image. A synchronous API for the analysis of potentially harmful image content. Currently, it supports @@ -268,14 +569,58 @@ async def analyze_image( :param options: The image analysis request. Is one of the following types: AnalyzeImageOptions, JSON, IO[bytes] Required. :type options: ~azure.ai.contentsafety.models.AnalyzeImageOptions or JSON or IO[bytes] - :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: AnalyzeImageResult. The AnalyzeImageResult is compatible with MutableMapping :rtype: ~azure.ai.contentsafety.models.AnalyzeImageResult :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + options = { + "image": { + "blobUrl": "str", # Optional. The blob url of the image. + "content": bytes("bytes", encoding="utf-8") # Optional. The Base64 + encoding of the image. + }, + "categories": [ + "str" # Optional. The categories will be analyzed. If they are not + assigned, a default set of analysis results for the categories will be + returned. + ], + "incidents": { + "haltOnIncidentHit": bool, # Optional. When set to true, further + analyses of harmful content will not be performed in cases where incidents + are hit. When set to false, all analyses of harmful content will be + performed, whether or not incidents are hit. + "incidentNames": [ + "str" # Optional. The accept decision made by service. + ] + }, + "outputType": "str" # Optional. This refers to the type of image analysis + output. If no value is assigned, the default value will be "FourSeverityLevels". + "FourSeverityLevels" + } + + # response body for status code(s): 200 + response == { + "categoriesAnalysis": [ + { + "category": "str", # The image analysis category. Required. + Known values are: "Hate", "SelfHarm", "Sexual", and "Violence". + "severity": 0 # Optional. 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 + "u2018FourSeverityLevels"u2019, and the output value can be 0, 2, 4, 6. + } + ], + "incidentMatches": [ + { + "incidentName": "str" # The name of the matched incident. + Required. + } + ] + } """ error_map = { 401: ClientAuthenticationError, @@ -333,6 +678,407 @@ async def analyze_image( return deserialized # type: ignore + @overload + @api_version_validation( + method_added_on="2023-10-15-preview", + ) + async def detect_text_jailbreak( + self, options: _models.AnalyzeTextJailbreakOptions, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AnalyzeTextJailbreakResult: + # pylint: disable=line-too-long + """Analyze Text Jailbreak. + + A synchronous API for the analysis of text jailbreak. + + :param options: The text jailbreak analysis request. Required. + :type options: ~azure.ai.contentsafety.models.AnalyzeTextJailbreakOptions + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: AnalyzeTextJailbreakResult. The AnalyzeTextJailbreakResult is compatible with + MutableMapping + :rtype: ~azure.ai.contentsafety.models.AnalyzeTextJailbreakResult + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + options = { + "text": "str" # The text needs to be analyzed if it attempt to jailbreak. We + support a maximum of 1k Unicode characters (Unicode code points) in the text of + one request. Required. + } + + # response body for status code(s): 200 + response == { + "jailbreakAnalysis": { + "detected": bool # Analysis result for jailbreak. Required. + } + } + """ + + @overload + @api_version_validation( + method_added_on="2023-10-15-preview", + ) + async def detect_text_jailbreak( + self, options: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AnalyzeTextJailbreakResult: + """Analyze Text Jailbreak. + + A synchronous API for the analysis of text jailbreak. + + :param options: The text jailbreak 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 + :return: AnalyzeTextJailbreakResult. The AnalyzeTextJailbreakResult is compatible with + MutableMapping + :rtype: ~azure.ai.contentsafety.models.AnalyzeTextJailbreakResult + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "jailbreakAnalysis": { + "detected": bool # Analysis result for jailbreak. Required. + } + } + """ + + @overload + @api_version_validation( + method_added_on="2023-10-15-preview", + ) + async def detect_text_jailbreak( + self, options: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AnalyzeTextJailbreakResult: + """Analyze Text Jailbreak. + + A synchronous API for the analysis of text jailbreak. + + :param options: The text jailbreak analysis request. Required. + :type options: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: AnalyzeTextJailbreakResult. The AnalyzeTextJailbreakResult is compatible with + MutableMapping + :rtype: ~azure.ai.contentsafety.models.AnalyzeTextJailbreakResult + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "jailbreakAnalysis": { + "detected": bool # Analysis result for jailbreak. Required. + } + } + """ + + @distributed_trace_async + @api_version_validation( + method_added_on="2023-10-15-preview", + ) + async def detect_text_jailbreak( + self, options: Union[_models.AnalyzeTextJailbreakOptions, JSON, IO[bytes]], **kwargs: Any + ) -> _models.AnalyzeTextJailbreakResult: + # pylint: disable=line-too-long + """Analyze Text Jailbreak. + + A synchronous API for the analysis of text jailbreak. + + :param options: The text jailbreak analysis request. Is one of the following types: + AnalyzeTextJailbreakOptions, JSON, IO[bytes] Required. + :type options: ~azure.ai.contentsafety.models.AnalyzeTextJailbreakOptions or JSON or IO[bytes] + :return: AnalyzeTextJailbreakResult. The AnalyzeTextJailbreakResult is compatible with + MutableMapping + :rtype: ~azure.ai.contentsafety.models.AnalyzeTextJailbreakResult + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + options = { + "text": "str" # The text needs to be analyzed if it attempt to jailbreak. We + support a maximum of 1k Unicode characters (Unicode code points) in the text of + one request. Required. + } + + # response body for status code(s): 200 + response == { + "jailbreakAnalysis": { + "detected": bool # Analysis result for jailbreak. Required. + } + } + """ + 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[_models.AnalyzeTextJailbreakResult] = 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_content_safety_detect_text_jailbreak_request( + 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 = 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.AnalyzeTextJailbreakResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + @api_version_validation( + method_added_on="2023-10-15-preview", + ) + async def detect_text_protected_material( + self, + options: _models.AnalyzeTextProtectedMaterialOptions, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AnalyzeTextProtectedMaterialResult: + # pylint: disable=line-too-long + """Analyze Protected Material. + + A synchronous API for the analysis of protected material. + + :param options: The text protected material analysis request. Required. + :type options: ~azure.ai.contentsafety.models.AnalyzeTextProtectedMaterialOptions + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: AnalyzeTextProtectedMaterialResult. The AnalyzeTextProtectedMaterialResult is + compatible with MutableMapping + :rtype: ~azure.ai.contentsafety.models.AnalyzeTextProtectedMaterialResult + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + options = { + "text": "str" # The text needs to be analyzed. We support a maximum of 1k + Unicode characters (Unicode code points) in the text of one request. Required. + } + + # response body for status code(s): 200 + response == { + "protectedMaterialAnalysis": { + "detected": bool # Analysis result for protected material.. + Required. + } + } + """ + + @overload + @api_version_validation( + method_added_on="2023-10-15-preview", + ) + async def detect_text_protected_material( + self, options: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AnalyzeTextProtectedMaterialResult: + """Analyze Protected Material. + + A synchronous API for the analysis of protected material. + + :param options: The text protected material 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 + :return: AnalyzeTextProtectedMaterialResult. The AnalyzeTextProtectedMaterialResult is + compatible with MutableMapping + :rtype: ~azure.ai.contentsafety.models.AnalyzeTextProtectedMaterialResult + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "protectedMaterialAnalysis": { + "detected": bool # Analysis result for protected material.. + Required. + } + } + """ + + @overload + @api_version_validation( + method_added_on="2023-10-15-preview", + ) + async def detect_text_protected_material( + self, options: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AnalyzeTextProtectedMaterialResult: + """Analyze Protected Material. + + A synchronous API for the analysis of protected material. + + :param options: The text protected material analysis request. Required. + :type options: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: AnalyzeTextProtectedMaterialResult. The AnalyzeTextProtectedMaterialResult is + compatible with MutableMapping + :rtype: ~azure.ai.contentsafety.models.AnalyzeTextProtectedMaterialResult + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "protectedMaterialAnalysis": { + "detected": bool # Analysis result for protected material.. + Required. + } + } + """ + + @distributed_trace_async + @api_version_validation( + method_added_on="2023-10-15-preview", + ) + async def detect_text_protected_material( + self, options: Union[_models.AnalyzeTextProtectedMaterialOptions, JSON, IO[bytes]], **kwargs: Any + ) -> _models.AnalyzeTextProtectedMaterialResult: + # pylint: disable=line-too-long + """Analyze Protected Material. + + A synchronous API for the analysis of protected material. + + :param options: The text protected material analysis request. Is one of the following types: + AnalyzeTextProtectedMaterialOptions, JSON, IO[bytes] Required. + :type options: ~azure.ai.contentsafety.models.AnalyzeTextProtectedMaterialOptions or JSON or + IO[bytes] + :return: AnalyzeTextProtectedMaterialResult. The AnalyzeTextProtectedMaterialResult is + compatible with MutableMapping + :rtype: ~azure.ai.contentsafety.models.AnalyzeTextProtectedMaterialResult + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + options = { + "text": "str" # The text needs to be analyzed. We support a maximum of 1k + Unicode characters (Unicode code points) in the text of one request. Required. + } + + # response body for status code(s): 200 + response == { + "protectedMaterialAnalysis": { + "detected": bool # Analysis result for protected material.. + Required. + } + } + """ + 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[_models.AnalyzeTextProtectedMaterialResult] = 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_content_safety_detect_text_protected_material_request( + 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 = 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.AnalyzeTextProtectedMaterialResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + class BlocklistClientOperationsMixin(BlocklistClientMixinABC): @overload @@ -356,12 +1102,37 @@ async def add_or_update_blocklist_items( :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: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + options = { + "blocklistItems": [ + { + "blocklistItemId": "str", # The service will generate a + BlocklistItemId, which will be a UUID. Required. + "text": "str", # BlocklistItem content. Required. + "description": "str" # Optional. BlocklistItem description. + } + ] + } + + # response body for status code(s): 200 + response == { + "blocklistItems": [ + { + "blocklistItemId": "str", # The service will generate a + BlocklistItemId, which will be a UUID. Required. + "text": "str", # BlocklistItem content. Required. + "description": "str" # Optional. BlocklistItem description. + } + ] + } """ @overload @@ -380,12 +1151,25 @@ async def add_or_update_blocklist_items( :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: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "blocklistItems": [ + { + "blocklistItemId": "str", # The service will generate a + BlocklistItemId, which will be a UUID. Required. + "text": "str", # BlocklistItem content. Required. + "description": "str" # Optional. BlocklistItem description. + } + ] + } """ @overload @@ -404,12 +1188,25 @@ async def add_or_update_blocklist_items( :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: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "blocklistItems": [ + { + "blocklistItemId": "str", # The service will generate a + BlocklistItemId, which will be a UUID. Required. + "text": "str", # BlocklistItem content. Required. + "description": "str" # Optional. BlocklistItem description. + } + ] + } """ @distributed_trace_async @@ -430,15 +1227,37 @@ async def add_or_update_blocklist_items( AddOrUpdateTextBlocklistItemsOptions, JSON, IO[bytes] Required. :type options: ~azure.ai.contentsafety.models.AddOrUpdateTextBlocklistItemsOptions or JSON or IO[bytes] - :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: AddOrUpdateTextBlocklistItemsResult. The AddOrUpdateTextBlocklistItemsResult is compatible with MutableMapping :rtype: ~azure.ai.contentsafety.models.AddOrUpdateTextBlocklistItemsResult :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + options = { + "blocklistItems": [ + { + "blocklistItemId": "str", # The service will generate a + BlocklistItemId, which will be a UUID. Required. + "text": "str", # BlocklistItem content. Required. + "description": "str" # Optional. BlocklistItem description. + } + ] + } + + # response body for status code(s): 200 + response == { + "blocklistItems": [ + { + "blocklistItemId": "str", # The service will generate a + BlocklistItemId, which will be a UUID. Required. + "text": "str", # BlocklistItem content. Required. + "description": "str" # Optional. BlocklistItem description. + } + ] + } """ error_map = { 401: ClientAuthenticationError, @@ -517,11 +1336,24 @@ async def create_or_update_text_blocklist( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+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: TextBlocklist. The TextBlocklist is compatible with MutableMapping :rtype: ~azure.ai.contentsafety.models.TextBlocklist :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + options = { + "blocklistName": "str", # Text blocklist name. Required. + "description": "str" # Optional. Text blocklist description. + } + + # response body for status code(s): 201, 200 + response == { + "blocklistName": "str", # Text blocklist name. Required. + "description": "str" # Optional. Text blocklist description. + } """ @overload @@ -539,11 +1371,18 @@ async def create_or_update_text_blocklist( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+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: TextBlocklist. The TextBlocklist is compatible with MutableMapping :rtype: ~azure.ai.contentsafety.models.TextBlocklist :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 201, 200 + response == { + "blocklistName": "str", # Text blocklist name. Required. + "description": "str" # Optional. Text blocklist description. + } """ @overload @@ -566,11 +1405,18 @@ async def create_or_update_text_blocklist( :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/merge-patch+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: TextBlocklist. The TextBlocklist is compatible with MutableMapping :rtype: ~azure.ai.contentsafety.models.TextBlocklist :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 201, 200 + response == { + "blocklistName": "str", # Text blocklist name. Required. + "description": "str" # Optional. Text blocklist description. + } """ @distributed_trace_async @@ -586,13 +1432,24 @@ async def create_or_update_text_blocklist( :param options: The resource instance. Is one of the following types: TextBlocklist, JSON, IO[bytes] Required. :type options: ~azure.ai.contentsafety.models.TextBlocklist or JSON or IO[bytes] - :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 - 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: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + options = { + "blocklistName": "str", # Text blocklist name. Required. + "description": "str" # Optional. Text blocklist description. + } + + # response body for status code(s): 201, 200 + response == { + "blocklistName": "str", # Text blocklist name. Required. + "description": "str" # Optional. Text blocklist description. + } """ error_map = { 401: ClientAuthenticationError, @@ -720,11 +1577,18 @@ async def get_text_blocklist(self, blocklist_name: str, **kwargs: Any) -> _model :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: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "blocklistName": "str", # Text blocklist name. Required. + "description": "str" # Optional. Text blocklist description. + } """ error_map = { 401: ClientAuthenticationError, @@ -786,11 +1650,20 @@ async def get_text_blocklist_item( :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: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "blocklistItemId": "str", # The service will generate a BlocklistItemId, + which will be a UUID. Required. + "text": "str", # BlocklistItem content. Required. + "description": "str" # Optional. BlocklistItem description. + } """ error_map = { 401: ClientAuthenticationError, @@ -858,6 +1731,17 @@ def list_text_blocklist_items( :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.contentsafety.models.TextBlocklistItem] :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "blocklistItemId": "str", # The service will generate a BlocklistItemId, + which will be a UUID. Required. + "text": "str", # BlocklistItem content. Required. + "description": "str" # Optional. BlocklistItem description. + } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} @@ -949,6 +1833,15 @@ def list_text_blocklists(self, **kwargs: Any) -> AsyncIterable["_models.TextBloc :return: An iterator like instance of TextBlocklist :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.contentsafety.models.TextBlocklist] :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "blocklistName": "str", # Text blocklist name. Required. + "description": "str" # Optional. Text blocklist description. + } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} @@ -1050,6 +1943,16 @@ async def remove_blocklist_items( # pylint: disable=inconsistent-return-stateme :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + options = { + "blocklistItemIds": [ + "str" # Array of blocklistItemIds to remove. Required. + ] + } """ @overload @@ -1112,12 +2015,19 @@ async def remove_blocklist_items( # pylint: disable=inconsistent-return-stateme RemoveTextBlocklistItemsOptions, JSON, IO[bytes] Required. :type options: ~azure.ai.contentsafety.models.RemoveTextBlocklistItemsOptions or JSON or IO[bytes] - :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: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + options = { + "blocklistItemIds": [ + "str" # Array of blocklistItemIds to remove. Required. + ] + } """ error_map = { 401: ClientAuthenticationError, 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 a4cd06fb66cf..5a48b3be0b7f 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 @@ -10,10 +10,18 @@ from ._models import AddOrUpdateTextBlocklistItemsResult from ._models import AnalyzeImageOptions from ._models import AnalyzeImageResult +from ._models import AnalyzeTextJailbreakOptions +from ._models import AnalyzeTextJailbreakResult from ._models import AnalyzeTextOptions +from ._models import AnalyzeTextProtectedMaterialOptions +from ._models import AnalyzeTextProtectedMaterialResult from ._models import AnalyzeTextResult from ._models import ImageCategoriesAnalysis from ._models import ImageData +from ._models import IncidentMatch +from ._models import IncidentOptions +from ._models import JailbreakAnalysisResult +from ._models import ProtectedMaterialAnalysisResult from ._models import RemoveTextBlocklistItemsOptions from ._models import TextBlocklist from ._models import TextBlocklistItem @@ -33,10 +41,18 @@ "AddOrUpdateTextBlocklistItemsResult", "AnalyzeImageOptions", "AnalyzeImageResult", + "AnalyzeTextJailbreakOptions", + "AnalyzeTextJailbreakResult", "AnalyzeTextOptions", + "AnalyzeTextProtectedMaterialOptions", + "AnalyzeTextProtectedMaterialResult", "AnalyzeTextResult", "ImageCategoriesAnalysis", "ImageData", + "IncidentMatch", + "IncidentOptions", + "JailbreakAnalysisResult", + "ProtectedMaterialAnalysisResult", "RemoveTextBlocklistItemsOptions", "TextBlocklist", "TextBlocklistItem", 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 cf0403b1cd4c..39c9d9141e73 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 @@ -92,6 +92,8 @@ class AnalyzeImageOptions(_model_base.Model): :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 + :ivar incidents: The incidents to detect. + :vartype incidents: ~azure.ai.contentsafety.models.IncidentOptions """ image: "_models.ImageData" = rest_field() @@ -102,6 +104,8 @@ class AnalyzeImageOptions(_model_base.Model): 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\"""" + incidents: Optional["_models.IncidentOptions"] = rest_field() + """The incidents to detect.""" @overload def __init__( @@ -110,6 +114,7 @@ def __init__( image: "_models.ImageData", categories: Optional[List[Union[str, "_models.ImageCategory"]]] = None, output_type: Optional[Union[str, "_models.AnalyzeImageOutputType"]] = None, + incidents: Optional["_models.IncidentOptions"] = None, ): ... @@ -131,16 +136,85 @@ class AnalyzeImageResult(_model_base.Model): :ivar categories_analysis: Analysis result for categories. Required. :vartype categories_analysis: list[~azure.ai.contentsafety.models.ImageCategoriesAnalysis] + :ivar incident_matches: The incident match details. + :vartype incident_matches: list[~azure.ai.contentsafety.models.IncidentMatch] """ categories_analysis: List["_models.ImageCategoriesAnalysis"] = rest_field(name="categoriesAnalysis") """Analysis result for categories. Required.""" + incident_matches: Optional[List["_models.IncidentMatch"]] = rest_field(name="incidentMatches") + """The incident match details.""" @overload def __init__( self, *, categories_analysis: List["_models.ImageCategoriesAnalysis"], + incident_matches: Optional[List["_models.IncidentMatch"]] = None, + ): + ... + + @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 AnalyzeTextJailbreakOptions(_model_base.Model): + """The text jailbreak analysis request. + + All required parameters must be populated in order to send to server. + + :ivar text: The text needs to be analyzed if it attempt to jailbreak. We support a maximum of + 1k Unicode characters (Unicode code points) in the text of one request. Required. + :vartype text: str + """ + + text: str = rest_field() + """The text needs to be analyzed if it attempt to jailbreak. We support a maximum of 1k Unicode + characters (Unicode code points) in the text of one request. Required.""" + + @overload + def __init__( + self, + *, + text: 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 AnalyzeTextJailbreakResult(_model_base.Model): + """The text jailbreak analysis request. + + All required parameters must be populated in order to send to server. + + :ivar jailbreak_analysis: Analysis result for jailbreak. Required. + :vartype jailbreak_analysis: ~azure.ai.contentsafety.models.JailbreakAnalysisResult + """ + + jailbreak_analysis: "_models.JailbreakAnalysisResult" = rest_field(name="jailbreakAnalysis") + """Analysis result for jailbreak. Required.""" + + @overload + def __init__( + self, + *, + jailbreak_analysis: "_models.JailbreakAnalysisResult", ): ... @@ -176,6 +250,8 @@ class AnalyzeTextOptions(_model_base.Model): the default value will be "FourSeverityLevels". Known values are: "FourSeverityLevels" and "EightSeverityLevels". :vartype output_type: str or ~azure.ai.contentsafety.models.AnalyzeTextOutputType + :ivar incidents: The incidents to detect. + :vartype incidents: ~azure.ai.contentsafety.models.IncidentOptions """ text: str = rest_field() @@ -194,6 +270,8 @@ class AnalyzeTextOptions(_model_base.Model): """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\".""" + incidents: Optional["_models.IncidentOptions"] = rest_field() + """The incidents to detect.""" @overload def __init__( @@ -204,6 +282,74 @@ def __init__( blocklist_names: Optional[List[str]] = None, halt_on_blocklist_hit: Optional[bool] = None, output_type: Optional[Union[str, "_models.AnalyzeTextOutputType"]] = None, + incidents: Optional["_models.IncidentOptions"] = None, + ): + ... + + @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 AnalyzeTextProtectedMaterialOptions(_model_base.Model): + """The protected material analysis request. + + All required parameters must be populated in order to send to server. + + :ivar text: The text needs to be analyzed. We support a maximum of 1k Unicode characters + (Unicode code points) in the text of one request. Required. + :vartype text: str + """ + + text: str = rest_field() + """The text needs to be analyzed. We support a maximum of 1k Unicode characters (Unicode code + points) in the text of one request. Required.""" + + @overload + def __init__( + self, + *, + text: 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 AnalyzeTextProtectedMaterialResult(_model_base.Model): + """The protected material analysis response. + + All required parameters must be populated in order to send to server. + + :ivar protected_material_analysis: Analysis result for protected material. Required. + :vartype protected_material_analysis: + ~azure.ai.contentsafety.models.ProtectedMaterialAnalysisResult + """ + + protected_material_analysis: "_models.ProtectedMaterialAnalysisResult" = rest_field( + name="protectedMaterialAnalysis" + ) + """Analysis result for protected material. Required.""" + + @overload + def __init__( + self, + *, + protected_material_analysis: "_models.ProtectedMaterialAnalysisResult", ): ... @@ -227,12 +373,22 @@ class AnalyzeTextResult(_model_base.Model): :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] + :ivar incident_matches: The incident match details. + :vartype incident_matches: list[~azure.ai.contentsafety.models.IncidentMatch] + :ivar citation: Chunks in the original text detected as harmful content. Analysis result and + scores are caused by these. + :vartype citation: list[str] """ 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.""" + incident_matches: Optional[List["_models.IncidentMatch"]] = rest_field(name="incidentMatches") + """The incident match details.""" + citation: Optional[List[str]] = rest_field() + """Chunks in the original text detected as harmful content. Analysis result and scores are caused + by these.""" @overload def __init__( @@ -240,6 +396,8 @@ def __init__( *, categories_analysis: List["_models.TextCategoriesAnalysis"], blocklists_match: Optional[List["_models.TextBlocklistMatch"]] = None, + incident_matches: Optional[List["_models.IncidentMatch"]] = None, + citation: Optional[List[str]] = None, ): ... @@ -332,6 +490,137 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useles super().__init__(*args, **kwargs) +class IncidentMatch(_model_base.Model): + """The result of text incident match. + + All required parameters must be populated in order to send to server. + + :ivar incident_name: The name of the matched incident. Required. + :vartype incident_name: str + """ + + incident_name: str = rest_field(name="incidentName") + """The name of the matched incident. Required.""" + + @overload + def __init__( + self, + *, + incident_name: 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 IncidentOptions(_model_base.Model): + """The text analysis request. + + :ivar incident_names: The accept decision made by service. + :vartype incident_names: list[str] + :ivar halt_on_incident_hit: When set to true, further analyses of harmful content will not be + performed in cases where incidents are hit. When set to false, all analyses of harmful content + will be performed, whether or not incidents are hit. + :vartype halt_on_incident_hit: bool + """ + + incident_names: Optional[List[str]] = rest_field(name="incidentNames") + """The accept decision made by service.""" + halt_on_incident_hit: Optional[bool] = rest_field(name="haltOnIncidentHit") + """When set to true, further analyses of harmful content will not be performed in cases where + incidents are hit. When set to false, all analyses of harmful content will be performed, + whether or not incidents are hit.""" + + @overload + def __init__( + self, + *, + incident_names: Optional[List[str]] = None, + halt_on_incident_hit: Optional[bool] = None, + ): + ... + + @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 JailbreakAnalysisResult(_model_base.Model): + """The text jailbreak analysis response. + + All required parameters must be populated in order to send to server. + + :ivar detected: Analysis result for jailbreak. Required. + :vartype detected: bool + """ + + detected: bool = rest_field() + """Analysis result for jailbreak. Required.""" + + @overload + def __init__( + self, + *, + detected: bool, + ): + ... + + @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 ProtectedMaterialAnalysisResult(_model_base.Model): + """The text protected material analysis response. + + All required parameters must be populated in order to send to server. + + :ivar detected: Analysis result for protected material.. Required. + :vartype detected: bool + """ + + detected: bool = rest_field() + """Analysis result for protected material.. Required.""" + + @overload + def __init__( + self, + *, + detected: bool, + ): + ... + + @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 RemoveTextBlocklistItemsOptions(_model_base.Model): """The request to remove blocklistItems from a text blocklist. diff --git a/sdk/contentsafety/azure-ai-contentsafety/setup.py b/sdk/contentsafety/azure-ai-contentsafety/setup.py index b4e939ee2c66..5d115e01ad02 100644 --- a/sdk/contentsafety/azure-ai-contentsafety/setup.py +++ b/sdk/contentsafety/azure-ai-contentsafety/setup.py @@ -42,11 +42,11 @@ "Programming Language :: Python", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", "License :: OSI Approved :: MIT License", ], zip_safe=False, @@ -64,8 +64,8 @@ }, install_requires=[ "isodate<1.0.0,>=0.6.1", - "azure-core<2.0.0,>=1.28.0", - "typing-extensions>=4.3.0; python_version<'3.8.0'", + "azure-core<2.0.0,>=1.30.0", + "typing-extensions>=4.6.0", ], - python_requires=">=3.7", + python_requires=">=3.8", ) diff --git a/sdk/contentsafety/azure-ai-contentsafety/tsp-location.yaml b/sdk/contentsafety/azure-ai-contentsafety/tsp-location.yaml index 6b117195f5d3..f832d5ba299b 100644 --- a/sdk/contentsafety/azure-ai-contentsafety/tsp-location.yaml +++ b/sdk/contentsafety/azure-ai-contentsafety/tsp-location.yaml @@ -1,4 +1,5 @@ +commit: 983ef3efcf3bf10eb4867009ee160eec742c2459 directory: specification/cognitiveservices/ContentSafety -commit: fb39d9813934567c594ca253efff7c5c01a474e8 repo: Azure/azure-rest-api-specs -additionalDirectories: [] \ No newline at end of file +additionalDirectories: [] +