diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/azure/ai/language/questionanswering/authoring/_utils/serialization.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/azure/ai/language/questionanswering/authoring/_utils/serialization.py index cca8513e0e67..81ec1de5922b 100644 --- a/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/azure/ai/language/questionanswering/authoring/_utils/serialization.py +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering-authoring/azure/ai/language/questionanswering/authoring/_utils/serialization.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,7 +6,6 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -# pylint: disable=line-too-long,useless-suppression,too-many-lines,duplicate-code,missing-module-docstring,missing-class-docstring,missing-function-docstring,consider-using-f-string,invalid-name,too-many-locals,too-many-branches # pyright: reportUnnecessaryTypeIgnoreComment=false @@ -787,7 +787,7 @@ def serialize_data(self, data, data_type, **kwargs): # If dependencies is empty, try with current data class # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) + enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) if issubclass(enum_type, Enum): return Serializer.serialize_enum(data, enum_obj=enum_type) @@ -821,13 +821,20 @@ def serialize_basic(cls, data, data_type, **kwargs): :param str data_type: Type of object in the iterable. :rtype: str, int, float, bool :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. """ custom_serializer = cls._get_custom_serializers(data_type, **kwargs) if custom_serializer: return custom_serializer(data) if data_type == "str": return cls.serialize_unicode(data) - return eval(data_type)(data) # nosec # pylint: disable=eval-used + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) @classmethod def serialize_unicode(cls, data): @@ -1757,7 +1764,7 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return :param str data_type: deserialization data type. :return: Deserialized basic type. :rtype: str, int, float or bool - :raises TypeError: if string format is not valid. + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. """ # If we're here, data is supposed to be a basic type. # If it's still an XML node, take the text @@ -1783,7 +1790,11 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return if data_type == "str": return self.deserialize_unicode(attr) - return eval(data_type)(attr) # nosec # pylint: disable=eval-used + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) @staticmethod def deserialize_unicode(data): diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/_utils/serialization.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/_utils/serialization.py index e81921cbb011..81ec1de5922b 100644 --- a/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/_utils/serialization.py +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/_utils/serialization.py @@ -787,7 +787,7 @@ def serialize_data(self, data, data_type, **kwargs): # If dependencies is empty, try with current data class # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) + enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) if issubclass(enum_type, Enum): return Serializer.serialize_enum(data, enum_obj=enum_type) @@ -821,13 +821,20 @@ def serialize_basic(cls, data, data_type, **kwargs): :param str data_type: Type of object in the iterable. :rtype: str, int, float, bool :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. """ custom_serializer = cls._get_custom_serializers(data_type, **kwargs) if custom_serializer: return custom_serializer(data) if data_type == "str": return cls.serialize_unicode(data) - return eval(data_type)(data) # nosec # pylint: disable=eval-used + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) @classmethod def serialize_unicode(cls, data): @@ -1757,7 +1764,7 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return :param str data_type: deserialization data type. :return: Deserialized basic type. :rtype: str, int, float or bool - :raises TypeError: if string format is not valid. + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. """ # If we're here, data is supposed to be a basic type. # If it's still an XML node, take the text @@ -1783,7 +1790,11 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return if data_type == "str": return self.deserialize_unicode(attr) - return eval(data_type)(attr) # nosec # pylint: disable=eval-used + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) @staticmethod def deserialize_unicode(data): diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/azure/ai/textanalytics/authoring/_utils/serialization.py b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/azure/ai/textanalytics/authoring/_utils/serialization.py index e81921cbb011..81ec1de5922b 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/azure/ai/textanalytics/authoring/_utils/serialization.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/azure/ai/textanalytics/authoring/_utils/serialization.py @@ -787,7 +787,7 @@ def serialize_data(self, data, data_type, **kwargs): # If dependencies is empty, try with current data class # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) + enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) if issubclass(enum_type, Enum): return Serializer.serialize_enum(data, enum_obj=enum_type) @@ -821,13 +821,20 @@ def serialize_basic(cls, data, data_type, **kwargs): :param str data_type: Type of object in the iterable. :rtype: str, int, float, bool :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. """ custom_serializer = cls._get_custom_serializers(data_type, **kwargs) if custom_serializer: return custom_serializer(data) if data_type == "str": return cls.serialize_unicode(data) - return eval(data_type)(data) # nosec # pylint: disable=eval-used + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) @classmethod def serialize_unicode(cls, data): @@ -1757,7 +1764,7 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return :param str data_type: deserialization data type. :return: Deserialized basic type. :rtype: str, int, float or bool - :raises TypeError: if string format is not valid. + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. """ # If we're here, data is supposed to be a basic type. # If it's still an XML node, take the text @@ -1783,7 +1790,11 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return if data_type == "str": return self.deserialize_unicode(attr) - return eval(data_type)(attr) # nosec # pylint: disable=eval-used + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) @staticmethod def deserialize_unicode(data): diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/tsp-location.yaml b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/tsp-location.yaml index 707ff1f6cc0c..70f30533931b 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/tsp-location.yaml +++ b/sdk/cognitivelanguage/azure-ai-textanalytics-authoring/tsp-location.yaml @@ -1,4 +1,4 @@ -directory: specification/cognitiveservices/Language.AnalyzeText-authoring -commit: a525e37a2b1546c47a778eda7106cfd7c04051e1 +directory: specification/cognitiveservices/data-plane/LanguageAnalyzeTextAuthoring +commit: 483301e475684d809bdc7e81aa786e84cfb4236f repo: Azure/azure-rest-api-specs additionalDirectories: diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/README.md b/sdk/cognitivelanguage/azure-ai-textanalytics/README.md index 1be2ef2d0a95..fd63a71d2667 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/README.md +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/README.md @@ -69,7 +69,7 @@ from azure.ai.textanalytics import TextAnalysisClient endpoint = os.environ["AZURE_TEXT_ENDPOINT"] key = os.environ["AZURE_TEXT_KEY"] -text_client = TextAnalysisClient(endpoint, AzureKeyCredential(key)) +text_client = TextAnalysisClient(endpoint, AzureKeyCredential(key)) # pylint:disable=unused-variable ``` @@ -126,7 +126,7 @@ from azure.ai.textanalytics import TextAnalysisClient endpoint = os.environ["AZURE_TEXT_ENDPOINT"] key = os.environ["AZURE_TEXT_KEY"] -text_client = TextAnalysisClient(endpoint, AzureKeyCredential(key)) +text_client = TextAnalysisClient(endpoint, AzureKeyCredential(key)) # pylint:disable=unused-variable ``` @@ -164,7 +164,7 @@ from azure.identity import DefaultAzureCredential endpoint = os.environ["AZURE_TEXT_ENDPOINT"] credential = DefaultAzureCredential() -text_client = TextAnalysisClient(endpoint, credential=credential) +text_client = TextAnalysisClient(endpoint, credential=credential) # pylint:disable=unused-variable ``` @@ -803,19 +803,12 @@ def sample_analyze_healthcare_entities(): print(f" Offset: {entity.offset}") print(f" Length: {entity.length}") print(f" Confidence score: {entity.confidence_score}") - if entity.links: - for link in entity.links: - print(f" Link ID: {link.id}") - print(f" Data source: {link.data_source}") print() # Relations print("Relations:") for relation in doc.relations or []: print(f" Relation type: {relation.relation_type}") - for rel_entity in relation.entities or []: - print(f" Role: {rel_entity.role}") - print(f" Ref: {rel_entity.ref}") print() else: # Other action kinds, if present @@ -824,8 +817,8 @@ def sample_analyze_healthcare_entities(): f"\n[Non-healthcare action] name={op_result.task_name}, " f"status={op_result.status}, kind={op_result.kind}" ) - except Exception: - print("\n[Non-healthcare action present]") + except (AttributeError, TypeError) as e: + print(f"\n[Non-healthcare action present] Error: {e}") ``` @@ -854,7 +847,6 @@ Note: Healthcare Entities Analysis is only available with API version v3.1 and n import os from azure.identity import DefaultAzureCredential -from azure.core.credentials import AzureKeyCredential from azure.ai.textanalytics import TextAnalysisClient from azure.ai.textanalytics.models import ( MultiLanguageTextInput, @@ -863,7 +855,6 @@ from azure.ai.textanalytics.models import ( KeyPhraseLROTask, EntityRecognitionOperationResult, KeyPhraseExtractionOperationResult, - EntityTag, ) @@ -931,12 +922,6 @@ def sample_analyze(): print(f" Type: {entity.type}") if hasattr(entity, "subcategory") and entity.subcategory: print(f" Subcategory: {entity.subcategory}") - if hasattr(entity, "tags") and entity.tags: - print(" Tags:") - for tag in entity.tags: - if isinstance(tag, EntityTag): - print(f" TagName: {tag.name}") - print(f" TagConfidenceScore: {tag.confidence_score}") print(f" Confidence score: {entity.confidence_score}") print() for err in action_result.results.errors: diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/assets.json b/sdk/cognitivelanguage/azure-ai-textanalytics/assets.json index c20f6411dd51..2e84d5bde809 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/assets.json +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "python", "TagPrefix": "python/cognitivelanguage/azure-ai-textanalytics", - "Tag": "python/cognitivelanguage/azure-ai-textanalytics_c820b61b7e" + "Tag": "python/cognitivelanguage/azure-ai-textanalytics_95abc8a0dd" } diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/_operations/_operations.py b/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/_operations/_operations.py index c56ea955c721..361efb3e6a6c 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/_operations/_operations.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/_operations/_operations.py @@ -280,7 +280,10 @@ def analyze_text( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.ErrorResponse, response) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -365,7 +368,10 @@ def get_job_status( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.ErrorResponse, response) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -448,7 +454,10 @@ def _analyze_text_job_initial( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.ErrorResponse, response) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -462,7 +471,7 @@ def _analyze_text_job_initial( return deserialized # type: ignore @overload - def _begin_analyze_text_job( + def begin_analyze_text_job( self, *, text_input: _models.MultiLanguageTextInput, @@ -497,7 +506,7 @@ def _begin_analyze_text_job( """ @overload - def _begin_analyze_text_job( + def begin_analyze_text_job( self, body: JSON, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[None]: """Submit a collection of text documents for analysis. Specify one or more unique tasks to be @@ -514,7 +523,7 @@ def _begin_analyze_text_job( """ @overload - def _begin_analyze_text_job( + def begin_analyze_text_job( self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[None]: """Submit a collection of text documents for analysis. Specify one or more unique tasks to be @@ -531,7 +540,7 @@ def _begin_analyze_text_job( """ @distributed_trace - def _begin_analyze_text_job( + def begin_analyze_text_job( self, body: Union[JSON, IO[bytes]] = _Unset, *, @@ -651,7 +660,10 @@ def _cancel_job_initial(self, job_id: str, **kwargs: Any) -> Iterator[bytes]: except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.ErrorResponse, response) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) response_headers = {} diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/_patch.py b/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/_patch.py index c0bc5c46f03f..155c134188dd 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/_patch.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/_patch.py @@ -141,7 +141,7 @@ def __init__( kwargs["api_version"] = api_version super().__init__(endpoint=endpoint, credential=credential, **kwargs) - @overload + @overload # type: ignore[override] def begin_analyze_text_job( self, *, @@ -178,7 +178,7 @@ def begin_analyze_text_job( """ @overload - def begin_analyze_text_job( + def begin_analyze_text_job( # type: ignore[override] self, body: JSON, *, content_type: str = "application/json", **kwargs: Any ) -> AnalyzeTextLROPoller[ItemPaged["TextActions"]]: """Submit a collection of text documents for analysis. Specify one or more unique tasks to be @@ -196,7 +196,7 @@ def begin_analyze_text_job( """ @overload - def begin_analyze_text_job( + def begin_analyze_text_job( # type: ignore[override] self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> AnalyzeTextLROPoller[ItemPaged["TextActions"]]: """Submit a collection of text documents for analysis. Specify one or more unique tasks to be diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/_utils/model_base.py b/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/_utils/model_base.py index 12926fa98dcf..097f8197cfd9 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/_utils/model_base.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/_utils/model_base.py @@ -37,6 +37,7 @@ TZ_UTC = timezone.utc _T = typing.TypeVar("_T") +_NONE_TYPE = type(None) def _timedelta_as_isostr(td: timedelta) -> str: @@ -171,6 +172,21 @@ def default(self, o): # pylint: disable=too-many-return-statements r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT" ) +_ARRAY_ENCODE_MAPPING = { + "pipeDelimited": "|", + "spaceDelimited": " ", + "commaDelimited": ",", + "newlineDelimited": "\n", +} + + +def _deserialize_array_encoded(delimit: str, attr): + if isinstance(attr, str): + if attr == "": + return [] + return attr.split(delimit) + return attr + def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: """Deserialize ISO-8601 formatted string into Datetime object. @@ -202,7 +218,7 @@ def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: test_utc = date_obj.utctimetuple() if test_utc.tm_year > 9999 or test_utc.tm_year < 1: raise OverflowError("Hit max or min date") - return date_obj + return date_obj # type: ignore[no-any-return] def _deserialize_datetime_rfc7231(attr: typing.Union[str, datetime]) -> datetime: @@ -256,7 +272,7 @@ def _deserialize_time(attr: typing.Union[str, time]) -> time: """ if isinstance(attr, time): return attr - return isodate.parse_time(attr) + return isodate.parse_time(attr) # type: ignore[no-any-return] def _deserialize_bytes(attr): @@ -315,6 +331,8 @@ def _deserialize_int_as_str(attr): def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): if annotation is int and rf and rf._format == "str": return _deserialize_int_as_str + if annotation is str and rf and rf._format in _ARRAY_ENCODE_MAPPING: + return functools.partial(_deserialize_array_encoded, _ARRAY_ENCODE_MAPPING[rf._format]) if rf and rf._format: return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore @@ -353,9 +371,39 @@ def __contains__(self, key: typing.Any) -> bool: return key in self._data def __getitem__(self, key: str) -> typing.Any: + # If this key has been deserialized (for mutable types), we need to handle serialization + if hasattr(self, "_attr_to_rest_field"): + cache_attr = f"_deserialized_{key}" + if hasattr(self, cache_attr): + rf = _get_rest_field(getattr(self, "_attr_to_rest_field"), key) + if rf: + value = self._data.get(key) + if isinstance(value, (dict, list, set)): + # For mutable types, serialize and return + # But also update _data with serialized form and clear flag + # so mutations via this returned value affect _data + serialized = _serialize(value, rf._format) + # If serialized form is same type (no transformation needed), + # return _data directly so mutations work + if isinstance(serialized, type(value)) and serialized == value: + return self._data.get(key) + # Otherwise return serialized copy and clear flag + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + # Store serialized form back + self._data[key] = serialized + return serialized return self._data.__getitem__(key) def __setitem__(self, key: str, value: typing.Any) -> None: + # Clear any cached deserialized value when setting through dictionary access + cache_attr = f"_deserialized_{key}" + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass self._data.__setitem__(key, value) def __delitem__(self, key: str) -> None: @@ -483,6 +531,8 @@ def _is_model(obj: typing.Any) -> bool: def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-many-return-statements if isinstance(o, list): + if format in _ARRAY_ENCODE_MAPPING and all(isinstance(x, str) for x in o): + return _ARRAY_ENCODE_MAPPING[format].join(o) return [_serialize(x, format) for x in o] if isinstance(o, dict): return {k: _serialize(v, format) for k, v in o.items()} @@ -638,6 +688,10 @@ def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: if not rf._rest_name_input: rf._rest_name_input = attr cls._attr_to_rest_field: dict[str, _RestField] = dict(attr_to_rest_field.items()) + cls._backcompat_attr_to_rest_field: dict[str, _RestField] = { + Model._get_backcompat_attribute_name(cls._attr_to_rest_field, attr): rf + for attr, rf in cls._attr_to_rest_field.items() + } cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") return super().__new__(cls) @@ -647,6 +701,16 @@ def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: if hasattr(base, "__mapping__"): base.__mapping__[discriminator or cls.__name__] = cls # type: ignore + @classmethod + def _get_backcompat_attribute_name(cls, attr_to_rest_field: dict[str, "_RestField"], attr_name: str) -> str: + rest_field_obj = attr_to_rest_field.get(attr_name) # pylint: disable=protected-access + if rest_field_obj is None: + return attr_name + original_tsp_name = getattr(rest_field_obj, "_original_tsp_name", None) # pylint: disable=protected-access + if original_tsp_name: + return original_tsp_name + return attr_name + @classmethod def _get_discriminator(cls, exist_discriminators) -> typing.Optional["_RestField"]: for v in cls.__dict__.values(): @@ -767,6 +831,17 @@ def _deserialize_sequence( return obj if isinstance(obj, ET.Element): obj = list(obj) + try: + if ( + isinstance(obj, str) + and isinstance(deserializer, functools.partial) + and isinstance(deserializer.args[0], functools.partial) + and deserializer.args[0].func == _deserialize_array_encoded # pylint: disable=comparison-with-callable + ): + # encoded string may be deserialized to sequence + return deserializer(obj) + except: # pylint: disable=bare-except + pass return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) @@ -817,16 +892,16 @@ def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-retur # is it optional? try: - if any(a for a in annotation.__args__ if a == type(None)): # pyright: ignore + if any(a is _NONE_TYPE for a in annotation.__args__): # pyright: ignore if len(annotation.__args__) <= 2: # pyright: ignore if_obj_deserializer = _get_deserialize_callable_from_annotation( - next(a for a in annotation.__args__ if a != type(None)), module, rf # pyright: ignore + next(a for a in annotation.__args__ if a is not _NONE_TYPE), module, rf # pyright: ignore ) return functools.partial(_deserialize_with_optional, if_obj_deserializer) # the type is Optional[Union[...]], we need to remove the None type from the Union annotation_copy = copy.copy(annotation) - annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a != type(None)] # pyright: ignore + annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a is not _NONE_TYPE] # pyright: ignore return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) except AttributeError: pass @@ -972,6 +1047,7 @@ def _failsafe_deserialize_xml( return None +# pylint: disable=too-many-instance-attributes class _RestField: def __init__( self, @@ -984,6 +1060,7 @@ def __init__( format: typing.Optional[str] = None, is_multipart_file_input: bool = False, xml: typing.Optional[dict[str, typing.Any]] = None, + original_tsp_name: typing.Optional[str] = None, ): self._type = type self._rest_name_input = name @@ -995,10 +1072,15 @@ def __init__( self._format = format self._is_multipart_file_input = is_multipart_file_input self._xml = xml if xml is not None else {} + self._original_tsp_name = original_tsp_name @property def _class_type(self) -> typing.Any: - return getattr(self._type, "args", [None])[0] + result = getattr(self._type, "args", [None])[0] + # type may be wrapped by nested functools.partial so we need to check for that + if isinstance(result, functools.partial): + return getattr(result, "args", [None])[0] + return result @property def _rest_name(self) -> str: @@ -1009,14 +1091,37 @@ def _rest_name(self) -> str: def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin # by this point, type and rest_name will have a value bc we default # them in __new__ of the Model class - item = obj.get(self._rest_name) + # Use _data.get() directly to avoid triggering __getitem__ which clears the cache + item = obj._data.get(self._rest_name) if item is None: return item if self._is_model: return item - return _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, we want mutations to directly affect _data + # Check if we've already deserialized this value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + # Return the value from _data directly (it's been deserialized in place) + return obj._data.get(self._rest_name) + + deserialized = _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, store the deserialized value back in _data + # so mutations directly affect _data + if isinstance(deserialized, (dict, list, set)): + obj._data[self._rest_name] = deserialized + object.__setattr__(obj, cache_attr, True) # Mark as deserialized + return deserialized + + return deserialized def __set__(self, obj: Model, value) -> None: + # Clear the cached deserialized object when setting a new value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + object.__delattr__(obj, cache_attr) + if value is None: # we want to wipe out entries if users set attr to None try: @@ -1046,6 +1151,7 @@ def rest_field( format: typing.Optional[str] = None, is_multipart_file_input: bool = False, xml: typing.Optional[dict[str, typing.Any]] = None, + original_tsp_name: typing.Optional[str] = None, ) -> typing.Any: return _RestField( name=name, @@ -1055,6 +1161,7 @@ def rest_field( format=format, is_multipart_file_input=is_multipart_file_input, xml=xml, + original_tsp_name=original_tsp_name, ) @@ -1184,7 +1291,7 @@ def _get_wrapped_element( _get_element(v, exclude_readonly, meta, wrapped_element) else: wrapped_element.text = _get_primitive_type_value(v) - return wrapped_element + return wrapped_element # type: ignore[no-any-return] def _get_primitive_type_value(v) -> str: @@ -1197,7 +1304,9 @@ def _get_primitive_type_value(v) -> str: return str(v) -def _create_xml_element(tag, prefix=None, ns=None): +def _create_xml_element( + tag: typing.Any, prefix: typing.Optional[str] = None, ns: typing.Optional[str] = None +) -> ET.Element: if prefix and ns: ET.register_namespace(prefix, ns) if ns: diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/_utils/serialization.py b/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/_utils/serialization.py index 45a3e44e45cb..81ec1de5922b 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/_utils/serialization.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/_utils/serialization.py @@ -821,13 +821,20 @@ def serialize_basic(cls, data, data_type, **kwargs): :param str data_type: Type of object in the iterable. :rtype: str, int, float, bool :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. """ custom_serializer = cls._get_custom_serializers(data_type, **kwargs) if custom_serializer: return custom_serializer(data) if data_type == "str": return cls.serialize_unicode(data) - return eval(data_type)(data) # nosec # pylint: disable=eval-used + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) @classmethod def serialize_unicode(cls, data): @@ -1757,7 +1764,7 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return :param str data_type: deserialization data type. :return: Deserialized basic type. :rtype: str, int, float or bool - :raises TypeError: if string format is not valid. + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. """ # If we're here, data is supposed to be a basic type. # If it's still an XML node, take the text @@ -1783,7 +1790,11 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return if data_type == "str": return self.deserialize_unicode(attr) - return eval(data_type)(attr) # nosec # pylint: disable=eval-used + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) @staticmethod def deserialize_unicode(data): diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/aio/_operations/_operations.py b/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/aio/_operations/_operations.py index f941fb2d0920..3c3b0d63f346 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/aio/_operations/_operations.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/aio/_operations/_operations.py @@ -185,7 +185,10 @@ async def analyze_text( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.ErrorResponse, response) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -270,7 +273,10 @@ async def get_job_status( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.ErrorResponse, response) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) if _stream: @@ -353,7 +359,10 @@ async def _analyze_text_job_initial( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.ErrorResponse, response) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -367,7 +376,7 @@ async def _analyze_text_job_initial( return deserialized # type: ignore @overload - async def _begin_analyze_text_job( + async def begin_analyze_text_job( self, *, text_input: _models.MultiLanguageTextInput, @@ -402,7 +411,7 @@ async def _begin_analyze_text_job( """ @overload - async def _begin_analyze_text_job( + async def begin_analyze_text_job( self, body: JSON, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[None]: """Submit a collection of text documents for analysis. Specify one or more unique tasks to be @@ -419,7 +428,7 @@ async def _begin_analyze_text_job( """ @overload - async def _begin_analyze_text_job( + async def begin_analyze_text_job( self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[None]: """Submit a collection of text documents for analysis. Specify one or more unique tasks to be @@ -436,7 +445,7 @@ async def _begin_analyze_text_job( """ @distributed_trace_async - async def _begin_analyze_text_job( + async def begin_analyze_text_job( self, body: Union[JSON, IO[bytes]] = _Unset, *, @@ -557,7 +566,10 @@ async def _cancel_job_initial(self, job_id: str, **kwargs: Any) -> AsyncIterator except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.ErrorResponse, response) + error = _failsafe_deserialize( + _models.ErrorResponse, + response, + ) raise HttpResponseError(response=response, model=error) response_headers = {} diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/aio/_patch.py b/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/aio/_patch.py index d418bf365d3c..4dff8f288feb 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/aio/_patch.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/aio/_patch.py @@ -127,7 +127,7 @@ def __init__( kwargs["api_version"] = api_version super().__init__(endpoint=endpoint, credential=credential, **kwargs) - @overload + @overload # type: ignore[override] async def begin_analyze_text_job( self, *, @@ -165,7 +165,7 @@ async def begin_analyze_text_job( """ @overload - async def begin_analyze_text_job( + async def begin_analyze_text_job( # type: ignore[override] self, body: JSON, *, content_type: str = "application/json", **kwargs: Any ) -> AnalyzeTextAsyncLROPoller[AsyncItemPaged["TextActions"]]: """Submit a collection of text documents for analysis. Specify one or more unique tasks to be @@ -184,7 +184,7 @@ async def begin_analyze_text_job( """ @overload - async def begin_analyze_text_job( + async def begin_analyze_text_job( # type: ignore[override] self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> AnalyzeTextAsyncLROPoller[AsyncItemPaged["TextActions"]]: """Submit a collection of text documents for analysis. Specify one or more unique tasks to be diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/models/_models.py b/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/models/_models.py index 2adc7201371f..309446e81c02 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/models/_models.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/azure/ai/textanalytics/models/_models.py @@ -6659,7 +6659,7 @@ class TextActions(_Model): total: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Count of total tasks. Required.""" items_property: Optional[list["_models.AnalyzeTextLROResult"]] = rest_field( - name="items", visibility=["read", "create", "update", "delete", "query"] + name="items", visibility=["read", "create", "update", "delete", "query"], original_tsp_name="items" ) """Enumerable of Analyze text job results.""" diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/dev_requirements.txt b/sdk/cognitivelanguage/azure-ai-textanalytics/dev_requirements.txt index 0e53b6a72db5..8756d22e0df1 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/dev_requirements.txt +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/dev_requirements.txt @@ -1,3 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools ../../core/azure-core -aiohttp \ No newline at end of file +aiohttp +-e ../../identity/azure-identity \ No newline at end of file diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/pyproject.toml b/sdk/cognitivelanguage/azure-ai-textanalytics/pyproject.toml index 821860de4bd1..72aeea038b21 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/pyproject.toml +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/pyproject.toml @@ -32,7 +32,7 @@ keywords = ["azure", "azure sdk"] dependencies = [ "isodate>=0.6.1", - "azure-core>=1.35.0", + "azure-core>=1.37.0", "typing-extensions>=4.6.0", ] dynamic = [ diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_abstract_summary_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_abstract_summary_async.py index 81e64d95205a..aadbbb28e623 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_abstract_summary_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_abstract_summary_async.py @@ -5,13 +5,13 @@ # ------------------------------------ """ -FILE: sample_text_abstractive_summarization_async.py +FILE: sample_abstract_summary_async.py DESCRIPTION: This sample demonstrates how to run an **abstractive summarization** action over text (async LRO). USAGE: - python sample_text_abstractive_summarization_async.py + python sample_abstract_summary_async.py REQUIRED ENV VARS (for AAD / DefaultAzureCredential): AZURE_TEXT_ENDPOINT @@ -27,7 +27,7 @@ # [START text_abstractive_summarization_async] import os -import asyncio +import asyncio # pylint:disable=do-not-import-asyncio from azure.identity.aio import DefaultAzureCredential from azure.ai.textanalytics.aio import TextAnalysisClient @@ -39,7 +39,7 @@ ) -async def sample_text_abstractive_summarization_async(): +async def sample_abstract_summary_async(): # settings endpoint = os.environ["AZURE_TEXT_ENDPOINT"] credential = DefaultAzureCredential() @@ -136,9 +136,6 @@ async def sample_text_abstractive_summarization_async(): print(f"\nDocument ID: {doc.id}") for s in doc.summaries or []: print(f" Summary: {s.text}") - if s.contexts: - for c in s.contexts: - print(f" Context offset={c.offset}, length={c.length}") else: # Other action kinds, if present try: @@ -146,15 +143,15 @@ async def sample_text_abstractive_summarization_async(): f"\n[Non-abstractive action] name={op_result.task_name}, " f"status={op_result.status}, kind={op_result.kind}" ) - except Exception: - print("\n[Non-abstractive action present]") + except (AttributeError, TypeError) as e: + print(f"\n[Non-abstractive action present] Error: {e}") # [END text_abstractive_summarization_async] async def main(): - await sample_text_abstractive_summarization_async() + await sample_abstract_summary_async() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_analyze_actions_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_analyze_actions_async.py index 41f07d950999..b576a43375f2 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_analyze_actions_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_analyze_actions_async.py @@ -29,7 +29,7 @@ # [START analyze_async] import os -import asyncio +import asyncio # pylint:disable=do-not-import-asyncio from azure.identity.aio import DefaultAzureCredential from azure.ai.textanalytics.aio import TextAnalysisClient @@ -40,7 +40,6 @@ KeyPhraseLROTask, EntityRecognitionOperationResult, KeyPhraseExtractionOperationResult, - EntityTag, ) @@ -106,13 +105,6 @@ async def sample_analyze_actions_async(): print(f" Type: {entity.type}") if hasattr(entity, "subcategory") and entity.subcategory: print(f" Subcategory: {entity.subcategory}") - if hasattr(entity, "tags") and entity.tags: - print(" Tags:") - for tag in entity.tags: - if isinstance(tag, EntityTag): - print(f" TagName: {tag.name}") - print(f" TagConfidenceScore: {tag.confidence_score}") - print(f" Confidence score: {entity.confidence_score}") print() for err in action_result.results.errors: print(f" Error in document: {err.id}!") diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_analyze_healthcare_entities_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_analyze_healthcare_entities_async.py index baa9073efc98..83499ddb80a5 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_analyze_healthcare_entities_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_analyze_healthcare_entities_async.py @@ -27,7 +27,7 @@ # [START analyze_healthcare_entities_async] import os -import asyncio +import asyncio # pylint:disable=do-not-import-asyncio from azure.identity.aio import DefaultAzureCredential from azure.ai.textanalytics.aio import TextAnalysisClient @@ -113,10 +113,6 @@ async def sample_analyze_healthcare_entities_async(): print(f" Offset: {entity.offset}") print(f" Length: {entity.length}") print(f" Confidence score: {entity.confidence_score}") - if entity.links: - for link in entity.links: - print(f" Link ID: {link.id}") - print(f" Data source: {link.data_source}") print() # Relations @@ -134,8 +130,8 @@ async def sample_analyze_healthcare_entities_async(): f"\n[Other action] name={op_result.task_name}, " f"status={op_result.status}, kind={op_result.kind}" ) - except Exception: - print("\n[Other action present]") + except (AttributeError, TypeError) as e: + print(f"\n[Other action present] Error: {e}") # [END analyze_healthcare_entities_async] diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_analyze_sentiment_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_analyze_sentiment_async.py index 121284fab3be..5a102a2b04e6 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_analyze_sentiment_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_analyze_sentiment_async.py @@ -27,7 +27,7 @@ # [START analyze_sentiment_async] import os -import asyncio +import asyncio # pylint:disable=do-not-import-asyncio from azure.identity.aio import DefaultAzureCredential from azure.ai.textanalytics.aio import TextAnalysisClient diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_authentication_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_authentication_async.py index 76cc43d62a1a..d74d68618159 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_authentication_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_authentication_async.py @@ -27,7 +27,7 @@ 2) AZURE_TEXT_KEY - your Text Analytics API key """ -import asyncio +import asyncio # pylint:disable=do-not-import-asyncio async def sample_authentication_api_key_async(): @@ -39,11 +39,11 @@ async def sample_authentication_api_key_async(): endpoint = os.environ["AZURE_TEXT_ENDPOINT"] key = os.environ["AZURE_TEXT_KEY"] - text_client = TextAnalysisClient(endpoint, AzureKeyCredential(key)) + text_client = TextAnalysisClient(endpoint, AzureKeyCredential(key)) # pylint:disable=unused-variable # [END create_ta_client_with_key_async] -async def sample_authentication_with_azure_active_directory(): +async def sample_authentication_with_aad(): """DefaultAzureCredential will use the values from these environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET """ @@ -56,13 +56,13 @@ async def sample_authentication_with_azure_active_directory(): endpoint = os.environ["AZURE_TEXT_ENDPOINT"] credential = DefaultAzureCredential() - text_client = TextAnalysisClient(endpoint, credential=credential) + text_client = TextAnalysisClient(endpoint, credential=credential) # pylint:disable=unused-variable # [END create_ta_client_with_aad_async] async def main(): await sample_authentication_api_key_async() - await sample_authentication_with_azure_active_directory() + await sample_authentication_with_aad() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_detect_language_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_detect_language_async.py index 106615ba78fc..7cbada1e54a9 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_detect_language_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_detect_language_async.py @@ -27,7 +27,7 @@ # [START detect_language_async] import os -import asyncio +import asyncio # pylint:disable=do-not-import-asyncio from azure.identity.aio import DefaultAzureCredential from azure.ai.textanalytics.aio import TextAnalysisClient diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_extract_key_phrases_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_extract_key_phrases_async.py index fcb4e6135644..4a3ccd3c089d 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_extract_key_phrases_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_extract_key_phrases_async.py @@ -27,7 +27,7 @@ # [START extract_key_phrases_async] import os -import asyncio +import asyncio # pylint:disable=do-not-import-asyncio from azure.identity.aio import DefaultAzureCredential from azure.ai.textanalytics.aio import TextAnalysisClient diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_extract_summary_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_extract_summary_async.py index f2dc95702ed0..0f1f7230f726 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_extract_summary_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_extract_summary_async.py @@ -5,13 +5,13 @@ # ------------------------------------ """ -FILE: sample_text_extractive_summarization_async.py +FILE: sample_extract_summary_async.py DESCRIPTION: This sample demonstrates how to run an **extractive summarization** action over text (async LRO). USAGE: - python sample_text_extractive_summarization_async.py + python sample_extract_summary_async.py REQUIRED ENV VARS (for AAD / DefaultAzureCredential): AZURE_TEXT_ENDPOINT @@ -27,7 +27,7 @@ # [START text_extractive_summarization_async] import os -import asyncio +import asyncio # pylint:disable=do-not-import-asyncio from azure.identity.aio import DefaultAzureCredential from azure.ai.textanalytics.aio import TextAnalysisClient @@ -39,7 +39,7 @@ ) -async def sample_text_extractive_summarization_async(): +async def sample_extract_summary_async(): # get settings endpoint = os.environ["AZURE_TEXT_ENDPOINT"] credential = DefaultAzureCredential() @@ -149,15 +149,15 @@ async def sample_text_extractive_summarization_async(): f"\n[Other action] name={op_result.task_name}, " f"status={op_result.status}, kind={op_result.kind}" ) - except Exception: - print("\n[Other action present]") + except (AttributeError, TypeError) as e: + print(f"\n[Other action present] Error: {e}") # [END text_extractive_summarization_async] async def main(): - await sample_text_extractive_summarization_async() + await sample_extract_summary_async() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_multi_label_classify_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_multi_label_classify_async.py index 00d524313f07..f68887266742 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_multi_label_classify_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_multi_label_classify_async.py @@ -5,13 +5,13 @@ # ------------------------------------ """ -FILE: sample_text_custom_multi_label_classification_async.py +FILE: sample_multi_label_classify_async.py DESCRIPTION: This sample demonstrates how to run a **custom multi-label classification** action over text (async LRO). USAGE: - python sample_text_custom_multi_label_classification_async.py + python sample_multi_label_classify_async.py REQUIRED ENV VARS (for AAD / DefaultAzureCredential): AZURE_TEXT_ENDPOINT @@ -30,7 +30,7 @@ # [START text_custom_multi_label_classification_async] import os -import asyncio +import asyncio # pylint:disable=do-not-import-asyncio from azure.identity.aio import DefaultAzureCredential from azure.ai.textanalytics.aio import TextAnalysisClient @@ -43,7 +43,7 @@ ) -async def sample_text_custom_multi_label_classification_async(): +async def sample_multi_label_classify_async(): # get settings endpoint = os.environ["AZURE_TEXT_ENDPOINT"] project_name = os.environ.get("PROJECT_NAME", "") @@ -127,15 +127,15 @@ async def sample_text_custom_multi_label_classification_async(): f"\n[Other action] name={op_result.task_name}, " f"status={op_result.status}, kind={op_result.kind}" ) - except Exception: - print("\n[Other action present]") + except (AttributeError, TypeError) as e: + print(f"\n[Other action present] Error: {e}") # [END text_custom_multi_label_classification_async] async def main(): - await sample_text_custom_multi_label_classification_async() + await sample_multi_label_classify_async() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_custom_entities_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_custom_entities_async.py index 424fbbbdc267..ec8b77d5890d 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_custom_entities_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_custom_entities_async.py @@ -29,7 +29,7 @@ # [START text_custom_entities_async] import os -import asyncio +import asyncio # pylint:disable=do-not-import-asyncio from azure.identity.aio import DefaultAzureCredential from azure.ai.textanalytics.aio import TextAnalysisClient @@ -117,8 +117,8 @@ async def sample_text_custom_entities_async(): f"\n[Other action] name={op_result.task_name}, " f"status={op_result.status}, kind={op_result.kind}" ) - except Exception: - print("\n[Other action present]") + except (AttributeError, TypeError) as e: + print(f"\n[Other action present] Error: {e}") # [END text_custom_entities_async] diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_entities_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_entities_async.py index 846c1686d31f..b2feba6efa92 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_entities_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_entities_async.py @@ -27,7 +27,7 @@ # [START recognize_entities_async] import os -import asyncio +import asyncio # pylint:disable=do-not-import-asyncio from azure.identity.aio import DefaultAzureCredential from azure.ai.textanalytics.aio import TextAnalysisClient diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_linked_entities_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_linked_entities_async.py index 128d373cdac3..2a5365cb57f1 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_linked_entities_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_linked_entities_async.py @@ -27,7 +27,7 @@ # [START recognize_linked_entities_async] import os -import asyncio +import asyncio # pylint:disable=do-not-import-asyncio from azure.identity.aio import DefaultAzureCredential from azure.ai.textanalytics.aio import TextAnalysisClient diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_pii_entities_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_pii_entities_async.py index b471bb6c9cd0..56415d831186 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_pii_entities_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_pii_entities_async.py @@ -27,7 +27,7 @@ # [START recognize_pii_entities_async] import os -import asyncio +import asyncio # pylint:disable=do-not-import-asyncio from azure.identity.aio import DefaultAzureCredential from azure.ai.textanalytics.aio import TextAnalysisClient diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_pii_entities_with_confidence_score_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_pii_entities_with_confidence_score_async.py index 84b1d6c8e3a4..de75831659e7 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_pii_entities_with_confidence_score_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_pii_entities_with_confidence_score_async.py @@ -5,14 +5,14 @@ # ------------------------------------ """ -FILE: sample_recognize_pii_entities_with_confidence_score_async.py +FILE: sample_pii_with_confidence_score_async.py DESCRIPTION: This sample demonstrates how to run **PII entity recognition** with confidence score thresholds (async), including entity-specific overrides. USAGE: - python sample_recognize_pii_entities_with_confidence_score_async.py + python sample_pii_with_confidence_score_async.py REQUIRED ENV VARS (for AAD / DefaultAzureCredential): AZURE_TEXT_ENDPOINT @@ -28,7 +28,7 @@ # [START recognize_pii_entities_with_confidence_score_async] import os -import asyncio +import asyncio # pylint:disable=do-not-import-asyncio from azure.identity.aio import DefaultAzureCredential from azure.ai.textanalytics.aio import TextAnalysisClient @@ -43,17 +43,14 @@ ) -async def sample_recognize_pii_entities_with_confidence_score_async(): +async def sample_pii_with_confidence_score_async(): # Settings endpoint = os.environ["AZURE_TEXT_ENDPOINT"] credential = DefaultAzureCredential() async with TextAnalysisClient(endpoint, credential=credential) as client: # Input text - text = ( - "My name is John Doe. My SSN is 222-45-6789. My email is john@example.com. " - "John Doe is my name." - ) + text = "My name is John Doe. My SSN is 222-45-6789. My email is john@example.com. John Doe is my name." # Confidence score thresholds: # - Default threshold is 0.3 @@ -105,7 +102,7 @@ async def sample_recognize_pii_entities_with_confidence_score_async(): async def main(): - await sample_recognize_pii_entities_with_confidence_score_async() + await sample_pii_with_confidence_score_async() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_pii_entities_with_redaction_policies_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_pii_entities_with_redaction_policies_async.py index fd5ea93a9128..833a42625802 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_pii_entities_with_redaction_policies_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_recognize_pii_entities_with_redaction_policies_async.py @@ -28,7 +28,7 @@ # [START recognize_pii_entities_with_redaction_policies_async] import os -import asyncio +import asyncio # pylint:disable=do-not-import-asyncio from azure.identity.aio import DefaultAzureCredential from azure.ai.textanalytics.aio import TextAnalysisClient @@ -44,7 +44,7 @@ ) -async def sample_recognize_pii_entities_with_redaction_policies_async(): +async def sample_pii_with_redaction_policies_async(): # Settings endpoint = os.environ["AZURE_TEXT_ENDPOINT"] credential = DefaultAzureCredential() @@ -66,7 +66,6 @@ async def sample_recognize_pii_entities_with_redaction_policies_async(): redaction_policies=[ # Default policy: mask all categories (asterisks) EntityMaskPolicyType(policy_name="defaultPolicy", is_default=True), - # SSN: keep first 4 characters visible, mask the rest CharacterMaskPolicyType( policy_name="ssnMaskPolicy", @@ -74,7 +73,6 @@ async def sample_recognize_pii_entities_with_redaction_policies_async(): unmask_from_end=False, entity_types=["USSocialSecurityNumber"], ), - # Person & Email: replace with synthetic (fake) values SyntheticReplacementPolicyType( policy_name="syntheticPolicy", @@ -114,7 +112,7 @@ async def sample_recognize_pii_entities_with_redaction_policies_async(): async def main(): - await sample_recognize_pii_entities_with_redaction_policies_async() + await sample_pii_with_redaction_policies_async() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_single_label_classify_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_single_label_classify_async.py index b2d22c832642..ebfd020392df 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_single_label_classify_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/async_samples/sample_single_label_classify_async.py @@ -30,7 +30,7 @@ # [START text_custom_single_label_classification_async] import os -import asyncio +import asyncio # pylint:disable=do-not-import-asyncio from azure.identity.aio import DefaultAzureCredential from azure.ai.textanalytics.aio import TextAnalysisClient @@ -43,7 +43,7 @@ ) -async def sample_text_custom_single_label_classification_async(): +async def sample_single_label_classify_async(): # get settings endpoint = os.environ["AZURE_TEXT_ENDPOINT"] project_name = os.environ.get("PROJECT_NAME", "") @@ -127,15 +127,15 @@ async def sample_text_custom_single_label_classification_async(): f"\n[Other action] name={op_result.task_name}, " f"status={op_result.status}, kind={op_result.kind}" ) - except Exception: - print("\n[Other action present]") + except (AttributeError, TypeError) as e: + print(f"\n[Other action present] Exception: {e}") # [END text_custom_single_label_classification_async] async def main(): - await sample_text_custom_single_label_classification_async() + await sample_single_label_classify_async() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_abstract_summary.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_abstract_summary.py index a51ce09dd335..03cc56fbc7ac 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_abstract_summary.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_abstract_summary.py @@ -134,9 +134,6 @@ def sample_text_abstractive_summarization(): print(f"\nDocument ID: {doc.id}") for s in doc.summaries or []: print(f" Summary: {s.text}") - if s.contexts: - for c in s.contexts: - print(f" Context offset={c.offset}, length={c.length}") else: # Other action kinds, if present try: @@ -144,8 +141,8 @@ def sample_text_abstractive_summarization(): f"\n[Non-abstractive action] name={op_result.task_name}, " f"status={op_result.status}, kind={op_result.kind}" ) - except Exception: - print("\n[Non-abstractive action present]") + except (AttributeError, TypeError) as e: + print(f"\n[Non-abstractive action present] Error: {e}") # [END text_abstractive_summarization] diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_analyze_actions.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_analyze_actions.py index 5874fd3d3b5c..5627592a58be 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_analyze_actions.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_analyze_actions.py @@ -31,7 +31,6 @@ import os from azure.identity import DefaultAzureCredential -from azure.core.credentials import AzureKeyCredential from azure.ai.textanalytics import TextAnalysisClient from azure.ai.textanalytics.models import ( MultiLanguageTextInput, @@ -40,7 +39,6 @@ KeyPhraseLROTask, EntityRecognitionOperationResult, KeyPhraseExtractionOperationResult, - EntityTag, ) @@ -108,12 +106,6 @@ def sample_analyze(): print(f" Type: {entity.type}") if hasattr(entity, "subcategory") and entity.subcategory: print(f" Subcategory: {entity.subcategory}") - if hasattr(entity, "tags") and entity.tags: - print(" Tags:") - for tag in entity.tags: - if isinstance(tag, EntityTag): - print(f" TagName: {tag.name}") - print(f" TagConfidenceScore: {tag.confidence_score}") print(f" Confidence score: {entity.confidence_score}") print() for err in action_result.results.errors: diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_analyze_healthcare_entities.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_analyze_healthcare_entities.py index 41514cd10398..5af3044e3341 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_analyze_healthcare_entities.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_analyze_healthcare_entities.py @@ -111,19 +111,12 @@ def sample_analyze_healthcare_entities(): print(f" Offset: {entity.offset}") print(f" Length: {entity.length}") print(f" Confidence score: {entity.confidence_score}") - if entity.links: - for link in entity.links: - print(f" Link ID: {link.id}") - print(f" Data source: {link.data_source}") print() # Relations print("Relations:") for relation in doc.relations or []: print(f" Relation type: {relation.relation_type}") - for rel_entity in relation.entities or []: - print(f" Role: {rel_entity.role}") - print(f" Ref: {rel_entity.ref}") print() else: # Other action kinds, if present @@ -132,8 +125,8 @@ def sample_analyze_healthcare_entities(): f"\n[Non-healthcare action] name={op_result.task_name}, " f"status={op_result.status}, kind={op_result.kind}" ) - except Exception: - print("\n[Non-healthcare action present]") + except (AttributeError, TypeError) as e: + print(f"\n[Non-healthcare action present] Error: {e}") # [END analyze_healthcare_entities] diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_authentication.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_authentication.py index 4f0ffe9ef552..780f1988ff0a 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_authentication.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_authentication.py @@ -38,11 +38,11 @@ def sample_authentication_api_key(): endpoint = os.environ["AZURE_TEXT_ENDPOINT"] key = os.environ["AZURE_TEXT_KEY"] - text_client = TextAnalysisClient(endpoint, AzureKeyCredential(key)) + text_client = TextAnalysisClient(endpoint, AzureKeyCredential(key)) # pylint:disable=unused-variable # [END create_ta_client_with_key] -def sample_authentication_with_azure_active_directory(): +def sample_authentication_with_aad(): """DefaultAzureCredential will use the values from these environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET """ @@ -55,7 +55,7 @@ def sample_authentication_with_azure_active_directory(): endpoint = os.environ["AZURE_TEXT_ENDPOINT"] credential = DefaultAzureCredential() - text_client = TextAnalysisClient(endpoint, credential=credential) + text_client = TextAnalysisClient(endpoint, credential=credential) # pylint:disable=unused-variable # [END create_ta_client_with_aad] diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_extract_summary.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_extract_summary.py index 38d9b56a14dc..23c234b9c327 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_extract_summary.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_extract_summary.py @@ -5,13 +5,13 @@ # ------------------------------------ """ -FILE: sample_text_extractive_summarization.py +FILE: sample_extract_summary.py DESCRIPTION: This sample demonstrates how to run an **extractive summarization** action over text. USAGE: - python sample_text_extractive_summarization.py + python sample_extract_summary.py REQUIRED ENV VARS (for AAD / DefaultAzureCredential): AZURE_TEXT_ENDPOINT @@ -38,7 +38,7 @@ ) -def sample_text_extractive_summarization(): +def sample_extract_summary(): # get settings endpoint = os.environ["AZURE_TEXT_ENDPOINT"] credential = DefaultAzureCredential() @@ -144,15 +144,15 @@ def sample_text_extractive_summarization(): f"\n[Non-extractive action] name={op_result.task_name}, " f"status={op_result.status}, kind={op_result.kind}" ) - except Exception: - print("\n[Non-extractive action present]") + except (AttributeError, TypeError) as e: + print(f"\n[Non-extractive action present] Error: {e}") # [END text_extractive_summarization] def main(): - sample_text_extractive_summarization() + sample_extract_summary() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_multi_label_classify.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_multi_label_classify.py index b81ec7e91779..8bb169e9d29d 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_multi_label_classify.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_multi_label_classify.py @@ -5,7 +5,7 @@ # ------------------------------------ """ -FILE: sample_text_custom_multi_label_classification.py +FILE: sample_multi_label_classify.py DESCRIPTION: This sample demonstrates how to run a **custom multi-label classification** action over text. @@ -42,7 +42,7 @@ ) -def sample_text_custom_multi_label_classification(): +def sample_multi_label_classify(): # get settings endpoint = os.environ["AZURE_TEXT_ENDPOINT"] project_name = os.environ.get("PROJECT_NAME", "") @@ -121,15 +121,15 @@ def sample_text_custom_multi_label_classification(): f"\n[Non-CMLC action] name={op_result.task_name}, " f"status={op_result.status}, kind={op_result.kind}" ) - except Exception: - print("\n[Non-CMLC action present]") + except (AttributeError, TypeError) as e: + print(f"\n[Non-CMLC action present] Error: {e}") # [END text_custom_multi_label_classification] def main(): - sample_text_custom_multi_label_classification() + sample_multi_label_classify() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_recognize_pii_entities_with_confidence_score.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_recognize_pii_entities_with_confidence_score.py index 2203a94daf88..722e6e43fd35 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_recognize_pii_entities_with_confidence_score.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_recognize_pii_entities_with_confidence_score.py @@ -41,7 +41,7 @@ ) -def sample_recognize_pii_entities_with_confidence_score(): +def sample_pii_with_confidence_score(): # Settings endpoint = os.environ["AZURE_TEXT_ENDPOINT"] credential = DefaultAzureCredential() @@ -49,10 +49,7 @@ def sample_recognize_pii_entities_with_confidence_score(): client = TextAnalysisClient(endpoint, credential=credential) # Input text - text = ( - "My name is John Doe. My SSN is 222-45-6789. My email is john@example.com. " - "John Doe is my name." - ) + text = "My name is John Doe. My SSN is 222-45-6789. My email is john@example.com. John Doe is my name." # Confidence score threshold configuration: # - Default threshold is 0.3 @@ -66,9 +63,7 @@ def sample_recognize_pii_entities_with_confidence_score(): ) body = TextPiiEntitiesRecognitionInput( - text_input=MultiLanguageTextInput( - multi_language_inputs=[MultiLanguageInput(id="1", text=text, language="en")] - ), + text_input=MultiLanguageTextInput(multi_language_inputs=[MultiLanguageInput(id="1", text=text, language="en")]), action_content=PiiActionContent( pii_categories=["All"], disable_entity_validation=True, @@ -102,7 +97,7 @@ def sample_recognize_pii_entities_with_confidence_score(): def main(): - sample_recognize_pii_entities_with_confidence_score() + sample_pii_with_confidence_score() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_recognize_pii_entities_with_redaction_policies.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_recognize_pii_entities_with_redaction_policies.py index e20170fb7bae..7c5570cd4ce2 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_recognize_pii_entities_with_redaction_policies.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_recognize_pii_entities_with_redaction_policies.py @@ -42,7 +42,7 @@ ) -def sample_recognize_pii_entities_with_redaction_policies(): +def sample_pii_with_redaction_policies(): # Settings endpoint = os.environ["AZURE_TEXT_ENDPOINT"] credential = DefaultAzureCredential() @@ -65,7 +65,6 @@ def sample_recognize_pii_entities_with_redaction_policies(): redaction_policies=[ # Default policy: mask all PII categories (asterisks) EntityMaskPolicyType(policy_name="defaultPolicy", is_default=True), - # For SSN: only mask characters except first 4 digits CharacterMaskPolicyType( policy_name="ssnMaskPolicy", @@ -73,7 +72,6 @@ def sample_recognize_pii_entities_with_redaction_policies(): unmask_from_end=False, entity_types=["USSocialSecurityNumber"], ), - # For Person & Email: replace with synthetic data (fake names/emails) SyntheticReplacementPolicyType( policy_name="syntheticPolicy", @@ -107,7 +105,7 @@ def sample_recognize_pii_entities_with_redaction_policies(): def main(): - sample_recognize_pii_entities_with_redaction_policies() + sample_pii_with_redaction_policies() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_single_label_classify.py b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_single_label_classify.py index 71d87b82f81d..fa055617e50b 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_single_label_classify.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/samples/sample_single_label_classify.py @@ -5,13 +5,13 @@ # ------------------------------------ """ -FILE: sample_text_custom_single_label_classification.py +FILE: sample_single_label_classify.py DESCRIPTION: This sample demonstrates how to run a **custom single-label classification** action over text. USAGE: - python sample_text_custom_single_label_classification.py + python sample_single_label_classify.py REQUIRED ENV VARS (for AAD / DefaultAzureCredential): AZURE_TEXT_ENDPOINT @@ -42,7 +42,7 @@ ) -def sample_text_custom_single_label_classification(): +def sample_single_label_classify(): # get settings endpoint = os.environ["AZURE_TEXT_ENDPOINT"] project_name = os.environ.get("PROJECT_NAME", "") @@ -121,15 +121,15 @@ def sample_text_custom_single_label_classification(): f"\n[Non-CSC action] name={op_result.task_name}, " f"status={op_result.status}, kind={op_result.kind}" ) - except Exception: - print("\n[Non-CSC action present]") + except (AttributeError, TypeError) as e: + print(f"\n[Non-CSC action present] Error: {e}") # [END text_custom_single_label_classification] def main(): - sample_text_custom_single_label_classification() + sample_single_label_classify() if __name__ == "__main__": diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/conftest.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/conftest.py index 53d000d3e73d..cf8fbcd9fb8c 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/conftest.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/conftest.py @@ -5,19 +5,22 @@ ENV_ENDPOINT = "TEXT_ANALYSIS_ENDPOINT" ENV_KEY = "TEXT_ANALYSIS_KEY" + @pytest.fixture(scope="session") def text_analysis_endpoint(environment_variables: EnvironmentVariableLoader) -> str: """Endpoint for Text Analysis tests.""" return environment_variables.get(ENV_ENDPOINT) + @pytest.fixture(scope="session") def text_analysis_key(environment_variables: EnvironmentVariableLoader) -> str: """API key for Text Analysis tests.""" return environment_variables.get(ENV_KEY) + # autouse=True will trigger this fixture on each pytest run # test_proxy auto-starts the test proxy # patch_sleep and patch_async_sleep remove wait times during polling @pytest.fixture(scope="session", autouse=True) def start_proxy(test_proxy, patch_sleep, patch_async_sleep): - return \ No newline at end of file + return diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_abstractive_summarization_lro_task.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_abstract_summary.py similarity index 92% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_abstractive_summarization_lro_task.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_abstract_summary.py index b01fd8cc5bb9..acc6ce377a6f 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_abstractive_summarization_lro_task.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_abstract_summary.py @@ -1,3 +1,11 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy @@ -11,7 +19,6 @@ AbstractiveSummarizationOperationResult, AbstractiveSummaryActionResult, AbstractiveSummary, - SummaryContext, ) TextAnalysisPreparer = functools.partial( @@ -30,7 +37,7 @@ def create_client(self, endpoint: str, key: str) -> TextAnalysisClient: class TestTextAnalysisCase(TestTextAnalysis): @TextAnalysisPreparer() @recorded_by_proxy - def test_analyze_text_abstractive_summarization_lro_task(self, text_analysis_endpoint, text_analysis_key): + def test_abstract_summary(self, text_analysis_endpoint, text_analysis_key): client = self.create_client(text_analysis_endpoint, text_analysis_key) text_a = ( @@ -115,11 +122,4 @@ def test_analyze_text_abstractive_summarization_lro_task(self, text_analysis_end assert isinstance(summary, AbstractiveSummary) assert summary.text is not None - # contexts may be optional - if summary.contexts is not None: - for ctx in summary.contexts: - assert isinstance(ctx, SummaryContext) - assert ctx.offset is not None - assert ctx.length is not None - assert found_abstractive, "Expected an AbstractiveSummarizationOperationResult in TextActions.items_property" diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_abstractive_summarization_lro_task_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_abstract_summary_async.py similarity index 93% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_abstractive_summarization_lro_task_async.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_abstract_summary_async.py index 8bdc61ddb8f2..c1abc6af1d27 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_abstractive_summarization_lro_task_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_abstract_summary_async.py @@ -1,3 +1,11 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 import pytest @@ -36,7 +44,7 @@ class TestTextAnalysisCaseAsync(TestTextAnalysisAsync): @TextAnalysisPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_analyze_text_abstractive_summarization_lro_task_async( + async def test_abstract_summary_async( self, text_analysis_endpoint, text_analysis_key ): async with self.create_client(text_analysis_endpoint, text_analysis_key) as client: diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_extract_key_phrases.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_extract_key_phrases.py similarity index 81% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_extract_key_phrases.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_extract_key_phrases.py index 0c1df5f193d1..31261f793463 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_extract_key_phrases.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_extract_key_phrases.py @@ -1,3 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy @@ -28,7 +35,7 @@ def create_client(self, endpoint: str, key: str) -> TextAnalysisClient: class TestTextAnalysisCase(TestTextAnalysis): @TextAnalysisPreparer() @recorded_by_proxy - def test_analyze_text_extract_key_phrases(self, text_analysis_endpoint, text_analysis_key): + def test_extract_key_phrases(self, text_analysis_endpoint, text_analysis_key): client = self.create_client(text_analysis_endpoint, text_analysis_key) text_a = ( diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_extract_key_phrases_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_extract_key_phrases_async.py similarity index 82% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_extract_key_phrases_async.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_extract_key_phrases_async.py index 52ef2a208343..015e73d3a879 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_extract_key_phrases_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_extract_key_phrases_async.py @@ -1,3 +1,11 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 import pytest @@ -34,7 +42,7 @@ class TestTextAnalysisCaseAsync(TestTextAnalysisAsync): @TextAnalysisPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_analyze_text_extract_key_phrases_async(self, text_analysis_endpoint, text_analysis_key): + async def test_extract_key_phrases_async(self, text_analysis_endpoint, text_analysis_key): async with self.create_client(text_analysis_endpoint, text_analysis_key) as client: text_a = ( "We love this trail and make the trip every year. The views are breathtaking and well worth the hike! " diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_extractive_summarization_lro_task.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_extract_summary.py similarity index 92% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_extractive_summarization_lro_task.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_extract_summary.py index 2289e7e2380c..7fddb0f9ca38 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_extractive_summarization_lro_task.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_extract_summary.py @@ -1,3 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy @@ -29,7 +36,7 @@ def create_client(self, endpoint: str, key: str) -> TextAnalysisClient: class TestTextAnalysisCase(TestTextAnalysis): @TextAnalysisPreparer() @recorded_by_proxy - def test_analyze_text_extractive_summarization_lro_task(self, text_analysis_endpoint, text_analysis_key): + def test_extract_summary(self, text_analysis_endpoint, text_analysis_key): client = self.create_client(text_analysis_endpoint, text_analysis_key) text_a = ( diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_extractive_summarization_lro_task_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_extract_summary_async.py similarity index 93% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_extractive_summarization_lro_task_async.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_extract_summary_async.py index 81017ba50b04..2815c3f92c96 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_extractive_summarization_lro_task_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_extract_summary_async.py @@ -1,3 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 import pytest @@ -35,7 +42,7 @@ class TestTextAnalysisCaseAsync(TestTextAnalysisAsync): @TextAnalysisPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_analyze_text_extractive_summarization_lro_task_async( + async def test_extract_summary_async( self, text_analysis_endpoint, text_analysis_key ): async with self.create_client(text_analysis_endpoint, text_analysis_key) as client: diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_health_care_lro_task.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_health_care_lro.py similarity index 74% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_health_care_lro_task.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_health_care_lro.py index 5f4e25127e67..f1d318618372 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_health_care_lro_task.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_health_care_lro.py @@ -1,5 +1,11 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 -import pytest from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy from azure.core.credentials import AzureKeyCredential @@ -13,8 +19,6 @@ TextActions, ) -from azure.core.credentials import AzureKeyCredential - TextAnalysisPreparer = functools.partial( EnvironmentVariableLoader, "text_analysis", @@ -37,7 +41,7 @@ def create_client(self, endpoint, key): class TestTextAnalysisCase(TestTextAnalysis): @TextAnalysisPreparer() @recorded_by_proxy - def test_analyze_text_health_care_lro_task(self, text_analysis_endpoint, text_analysis_key): + def test_health_care_lro(self, text_analysis_endpoint, text_analysis_key): client = self.create_client(text_analysis_endpoint, text_analysis_key) text_a = "Prescribed 100mg ibuprofen, taken twice daily." @@ -88,26 +92,9 @@ def test_analyze_text_health_care_lro_task(self, text_analysis_endpoint, text_an assert doc.entities is not None assert doc.relations is not None - for entity in doc.entities: - assert entity is not None - assert entity.text is not None - assert entity.category is not None - assert entity.offset is not None - assert entity.length is not None - assert entity.confidence_score is not None - - if entity.links is not None: - for link in entity.links: - assert link is not None - assert link.id is not None - assert link.data_source is not None - for relation in doc.relations: assert relation is not None assert relation.relation_type is not None assert relation.entities is not None - for rel_entity in relation.entities: - assert rel_entity.role is not None - assert rel_entity.ref is not None assert found_healthcare, "Expected a HealthcareLROResult in TextActions.items_property" diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_health_care_lro_task_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_health_care_lro_async.py similarity index 87% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_health_care_lro_task_async.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_health_care_lro_async.py index 27cb30ccf705..6cb331719cea 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_health_care_lro_task_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_health_care_lro_async.py @@ -1,3 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 import pytest @@ -34,7 +41,7 @@ class TestTextAnalysisCaseAsync(TestTextAnalysisAsync): @TextAnalysisPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_analyze_text_health_care_lro_task_async(self, text_analysis_endpoint, text_analysis_key): + async def test_health_care_lro_async(self, text_analysis_endpoint, text_analysis_key): async with self.create_client(text_analysis_endpoint, text_analysis_key) as client: text_a = "Prescribed 100mg ibuprofen, taken twice daily." @@ -91,12 +98,6 @@ async def test_analyze_text_health_care_lro_task_async(self, text_analysis_endpo assert entity.length is not None assert entity.confidence_score is not None - if entity.links is not None: - for link in entity.links: - assert link is not None - assert link.id is not None - assert link.data_source is not None - for relation in doc.relations: assert relation is not None assert relation.relation_type is not None diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_language_detection.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_language_detection.py similarity index 77% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_language_detection.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_language_detection.py index 1bb3bdf93f9d..aaf56169fb5a 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_language_detection.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_language_detection.py @@ -1,3 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy @@ -27,7 +34,7 @@ def create_client(self, endpoint: str, key: str) -> TextAnalysisClient: class TestTextAnalysisCase(TestTextAnalysis): @TextAnalysisPreparer() @recorded_by_proxy - def test_analyze_text_language_detection(self, text_analysis_endpoint, text_analysis_key): + def test_language_detection(self, text_analysis_endpoint, text_analysis_key): client = self.create_client(text_analysis_endpoint, text_analysis_key) text_a = "Sentences in different languages." diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_language_detection_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_language_detection_async.py similarity index 78% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_language_detection_async.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_language_detection_async.py index af48a0bb1ba6..56d965fdd130 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_language_detection_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_language_detection_async.py @@ -1,3 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 import pytest @@ -33,7 +40,7 @@ class TestTextAnalysisCaseAsync(TestTextAnalysisAsync): @TextAnalysisPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_analyze_text_language_detection_async(self, text_analysis_endpoint, text_analysis_key): + async def test_language_detection_async(self, text_analysis_endpoint, text_analysis_key): async with self.create_client(text_analysis_endpoint, text_analysis_key) as client: text_a = "Sentences in different languages." diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_multi_label_classification_lro_task.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_multi_label_classify.py similarity index 86% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_multi_label_classification_lro_task.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_multi_label_classify.py index 2fb0bed4b290..89021fb6fba5 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_multi_label_classification_lro_task.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_multi_label_classify.py @@ -1,3 +1,11 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy @@ -30,7 +38,7 @@ def create_client(self, endpoint: str, key: str) -> TextAnalysisClient: class TestTextAnalysisCase(TestTextAnalysis): @TextAnalysisPreparer() @recorded_by_proxy - def test_analyze_text_custom_multi_label_classification_lro_task(self, text_analysis_endpoint, text_analysis_key): + def test_multi_label_classify(self, text_analysis_endpoint, text_analysis_key): client = self.create_client(text_analysis_endpoint, text_analysis_key) project_name = "multi-class-project" diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_multi_label_classification_lro_task_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_multi_label_classify_async.py similarity index 88% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_multi_label_classification_lro_task_async.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_multi_label_classify_async.py index c4935cb3f774..a1b1f1ad3d60 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_multi_label_classification_lro_task_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_multi_label_classify_async.py @@ -1,3 +1,11 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 import pytest @@ -36,7 +44,7 @@ class TestTextAnalysisCaseAsync(TestTextAnalysisAsync): @TextAnalysisPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_analyze_text_custom_multi_label_classification_lro_task_async( + async def test_multi_label_classify_async( self, text_analysis_endpoint, text_analysis_key ): async with self.create_client(text_analysis_endpoint, text_analysis_key) as client: diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_entities.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_entities.py similarity index 83% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_entities.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_entities.py index 560a9e744b22..2d9538993bfc 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_entities.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_entities.py @@ -1,3 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy @@ -29,7 +36,7 @@ def create_client(self, endpoint: str, key: str) -> TextAnalysisClient: class TestTextAnalysisCase(TestTextAnalysis): @TextAnalysisPreparer() @recorded_by_proxy - def test_analyze_text_recognize_entities(self, text_analysis_endpoint, text_analysis_key): + def test_recognize_entities(self, text_analysis_endpoint, text_analysis_key): client = self.create_client(text_analysis_endpoint, text_analysis_key) text_a = ( diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_entities_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_entities_async.py similarity index 84% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_entities_async.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_entities_async.py index 84bbaecfef16..83ade53baa97 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_entities_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_entities_async.py @@ -1,3 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 import pytest @@ -35,7 +42,7 @@ class TestTextAnalysisCaseAsync(TestTextAnalysisAsync): @TextAnalysisPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_analyze_text_recognize_entities_async(self, text_analysis_endpoint, text_analysis_key): + async def test_recognize_entities_async(self, text_analysis_endpoint, text_analysis_key): async with self.create_client(text_analysis_endpoint, text_analysis_key) as client: text_a = ( "We love this trail and make the trip every year. The views are breathtaking and well worth the hike! " diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_entities_lro_task.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_entities_ner.py similarity index 88% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_entities_lro_task.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_entities_ner.py index 412698e617d6..cedd496fd259 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_entities_lro_task.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_entities_ner.py @@ -1,3 +1,11 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy @@ -15,8 +23,6 @@ NamedEntity, ) -from azure.core.credentials import AzureKeyCredential - TextAnalysisPreparer = functools.partial( EnvironmentVariableLoader, "text_analysis", @@ -39,7 +45,7 @@ def create_client(self, endpoint, key): class TestTextAnalysisCase(TestTextAnalysis): @TextAnalysisPreparer() @recorded_by_proxy - def test_analyze_text_custom_entities_lro_task(self, text_analysis_endpoint, text_analysis_key): + def test_recognize_entities(self, text_analysis_endpoint, text_analysis_key): client = self.create_client(text_analysis_endpoint, text_analysis_key) project_name = "Example-ner-project" deployment_name = "TestDeployment" diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_entities_lro_task_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_entities_ner_async.py similarity index 88% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_entities_lro_task_async.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_entities_ner_async.py index 05683f785b0a..51498c3b17cc 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_entities_lro_task_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_entities_ner_async.py @@ -1,3 +1,11 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 import pytest @@ -37,7 +45,7 @@ class TestTextAnalysisCaseAsync(TestTextAnalysisAsync): @TextAnalysisPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_analyze_text_custom_entities_lro_task_async(self, text_analysis_endpoint, text_analysis_key): + async def test_recognize_entities_async(self, text_analysis_endpoint, text_analysis_key): async with self.create_client(text_analysis_endpoint, text_analysis_key) as client: project_name = "Example-ner-project" deployment_name = "TestDeployment" diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_linked_entities.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_linked_entities.py similarity index 84% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_linked_entities.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_linked_entities.py index 3644b4688770..20a40b61f6cb 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_linked_entities.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_linked_entities.py @@ -1,3 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy @@ -30,7 +37,7 @@ def create_client(self, endpoint: str, key: str) -> TextAnalysisClient: class TestTextAnalysisCase(TestTextAnalysis): @TextAnalysisPreparer() @recorded_by_proxy - def test_analyze_text_recognize_linked_entities(self, text_analysis_endpoint, text_analysis_key): + def test_recognize_linked_entities(self, text_analysis_endpoint, text_analysis_key): client = self.create_client(text_analysis_endpoint, text_analysis_key) text_a = ( diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_linked_entities_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_linked_entities_async.py similarity index 85% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_linked_entities_async.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_linked_entities_async.py index 7e6654cee8e6..2bb56454feaa 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_linked_entities_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_linked_entities_async.py @@ -1,3 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 import pytest @@ -36,7 +43,7 @@ class TestTextAnalysisCaseAsync(TestTextAnalysisAsync): @TextAnalysisPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_analyze_text_recognize_linked_entities_async(self, text_analysis_endpoint, text_analysis_key): + async def test_recognize_linked_entities_async(self, text_analysis_endpoint, text_analysis_key): async with self.create_client(text_analysis_endpoint, text_analysis_key) as client: text_a = ( "Microsoft was founded by Bill Gates with some friends he met at Harvard. One of his friends, Steve " diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii.py similarity index 81% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii.py index dd77a5ec2d19..84bcae87e035 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii.py @@ -1,3 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy @@ -28,7 +35,7 @@ def create_client(self, endpoint: str, key: str) -> TextAnalysisClient: class TestTextAnalysisCase(TestTextAnalysis): @TextAnalysisPreparer() @recorded_by_proxy - def test_analyze_text_recognize_pii(self, text_analysis_endpoint, text_analysis_key): + def test_recognize_pii(self, text_analysis_endpoint, text_analysis_key): client = self.create_client(text_analysis_endpoint, text_analysis_key) text_a = ( diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii_async.py similarity index 82% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii_async.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii_async.py index 7e3afbc21dea..a6e29ced9426 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii_async.py @@ -1,4 +1,11 @@ # pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 import pytest @@ -35,7 +42,7 @@ class TestTextAnalysisCaseAsync(TestTextAnalysisAsync): @TextAnalysisPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_analyze_text_recognize_pii_async(self, text_analysis_endpoint, text_analysis_key): + async def test_recognize_pii_async(self, text_analysis_endpoint, text_analysis_key): async with self.create_client(text_analysis_endpoint, text_analysis_key) as client: text_a = ( "Parker Doe has repaid all of their loans as of 2020-04-25. Their SSN is 859-98-0987. To contact them, " diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii_confidence_score_threshold.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii_confidence_score.py similarity index 61% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii_confidence_score_threshold.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii_confidence_score.py index 01a2241db0b1..4d7e0e7dcf31 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii_confidence_score_threshold.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii_confidence_score.py @@ -1,3 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy @@ -8,8 +15,6 @@ MultiLanguageInput, TextPiiEntitiesRecognitionInput, AnalyzeTextPiiResult, - PiiResultWithDetectedLanguage, - PiiEntity, ConfidenceScoreThreshold, ConfidenceScoreThresholdOverride, PiiActionContent, @@ -18,7 +23,7 @@ TextAnalysisPreparer = functools.partial( EnvironmentVariableLoader, "text_analysis", - text_analysis_endpoint="https://Sanitized.azure-api.net/", + text_analysis_endpoint="https://Sanitized.cognitiveservices.azure.com/", text_analysis_key="fake_key", ) @@ -31,7 +36,7 @@ def create_client(self, endpoint: str, key: str) -> TextAnalysisClient: class TestTextAnalysisCase_NewPIIThresholds(TestTextAnalysis): @TextAnalysisPreparer() @recorded_by_proxy - def test_analyze_text_recognize_pii_confidence_score_threshold(self, text_analysis_endpoint, text_analysis_key): + def test_recognize_pii_confidence_score(self, text_analysis_endpoint, text_analysis_key): client = self.create_client(text_analysis_endpoint, text_analysis_key) # Input documents @@ -46,15 +51,11 @@ def test_analyze_text_recognize_pii_confidence_score_threshold(self, text_analys # Confidence score overrides ssn_override = ConfidenceScoreThresholdOverride(value=0.9, entity="USSocialSecurityNumber") - email_override = ConfidenceScoreThresholdOverride( - value=0.9, entity="Email" - ) - confidence_threshold = ConfidenceScoreThreshold( - default=0.3, overrides=[ssn_override, email_override] - ) + email_override = ConfidenceScoreThresholdOverride(value=0.9, entity="Email") + confidence_threshold = ConfidenceScoreThreshold(default=0.3, overrides=[ssn_override, email_override]) # Parameters parameters = PiiActionContent( - pii_categories=["All"], disable_entity_validation=True, confidence_score_threshold=confidence_threshold + pii_categories=["All"], confidence_score_threshold=confidence_threshold ) body = TextPiiEntitiesRecognitionInput(text_input=text_input, action_content=parameters) @@ -73,16 +74,16 @@ def test_analyze_text_recognize_pii_confidence_score_threshold(self, text_analys # Person should be masked out in text; SSN & Email should remain (filtered out as entities) assert "John Doe" not in redacted - assert "222-45-6789" in redacted - assert "john@example.com" in redacted + assert doc.entities is not None + assert len(doc.entities) > 0 + + # Person is present + assert any(e.category == "Person" for e in doc.entities), "Expected at least one Person entity" - # Only Person entities should be returned (SSN & Email removed by 0.9 thresholds) - assert len(doc.entities) == 2 - cats = {e.category for e in doc.entities} - assert cats == {"Person"} + # Verify SSN / Email are NOT returned as entities + bad_categories = {"USSocialSecurityNumber", "Email"} + bad_types = {"USSocialSecurityNumber", "Email"} - # Quick sanity on masking and confidence (no brittle exact names) for e in doc.entities: - assert e.category == "Person" - assert e.mask is not None and e.mask != e.text # masked - assert e.confidence_score >= 0.3 # respects default floor + assert e.category not in bad_categories + assert e.type not in bad_types diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii_confidence_score_threshold_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii_confidence_score_async.py similarity index 62% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii_confidence_score_threshold_async.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii_confidence_score_async.py index b5f54e036531..4e40209054fd 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii_confidence_score_threshold_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii_confidence_score_async.py @@ -1,4 +1,11 @@ # pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 import pytest @@ -14,8 +21,6 @@ MultiLanguageInput, TextPiiEntitiesRecognitionInput, AnalyzeTextPiiResult, - PiiResultWithDetectedLanguage, - PiiEntity, ConfidenceScoreThreshold, ConfidenceScoreThresholdOverride, PiiActionContent, @@ -24,7 +29,7 @@ TextAnalysisPreparer = functools.partial( EnvironmentVariableLoader, "text_analysis", - text_analysis_endpoint="https://Sanitized.azure-api.net/", + text_analysis_endpoint="https://Sanitized.cognitiveservices.azure.com/", text_analysis_key="fake_key", ) @@ -38,7 +43,7 @@ class TestTextAnalysisCase_NewPIIThresholds(TestTextAnalysis): @TextAnalysisPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_analyze_text_recognize_pii_confidence_score_threshold_async( + async def test_recognize_pii_confidence_score_async( # pylint: disable=name-too-long self, text_analysis_endpoint, text_analysis_key ): async with self.create_client(text_analysis_endpoint, text_analysis_key) as client: @@ -55,16 +60,12 @@ async def test_analyze_text_recognize_pii_confidence_score_threshold_async( # Confidence score overrides ssn_override = ConfidenceScoreThresholdOverride(value=0.9, entity="USSocialSecurityNumber") - email_override = ConfidenceScoreThresholdOverride( - value=0.9, entity="Email" - ) - confidence_threshold = ConfidenceScoreThreshold( - default=0.3, overrides=[ssn_override, email_override] - ) + email_override = ConfidenceScoreThresholdOverride(value=0.9, entity="Email") + confidence_threshold = ConfidenceScoreThreshold(default=0.3, overrides=[ssn_override, email_override]) # Parameters parameters = PiiActionContent( - pii_categories=["All"], disable_entity_validation=True, confidence_score_threshold=confidence_threshold + pii_categories=["All"], confidence_score_threshold=confidence_threshold ) body = TextPiiEntitiesRecognitionInput(text_input=text_input, action_content=parameters) @@ -81,18 +82,18 @@ async def test_analyze_text_recognize_pii_confidence_score_threshold_async( doc = result.results.documents[0] redacted = doc.redacted_text - # Person should be masked out in text; SSN & Email should remain (filtered out as entities) + # Person should be masked out in text; assert "John Doe" not in redacted - assert "222-45-6789" in redacted - assert "john@example.com" in redacted + assert doc.entities is not None + assert len(doc.entities) > 0 + + # Person is present + assert any(e.category == "Person" for e in doc.entities), "Expected at least one Person entity" - # Only Person entities should be returned (SSN & Email removed by 0.9 thresholds) - assert len(doc.entities) == 2 - cats = {e.category for e in doc.entities} - assert cats == {"Person"} + # Verify SSN / Email are NOT returned as entities + bad_categories = {"USSocialSecurityNumber", "Email"} + bad_types = {"USSocialSecurityNumber", "Email"} - # Quick sanity on masking and confidence (no brittle exact names) for e in doc.entities: - assert e.category == "Person" - assert e.mask is not None and e.mask != e.text # masked - assert e.confidence_score >= 0.3 # respects default floor + assert e.category not in bad_categories + assert e.type not in bad_types diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii_redaction_policies.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii_redaction_policies.py similarity index 86% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii_redaction_policies.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii_redaction_policies.py index 19e2eb955185..c5e322684e5e 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii_redaction_policies.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii_redaction_policies.py @@ -1,3 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy @@ -17,7 +24,7 @@ TextAnalysisPreparer = functools.partial( EnvironmentVariableLoader, "text_analysis", - text_analysis_endpoint="https://Sanitized.azure-api.net/", + text_analysis_endpoint="https://Sanitized.cognitiveservices.azure.com/", text_analysis_key="fake_key", ) @@ -30,7 +37,7 @@ def create_client(self, endpoint: str, key: str) -> TextAnalysisClient: class TestTextAnalysisCase(TestTextAnalysis): @TextAnalysisPreparer() @recorded_by_proxy - def test_analyze_text_recognize_pii_redaction_policies(self, text_analysis_endpoint, text_analysis_key): + def test_recognize_pii_redaction_policies(self, text_analysis_endpoint, text_analysis_key): client = self.create_client(text_analysis_endpoint, text_analysis_key) # Documents diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii_redaction_policies_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii_redaction_policies_async.py similarity index 86% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii_redaction_policies_async.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii_redaction_policies_async.py index ac182453bf92..b87de711542f 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_recognize_pii_redaction_policies_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_recognize_pii_redaction_policies_async.py @@ -1,3 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 import pytest @@ -13,8 +20,6 @@ MultiLanguageInput, TextPiiEntitiesRecognitionInput, AnalyzeTextPiiResult, - PiiResultWithDetectedLanguage, - PiiEntity, PiiActionContent, EntityMaskPolicyType, CharacterMaskPolicyType, @@ -24,7 +29,7 @@ TextAnalysisPreparer = functools.partial( EnvironmentVariableLoader, "text_analysis", - text_analysis_endpoint="https://Sanitized.azure-api.net/", + text_analysis_endpoint="https://Sanitized.cognitiveservices.azure.com/", text_analysis_key="fake_key", ) @@ -38,7 +43,7 @@ class TestTextAnalysisCase(TestTextAnalysis): @TextAnalysisPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_analyze_text_recognize_pii_redaction_policies_async(self, text_analysis_endpoint, text_analysis_key): + async def test_recognize_pii_redaction_policies_async(self, text_analysis_endpoint, text_analysis_key): # pylint: disable=name-too-long async with self.create_client(text_analysis_endpoint, text_analysis_key) as client: # Documents diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_single_label_classification_lro_task.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_single_label_classify.py similarity index 86% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_single_label_classification_lro_task.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_single_label_classify.py index 25ae2e4e39f9..7a2c57c9b1b1 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_single_label_classification_lro_task.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_single_label_classify.py @@ -1,3 +1,11 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy @@ -30,7 +38,7 @@ def create_client(self, endpoint: str, key: str) -> TextAnalysisClient: class TestTextAnalysisCase(TestTextAnalysis): @TextAnalysisPreparer() @recorded_by_proxy - def test_analyze_text_custom_single_label_classification_lro_task(self, text_analysis_endpoint, text_analysis_key): + def test_single_label_classify(self, text_analysis_endpoint, text_analysis_key): client = self.create_client(text_analysis_endpoint, text_analysis_key) project_name = "single-class-project" diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_single_label_classification_lro_task_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_single_label_classify_async.py similarity index 88% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_single_label_classification_lro_task_async.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_single_label_classify_async.py index 99db2549854e..886e7d50fea6 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_custom_single_label_classification_lro_task_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_single_label_classify_async.py @@ -1,3 +1,11 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 import pytest @@ -36,7 +44,7 @@ class TestTextAnalysisCaseAsync(TestTextAnalysisAsync): @TextAnalysisPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_analyze_text_custom_single_label_classification_lro_task_async( + async def test_single_label_classify_async( self, text_analysis_endpoint, text_analysis_key ): async with self.create_client(text_analysis_endpoint, text_analysis_key) as client: diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_sentiment.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_text_sentiment.py similarity index 84% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_sentiment.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_text_sentiment.py index 44e26e04f226..c2d78a07bc5e 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_sentiment.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_text_sentiment.py @@ -1,3 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 from devtools_testutils import AzureRecordedTestCase, EnvironmentVariableLoader, recorded_by_proxy @@ -28,7 +35,7 @@ def create_client(self, endpoint: str, key: str) -> TextAnalysisClient: class TestTextAnalysisCase(TestTextAnalysis): @TextAnalysisPreparer() @recorded_by_proxy - def test_analyze_text_sentiment(self, text_analysis_endpoint, text_analysis_key): + def test_text_sentiment(self, text_analysis_endpoint, text_analysis_key): client = self.create_client(text_analysis_endpoint, text_analysis_key) text_a = ( diff --git a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_sentiment_async.py b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_text_sentiment_async.py similarity index 85% rename from sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_sentiment_async.py rename to sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_text_sentiment_async.py index 3b02385d940d..e3c207b72027 100644 --- a/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_analyze_text_sentiment_async.py +++ b/sdk/cognitivelanguage/azure-ai-textanalytics/tests/test_text_sentiment_async.py @@ -1,3 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 import pytest @@ -34,7 +41,7 @@ class TestTextAnalysisCaseAsync(TestTextAnalysisAsync): @TextAnalysisPreparer() @recorded_by_proxy_async @pytest.mark.asyncio - async def test_analyze_text_sentiment_async(self, text_analysis_endpoint, text_analysis_key): + async def test_text_sentiment_async(self, text_analysis_endpoint, text_analysis_key): async with self.create_client(text_analysis_endpoint, text_analysis_key) as client: text_a = ( "The food and service were unacceptable, but the concierge were nice. After talking to them about the "