diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/_meta.json b/sdk/anomalydetector/azure-ai-anomalydetector/_meta.json new file mode 100644 index 000000000000..77f1e7e475bc --- /dev/null +++ b/sdk/anomalydetector/azure-ai-anomalydetector/_meta.json @@ -0,0 +1,15 @@ +{ + "commit": "324a5095c5b33493b59da70803a2e2e7f35034a9", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "typespec_src": "specification/cognitiveservices/AnomalyDetector", + "@azure-tools/typespec-python": { + "version": "0.8.4", + "resolved": "https://registry.npmjs.org/@azure-tools/typespec-python/-/typespec-python-0.8.4.tgz", + "dependencies": { + "@autorest/python": { + "version": "6.4.11", + "resolved": "https://registry.npmjs.org/@autorest/python/-/python-6.4.11.tgz" + } + } + } +} \ No newline at end of file diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_client.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_client.py index dce24dbcda8e..f11ef5c2f10f 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_client.py +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_client.py @@ -20,23 +20,23 @@ class AnomalyDetectorClient(AnomalyDetectorClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword """The Anomaly Detector API detects anomalies automatically in time series data. - It supports two kinds of mode, one is for stateless using, another is for - stateful using. In stateless mode, there are three functionalities. Entire - Detect is for detecting the whole series with model trained by the time series, - Last Detect is detecting last point with model trained by points before. - ChangePoint Detect is for detecting trend changes in time series. In stateful - mode, user can store time series, the stored time series will be used for - detection anomalies. Under this mode, user can still use the above three - functionalities by only giving a time range without preparing time series in - client side. Besides the above three functionalities, stateful model also - provide group based detection and labeling service. By leveraging labeling - service user can provide labels for each detection result, these labels will be + It supports both a stateless detection mode and a + stateful detection mode. In stateless mode, there are three functionalities. Entire + Detect is for detecting the whole series, with the model trained by the time series. + Last Detect is for detecting the last point, with the model trained by points before. + ChangePoint Detect is for detecting trend changes in the time series. In stateful + mode, the user can store time series. The stored time series will be used for + detection anomalies. In this mode, the user can still use the preceding three + functionalities by only giving a time range without preparing time series on the + client side. Besides the preceding three functionalities, the stateful model + provides group-based detection and labeling services. By using the labeling + service, the user can provide labels for each detection result. These labels will be used for retuning or regenerating detection models. Inconsistency detection is - a kind of group based detection, this detection will find inconsistency ones in - a set of time series. By using anomaly detector service, business customers can + a kind of group-based detection that finds inconsistencies in + a set of time series. By using the anomaly detector service, business customers can discover incidents and establish a logic flow for root cause analysis. - :param endpoint: Supported Cognitive Services endpoints (protocol and hostname, for example: + :param endpoint: Supported Azure Cognitive Services endpoints (protocol and host name, such as https://westus2.api.cognitive.microsoft.com). Required. :type endpoint: str :param credential: Credential needed for the client to connect to Azure. Required. @@ -49,7 +49,7 @@ class AnomalyDetectorClient(AnomalyDetectorClientOperationsMixin): # pylint: di def __init__(self, endpoint: str, credential: AzureKeyCredential, **kwargs: Any) -> None: _endpoint = "{Endpoint}/anomalydetector/{ApiVersion}" self._config = AnomalyDetectorClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) - self._client = PipelineClient(base_url=_endpoint, config=self._config, **kwargs) + self._client: PipelineClient = PipelineClient(base_url=_endpoint, config=self._config, **kwargs) self._serialize = Serializer() self._deserialize = Deserializer() @@ -91,5 +91,5 @@ def __enter__(self) -> "AnomalyDetectorClient": self._client.__enter__() return self - def __exit__(self, *exc_details) -> None: + def __exit__(self, *exc_details: Any) -> None: self._client.__exit__(*exc_details) diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_configuration.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_configuration.py index 3bebdc1f4a5d..3946a5c5ec1a 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_configuration.py +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_configuration.py @@ -6,7 +6,6 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys from typing import Any from azure.core.configuration import Configuration @@ -15,11 +14,6 @@ from ._version import VERSION -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports - class AnomalyDetectorClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for AnomalyDetectorClient. @@ -27,7 +21,7 @@ class AnomalyDetectorClientConfiguration(Configuration): # pylint: disable=too- Note that all parameters used to create this instance are saved as instance attributes. - :param endpoint: Supported Cognitive Services endpoints (protocol and hostname, for example: + :param endpoint: Supported Azure Cognitive Services endpoints (protocol and host name, such as https://westus2.api.cognitive.microsoft.com). Required. :type endpoint: str :param credential: Credential needed for the client to connect to Azure. Required. @@ -39,7 +33,7 @@ class AnomalyDetectorClientConfiguration(Configuration): # pylint: disable=too- def __init__(self, endpoint: str, credential: AzureKeyCredential, **kwargs: Any) -> None: super(AnomalyDetectorClientConfiguration, self).__init__(**kwargs) - api_version: Literal["v1.1"] = kwargs.pop("api_version", "v1.1") + api_version: str = kwargs.pop("api_version", "v1.1") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_model_base.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_model_base.py index da265d2e0c19..7bce6c197f6a 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_model_base.py +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_model_base.py @@ -4,48 +4,45 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- +# pylint: disable=protected-access, arguments-differ, signature-differs, broad-except +# pyright: reportGeneralTypeIssues=false import functools import sys import logging import base64 import re -import isodate -from json import JSONEncoder +import copy import typing -from datetime import datetime, date, time, timedelta -from azure.core.utils._utils import _FixedOffset -from collections.abc import MutableMapping +from datetime import datetime, date, time, timedelta, timezone +from json import JSONEncoder +import isodate from azure.core.exceptions import DeserializationError from azure.core import CaseInsensitiveEnumMeta from azure.core.pipeline import PipelineResponse -import copy - -_LOGGER = logging.getLogger(__name__) - -__all__ = ["NULL", "AzureJSONEncoder", "Model", "rest_field", "rest_discriminator"] +from azure.core.serialization import _Null # pylint: disable=protected-access +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping -class _Null(object): - """To create a Falsy object""" - - def __bool__(self): - return False +_LOGGER = logging.getLogger(__name__) - __nonzero__ = __bool__ # Python2 compatibility +__all__ = ["AzureJSONEncoder", "Model", "rest_field", "rest_discriminator"] -NULL = _Null() -""" -A falsy sentinel object which is supposed to be used to specify attributes -with no data. This gets serialized to `null` on the wire. -""" +TZ_UTC = timezone.utc def _timedelta_as_isostr(td: timedelta) -> str: """Converts a datetime.timedelta object into an ISO 8601 formatted string, e.g. 'P4DT12H30M05S' Function adapted from the Tin Can Python project: https://github.com/RusticiSoftware/TinCanPython + + :param timedelta td: The timedelta to convert + :rtype: str + :return: ISO8601 version of this timedelta """ # Split seconds to larger units @@ -93,7 +90,12 @@ def _timedelta_as_isostr(td: timedelta) -> str: def _datetime_as_isostr(dt: typing.Union[datetime, date, time, timedelta]) -> str: - """Converts a datetime.(datetime|date|time|timedelta) object into an ISO 8601 formatted string""" + """Converts a datetime.(datetime|date|time|timedelta) object into an ISO 8601 formatted string + + :param timedelta dt: The date object to convert + :rtype: str + :return: ISO8601 version of this datetime + """ # First try datetime.datetime if hasattr(dt, "year") and hasattr(dt, "hour"): dt = typing.cast(datetime, dt) @@ -114,14 +116,6 @@ def _datetime_as_isostr(dt: typing.Union[datetime, date, time, timedelta]) -> st return _timedelta_as_isostr(dt) -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = _FixedOffset(0) # type: ignore - - def _serialize_bytes(o) -> str: return base64.b64encode(o).decode() @@ -141,7 +135,7 @@ def _serialize_datetime(o): def _is_readonly(p): try: - return p._readonly + return p._readonly # pylint: disable=protected-access except AttributeError: return False @@ -151,10 +145,14 @@ class AzureJSONEncoder(JSONEncoder): def default(self, o): # pylint: disable=too-many-return-statements if _is_model(o): - readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + readonly_props = [ + p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p) + ] # pylint: disable=protected-access return {k: v for k, v in o.items() if k not in readonly_props} if isinstance(o, (bytes, bytearray)): return base64.b64encode(o).decode() + if isinstance(o, _Null): + return None try: return super(AzureJSONEncoder, self).default(o) except TypeError: @@ -174,7 +172,7 @@ def default(self, o): # pylint: disable=too-many-return-statements return super(AzureJSONEncoder, self).default(o) -_VALID_DATE = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") +_VALID_DATE = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" + r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: @@ -182,6 +180,7 @@ def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: :param str attr: response string to be deserialized. :rtype: ~datetime.datetime + :returns: The datetime object from that input """ if isinstance(attr, datetime): # i'm already deserialized @@ -212,7 +211,8 @@ def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: def _deserialize_date(attr: typing.Union[str, date]) -> date: """Deserialize ISO-8601 formatted string into Date object. :param str attr: response string to be deserialized. - :rtype: Date + :rtype: date + :returns: The date object from that input """ # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. if isinstance(attr, date): @@ -225,6 +225,7 @@ def _deserialize_time(attr: typing.Union[str, time]) -> time: :param str attr: response string to be deserialized. :rtype: datetime.time + :returns: The time object from that input """ if isinstance(attr, time): return attr @@ -258,7 +259,8 @@ def _get_model(module_name: str, model_name: str): module_end = module_name.rsplit(".", 1)[0] module = sys.modules[module_end] models.update({k: v for k, v in module.__dict__.items() if isinstance(v, type)}) - model_name = model_name.split(".")[-1] + if isinstance(model_name, str): + model_name = model_name.split(".")[-1] if model_name not in models: return model_name return models[model_name] @@ -267,11 +269,11 @@ def _get_model(module_name: str, model_name: str): _UNSET = object() -class _MyMutableMapping(MutableMapping): +class _MyMutableMapping(MutableMapping[str, typing.Any]): # pylint: disable=unsubscriptable-object def __init__(self, data: typing.Dict[str, typing.Any]) -> None: self._data = copy.deepcopy(data) - def __contains__(self, key: str) -> bool: + def __contains__(self, key: typing.Any) -> bool: return key in self._data def __getitem__(self, key: str) -> typing.Any: @@ -292,13 +294,13 @@ def __len__(self) -> int: def __ne__(self, other: typing.Any) -> bool: return not self.__eq__(other) - def keys(self) -> typing.KeysView: + def keys(self) -> typing.KeysView[str]: return self._data.keys() - def values(self) -> typing.ValuesView: + def values(self) -> typing.ValuesView[typing.Any]: return self._data.values() - def items(self) -> typing.ItemsView: + def items(self) -> typing.ItemsView[str, typing.Any]: return self._data.items() def get(self, key: str, default: typing.Any = None) -> typing.Any: @@ -307,15 +309,15 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: except KeyError: return default - @typing.overload - def pop(self, key: str) -> typing.Any: + @typing.overload # type: ignore + def pop(self, key: str) -> typing.Any: # pylint: disable=no-member ... @typing.overload def pop(self, key: str, default: typing.Any) -> typing.Any: ... - def pop(self, key: typing.Any, default: typing.Any = _UNSET) -> typing.Any: + def pop(self, key: str, default: typing.Any = _UNSET) -> typing.Any: if default is _UNSET: return self._data.pop(key) return self._data.pop(key, default) @@ -329,7 +331,7 @@ def clear(self) -> None: def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: self._data.update(*args, **kwargs) - @typing.overload + @typing.overload # type: ignore def setdefault(self, key: str) -> typing.Any: ... @@ -337,7 +339,7 @@ def setdefault(self, key: str) -> typing.Any: def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... - def setdefault(self, key: typing.Any, default: typing.Any = _UNSET) -> typing.Any: + def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: if default is _UNSET: return self._data.setdefault(key) return self._data.setdefault(key, default) @@ -383,14 +385,14 @@ def _get_rest_field( return None -def _create_value(rest_field: typing.Optional["_RestField"], value: typing.Any) -> typing.Any: - return _deserialize(rest_field._type, value) if (rest_field and rest_field._is_model) else _serialize(value) +def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typing.Any: + return _deserialize(rf._type, value) if (rf and rf._is_model) else _serialize(value) class Model(_MyMutableMapping): _is_model = True - def __init__(self, *args, **kwargs): + def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: class_name = self.__class__.__name__ if len(args) > 1: raise TypeError(f"{class_name}.__init__() takes 2 positional arguments but {len(args) + 1} were given") @@ -408,13 +410,15 @@ def __init__(self, *args, **kwargs): if non_attr_kwargs: # actual type errors only throw the first wrong keyword arg they see, so following that. raise TypeError(f"{class_name}.__init__() got an unexpected keyword argument '{non_attr_kwargs[0]}'") - dict_to_pass.update({self._attr_to_rest_field[k]._rest_name: _serialize(v) for k, v in kwargs.items()}) + dict_to_pass.update( + {self._attr_to_rest_field[k]._rest_name: _serialize(v) for k, v in kwargs.items() if v is not None} + ) super().__init__(dict_to_pass) - def copy(self): + def copy(self) -> "Model": return Model(self.__dict__) - def __new__(cls, *args: typing.Any, **kwargs: typing.Any): + def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> "Model": # pylint: disable=unused-argument # we know the last three classes in mro are going to be 'Model', 'dict', and 'object' mros = cls.__mro__[:-3][::-1] # ignore model, dict, and object parents, and reverse the mro order attr_to_rest_field: typing.Dict[str, _RestField] = { # map attribute name to rest_field property @@ -423,51 +427,52 @@ def __new__(cls, *args: typing.Any, **kwargs: typing.Any): annotations = { k: v for mro_class in mros - if hasattr(mro_class, "__annotations__") - for k, v in mro_class.__annotations__.items() + if hasattr(mro_class, "__annotations__") # pylint: disable=no-member + for k, v in mro_class.__annotations__.items() # pylint: disable=no-member } - for attr, rest_field in attr_to_rest_field.items(): - rest_field._module = cls.__module__ - if not rest_field._type: - rest_field._type = rest_field._get_deserialize_callable_from_annotation(annotations.get(attr, None)) - if not rest_field._rest_name_input: - rest_field._rest_name_input = attr - cls._attr_to_rest_field: typing.Dict[str, _RestField] = {k: v for k, v in attr_to_rest_field.items()} + for attr, rf in attr_to_rest_field.items(): + rf._module = cls.__module__ + if not rf._type: + rf._type = rf._get_deserialize_callable_from_annotation(annotations.get(attr, None)) + if not rf._rest_name_input: + rf._rest_name_input = attr + cls._attr_to_rest_field: typing.Dict[str, _RestField] = dict(attr_to_rest_field.items()) - return super().__new__(cls) + return super().__new__(cls) # pylint: disable=no-value-for-parameter - def __init_subclass__(cls, discriminator=None): + def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: for base in cls.__bases__: - if hasattr(base, "__mapping__"): - base.__mapping__[discriminator or cls.__name__] = cls + if hasattr(base, "__mapping__"): # pylint: disable=no-member + base.__mapping__[discriminator or cls.__name__] = cls # type: ignore # pylint: disable=no-member @classmethod def _get_discriminator(cls) -> typing.Optional[str]: for v in cls.__dict__.values(): - if isinstance(v, _RestField) and v._is_discriminator: - return v._rest_name + if isinstance(v, _RestField) and v._is_discriminator: # pylint: disable=protected-access + return v._rest_name # pylint: disable=protected-access return None @classmethod def _deserialize(cls, data): - if not hasattr(cls, "__mapping__"): + if not hasattr(cls, "__mapping__"): # pylint: disable=no-member return cls(data) discriminator = cls._get_discriminator() - mapped_cls = cls.__mapping__.get(data.get(discriminator), cls) + mapped_cls = cls.__mapping__.get(data.get(discriminator), cls) # pylint: disable=no-member if mapped_cls == cls: return cls(data) - return mapped_cls._deserialize(data) + return mapped_cls._deserialize(data) # pylint: disable=protected-access -def _get_deserialize_callable_from_annotation( - annotation: typing.Any, - module: str, +def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-return-statements, too-many-statements + annotation: typing.Any, module: typing.Optional[str], rf: typing.Optional["_RestField"] = None ) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: if not annotation or annotation in [int, float]: return None try: - if _is_model(_get_model(module, annotation)): + if module and _is_model(_get_model(module, annotation)): + if rf: + rf._is_model = True def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj): if _is_model(obj): @@ -480,23 +485,27 @@ def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj # is it a literal? try: - if annotation.__origin__ == typing.Literal: + if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports + else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + + if annotation.__origin__ == Literal: return None except AttributeError: pass - if isinstance(annotation, typing._GenericAlias): # pylint: disable=protected-access - if annotation.__origin__ is typing.Union: + if getattr(annotation, "__origin__", None) is typing.Union: - def _deserialize_with_union(union_annotation: typing._GenericAlias, obj): - for t in union_annotation.__args__: - try: - return _deserialize(t, obj, module) - except DeserializationError: - pass - raise DeserializationError() + def _deserialize_with_union(union_annotation, obj): + for t in union_annotation.__args__: + try: + return _deserialize(t, obj, module) + except DeserializationError: + pass + raise DeserializationError() - return functools.partial(_deserialize_with_union, annotation) + return functools.partial(_deserialize_with_union, annotation) # is it optional? try: @@ -505,7 +514,7 @@ def _deserialize_with_union(union_annotation: typing._GenericAlias, obj): if any(a for a in annotation.__args__ if a == type(None)): if_obj_deserializer = _get_deserialize_callable_from_annotation( - next(a for a in annotation.__args__ if a != type(None)), module + next(a for a in annotation.__args__ if a != type(None)), module, rf ) def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Callable], obj): @@ -514,11 +523,11 @@ def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Calla return _deserialize_with_callable(if_obj_deserializer, obj) return functools.partial(_deserialize_with_optional, if_obj_deserializer) - except (AttributeError): + except AttributeError: pass # is it a forward ref / in quotes? - if isinstance(annotation, str) or type(annotation) == typing.ForwardRef: + if isinstance(annotation, (str, typing.ForwardRef)): try: model_name = annotation.__forward_arg__ # type: ignore except AttributeError: @@ -528,8 +537,8 @@ def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Calla try: if annotation._name == "Dict": - key_deserializer = _get_deserialize_callable_from_annotation(annotation.__args__[0], module) - value_deserializer = _get_deserialize_callable_from_annotation(annotation.__args__[1], module) + key_deserializer = _get_deserialize_callable_from_annotation(annotation.__args__[0], module, rf) + value_deserializer = _get_deserialize_callable_from_annotation(annotation.__args__[1], module, rf) def _deserialize_dict( key_deserializer: typing.Optional[typing.Callable], @@ -565,10 +574,10 @@ def _deserialize_multiple_sequence( ) entry_deserializers = [ - _get_deserialize_callable_from_annotation(dt, module) for dt in annotation.__args__ + _get_deserialize_callable_from_annotation(dt, module, rf) for dt in annotation.__args__ ] return functools.partial(_deserialize_multiple_sequence, entry_deserializers) - deserializer = _get_deserialize_callable_from_annotation(annotation.__args__[0], module) + deserializer = _get_deserialize_callable_from_annotation(annotation.__args__[0], module, rf) def _deserialize_sequence( deserializer: typing.Optional[typing.Callable], @@ -604,6 +613,8 @@ def _deserialize_with_callable( try: if value is None: return None + if deserializer is None: + return value if isinstance(deserializer, CaseInsensitiveEnumMeta): try: return deserializer(value) @@ -612,14 +623,12 @@ def _deserialize_with_callable( return value if isinstance(deserializer, type) and issubclass(deserializer, Model): return deserializer._deserialize(value) - return deserializer(value) if deserializer else value + return typing.cast(typing.Callable[[typing.Any], typing.Any], deserializer)(value) except Exception as e: raise DeserializationError() from e -def _deserialize( - deserializer: typing.Optional[typing.Callable[[typing.Any], typing.Any]], value: typing.Any, module: str = "" -): +def _deserialize(deserializer: typing.Any, value: typing.Any, module: typing.Optional[str] = None) -> typing.Any: if isinstance(value, PipelineResponse): value = value.http_response.json() deserializer = _get_deserialize_callable_from_annotation(deserializer, module) @@ -673,7 +682,7 @@ def __set__(self, obj: Model, value) -> None: def _get_deserialize_callable_from_annotation( self, annotation: typing.Any ) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: - return _get_deserialize_callable_from_annotation(annotation, self._module) + return _get_deserialize_callable_from_annotation(annotation, self._module, self) def rest_field( diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_operations/_operations.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_operations/_operations.py index 6e61483f0ac3..04edf9c11f3e 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_operations/_operations.py +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_operations/_operations.py @@ -6,9 +6,11 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase import json import sys -from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +from typing import Any, Callable, Dict, IO, Iterable, List, Optional, TypeVar, Union, overload +import urllib.parse from azure.core.exceptions import ( ClientAuthenticationError, @@ -42,7 +44,9 @@ _SERIALIZER.client_side_validation = False -def build_anomaly_detector_detect_univariate_entire_series_request(**kwargs: Any) -> HttpRequest: +def build_anomaly_detector_detect_univariate_entire_series_request( # pylint: disable=name-too-long + **kwargs: Any, +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) @@ -59,7 +63,9 @@ def build_anomaly_detector_detect_univariate_entire_series_request(**kwargs: Any return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) -def build_anomaly_detector_detect_univariate_last_point_request(**kwargs: Any) -> HttpRequest: +def build_anomaly_detector_detect_univariate_last_point_request( # pylint: disable=name-too-long + **kwargs: Any, +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) @@ -76,7 +82,9 @@ def build_anomaly_detector_detect_univariate_last_point_request(**kwargs: Any) - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) -def build_anomaly_detector_detect_univariate_change_point_request(**kwargs: Any) -> HttpRequest: +def build_anomaly_detector_detect_univariate_change_point_request( # pylint: disable=name-too-long + **kwargs: Any, +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) @@ -93,7 +101,7 @@ def build_anomaly_detector_detect_univariate_change_point_request(**kwargs: Any) return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) -def build_anomaly_detector_get_multivariate_batch_detection_result_request( +def build_anomaly_detector_get_multivariate_batch_detection_result_request( # pylint: disable=name-too-long result_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -114,7 +122,9 @@ def build_anomaly_detector_get_multivariate_batch_detection_result_request( return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) -def build_anomaly_detector_train_multivariate_model_request(**kwargs: Any) -> HttpRequest: +def build_anomaly_detector_train_multivariate_model_request( # pylint: disable=name-too-long + **kwargs: Any, +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) @@ -131,7 +141,7 @@ def build_anomaly_detector_train_multivariate_model_request(**kwargs: Any) -> Ht return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) -def build_anomaly_detector_list_multivariate_models_request( +def build_anomaly_detector_list_multivariate_models_request( # pylint: disable=name-too-long *, skip: Optional[int] = None, top: Optional[int] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -154,7 +164,9 @@ def build_anomaly_detector_list_multivariate_models_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_anomaly_detector_delete_multivariate_model_request(model_id: str, **kwargs: Any) -> HttpRequest: +def build_anomaly_detector_delete_multivariate_model_request( # pylint: disable=name-too-long + model_id: str, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) accept = _headers.pop("Accept", "application/json") @@ -173,7 +185,9 @@ def build_anomaly_detector_delete_multivariate_model_request(model_id: str, **kw return HttpRequest(method="DELETE", url=_url, headers=_headers, **kwargs) -def build_anomaly_detector_get_multivariate_model_request(model_id: str, **kwargs: Any) -> HttpRequest: +def build_anomaly_detector_get_multivariate_model_request( # pylint: disable=name-too-long + model_id: str, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) accept = _headers.pop("Accept", "application/json") @@ -192,7 +206,9 @@ def build_anomaly_detector_get_multivariate_model_request(model_id: str, **kwarg return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) -def build_anomaly_detector_detect_multivariate_batch_anomaly_request(model_id: str, **kwargs: Any) -> HttpRequest: +def build_anomaly_detector_detect_multivariate_batch_anomaly_request( # pylint: disable=name-too-long + model_id: str, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) @@ -214,7 +230,9 @@ def build_anomaly_detector_detect_multivariate_batch_anomaly_request(model_id: s return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) -def build_anomaly_detector_detect_multivariate_last_anomaly_request(model_id: str, **kwargs: Any) -> HttpRequest: +def build_anomaly_detector_detect_multivariate_last_anomaly_request( # pylint: disable=name-too-long + model_id: str, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) @@ -243,19 +261,21 @@ def detect_univariate_entire_series( ) -> _models.UnivariateEntireDetectionResult: """Detect anomalies for the entire series in batch. - This operation generates a model with an entire series, each point is detected + This operation generates a model with an entire series. Each point is detected with the same model. With this method, points before and after a certain point - are used to determine whether it is an anomaly. The entire detection can give + are used to determine whether it's an anomaly. The entire detection can give the user an overall status of the time series. :param options: Method of univariate anomaly detection. Required. - :type options: ~anomalydetector.models.UnivariateDetectionOptions + :type options: ~azure.ai.anomalydetector.models.UnivariateDetectionOptions :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: UnivariateEntireDetectionResult. The UnivariateEntireDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.UnivariateEntireDetectionResult + :rtype: ~azure.ai.anomalydetector.models.UnivariateEntireDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ @@ -265,9 +285,9 @@ def detect_univariate_entire_series( ) -> _models.UnivariateEntireDetectionResult: """Detect anomalies for the entire series in batch. - This operation generates a model with an entire series, each point is detected + This operation generates a model with an entire series. Each point is detected with the same model. With this method, points before and after a certain point - are used to determine whether it is an anomaly. The entire detection can give + are used to determine whether it's an anomaly. The entire detection can give the user an overall status of the time series. :param options: Method of univariate anomaly detection. Required. @@ -275,9 +295,11 @@ def detect_univariate_entire_series( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: UnivariateEntireDetectionResult. The UnivariateEntireDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.UnivariateEntireDetectionResult + :rtype: ~azure.ai.anomalydetector.models.UnivariateEntireDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ @@ -287,9 +309,9 @@ def detect_univariate_entire_series( ) -> _models.UnivariateEntireDetectionResult: """Detect anomalies for the entire series in batch. - This operation generates a model with an entire series, each point is detected + This operation generates a model with an entire series. Each point is detected with the same model. With this method, points before and after a certain point - are used to determine whether it is an anomaly. The entire detection can give + are used to determine whether it's an anomaly. The entire detection can give the user an overall status of the time series. :param options: Method of univariate anomaly detection. Required. @@ -297,9 +319,11 @@ def detect_univariate_entire_series( :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: UnivariateEntireDetectionResult. The UnivariateEntireDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.UnivariateEntireDetectionResult + :rtype: ~azure.ai.anomalydetector.models.UnivariateEntireDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ @@ -309,20 +333,22 @@ def detect_univariate_entire_series( ) -> _models.UnivariateEntireDetectionResult: """Detect anomalies for the entire series in batch. - This operation generates a model with an entire series, each point is detected + This operation generates a model with an entire series. Each point is detected with the same model. With this method, points before and after a certain point - are used to determine whether it is an anomaly. The entire detection can give + are used to determine whether it's an anomaly. The entire detection can give the user an overall status of the time series. - :param options: Method of univariate anomaly detection. Is one of the following types: model, - JSON, IO Required. - :type options: ~anomalydetector.models.UnivariateDetectionOptions or JSON or IO + :param options: Method of univariate anomaly detection. Is one of the following types: + UnivariateDetectionOptions, JSON, IO Required. + :type options: ~azure.ai.anomalydetector.models.UnivariateDetectionOptions or JSON or IO :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default value is None. :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: UnivariateEntireDetectionResult. The UnivariateEntireDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.UnivariateEntireDetectionResult + :rtype: ~azure.ai.anomalydetector.models.UnivariateEntireDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { @@ -341,10 +367,10 @@ def detect_univariate_entire_series( content_type = content_type or "application/json" _content = None - if isinstance(options, (IO, bytes)): + if isinstance(options, (IOBase, bytes)): _content = options else: - _content = json.dumps(options, cls=AzureJSONEncoder) + _content = json.dumps(options, cls=AzureJSONEncoder) # type: ignore request = build_anomaly_detector_detect_univariate_entire_series_request( content_type=content_type, @@ -360,8 +386,9 @@ def detect_univariate_entire_series( } request.url = self._client.format_url(request.url, **path_format_arguments) + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -371,7 +398,10 @@ def detect_univariate_entire_series( error = _deserialize(_models.AnomalyDetectorError, response.json()) raise HttpResponseError(response=response, model=error) - deserialized = _deserialize(_models.UnivariateEntireDetectionResult, response.json()) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.UnivariateEntireDetectionResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -384,17 +414,19 @@ def detect_univariate_last_point( ) -> _models.UnivariateLastDetectionResult: """Detect anomaly status of the latest point in time series. - This operation generates a model using the points that you sent into the API, + This operation generates a model by using the points that you sent in to the API and based on all data to determine whether the last point is anomalous. :param options: Method of univariate anomaly detection. Required. - :type options: ~anomalydetector.models.UnivariateDetectionOptions + :type options: ~azure.ai.anomalydetector.models.UnivariateDetectionOptions :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: UnivariateLastDetectionResult. The UnivariateLastDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.UnivariateLastDetectionResult + :rtype: ~azure.ai.anomalydetector.models.UnivariateLastDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ @@ -404,7 +436,7 @@ def detect_univariate_last_point( ) -> _models.UnivariateLastDetectionResult: """Detect anomaly status of the latest point in time series. - This operation generates a model using the points that you sent into the API, + This operation generates a model by using the points that you sent in to the API and based on all data to determine whether the last point is anomalous. :param options: Method of univariate anomaly detection. Required. @@ -412,9 +444,11 @@ def detect_univariate_last_point( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: UnivariateLastDetectionResult. The UnivariateLastDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.UnivariateLastDetectionResult + :rtype: ~azure.ai.anomalydetector.models.UnivariateLastDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ @@ -424,7 +458,7 @@ def detect_univariate_last_point( ) -> _models.UnivariateLastDetectionResult: """Detect anomaly status of the latest point in time series. - This operation generates a model using the points that you sent into the API, + This operation generates a model by using the points that you sent in to the API and based on all data to determine whether the last point is anomalous. :param options: Method of univariate anomaly detection. Required. @@ -432,9 +466,11 @@ def detect_univariate_last_point( :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: UnivariateLastDetectionResult. The UnivariateLastDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.UnivariateLastDetectionResult + :rtype: ~azure.ai.anomalydetector.models.UnivariateLastDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ @@ -444,18 +480,20 @@ def detect_univariate_last_point( ) -> _models.UnivariateLastDetectionResult: """Detect anomaly status of the latest point in time series. - This operation generates a model using the points that you sent into the API, + This operation generates a model by using the points that you sent in to the API and based on all data to determine whether the last point is anomalous. - :param options: Method of univariate anomaly detection. Is one of the following types: model, - JSON, IO Required. - :type options: ~anomalydetector.models.UnivariateDetectionOptions or JSON or IO + :param options: Method of univariate anomaly detection. Is one of the following types: + UnivariateDetectionOptions, JSON, IO Required. + :type options: ~azure.ai.anomalydetector.models.UnivariateDetectionOptions or JSON or IO :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default value is None. :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: UnivariateLastDetectionResult. The UnivariateLastDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.UnivariateLastDetectionResult + :rtype: ~azure.ai.anomalydetector.models.UnivariateLastDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { @@ -474,10 +512,10 @@ def detect_univariate_last_point( content_type = content_type or "application/json" _content = None - if isinstance(options, (IO, bytes)): + if isinstance(options, (IOBase, bytes)): _content = options else: - _content = json.dumps(options, cls=AzureJSONEncoder) + _content = json.dumps(options, cls=AzureJSONEncoder) # type: ignore request = build_anomaly_detector_detect_univariate_last_point_request( content_type=content_type, @@ -493,8 +531,9 @@ def detect_univariate_last_point( } request.url = self._client.format_url(request.url, **path_format_arguments) + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -504,7 +543,10 @@ def detect_univariate_last_point( error = _deserialize(_models.AnomalyDetectorError, response.json()) raise HttpResponseError(response=response, model=error) - deserialized = _deserialize(_models.UnivariateLastDetectionResult, response.json()) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.UnivariateLastDetectionResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -517,20 +559,22 @@ def detect_univariate_change_point( options: _models.UnivariateChangePointDetectionOptions, *, content_type: str = "application/json", - **kwargs: Any + **kwargs: Any, ) -> _models.UnivariateChangePointDetectionResult: """Detect change point for the entire series. - Evaluate change point score of every series point. + Evaluate the change point score of every series point. :param options: Method of univariate anomaly detection. Required. - :type options: ~anomalydetector.models.UnivariateChangePointDetectionOptions + :type options: ~azure.ai.anomalydetector.models.UnivariateChangePointDetectionOptions :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: UnivariateChangePointDetectionResult. The UnivariateChangePointDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.UnivariateChangePointDetectionResult + :rtype: ~azure.ai.anomalydetector.models.UnivariateChangePointDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ @@ -540,16 +584,18 @@ def detect_univariate_change_point( ) -> _models.UnivariateChangePointDetectionResult: """Detect change point for the entire series. - Evaluate change point score of every series point. + Evaluate the change point score of every series point. :param options: Method of univariate anomaly detection. Required. :type options: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: UnivariateChangePointDetectionResult. The UnivariateChangePointDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.UnivariateChangePointDetectionResult + :rtype: ~azure.ai.anomalydetector.models.UnivariateChangePointDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ @@ -559,16 +605,18 @@ def detect_univariate_change_point( ) -> _models.UnivariateChangePointDetectionResult: """Detect change point for the entire series. - Evaluate change point score of every series point. + Evaluate the change point score of every series point. :param options: Method of univariate anomaly detection. Required. :type options: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: UnivariateChangePointDetectionResult. The UnivariateChangePointDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.UnivariateChangePointDetectionResult + :rtype: ~azure.ai.anomalydetector.models.UnivariateChangePointDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ @@ -578,17 +626,20 @@ def detect_univariate_change_point( ) -> _models.UnivariateChangePointDetectionResult: """Detect change point for the entire series. - Evaluate change point score of every series point. + Evaluate the change point score of every series point. - :param options: Method of univariate anomaly detection. Is one of the following types: model, - JSON, IO Required. - :type options: ~anomalydetector.models.UnivariateChangePointDetectionOptions or JSON or IO + :param options: Method of univariate anomaly detection. Is one of the following types: + UnivariateChangePointDetectionOptions, JSON, IO Required. + :type options: ~azure.ai.anomalydetector.models.UnivariateChangePointDetectionOptions or JSON + or IO :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default value is None. :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: UnivariateChangePointDetectionResult. The UnivariateChangePointDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.UnivariateChangePointDetectionResult + :rtype: ~azure.ai.anomalydetector.models.UnivariateChangePointDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { @@ -607,10 +658,10 @@ def detect_univariate_change_point( content_type = content_type or "application/json" _content = None - if isinstance(options, (IO, bytes)): + if isinstance(options, (IOBase, bytes)): _content = options else: - _content = json.dumps(options, cls=AzureJSONEncoder) + _content = json.dumps(options, cls=AzureJSONEncoder) # type: ignore request = build_anomaly_detector_detect_univariate_change_point_request( content_type=content_type, @@ -626,8 +677,9 @@ def detect_univariate_change_point( } request.url = self._client.format_url(request.url, **path_format_arguments) + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -637,7 +689,10 @@ def detect_univariate_change_point( error = _deserialize(_models.AnomalyDetectorError, response.json()) raise HttpResponseError(response=response, model=error) - deserialized = _deserialize(_models.UnivariateChangePointDetectionResult, response.json()) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.UnivariateChangePointDetectionResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -650,14 +705,16 @@ def get_multivariate_batch_detection_result( ) -> _models.MultivariateDetectionResult: """Get Multivariate Anomaly Detection Result. - For asynchronous inference, get multivariate anomaly detection result based on - resultId returned by the BatchDetectAnomaly api. + For asynchronous inference, get a multivariate anomaly detection result based on the + resultId value that the BatchDetectAnomaly API returns. :param result_id: ID of a batch detection result. Required. :type result_id: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: MultivariateDetectionResult. The MultivariateDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.MultivariateDetectionResult + :rtype: ~azure.ai.anomalydetector.models.MultivariateDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { @@ -686,18 +743,22 @@ def get_multivariate_batch_detection_result( } request.url = self._client.format_url(request.url, **path_format_arguments) + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _deserialize(_models.ResponseError, response.json()) + error = _deserialize(_models.ErrorResponse, response.json()) raise HttpResponseError(response=response, model=error) - deserialized = _deserialize(_models.MultivariateDetectionResult, response.json()) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.MultivariateDetectionResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -711,20 +772,27 @@ def train_multivariate_model( """Train a Multivariate Anomaly Detection Model. Create and train a multivariate anomaly detection model. The request must - include a source parameter to indicate an externally accessible Azure blob - storage URI.There are two types of data input: An URI pointed to an Azure blob - storage folder which contains multiple CSV files, and each CSV file contains - two columns, timestamp and variable. Another type of input is an URI pointed to - a CSV file in Azure blob storage, which contains all the variables and a - timestamp column. + include a source parameter to indicate an Azure Blob + Storage URI that's accessible to the service. There are two types of data input. The Blob + Storage URI can point to an Azure Blob + Storage folder that contains multiple CSV files, where each CSV file has + two columns, time stamp and variable. Or the Blob Storage URI can point to a single blob that + contains a CSV file that has all the variables and a + time stamp column. + The model object will be created and returned in the response, but the + training process happens asynchronously. To check the training status, call + GetMultivariateModel with the modelId value and check the status field in the + modelInfo object. :param model_info: Model information. Required. - :type model_info: ~anomalydetector.models.ModelInfo + :type model_info: ~azure.ai.anomalydetector.models.ModelInfo :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: AnomalyDetectionModel. The AnomalyDetectionModel is compatible with MutableMapping - :rtype: ~anomalydetector.models.AnomalyDetectionModel + :rtype: ~azure.ai.anomalydetector.models.AnomalyDetectionModel :raises ~azure.core.exceptions.HttpResponseError: """ @@ -735,20 +803,27 @@ def train_multivariate_model( """Train a Multivariate Anomaly Detection Model. Create and train a multivariate anomaly detection model. The request must - include a source parameter to indicate an externally accessible Azure blob - storage URI.There are two types of data input: An URI pointed to an Azure blob - storage folder which contains multiple CSV files, and each CSV file contains - two columns, timestamp and variable. Another type of input is an URI pointed to - a CSV file in Azure blob storage, which contains all the variables and a - timestamp column. + include a source parameter to indicate an Azure Blob + Storage URI that's accessible to the service. There are two types of data input. The Blob + Storage URI can point to an Azure Blob + Storage folder that contains multiple CSV files, where each CSV file has + two columns, time stamp and variable. Or the Blob Storage URI can point to a single blob that + contains a CSV file that has all the variables and a + time stamp column. + The model object will be created and returned in the response, but the + training process happens asynchronously. To check the training status, call + GetMultivariateModel with the modelId value and check the status field in the + modelInfo object. :param model_info: Model information. Required. :type model_info: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: AnomalyDetectionModel. The AnomalyDetectionModel is compatible with MutableMapping - :rtype: ~anomalydetector.models.AnomalyDetectionModel + :rtype: ~azure.ai.anomalydetector.models.AnomalyDetectionModel :raises ~azure.core.exceptions.HttpResponseError: """ @@ -759,20 +834,27 @@ def train_multivariate_model( """Train a Multivariate Anomaly Detection Model. Create and train a multivariate anomaly detection model. The request must - include a source parameter to indicate an externally accessible Azure blob - storage URI.There are two types of data input: An URI pointed to an Azure blob - storage folder which contains multiple CSV files, and each CSV file contains - two columns, timestamp and variable. Another type of input is an URI pointed to - a CSV file in Azure blob storage, which contains all the variables and a - timestamp column. + include a source parameter to indicate an Azure Blob + Storage URI that's accessible to the service. There are two types of data input. The Blob + Storage URI can point to an Azure Blob + Storage folder that contains multiple CSV files, where each CSV file has + two columns, time stamp and variable. Or the Blob Storage URI can point to a single blob that + contains a CSV file that has all the variables and a + time stamp column. + The model object will be created and returned in the response, but the + training process happens asynchronously. To check the training status, call + GetMultivariateModel with the modelId value and check the status field in the + modelInfo object. :param model_info: Model information. Required. :type model_info: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: AnomalyDetectionModel. The AnomalyDetectionModel is compatible with MutableMapping - :rtype: ~anomalydetector.models.AnomalyDetectionModel + :rtype: ~azure.ai.anomalydetector.models.AnomalyDetectionModel :raises ~azure.core.exceptions.HttpResponseError: """ @@ -783,20 +865,28 @@ def train_multivariate_model( """Train a Multivariate Anomaly Detection Model. Create and train a multivariate anomaly detection model. The request must - include a source parameter to indicate an externally accessible Azure blob - storage URI.There are two types of data input: An URI pointed to an Azure blob - storage folder which contains multiple CSV files, and each CSV file contains - two columns, timestamp and variable. Another type of input is an URI pointed to - a CSV file in Azure blob storage, which contains all the variables and a - timestamp column. - - :param model_info: Model information. Is one of the following types: model, JSON, IO Required. - :type model_info: ~anomalydetector.models.ModelInfo or JSON or IO + include a source parameter to indicate an Azure Blob + Storage URI that's accessible to the service. There are two types of data input. The Blob + Storage URI can point to an Azure Blob + Storage folder that contains multiple CSV files, where each CSV file has + two columns, time stamp and variable. Or the Blob Storage URI can point to a single blob that + contains a CSV file that has all the variables and a + time stamp column. + The model object will be created and returned in the response, but the + training process happens asynchronously. To check the training status, call + GetMultivariateModel with the modelId value and check the status field in the + modelInfo object. + + :param model_info: Model information. Is one of the following types: ModelInfo, JSON, IO + Required. + :type model_info: ~azure.ai.anomalydetector.models.ModelInfo or JSON or IO :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default value is None. :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: AnomalyDetectionModel. The AnomalyDetectionModel is compatible with MutableMapping - :rtype: ~anomalydetector.models.AnomalyDetectionModel + :rtype: ~azure.ai.anomalydetector.models.AnomalyDetectionModel :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { @@ -815,10 +905,10 @@ def train_multivariate_model( content_type = content_type or "application/json" _content = None - if isinstance(model_info, (IO, bytes)): + if isinstance(model_info, (IOBase, bytes)): _content = model_info else: - _content = json.dumps(model_info, cls=AzureJSONEncoder) + _content = json.dumps(model_info, cls=AzureJSONEncoder) # type: ignore request = build_anomaly_detector_train_multivariate_model_request( content_type=content_type, @@ -834,21 +924,25 @@ def train_multivariate_model( } request.url = self._client.format_url(request.url, **path_format_arguments) + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _deserialize(_models.ResponseError, response.json()) + error = _deserialize(_models.ErrorResponse, response.json()) raise HttpResponseError(response=response, model=error) response_headers = {} response_headers["location"] = self._deserialize("str", response.headers.get("location")) - deserialized = _deserialize(_models.AnomalyDetectionModel, response.json()) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.AnomalyDetectionModel, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -863,19 +957,18 @@ def list_multivariate_models( List models of a resource. - :keyword skip: Skip indicates how many models will be skipped. Default value is None. + :keyword skip: The number of result items to skip. Default value is None. :paramtype skip: int - :keyword top: Top indicates how many models will be fetched. Default value is None. + :keyword top: The number of result items to return. Default value is None. :paramtype top: int - :return: An iterator like instance of AnomalyDetectionModel. The AnomalyDetectionModel is - compatible with MutableMapping - :rtype: ~azure.core.paging.ItemPaged[~anomalydetector.models.AnomalyDetectionModel] + :return: An iterator like instance of AnomalyDetectionModel + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.anomalydetector.models.AnomalyDetectionModel] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models._models.ModelList] = kwargs.pop("cls", None) # pylint: disable=protected-access + cls: ClsType[List[_models.AnomalyDetectionModel]] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, @@ -919,23 +1012,24 @@ def prepare_request(next_link=None): return request def extract_data(pipeline_response): - deserialized = _deserialize(_models._models.ModelList, pipeline_response) - list_of_elem = deserialized.models + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(List[_models.AnomalyDetectionModel], deserialized["models"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, iter(list_of_elem) + return deserialized.get("nextLink") or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _deserialize(_models.ResponseError, response.json()) + error = _deserialize(_models.ErrorResponse, response.json()) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -948,10 +1042,12 @@ def delete_multivariate_model( # pylint: disable=inconsistent-return-statements ) -> None: """Delete Multivariate Model. - Delete an existing multivariate model according to the modelId. + Delete an existing multivariate model according to the modelId value. :param model_id: Model identifier. Required. :type model_id: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -982,15 +1078,16 @@ def delete_multivariate_model( # pylint: disable=inconsistent-return-statements } request.url = self._client.format_url(request.url, **path_format_arguments) + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _deserialize(_models.ResponseError, response.json()) + error = _deserialize(_models.ErrorResponse, response.json()) raise HttpResponseError(response=response, model=error) if cls: @@ -1000,13 +1097,15 @@ def delete_multivariate_model( # pylint: disable=inconsistent-return-statements def get_multivariate_model(self, model_id: str, **kwargs: Any) -> _models.AnomalyDetectionModel: """Get Multivariate Model. - Get detailed information of multivariate model, including the training status + Get detailed information about the multivariate model, including the training status and variables used in the model. :param model_id: Model identifier. Required. :type model_id: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: AnomalyDetectionModel. The AnomalyDetectionModel is compatible with MutableMapping - :rtype: ~anomalydetector.models.AnomalyDetectionModel + :rtype: ~azure.ai.anomalydetector.models.AnomalyDetectionModel :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { @@ -1035,18 +1134,22 @@ def get_multivariate_model(self, model_id: str, **kwargs: Any) -> _models.Anomal } request.url = self._client.format_url(request.url, **path_format_arguments) + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _deserialize(_models.ResponseError, response.json()) + error = _deserialize(_models.ErrorResponse, response.json()) raise HttpResponseError(response=response, model=error) - deserialized = _deserialize(_models.AnomalyDetectionModel, response.json()) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.AnomalyDetectionModel, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -1060,27 +1163,29 @@ def detect_multivariate_batch_anomaly( options: _models.MultivariateBatchDetectionOptions, *, content_type: str = "application/json", - **kwargs: Any + **kwargs: Any, ) -> _models.MultivariateDetectionResult: """Detect Multivariate Anomaly. - Submit multivariate anomaly detection task with the modelId of trained model - and inference data, the input schema should be the same with the training - request. The request will complete asynchronously and return a resultId to - query the detection result.The request should be a source link to indicate an - externally accessible Azure storage Uri, either pointed to an Azure blob - storage folder, or pointed to a CSV file in Azure blob storage. + Submit a multivariate anomaly detection task with the modelId value of a trained model + and inference data. The input schema should be the same with the training + request. The request will finish asynchronously and return a resultId value to + query the detection result. The request should be a source link to indicate an + externally accessible Azure Storage URI that either points to an Azure Blob + Storage folder or points to a CSV file in Azure Blob Storage. :param model_id: Model identifier. Required. :type model_id: str :param options: Request of multivariate anomaly detection. Required. - :type options: ~anomalydetector.models.MultivariateBatchDetectionOptions + :type options: ~azure.ai.anomalydetector.models.MultivariateBatchDetectionOptions :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: MultivariateDetectionResult. The MultivariateDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.MultivariateDetectionResult + :rtype: ~azure.ai.anomalydetector.models.MultivariateDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ @@ -1090,12 +1195,12 @@ def detect_multivariate_batch_anomaly( ) -> _models.MultivariateDetectionResult: """Detect Multivariate Anomaly. - Submit multivariate anomaly detection task with the modelId of trained model - and inference data, the input schema should be the same with the training - request. The request will complete asynchronously and return a resultId to - query the detection result.The request should be a source link to indicate an - externally accessible Azure storage Uri, either pointed to an Azure blob - storage folder, or pointed to a CSV file in Azure blob storage. + Submit a multivariate anomaly detection task with the modelId value of a trained model + and inference data. The input schema should be the same with the training + request. The request will finish asynchronously and return a resultId value to + query the detection result. The request should be a source link to indicate an + externally accessible Azure Storage URI that either points to an Azure Blob + Storage folder or points to a CSV file in Azure Blob Storage. :param model_id: Model identifier. Required. :type model_id: str @@ -1104,9 +1209,11 @@ def detect_multivariate_batch_anomaly( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: MultivariateDetectionResult. The MultivariateDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.MultivariateDetectionResult + :rtype: ~azure.ai.anomalydetector.models.MultivariateDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ @@ -1116,12 +1223,12 @@ def detect_multivariate_batch_anomaly( ) -> _models.MultivariateDetectionResult: """Detect Multivariate Anomaly. - Submit multivariate anomaly detection task with the modelId of trained model - and inference data, the input schema should be the same with the training - request. The request will complete asynchronously and return a resultId to - query the detection result.The request should be a source link to indicate an - externally accessible Azure storage Uri, either pointed to an Azure blob - storage folder, or pointed to a CSV file in Azure blob storage. + Submit a multivariate anomaly detection task with the modelId value of a trained model + and inference data. The input schema should be the same with the training + request. The request will finish asynchronously and return a resultId value to + query the detection result. The request should be a source link to indicate an + externally accessible Azure Storage URI that either points to an Azure Blob + Storage folder or points to a CSV file in Azure Blob Storage. :param model_id: Model identifier. Required. :type model_id: str @@ -1130,9 +1237,11 @@ def detect_multivariate_batch_anomaly( :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: MultivariateDetectionResult. The MultivariateDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.MultivariateDetectionResult + :rtype: ~azure.ai.anomalydetector.models.MultivariateDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ @@ -1142,24 +1251,26 @@ def detect_multivariate_batch_anomaly( ) -> _models.MultivariateDetectionResult: """Detect Multivariate Anomaly. - Submit multivariate anomaly detection task with the modelId of trained model - and inference data, the input schema should be the same with the training - request. The request will complete asynchronously and return a resultId to - query the detection result.The request should be a source link to indicate an - externally accessible Azure storage Uri, either pointed to an Azure blob - storage folder, or pointed to a CSV file in Azure blob storage. + Submit a multivariate anomaly detection task with the modelId value of a trained model + and inference data. The input schema should be the same with the training + request. The request will finish asynchronously and return a resultId value to + query the detection result. The request should be a source link to indicate an + externally accessible Azure Storage URI that either points to an Azure Blob + Storage folder or points to a CSV file in Azure Blob Storage. :param model_id: Model identifier. Required. :type model_id: str :param options: Request of multivariate anomaly detection. Is one of the following types: - model, JSON, IO Required. - :type options: ~anomalydetector.models.MultivariateBatchDetectionOptions or JSON or IO + MultivariateBatchDetectionOptions, JSON, IO Required. + :type options: ~azure.ai.anomalydetector.models.MultivariateBatchDetectionOptions or JSON or IO :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default value is None. :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: MultivariateDetectionResult. The MultivariateDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.MultivariateDetectionResult + :rtype: ~azure.ai.anomalydetector.models.MultivariateDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { @@ -1178,10 +1289,10 @@ def detect_multivariate_batch_anomaly( content_type = content_type or "application/json" _content = None - if isinstance(options, (IO, bytes)): + if isinstance(options, (IOBase, bytes)): _content = options else: - _content = json.dumps(options, cls=AzureJSONEncoder) + _content = json.dumps(options, cls=AzureJSONEncoder) # type: ignore request = build_anomaly_detector_detect_multivariate_batch_anomaly_request( model_id=model_id, @@ -1198,22 +1309,26 @@ def detect_multivariate_batch_anomaly( } request.url = self._client.format_url(request.url, **path_format_arguments) + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _deserialize(_models.ResponseError, response.json()) + error = _deserialize(_models.ErrorResponse, response.json()) raise HttpResponseError(response=response, model=error) response_headers = {} - response_headers["operation-id"] = self._deserialize("str", response.headers.get("operation-id")) - response_headers["operation-location"] = self._deserialize("str", response.headers.get("operation-location")) + response_headers["Operation-Id"] = self._deserialize("str", response.headers.get("Operation-Id")) + response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) - deserialized = _deserialize(_models.MultivariateDetectionResult, response.json()) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.MultivariateDetectionResult, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -1227,25 +1342,27 @@ def detect_multivariate_last_anomaly( options: _models.MultivariateLastDetectionOptions, *, content_type: str = "application/json", - **kwargs: Any + **kwargs: Any, ) -> _models.MultivariateLastDetectionResult: """Detect anomalies in the last point of the request body. - Submit multivariate anomaly detection task with the modelId of trained model - and inference data, and the inference data should be put into request body in a - JSON format. The request will complete synchronously and return the detection + Submit a multivariate anomaly detection task with the modelId value of a trained model + and inference data. The inference data should be put into the request body in + JSON format. The request will finish synchronously and return the detection immediately in the response body. :param model_id: Model identifier. Required. :type model_id: str - :param options: Request of last detection. Required. - :type options: ~anomalydetector.models.MultivariateLastDetectionOptions + :param options: Request of the last detection. Required. + :type options: ~azure.ai.anomalydetector.models.MultivariateLastDetectionOptions :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: MultivariateLastDetectionResult. The MultivariateLastDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.MultivariateLastDetectionResult + :rtype: ~azure.ai.anomalydetector.models.MultivariateLastDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ @@ -1255,21 +1372,23 @@ def detect_multivariate_last_anomaly( ) -> _models.MultivariateLastDetectionResult: """Detect anomalies in the last point of the request body. - Submit multivariate anomaly detection task with the modelId of trained model - and inference data, and the inference data should be put into request body in a - JSON format. The request will complete synchronously and return the detection + Submit a multivariate anomaly detection task with the modelId value of a trained model + and inference data. The inference data should be put into the request body in + JSON format. The request will finish synchronously and return the detection immediately in the response body. :param model_id: Model identifier. Required. :type model_id: str - :param options: Request of last detection. Required. + :param options: Request of the last detection. Required. :type options: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: MultivariateLastDetectionResult. The MultivariateLastDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.MultivariateLastDetectionResult + :rtype: ~azure.ai.anomalydetector.models.MultivariateLastDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ @@ -1279,21 +1398,23 @@ def detect_multivariate_last_anomaly( ) -> _models.MultivariateLastDetectionResult: """Detect anomalies in the last point of the request body. - Submit multivariate anomaly detection task with the modelId of trained model - and inference data, and the inference data should be put into request body in a - JSON format. The request will complete synchronously and return the detection + Submit a multivariate anomaly detection task with the modelId value of a trained model + and inference data. The inference data should be put into the request body in + JSON format. The request will finish synchronously and return the detection immediately in the response body. :param model_id: Model identifier. Required. :type model_id: str - :param options: Request of last detection. Required. + :param options: Request of the last detection. Required. :type options: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: MultivariateLastDetectionResult. The MultivariateLastDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.MultivariateLastDetectionResult + :rtype: ~azure.ai.anomalydetector.models.MultivariateLastDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ @@ -1303,22 +1424,24 @@ def detect_multivariate_last_anomaly( ) -> _models.MultivariateLastDetectionResult: """Detect anomalies in the last point of the request body. - Submit multivariate anomaly detection task with the modelId of trained model - and inference data, and the inference data should be put into request body in a - JSON format. The request will complete synchronously and return the detection + Submit a multivariate anomaly detection task with the modelId value of a trained model + and inference data. The inference data should be put into the request body in + JSON format. The request will finish synchronously and return the detection immediately in the response body. :param model_id: Model identifier. Required. :type model_id: str - :param options: Request of last detection. Is one of the following types: model, JSON, IO - Required. - :type options: ~anomalydetector.models.MultivariateLastDetectionOptions or JSON or IO + :param options: Request of the last detection. Is one of the following types: + MultivariateLastDetectionOptions, JSON, IO Required. + :type options: ~azure.ai.anomalydetector.models.MultivariateLastDetectionOptions or JSON or IO :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default value is None. :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: MultivariateLastDetectionResult. The MultivariateLastDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.MultivariateLastDetectionResult + :rtype: ~azure.ai.anomalydetector.models.MultivariateLastDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { @@ -1337,10 +1460,10 @@ def detect_multivariate_last_anomaly( content_type = content_type or "application/json" _content = None - if isinstance(options, (IO, bytes)): + if isinstance(options, (IOBase, bytes)): _content = options else: - _content = json.dumps(options, cls=AzureJSONEncoder) + _content = json.dumps(options, cls=AzureJSONEncoder) # type: ignore request = build_anomaly_detector_detect_multivariate_last_anomaly_request( model_id=model_id, @@ -1357,18 +1480,22 @@ def detect_multivariate_last_anomaly( } request.url = self._client.format_url(request.url, **path_format_arguments) + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _deserialize(_models.ResponseError, response.json()) + error = _deserialize(_models.ErrorResponse, response.json()) raise HttpResponseError(response=response, model=error) - deserialized = _deserialize(_models.MultivariateLastDetectionResult, response.json()) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.MultivariateLastDetectionResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_serialization.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_serialization.py index 2c170e28dbca..842ae727fbbc 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_serialization.py +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_serialization.py @@ -38,7 +38,22 @@ import re import sys import codecs -from typing import Optional, Union, AnyStr, IO, Mapping +from typing import ( + Dict, + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + TypeVar, + MutableMapping, + Type, + List, + Mapping, +) try: from urllib import quote # type: ignore @@ -48,12 +63,14 @@ import isodate # type: ignore -from typing import Dict, Any, cast - from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback +from azure.core.serialization import NULL as AzureCoreNull _BOM = codecs.BOM_UTF8.decode(encoding="utf-8") +ModelType = TypeVar("ModelType", bound="Model") +JSON = MutableMapping[str, Any] + class RawDeserializer: @@ -277,8 +294,8 @@ class Model(object): _attribute_map: Dict[str, Dict[str, Any]] = {} _validation: Dict[str, Dict[str, Any]] = {} - def __init__(self, **kwargs): - self.additional_properties = {} + def __init__(self, **kwargs: Any) -> None: + self.additional_properties: Dict[str, Any] = {} for k in kwargs: if k not in self._attribute_map: _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) @@ -287,25 +304,25 @@ def __init__(self, **kwargs): else: setattr(self, k, kwargs[k]) - def __eq__(self, other): + def __eq__(self, other: Any) -> bool: """Compare objects by comparing all attributes.""" if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ return False - def __ne__(self, other): + def __ne__(self, other: Any) -> bool: """Compare objects by comparing all attributes.""" return not self.__eq__(other) - def __str__(self): + def __str__(self) -> str: return str(self.__dict__) @classmethod - def enable_additional_properties_sending(cls): + def enable_additional_properties_sending(cls) -> None: cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} @classmethod - def is_xml_model(cls): + def is_xml_model(cls) -> bool: try: cls._xml_map # type: ignore except AttributeError: @@ -322,7 +339,7 @@ def _create_xml_node(cls): return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) - def serialize(self, keep_readonly=False, **kwargs): + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: """Return the JSON that would be sent to azure from this model. This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. @@ -336,8 +353,13 @@ def serialize(self, keep_readonly=False, **kwargs): serializer = Serializer(self._infer_class_models()) return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs) - def as_dict(self, keep_readonly=True, key_transformer=attribute_transformer, **kwargs): - """Return a dict that can be JSONify using json.dump. + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, Dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: + """Return a dict that can be serialized using json.dump. Advanced usage might optionally use a callback as parameter: @@ -384,7 +406,7 @@ def _infer_class_models(cls): return client_models @classmethod - def deserialize(cls, data, content_type=None): + def deserialize(cls: Type[ModelType], data: Any, content_type: Optional[str] = None) -> ModelType: """Parse a str using the RestAPI syntax and return a model. :param str data: A str using RestAPI structure. JSON by default. @@ -396,7 +418,12 @@ def deserialize(cls, data, content_type=None): return deserializer(cls.__name__, data, content_type=content_type) @classmethod - def from_dict(cls, data, key_extractors=None, content_type=None): + def from_dict( + cls: Type[ModelType], + data: Any, + key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> ModelType: """Parse a dict using given key extractor return a model. By default consider key @@ -409,8 +436,8 @@ def from_dict(cls, data, key_extractors=None, content_type=None): :raises: DeserializationError if something went wrong """ deserializer = Deserializer(cls._infer_class_models()) - deserializer.key_extractors = ( - [ + deserializer.key_extractors = ( # type: ignore + [ # type: ignore attribute_key_case_insensitive_extractor, rest_key_case_insensitive_extractor, last_rest_key_case_insensitive_extractor, @@ -518,7 +545,7 @@ class Serializer(object): "multiple": lambda x, y: x % y != 0, } - def __init__(self, classes=None): + def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): self.serialize_type = { "iso-8601": Serializer.serialize_iso, "rfc-1123": Serializer.serialize_rfc, @@ -534,7 +561,7 @@ def __init__(self, classes=None): "[]": self.serialize_iter, "{}": self.serialize_dict, } - self.dependencies = dict(classes) if classes else {} + self.dependencies: Dict[str, Type[ModelType]] = dict(classes) if classes else {} self.key_transformer = full_restapi_key_transformer self.client_side_validation = True @@ -602,7 +629,7 @@ def _serialize(self, target_obj, data_type=None, **kwargs): if xml_desc.get("attr", False): if xml_ns: ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) serialized.set(xml_name, new_attr) # type: ignore continue if xml_desc.get("text", False): @@ -626,8 +653,7 @@ def _serialize(self, target_obj, data_type=None, **kwargs): serialized.append(local_node) # type: ignore else: # JSON for k in reversed(keys): # type: ignore - unflattened = {k: new_attr} - new_attr = unflattened + new_attr = {k: new_attr} _new_attr = new_attr _serialized = serialized @@ -656,8 +682,8 @@ def body(self, data, data_type, **kwargs): """ # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) + internal_data_type_str = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type_str, None) try: is_xml_model_serialization = kwargs["is_xml"] except KeyError: @@ -777,6 +803,8 @@ def serialize_data(self, data, data_type, **kwargs): raise ValueError("No value for given attribute") try: + if data is AzureCoreNull: + return None if data_type in self.basic_types.values(): return self.serialize_basic(data, data_type, **kwargs) @@ -1161,7 +1189,8 @@ def rest_key_extractor(attr, attr_desc, data): working_data = data while "." in key: - dict_keys = _FLATTEN.split(key) + # Need the cast, as for some reasons "split" is typed as list[str | Any] + dict_keys = cast(List[str], _FLATTEN.split(key)) if len(dict_keys) == 1: key = _decode_attribute_map_key(dict_keys[0]) break @@ -1242,7 +1271,7 @@ def _extract_name_from_internal_type(internal_type): xml_name = internal_type_xml_map.get("name", internal_type.__name__) xml_ns = internal_type_xml_map.get("ns", None) if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) return xml_name @@ -1266,7 +1295,7 @@ def xml_key_extractor(attr, attr_desc, data): # Integrate namespace if necessary xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) # If it's an attribute, that's simple if xml_desc.get("attr", False): @@ -1332,7 +1361,7 @@ class Deserializer(object): valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") - def __init__(self, classes=None): + def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): self.deserialize_type = { "iso-8601": Deserializer.deserialize_iso, "rfc-1123": Deserializer.deserialize_rfc, @@ -1352,7 +1381,7 @@ def __init__(self, classes=None): "duration": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } - self.dependencies = dict(classes) if classes else {} + self.dependencies: Dict[str, Type[ModelType]] = dict(classes) if classes else {} self.key_extractors = [rest_key_extractor, xml_key_extractor] # Additional properties only works if the "rest_key_extractor" is used to # extract the keys. Making it to work whatever the key extractor is too much @@ -1471,7 +1500,7 @@ def _classify_target(self, target, data): Once classification has been determined, initialize object. :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. + :param str/dict data: The response data to deserialize. """ if target is None: return None, None @@ -1486,7 +1515,7 @@ def _classify_target(self, target, data): target = target._classify(data, self.dependencies) except AttributeError: pass # Target is not a Model, no classify - return target, target.__class__.__name__ + return target, target.__class__.__name__ # type: ignore def failsafe_deserialize(self, target_obj, data, content_type=None): """Ignores any errors encountered in deserialization, @@ -1496,7 +1525,7 @@ def failsafe_deserialize(self, target_obj, data, content_type=None): a deserialization error. :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. + :param str/dict data: The response data to deserialize. :param str content_type: Swagger "produces" if available. """ try: diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_vendor.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_vendor.py index 3293d0c2702c..70c7791aefa4 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_vendor.py +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_vendor.py @@ -6,7 +6,7 @@ # -------------------------------------------------------------------------- from abc import ABC -from typing import TYPE_CHECKING +from typing import List, TYPE_CHECKING, cast from ._configuration import AnomalyDetectorClientConfiguration @@ -23,7 +23,8 @@ def _format_url_section(template, **kwargs): try: return template.format(**kwargs) except KeyError as key: - formatted_components = template.split("/") + # Need the cast, as for some reasons "split" is typed as list[str | Any] + formatted_components = cast(List[str], template.split("/")) components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] template = "/".join(components) diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_version.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_version.py index c8062ad3199a..7b1116c95ad7 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_version.py +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "3.0.0b7" +VERSION = "3.0.0" diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/_client.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/_client.py index 5ab7f788d15f..82e1fabb7734 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/_client.py +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/_client.py @@ -20,23 +20,23 @@ class AnomalyDetectorClient(AnomalyDetectorClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword """The Anomaly Detector API detects anomalies automatically in time series data. - It supports two kinds of mode, one is for stateless using, another is for - stateful using. In stateless mode, there are three functionalities. Entire - Detect is for detecting the whole series with model trained by the time series, - Last Detect is detecting last point with model trained by points before. - ChangePoint Detect is for detecting trend changes in time series. In stateful - mode, user can store time series, the stored time series will be used for - detection anomalies. Under this mode, user can still use the above three - functionalities by only giving a time range without preparing time series in - client side. Besides the above three functionalities, stateful model also - provide group based detection and labeling service. By leveraging labeling - service user can provide labels for each detection result, these labels will be + It supports both a stateless detection mode and a + stateful detection mode. In stateless mode, there are three functionalities. Entire + Detect is for detecting the whole series, with the model trained by the time series. + Last Detect is for detecting the last point, with the model trained by points before. + ChangePoint Detect is for detecting trend changes in the time series. In stateful + mode, the user can store time series. The stored time series will be used for + detection anomalies. In this mode, the user can still use the preceding three + functionalities by only giving a time range without preparing time series on the + client side. Besides the preceding three functionalities, the stateful model + provides group-based detection and labeling services. By using the labeling + service, the user can provide labels for each detection result. These labels will be used for retuning or regenerating detection models. Inconsistency detection is - a kind of group based detection, this detection will find inconsistency ones in - a set of time series. By using anomaly detector service, business customers can + a kind of group-based detection that finds inconsistencies in + a set of time series. By using the anomaly detector service, business customers can discover incidents and establish a logic flow for root cause analysis. - :param endpoint: Supported Cognitive Services endpoints (protocol and hostname, for example: + :param endpoint: Supported Azure Cognitive Services endpoints (protocol and host name, such as https://westus2.api.cognitive.microsoft.com). Required. :type endpoint: str :param credential: Credential needed for the client to connect to Azure. Required. @@ -49,7 +49,7 @@ class AnomalyDetectorClient(AnomalyDetectorClientOperationsMixin): # pylint: di def __init__(self, endpoint: str, credential: AzureKeyCredential, **kwargs: Any) -> None: _endpoint = "{Endpoint}/anomalydetector/{ApiVersion}" self._config = AnomalyDetectorClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) - self._client = AsyncPipelineClient(base_url=_endpoint, config=self._config, **kwargs) + self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, config=self._config, **kwargs) self._serialize = Serializer() self._deserialize = Deserializer() @@ -91,5 +91,5 @@ async def __aenter__(self) -> "AnomalyDetectorClient": await self._client.__aenter__() return self - async def __aexit__(self, *exc_details) -> None: + async def __aexit__(self, *exc_details: Any) -> None: await self._client.__aexit__(*exc_details) diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/_configuration.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/_configuration.py index 209ae66f04d4..de7df6c13f8a 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/_configuration.py +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/_configuration.py @@ -6,7 +6,6 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys from typing import Any from azure.core.configuration import Configuration @@ -15,11 +14,6 @@ from .._version import VERSION -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports - class AnomalyDetectorClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for AnomalyDetectorClient. @@ -27,7 +21,7 @@ class AnomalyDetectorClientConfiguration(Configuration): # pylint: disable=too- Note that all parameters used to create this instance are saved as instance attributes. - :param endpoint: Supported Cognitive Services endpoints (protocol and hostname, for example: + :param endpoint: Supported Azure Cognitive Services endpoints (protocol and host name, such as https://westus2.api.cognitive.microsoft.com). Required. :type endpoint: str :param credential: Credential needed for the client to connect to Azure. Required. @@ -39,7 +33,7 @@ class AnomalyDetectorClientConfiguration(Configuration): # pylint: disable=too- def __init__(self, endpoint: str, credential: AzureKeyCredential, **kwargs: Any) -> None: super(AnomalyDetectorClientConfiguration, self).__init__(**kwargs) - api_version: Literal["v1.1"] = kwargs.pop("api_version", "v1.1") + api_version: str = kwargs.pop("api_version", "v1.1") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/_operations/_operations.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/_operations/_operations.py index 292c77009ae0..c543d7f813fb 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/_operations/_operations.py +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/_operations/_operations.py @@ -6,9 +6,11 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase import json import sys -from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +from typing import Any, AsyncIterable, Callable, Dict, IO, List, Optional, TypeVar, Union, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( @@ -58,19 +60,21 @@ async def detect_univariate_entire_series( ) -> _models.UnivariateEntireDetectionResult: """Detect anomalies for the entire series in batch. - This operation generates a model with an entire series, each point is detected + This operation generates a model with an entire series. Each point is detected with the same model. With this method, points before and after a certain point - are used to determine whether it is an anomaly. The entire detection can give + are used to determine whether it's an anomaly. The entire detection can give the user an overall status of the time series. :param options: Method of univariate anomaly detection. Required. - :type options: ~anomalydetector.models.UnivariateDetectionOptions + :type options: ~azure.ai.anomalydetector.models.UnivariateDetectionOptions :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: UnivariateEntireDetectionResult. The UnivariateEntireDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.UnivariateEntireDetectionResult + :rtype: ~azure.ai.anomalydetector.models.UnivariateEntireDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ @@ -80,9 +84,9 @@ async def detect_univariate_entire_series( ) -> _models.UnivariateEntireDetectionResult: """Detect anomalies for the entire series in batch. - This operation generates a model with an entire series, each point is detected + This operation generates a model with an entire series. Each point is detected with the same model. With this method, points before and after a certain point - are used to determine whether it is an anomaly. The entire detection can give + are used to determine whether it's an anomaly. The entire detection can give the user an overall status of the time series. :param options: Method of univariate anomaly detection. Required. @@ -90,9 +94,11 @@ async def detect_univariate_entire_series( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: UnivariateEntireDetectionResult. The UnivariateEntireDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.UnivariateEntireDetectionResult + :rtype: ~azure.ai.anomalydetector.models.UnivariateEntireDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ @@ -102,9 +108,9 @@ async def detect_univariate_entire_series( ) -> _models.UnivariateEntireDetectionResult: """Detect anomalies for the entire series in batch. - This operation generates a model with an entire series, each point is detected + This operation generates a model with an entire series. Each point is detected with the same model. With this method, points before and after a certain point - are used to determine whether it is an anomaly. The entire detection can give + are used to determine whether it's an anomaly. The entire detection can give the user an overall status of the time series. :param options: Method of univariate anomaly detection. Required. @@ -112,9 +118,11 @@ async def detect_univariate_entire_series( :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: UnivariateEntireDetectionResult. The UnivariateEntireDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.UnivariateEntireDetectionResult + :rtype: ~azure.ai.anomalydetector.models.UnivariateEntireDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ @@ -124,20 +132,22 @@ async def detect_univariate_entire_series( ) -> _models.UnivariateEntireDetectionResult: """Detect anomalies for the entire series in batch. - This operation generates a model with an entire series, each point is detected + This operation generates a model with an entire series. Each point is detected with the same model. With this method, points before and after a certain point - are used to determine whether it is an anomaly. The entire detection can give + are used to determine whether it's an anomaly. The entire detection can give the user an overall status of the time series. - :param options: Method of univariate anomaly detection. Is one of the following types: model, - JSON, IO Required. - :type options: ~anomalydetector.models.UnivariateDetectionOptions or JSON or IO + :param options: Method of univariate anomaly detection. Is one of the following types: + UnivariateDetectionOptions, JSON, IO Required. + :type options: ~azure.ai.anomalydetector.models.UnivariateDetectionOptions or JSON or IO :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default value is None. :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: UnivariateEntireDetectionResult. The UnivariateEntireDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.UnivariateEntireDetectionResult + :rtype: ~azure.ai.anomalydetector.models.UnivariateEntireDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { @@ -156,10 +166,10 @@ async def detect_univariate_entire_series( content_type = content_type or "application/json" _content = None - if isinstance(options, (IO, bytes)): + if isinstance(options, (IOBase, bytes)): _content = options else: - _content = json.dumps(options, cls=AzureJSONEncoder) + _content = json.dumps(options, cls=AzureJSONEncoder) # type: ignore request = build_anomaly_detector_detect_univariate_entire_series_request( content_type=content_type, @@ -175,8 +185,9 @@ async def detect_univariate_entire_series( } request.url = self._client.format_url(request.url, **path_format_arguments) + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -186,7 +197,10 @@ async def detect_univariate_entire_series( error = _deserialize(_models.AnomalyDetectorError, response.json()) raise HttpResponseError(response=response, model=error) - deserialized = _deserialize(_models.UnivariateEntireDetectionResult, response.json()) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.UnivariateEntireDetectionResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -199,17 +213,19 @@ async def detect_univariate_last_point( ) -> _models.UnivariateLastDetectionResult: """Detect anomaly status of the latest point in time series. - This operation generates a model using the points that you sent into the API, + This operation generates a model by using the points that you sent in to the API and based on all data to determine whether the last point is anomalous. :param options: Method of univariate anomaly detection. Required. - :type options: ~anomalydetector.models.UnivariateDetectionOptions + :type options: ~azure.ai.anomalydetector.models.UnivariateDetectionOptions :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: UnivariateLastDetectionResult. The UnivariateLastDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.UnivariateLastDetectionResult + :rtype: ~azure.ai.anomalydetector.models.UnivariateLastDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ @@ -219,7 +235,7 @@ async def detect_univariate_last_point( ) -> _models.UnivariateLastDetectionResult: """Detect anomaly status of the latest point in time series. - This operation generates a model using the points that you sent into the API, + This operation generates a model by using the points that you sent in to the API and based on all data to determine whether the last point is anomalous. :param options: Method of univariate anomaly detection. Required. @@ -227,9 +243,11 @@ async def detect_univariate_last_point( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: UnivariateLastDetectionResult. The UnivariateLastDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.UnivariateLastDetectionResult + :rtype: ~azure.ai.anomalydetector.models.UnivariateLastDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ @@ -239,7 +257,7 @@ async def detect_univariate_last_point( ) -> _models.UnivariateLastDetectionResult: """Detect anomaly status of the latest point in time series. - This operation generates a model using the points that you sent into the API, + This operation generates a model by using the points that you sent in to the API and based on all data to determine whether the last point is anomalous. :param options: Method of univariate anomaly detection. Required. @@ -247,9 +265,11 @@ async def detect_univariate_last_point( :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: UnivariateLastDetectionResult. The UnivariateLastDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.UnivariateLastDetectionResult + :rtype: ~azure.ai.anomalydetector.models.UnivariateLastDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ @@ -259,18 +279,20 @@ async def detect_univariate_last_point( ) -> _models.UnivariateLastDetectionResult: """Detect anomaly status of the latest point in time series. - This operation generates a model using the points that you sent into the API, + This operation generates a model by using the points that you sent in to the API and based on all data to determine whether the last point is anomalous. - :param options: Method of univariate anomaly detection. Is one of the following types: model, - JSON, IO Required. - :type options: ~anomalydetector.models.UnivariateDetectionOptions or JSON or IO + :param options: Method of univariate anomaly detection. Is one of the following types: + UnivariateDetectionOptions, JSON, IO Required. + :type options: ~azure.ai.anomalydetector.models.UnivariateDetectionOptions or JSON or IO :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default value is None. :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: UnivariateLastDetectionResult. The UnivariateLastDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.UnivariateLastDetectionResult + :rtype: ~azure.ai.anomalydetector.models.UnivariateLastDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { @@ -289,10 +311,10 @@ async def detect_univariate_last_point( content_type = content_type or "application/json" _content = None - if isinstance(options, (IO, bytes)): + if isinstance(options, (IOBase, bytes)): _content = options else: - _content = json.dumps(options, cls=AzureJSONEncoder) + _content = json.dumps(options, cls=AzureJSONEncoder) # type: ignore request = build_anomaly_detector_detect_univariate_last_point_request( content_type=content_type, @@ -308,8 +330,9 @@ async def detect_univariate_last_point( } request.url = self._client.format_url(request.url, **path_format_arguments) + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -319,7 +342,10 @@ async def detect_univariate_last_point( error = _deserialize(_models.AnomalyDetectorError, response.json()) raise HttpResponseError(response=response, model=error) - deserialized = _deserialize(_models.UnivariateLastDetectionResult, response.json()) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.UnivariateLastDetectionResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -336,16 +362,18 @@ async def detect_univariate_change_point( ) -> _models.UnivariateChangePointDetectionResult: """Detect change point for the entire series. - Evaluate change point score of every series point. + Evaluate the change point score of every series point. :param options: Method of univariate anomaly detection. Required. - :type options: ~anomalydetector.models.UnivariateChangePointDetectionOptions + :type options: ~azure.ai.anomalydetector.models.UnivariateChangePointDetectionOptions :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: UnivariateChangePointDetectionResult. The UnivariateChangePointDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.UnivariateChangePointDetectionResult + :rtype: ~azure.ai.anomalydetector.models.UnivariateChangePointDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ @@ -355,16 +383,18 @@ async def detect_univariate_change_point( ) -> _models.UnivariateChangePointDetectionResult: """Detect change point for the entire series. - Evaluate change point score of every series point. + Evaluate the change point score of every series point. :param options: Method of univariate anomaly detection. Required. :type options: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: UnivariateChangePointDetectionResult. The UnivariateChangePointDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.UnivariateChangePointDetectionResult + :rtype: ~azure.ai.anomalydetector.models.UnivariateChangePointDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ @@ -374,16 +404,18 @@ async def detect_univariate_change_point( ) -> _models.UnivariateChangePointDetectionResult: """Detect change point for the entire series. - Evaluate change point score of every series point. + Evaluate the change point score of every series point. :param options: Method of univariate anomaly detection. Required. :type options: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: UnivariateChangePointDetectionResult. The UnivariateChangePointDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.UnivariateChangePointDetectionResult + :rtype: ~azure.ai.anomalydetector.models.UnivariateChangePointDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ @@ -393,17 +425,20 @@ async def detect_univariate_change_point( ) -> _models.UnivariateChangePointDetectionResult: """Detect change point for the entire series. - Evaluate change point score of every series point. + Evaluate the change point score of every series point. - :param options: Method of univariate anomaly detection. Is one of the following types: model, - JSON, IO Required. - :type options: ~anomalydetector.models.UnivariateChangePointDetectionOptions or JSON or IO + :param options: Method of univariate anomaly detection. Is one of the following types: + UnivariateChangePointDetectionOptions, JSON, IO Required. + :type options: ~azure.ai.anomalydetector.models.UnivariateChangePointDetectionOptions or JSON + or IO :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default value is None. :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: UnivariateChangePointDetectionResult. The UnivariateChangePointDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.UnivariateChangePointDetectionResult + :rtype: ~azure.ai.anomalydetector.models.UnivariateChangePointDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { @@ -422,10 +457,10 @@ async def detect_univariate_change_point( content_type = content_type or "application/json" _content = None - if isinstance(options, (IO, bytes)): + if isinstance(options, (IOBase, bytes)): _content = options else: - _content = json.dumps(options, cls=AzureJSONEncoder) + _content = json.dumps(options, cls=AzureJSONEncoder) # type: ignore request = build_anomaly_detector_detect_univariate_change_point_request( content_type=content_type, @@ -441,8 +476,9 @@ async def detect_univariate_change_point( } request.url = self._client.format_url(request.url, **path_format_arguments) + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -452,7 +488,10 @@ async def detect_univariate_change_point( error = _deserialize(_models.AnomalyDetectorError, response.json()) raise HttpResponseError(response=response, model=error) - deserialized = _deserialize(_models.UnivariateChangePointDetectionResult, response.json()) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.UnivariateChangePointDetectionResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -465,14 +504,16 @@ async def get_multivariate_batch_detection_result( ) -> _models.MultivariateDetectionResult: """Get Multivariate Anomaly Detection Result. - For asynchronous inference, get multivariate anomaly detection result based on - resultId returned by the BatchDetectAnomaly api. + For asynchronous inference, get a multivariate anomaly detection result based on the + resultId value that the BatchDetectAnomaly API returns. :param result_id: ID of a batch detection result. Required. :type result_id: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: MultivariateDetectionResult. The MultivariateDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.MultivariateDetectionResult + :rtype: ~azure.ai.anomalydetector.models.MultivariateDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { @@ -501,18 +542,22 @@ async def get_multivariate_batch_detection_result( } request.url = self._client.format_url(request.url, **path_format_arguments) + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _deserialize(_models.ResponseError, response.json()) + error = _deserialize(_models.ErrorResponse, response.json()) raise HttpResponseError(response=response, model=error) - deserialized = _deserialize(_models.MultivariateDetectionResult, response.json()) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.MultivariateDetectionResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -526,20 +571,27 @@ async def train_multivariate_model( """Train a Multivariate Anomaly Detection Model. Create and train a multivariate anomaly detection model. The request must - include a source parameter to indicate an externally accessible Azure blob - storage URI.There are two types of data input: An URI pointed to an Azure blob - storage folder which contains multiple CSV files, and each CSV file contains - two columns, timestamp and variable. Another type of input is an URI pointed to - a CSV file in Azure blob storage, which contains all the variables and a - timestamp column. + include a source parameter to indicate an Azure Blob + Storage URI that's accessible to the service. There are two types of data input. The Blob + Storage URI can point to an Azure Blob + Storage folder that contains multiple CSV files, where each CSV file has + two columns, time stamp and variable. Or the Blob Storage URI can point to a single blob that + contains a CSV file that has all the variables and a + time stamp column. + The model object will be created and returned in the response, but the + training process happens asynchronously. To check the training status, call + GetMultivariateModel with the modelId value and check the status field in the + modelInfo object. :param model_info: Model information. Required. - :type model_info: ~anomalydetector.models.ModelInfo + :type model_info: ~azure.ai.anomalydetector.models.ModelInfo :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: AnomalyDetectionModel. The AnomalyDetectionModel is compatible with MutableMapping - :rtype: ~anomalydetector.models.AnomalyDetectionModel + :rtype: ~azure.ai.anomalydetector.models.AnomalyDetectionModel :raises ~azure.core.exceptions.HttpResponseError: """ @@ -550,20 +602,27 @@ async def train_multivariate_model( """Train a Multivariate Anomaly Detection Model. Create and train a multivariate anomaly detection model. The request must - include a source parameter to indicate an externally accessible Azure blob - storage URI.There are two types of data input: An URI pointed to an Azure blob - storage folder which contains multiple CSV files, and each CSV file contains - two columns, timestamp and variable. Another type of input is an URI pointed to - a CSV file in Azure blob storage, which contains all the variables and a - timestamp column. + include a source parameter to indicate an Azure Blob + Storage URI that's accessible to the service. There are two types of data input. The Blob + Storage URI can point to an Azure Blob + Storage folder that contains multiple CSV files, where each CSV file has + two columns, time stamp and variable. Or the Blob Storage URI can point to a single blob that + contains a CSV file that has all the variables and a + time stamp column. + The model object will be created and returned in the response, but the + training process happens asynchronously. To check the training status, call + GetMultivariateModel with the modelId value and check the status field in the + modelInfo object. :param model_info: Model information. Required. :type model_info: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: AnomalyDetectionModel. The AnomalyDetectionModel is compatible with MutableMapping - :rtype: ~anomalydetector.models.AnomalyDetectionModel + :rtype: ~azure.ai.anomalydetector.models.AnomalyDetectionModel :raises ~azure.core.exceptions.HttpResponseError: """ @@ -574,20 +633,27 @@ async def train_multivariate_model( """Train a Multivariate Anomaly Detection Model. Create and train a multivariate anomaly detection model. The request must - include a source parameter to indicate an externally accessible Azure blob - storage URI.There are two types of data input: An URI pointed to an Azure blob - storage folder which contains multiple CSV files, and each CSV file contains - two columns, timestamp and variable. Another type of input is an URI pointed to - a CSV file in Azure blob storage, which contains all the variables and a - timestamp column. + include a source parameter to indicate an Azure Blob + Storage URI that's accessible to the service. There are two types of data input. The Blob + Storage URI can point to an Azure Blob + Storage folder that contains multiple CSV files, where each CSV file has + two columns, time stamp and variable. Or the Blob Storage URI can point to a single blob that + contains a CSV file that has all the variables and a + time stamp column. + The model object will be created and returned in the response, but the + training process happens asynchronously. To check the training status, call + GetMultivariateModel with the modelId value and check the status field in the + modelInfo object. :param model_info: Model information. Required. :type model_info: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: AnomalyDetectionModel. The AnomalyDetectionModel is compatible with MutableMapping - :rtype: ~anomalydetector.models.AnomalyDetectionModel + :rtype: ~azure.ai.anomalydetector.models.AnomalyDetectionModel :raises ~azure.core.exceptions.HttpResponseError: """ @@ -598,20 +664,28 @@ async def train_multivariate_model( """Train a Multivariate Anomaly Detection Model. Create and train a multivariate anomaly detection model. The request must - include a source parameter to indicate an externally accessible Azure blob - storage URI.There are two types of data input: An URI pointed to an Azure blob - storage folder which contains multiple CSV files, and each CSV file contains - two columns, timestamp and variable. Another type of input is an URI pointed to - a CSV file in Azure blob storage, which contains all the variables and a - timestamp column. - - :param model_info: Model information. Is one of the following types: model, JSON, IO Required. - :type model_info: ~anomalydetector.models.ModelInfo or JSON or IO + include a source parameter to indicate an Azure Blob + Storage URI that's accessible to the service. There are two types of data input. The Blob + Storage URI can point to an Azure Blob + Storage folder that contains multiple CSV files, where each CSV file has + two columns, time stamp and variable. Or the Blob Storage URI can point to a single blob that + contains a CSV file that has all the variables and a + time stamp column. + The model object will be created and returned in the response, but the + training process happens asynchronously. To check the training status, call + GetMultivariateModel with the modelId value and check the status field in the + modelInfo object. + + :param model_info: Model information. Is one of the following types: ModelInfo, JSON, IO + Required. + :type model_info: ~azure.ai.anomalydetector.models.ModelInfo or JSON or IO :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default value is None. :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: AnomalyDetectionModel. The AnomalyDetectionModel is compatible with MutableMapping - :rtype: ~anomalydetector.models.AnomalyDetectionModel + :rtype: ~azure.ai.anomalydetector.models.AnomalyDetectionModel :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { @@ -630,10 +704,10 @@ async def train_multivariate_model( content_type = content_type or "application/json" _content = None - if isinstance(model_info, (IO, bytes)): + if isinstance(model_info, (IOBase, bytes)): _content = model_info else: - _content = json.dumps(model_info, cls=AzureJSONEncoder) + _content = json.dumps(model_info, cls=AzureJSONEncoder) # type: ignore request = build_anomaly_detector_train_multivariate_model_request( content_type=content_type, @@ -649,21 +723,25 @@ async def train_multivariate_model( } request.url = self._client.format_url(request.url, **path_format_arguments) + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _deserialize(_models.ResponseError, response.json()) + error = _deserialize(_models.ErrorResponse, response.json()) raise HttpResponseError(response=response, model=error) response_headers = {} response_headers["location"] = self._deserialize("str", response.headers.get("location")) - deserialized = _deserialize(_models.AnomalyDetectionModel, response.json()) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.AnomalyDetectionModel, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -678,19 +756,19 @@ def list_multivariate_models( List models of a resource. - :keyword skip: Skip indicates how many models will be skipped. Default value is None. + :keyword skip: The number of result items to skip. Default value is None. :paramtype skip: int - :keyword top: Top indicates how many models will be fetched. Default value is None. + :keyword top: The number of result items to return. Default value is None. :paramtype top: int - :return: An iterator like instance of AnomalyDetectionModel. The AnomalyDetectionModel is - compatible with MutableMapping - :rtype: ~azure.core.async_paging.AsyncItemPaged[~anomalydetector.models.AnomalyDetectionModel] + :return: An iterator like instance of AnomalyDetectionModel + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.ai.anomalydetector.models.AnomalyDetectionModel] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models._models.ModelList] = kwargs.pop("cls", None) # pylint: disable=protected-access + cls: ClsType[List[_models.AnomalyDetectionModel]] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, @@ -734,23 +812,24 @@ def prepare_request(next_link=None): return request async def extract_data(pipeline_response): - deserialized = _deserialize(_models._models.ModelList, pipeline_response) - list_of_elem = deserialized.models + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(List[_models.AnomalyDetectionModel], deserialized["models"]) if cls: list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.next_link or None, AsyncList(list_of_elem) + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _deserialize(_models.ResponseError, response.json()) + error = _deserialize(_models.ErrorResponse, response.json()) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -763,10 +842,12 @@ async def delete_multivariate_model( # pylint: disable=inconsistent-return-stat ) -> None: """Delete Multivariate Model. - Delete an existing multivariate model according to the modelId. + Delete an existing multivariate model according to the modelId value. :param model_id: Model identifier. Required. :type model_id: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -797,15 +878,16 @@ async def delete_multivariate_model( # pylint: disable=inconsistent-return-stat } request.url = self._client.format_url(request.url, **path_format_arguments) + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _deserialize(_models.ResponseError, response.json()) + error = _deserialize(_models.ErrorResponse, response.json()) raise HttpResponseError(response=response, model=error) if cls: @@ -815,13 +897,15 @@ async def delete_multivariate_model( # pylint: disable=inconsistent-return-stat async def get_multivariate_model(self, model_id: str, **kwargs: Any) -> _models.AnomalyDetectionModel: """Get Multivariate Model. - Get detailed information of multivariate model, including the training status + Get detailed information about the multivariate model, including the training status and variables used in the model. :param model_id: Model identifier. Required. :type model_id: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: AnomalyDetectionModel. The AnomalyDetectionModel is compatible with MutableMapping - :rtype: ~anomalydetector.models.AnomalyDetectionModel + :rtype: ~azure.ai.anomalydetector.models.AnomalyDetectionModel :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { @@ -850,18 +934,22 @@ async def get_multivariate_model(self, model_id: str, **kwargs: Any) -> _models. } request.url = self._client.format_url(request.url, **path_format_arguments) + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _deserialize(_models.ResponseError, response.json()) + error = _deserialize(_models.ErrorResponse, response.json()) raise HttpResponseError(response=response, model=error) - deserialized = _deserialize(_models.AnomalyDetectionModel, response.json()) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.AnomalyDetectionModel, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -879,23 +967,25 @@ async def detect_multivariate_batch_anomaly( ) -> _models.MultivariateDetectionResult: """Detect Multivariate Anomaly. - Submit multivariate anomaly detection task with the modelId of trained model - and inference data, the input schema should be the same with the training - request. The request will complete asynchronously and return a resultId to - query the detection result.The request should be a source link to indicate an - externally accessible Azure storage Uri, either pointed to an Azure blob - storage folder, or pointed to a CSV file in Azure blob storage. + Submit a multivariate anomaly detection task with the modelId value of a trained model + and inference data. The input schema should be the same with the training + request. The request will finish asynchronously and return a resultId value to + query the detection result. The request should be a source link to indicate an + externally accessible Azure Storage URI that either points to an Azure Blob + Storage folder or points to a CSV file in Azure Blob Storage. :param model_id: Model identifier. Required. :type model_id: str :param options: Request of multivariate anomaly detection. Required. - :type options: ~anomalydetector.models.MultivariateBatchDetectionOptions + :type options: ~azure.ai.anomalydetector.models.MultivariateBatchDetectionOptions :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: MultivariateDetectionResult. The MultivariateDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.MultivariateDetectionResult + :rtype: ~azure.ai.anomalydetector.models.MultivariateDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ @@ -905,12 +995,12 @@ async def detect_multivariate_batch_anomaly( ) -> _models.MultivariateDetectionResult: """Detect Multivariate Anomaly. - Submit multivariate anomaly detection task with the modelId of trained model - and inference data, the input schema should be the same with the training - request. The request will complete asynchronously and return a resultId to - query the detection result.The request should be a source link to indicate an - externally accessible Azure storage Uri, either pointed to an Azure blob - storage folder, or pointed to a CSV file in Azure blob storage. + Submit a multivariate anomaly detection task with the modelId value of a trained model + and inference data. The input schema should be the same with the training + request. The request will finish asynchronously and return a resultId value to + query the detection result. The request should be a source link to indicate an + externally accessible Azure Storage URI that either points to an Azure Blob + Storage folder or points to a CSV file in Azure Blob Storage. :param model_id: Model identifier. Required. :type model_id: str @@ -919,9 +1009,11 @@ async def detect_multivariate_batch_anomaly( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: MultivariateDetectionResult. The MultivariateDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.MultivariateDetectionResult + :rtype: ~azure.ai.anomalydetector.models.MultivariateDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ @@ -931,12 +1023,12 @@ async def detect_multivariate_batch_anomaly( ) -> _models.MultivariateDetectionResult: """Detect Multivariate Anomaly. - Submit multivariate anomaly detection task with the modelId of trained model - and inference data, the input schema should be the same with the training - request. The request will complete asynchronously and return a resultId to - query the detection result.The request should be a source link to indicate an - externally accessible Azure storage Uri, either pointed to an Azure blob - storage folder, or pointed to a CSV file in Azure blob storage. + Submit a multivariate anomaly detection task with the modelId value of a trained model + and inference data. The input schema should be the same with the training + request. The request will finish asynchronously and return a resultId value to + query the detection result. The request should be a source link to indicate an + externally accessible Azure Storage URI that either points to an Azure Blob + Storage folder or points to a CSV file in Azure Blob Storage. :param model_id: Model identifier. Required. :type model_id: str @@ -945,9 +1037,11 @@ async def detect_multivariate_batch_anomaly( :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: MultivariateDetectionResult. The MultivariateDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.MultivariateDetectionResult + :rtype: ~azure.ai.anomalydetector.models.MultivariateDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ @@ -957,24 +1051,26 @@ async def detect_multivariate_batch_anomaly( ) -> _models.MultivariateDetectionResult: """Detect Multivariate Anomaly. - Submit multivariate anomaly detection task with the modelId of trained model - and inference data, the input schema should be the same with the training - request. The request will complete asynchronously and return a resultId to - query the detection result.The request should be a source link to indicate an - externally accessible Azure storage Uri, either pointed to an Azure blob - storage folder, or pointed to a CSV file in Azure blob storage. + Submit a multivariate anomaly detection task with the modelId value of a trained model + and inference data. The input schema should be the same with the training + request. The request will finish asynchronously and return a resultId value to + query the detection result. The request should be a source link to indicate an + externally accessible Azure Storage URI that either points to an Azure Blob + Storage folder or points to a CSV file in Azure Blob Storage. :param model_id: Model identifier. Required. :type model_id: str :param options: Request of multivariate anomaly detection. Is one of the following types: - model, JSON, IO Required. - :type options: ~anomalydetector.models.MultivariateBatchDetectionOptions or JSON or IO + MultivariateBatchDetectionOptions, JSON, IO Required. + :type options: ~azure.ai.anomalydetector.models.MultivariateBatchDetectionOptions or JSON or IO :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default value is None. :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: MultivariateDetectionResult. The MultivariateDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.MultivariateDetectionResult + :rtype: ~azure.ai.anomalydetector.models.MultivariateDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { @@ -993,10 +1089,10 @@ async def detect_multivariate_batch_anomaly( content_type = content_type or "application/json" _content = None - if isinstance(options, (IO, bytes)): + if isinstance(options, (IOBase, bytes)): _content = options else: - _content = json.dumps(options, cls=AzureJSONEncoder) + _content = json.dumps(options, cls=AzureJSONEncoder) # type: ignore request = build_anomaly_detector_detect_multivariate_batch_anomaly_request( model_id=model_id, @@ -1013,22 +1109,26 @@ async def detect_multivariate_batch_anomaly( } request.url = self._client.format_url(request.url, **path_format_arguments) + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _deserialize(_models.ResponseError, response.json()) + error = _deserialize(_models.ErrorResponse, response.json()) raise HttpResponseError(response=response, model=error) response_headers = {} - response_headers["operation-id"] = self._deserialize("str", response.headers.get("operation-id")) - response_headers["operation-location"] = self._deserialize("str", response.headers.get("operation-location")) + response_headers["Operation-Id"] = self._deserialize("str", response.headers.get("Operation-Id")) + response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) - deserialized = _deserialize(_models.MultivariateDetectionResult, response.json()) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.MultivariateDetectionResult, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -1046,21 +1146,23 @@ async def detect_multivariate_last_anomaly( ) -> _models.MultivariateLastDetectionResult: """Detect anomalies in the last point of the request body. - Submit multivariate anomaly detection task with the modelId of trained model - and inference data, and the inference data should be put into request body in a - JSON format. The request will complete synchronously and return the detection + Submit a multivariate anomaly detection task with the modelId value of a trained model + and inference data. The inference data should be put into the request body in + JSON format. The request will finish synchronously and return the detection immediately in the response body. :param model_id: Model identifier. Required. :type model_id: str - :param options: Request of last detection. Required. - :type options: ~anomalydetector.models.MultivariateLastDetectionOptions + :param options: Request of the last detection. Required. + :type options: ~azure.ai.anomalydetector.models.MultivariateLastDetectionOptions :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: MultivariateLastDetectionResult. The MultivariateLastDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.MultivariateLastDetectionResult + :rtype: ~azure.ai.anomalydetector.models.MultivariateLastDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ @@ -1070,21 +1172,23 @@ async def detect_multivariate_last_anomaly( ) -> _models.MultivariateLastDetectionResult: """Detect anomalies in the last point of the request body. - Submit multivariate anomaly detection task with the modelId of trained model - and inference data, and the inference data should be put into request body in a - JSON format. The request will complete synchronously and return the detection + Submit a multivariate anomaly detection task with the modelId value of a trained model + and inference data. The inference data should be put into the request body in + JSON format. The request will finish synchronously and return the detection immediately in the response body. :param model_id: Model identifier. Required. :type model_id: str - :param options: Request of last detection. Required. + :param options: Request of the last detection. Required. :type options: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: MultivariateLastDetectionResult. The MultivariateLastDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.MultivariateLastDetectionResult + :rtype: ~azure.ai.anomalydetector.models.MultivariateLastDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ @@ -1094,21 +1198,23 @@ async def detect_multivariate_last_anomaly( ) -> _models.MultivariateLastDetectionResult: """Detect anomalies in the last point of the request body. - Submit multivariate anomaly detection task with the modelId of trained model - and inference data, and the inference data should be put into request body in a - JSON format. The request will complete synchronously and return the detection + Submit a multivariate anomaly detection task with the modelId value of a trained model + and inference data. The inference data should be put into the request body in + JSON format. The request will finish synchronously and return the detection immediately in the response body. :param model_id: Model identifier. Required. :type model_id: str - :param options: Request of last detection. Required. + :param options: Request of the last detection. Required. :type options: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: MultivariateLastDetectionResult. The MultivariateLastDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.MultivariateLastDetectionResult + :rtype: ~azure.ai.anomalydetector.models.MultivariateLastDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ @@ -1118,22 +1224,24 @@ async def detect_multivariate_last_anomaly( ) -> _models.MultivariateLastDetectionResult: """Detect anomalies in the last point of the request body. - Submit multivariate anomaly detection task with the modelId of trained model - and inference data, and the inference data should be put into request body in a - JSON format. The request will complete synchronously and return the detection + Submit a multivariate anomaly detection task with the modelId value of a trained model + and inference data. The inference data should be put into the request body in + JSON format. The request will finish synchronously and return the detection immediately in the response body. :param model_id: Model identifier. Required. :type model_id: str - :param options: Request of last detection. Is one of the following types: model, JSON, IO - Required. - :type options: ~anomalydetector.models.MultivariateLastDetectionOptions or JSON or IO + :param options: Request of the last detection. Is one of the following types: + MultivariateLastDetectionOptions, JSON, IO Required. + :type options: ~azure.ai.anomalydetector.models.MultivariateLastDetectionOptions or JSON or IO :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default value is None. :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. :return: MultivariateLastDetectionResult. The MultivariateLastDetectionResult is compatible with MutableMapping - :rtype: ~anomalydetector.models.MultivariateLastDetectionResult + :rtype: ~azure.ai.anomalydetector.models.MultivariateLastDetectionResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { @@ -1152,10 +1260,10 @@ async def detect_multivariate_last_anomaly( content_type = content_type or "application/json" _content = None - if isinstance(options, (IO, bytes)): + if isinstance(options, (IOBase, bytes)): _content = options else: - _content = json.dumps(options, cls=AzureJSONEncoder) + _content = json.dumps(options, cls=AzureJSONEncoder) # type: ignore request = build_anomaly_detector_detect_multivariate_last_anomaly_request( model_id=model_id, @@ -1172,18 +1280,22 @@ async def detect_multivariate_last_anomaly( } request.url = self._client.format_url(request.url, **path_format_arguments) + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _deserialize(_models.ResponseError, response.json()) + error = _deserialize(_models.ErrorResponse, response.json()) raise HttpResponseError(response=response, model=error) - deserialized = _deserialize(_models.MultivariateLastDetectionResult, response.json()) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.MultivariateLastDetectionResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/models/__init__.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/models/__init__.py index c482718b718d..13198d7ce988 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/models/__init__.py +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/models/__init__.py @@ -22,7 +22,6 @@ from ._models import MultivariateDetectionResult from ._models import MultivariateLastDetectionOptions from ._models import MultivariateLastDetectionResult -from ._models import ResponseError from ._models import TimeSeriesPoint from ._models import UnivariateChangePointDetectionOptions from ._models import UnivariateChangePointDetectionResult @@ -62,7 +61,6 @@ "MultivariateDetectionResult", "MultivariateLastDetectionOptions", "MultivariateLastDetectionResult", - "ResponseError", "TimeSeriesPoint", "UnivariateChangePointDetectionOptions", "UnivariateChangePointDetectionResult", diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/models/_enums.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/models/_enums.py index 75236a7a77cc..97c48cc79ada 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/models/_enums.py +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/models/_enums.py @@ -40,19 +40,19 @@ class APIVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): class DataSchema(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """DataSchema.""" + """Data schema of the input data source. The default is OneTable.""" - #: OneTable means that your input data are all in one CSV file, which contains one 'timestamp' - #: column and several variable columns. The default DataSchema is OneTable. ONE_TABLE = "OneTable" - #: MultiTable means that your input data are separated in multiple CSV files, in each file - #: containing one 'timestamp' column and one 'variable' column, and the CSV file name should - #: indicate the name of the variable. The default DataSchema is OneTable. + """OneTable means that your input data is in one CSV file, which contains one time stamp column + #: and several variable columns. The default DataSchema value is OneTable.""" MULTI_TABLE = "MultiTable" + """MultiTable means that your input data is separated in multiple CSV files. Each file contains + #: one time stamp column and one variable column, and the CSV file name should indicate the name + #: of the variable. The default DataSchema value is OneTable.""" class FillNAMethod(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """FillNAMethod.""" + """Field that indicates how missing values will be filled.""" PREVIOUS = "Previous" SUBSEQUENT = "Subsequent" @@ -76,9 +76,13 @@ class ModelStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): """ModelStatus.""" CREATED = "CREATED" + """The model has been created. Training has been scheduled but not yet started.""" RUNNING = "RUNNING" + """The model is being trained.""" READY = "READY" + """The model has been trained and is ready to be used for anomaly detection.""" FAILED = "FAILED" + """The model training failed.""" class MultivariateBatchDetectionStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/models/_models.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/models/_models.py index 4e5748ae57d2..183eca718893 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/models/_models.py +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/models/_models.py @@ -8,45 +8,37 @@ # -------------------------------------------------------------------------- import datetime -import sys from typing import Any, List, Mapping, Optional, TYPE_CHECKING, Union, overload from .. import _model_base from .._model_base import rest_field -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports - if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from .. import models as _models -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object class AlignPolicy(_model_base.Model): - """An optional field, indicating the manner to align multiple variables. - - :ivar align_mode: An optional field, indicating how to align different variables to the same - time-range. Either Inner or Outer. Known values are: "Inner" and "Outer". - :vartype align_mode: str or ~anomalydetector.models.AlignMode - :ivar fill_n_a_method: An optional field, indicating how missing values will be filled. One of - Previous, Subsequent, Linear, Zero, Fixed. Known values are: "Previous", "Subsequent", - "Linear", "Zero", and "Fixed". - :vartype fill_n_a_method: str or ~anomalydetector.models.FillNAMethod - :ivar padding_value: An optional field. Required when fillNAMethod is Fixed. + """Manner of aligning multiple variables. + + :ivar align_mode: Field that indicates how to align different variables to the same + time range. Known values are: "Inner" and "Outer". + :vartype align_mode: str or ~azure.ai.anomalydetector.models.AlignMode + :ivar fill_n_a_method: Field that indicates how missing values will be filled. Known values + are: "Previous", "Subsequent", "Linear", "Zero", and "Fixed". + :vartype fill_n_a_method: str or ~azure.ai.anomalydetector.models.FillNAMethod + :ivar padding_value: Field that's required when fillNAMethod is Fixed. :vartype padding_value: float """ align_mode: Optional[Union[str, "_models.AlignMode"]] = rest_field(name="alignMode") - """An optional field, indicating how to align different variables to the same -time-range. Either Inner or Outer. Known values are: \"Inner\" and \"Outer\".""" + """Field that indicates how to align different variables to the same + time range. Known values are: \"Inner\" and \"Outer\".""" fill_n_a_method: Optional[Union[str, "_models.FillNAMethod"]] = rest_field(name="fillNAMethod") - """An optional field, indicating how missing values will be filled. One of -Previous, Subsequent, Linear, Zero, Fixed. Known values are: \"Previous\", \"Subsequent\", \"Linear\", \"Zero\", and \"Fixed\".""" + """Field that indicates how missing values will be filled. Known values are: \"Previous\", + \"Subsequent\", \"Linear\", \"Zero\", and \"Fixed\".""" padding_value: Optional[float] = rest_field(name="paddingValue") - """An optional field. Required when fillNAMethod is Fixed. """ + """Field that's required when fillNAMethod is Fixed.""" @overload def __init__( @@ -64,9 +56,8 @@ def __init__(self, mapping: Mapping[str, Any]): :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - ... - def __init__(self, *args, **kwargs): + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation super().__init__(*args, **kwargs) @@ -83,20 +74,20 @@ class AnomalyDetectionModel(_model_base.Model): :vartype created_time: ~datetime.datetime :ivar last_updated_time: Date and time (UTC) when the model was last updated. Required. :vartype last_updated_time: ~datetime.datetime - :ivar model_info: Training result of a model including its status, errors and diagnostics + :ivar model_info: Training result of a model, including its status, errors, and diagnostics information. - :vartype model_info: ~anomalydetector.models.ModelInfo + :vartype model_info: ~azure.ai.anomalydetector.models.ModelInfo """ model_id: str = rest_field(name="modelId", readonly=True) - """Model identifier. Required. """ + """Model identifier. Required.""" created_time: datetime.datetime = rest_field(name="createdTime") - """Date and time (UTC) when the model was created. Required. """ + """Date and time (UTC) when the model was created. Required.""" last_updated_time: datetime.datetime = rest_field(name="lastUpdatedTime") - """Date and time (UTC) when the model was last updated. Required. """ + """Date and time (UTC) when the model was last updated. Required.""" model_info: Optional["_models.ModelInfo"] = rest_field(name="modelInfo") - """Training result of a model including its status, errors and diagnostics -information. """ + """Training result of a model, including its status, errors, and diagnostics + information.""" @overload def __init__( @@ -114,40 +105,39 @@ def __init__(self, mapping: Mapping[str, Any]): :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - ... - def __init__(self, *args, **kwargs): + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation super().__init__(*args, **kwargs) class AnomalyDetectorError(_model_base.Model): - """Error information returned by the API. + """Error information that the API returned. + + All required parameters must be populated in order to send to Azure. - :ivar x_ms_error_code: Error code. - :vartype x_ms_error_code: str - :ivar code: The error code. Known values are: "InvalidCustomInterval", "BadArgument", + :ivar code: Error code. Required. Known values are: "InvalidCustomInterval", "BadArgument", "InvalidGranularity", "InvalidPeriod", "InvalidModelArgument", "InvalidSeries", "InvalidJsonFormat", "RequiredGranularity", "RequiredSeries", "InvalidImputeMode", and "InvalidImputeFixedValue". - :vartype code: str or ~anomalydetector.models.AnomalyDetectorErrorCodes - :ivar message: A message explaining the error reported by the service. + :vartype code: str or ~azure.ai.anomalydetector.models.AnomalyDetectorErrorCodes + :ivar message: Message that explains the error that the service reported. Required. :vartype message: str """ - x_ms_error_code: Optional[str] = rest_field(name="x-ms-error-code") - """Error code. """ - code: Optional[Union[str, "_models.AnomalyDetectorErrorCodes"]] = rest_field() - """The error code. Known values are: \"InvalidCustomInterval\", \"BadArgument\", \"InvalidGranularity\", \"InvalidPeriod\", \"InvalidModelArgument\", \"InvalidSeries\", \"InvalidJsonFormat\", \"RequiredGranularity\", \"RequiredSeries\", \"InvalidImputeMode\", and \"InvalidImputeFixedValue\".""" - message: Optional[str] = rest_field() - """A message explaining the error reported by the service. """ + code: Union[str, "_models.AnomalyDetectorErrorCodes"] = rest_field() + """Error code. Required. Known values are: \"InvalidCustomInterval\", \"BadArgument\", + \"InvalidGranularity\", \"InvalidPeriod\", \"InvalidModelArgument\", \"InvalidSeries\", + \"InvalidJsonFormat\", \"RequiredGranularity\", \"RequiredSeries\", \"InvalidImputeMode\", and + \"InvalidImputeFixedValue\".""" + message: str = rest_field() + """Message that explains the error that the service reported. Required.""" @overload def __init__( self, *, - x_ms_error_code: Optional[str] = None, - code: Optional[Union[str, "_models.AnomalyDetectorErrorCodes"]] = None, - message: Optional[str] = None, + code: Union[str, "_models.AnomalyDetectorErrorCodes"], + message: str, ): ... @@ -157,32 +147,31 @@ def __init__(self, mapping: Mapping[str, Any]): :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - ... - def __init__(self, *args, **kwargs): + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation super().__init__(*args, **kwargs) class AnomalyInterpretation(_model_base.Model): - """Interpretation of the anomalous timestamp. + """Interpretation of the anomalous time stamp. :ivar variable: Variable. :vartype variable: str - :ivar contribution_score: This score shows the percentage contributing to the anomalous - timestamp. A + :ivar contribution_score: This score shows the percentage that contributes to the anomalous + time stamp. It's a number between 0 and 1. :vartype contribution_score: float :ivar correlation_changes: Correlation changes among the anomalous variables. - :vartype correlation_changes: ~anomalydetector.models.CorrelationChanges + :vartype correlation_changes: ~azure.ai.anomalydetector.models.CorrelationChanges """ variable: Optional[str] = rest_field() - """Variable. """ + """Variable.""" contribution_score: Optional[float] = rest_field(name="contributionScore") - """This score shows the percentage contributing to the anomalous timestamp. A -number between 0 and 1. """ + """This score shows the percentage that contributes to the anomalous time stamp. It's a + number between 0 and 1.""" correlation_changes: Optional["_models.CorrelationChanges"] = rest_field(name="correlationChanges") - """Correlation changes among the anomalous variables. """ + """Correlation changes among the anomalous variables.""" @overload def __init__( @@ -200,9 +189,8 @@ def __init__(self, mapping: Mapping[str, Any]): :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - ... - def __init__(self, *args, **kwargs): + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation super().__init__(*args, **kwargs) @@ -211,20 +199,20 @@ class AnomalyState(_model_base.Model): All required parameters must be populated in order to send to Azure. - :ivar timestamp: The timestamp for this anomaly. Required. + :ivar timestamp: Time stamp for this anomaly. Required. :vartype timestamp: ~datetime.datetime - :ivar value: The detailed value of this anomalous timestamp. - :vartype value: ~anomalydetector.models.AnomalyValue - :ivar errors: Error message for the current timestamp. - :vartype errors: list[~anomalydetector.models.ErrorResponse] + :ivar value: Detailed value of this anomalous time stamp. + :vartype value: ~azure.ai.anomalydetector.models.AnomalyValue + :ivar errors: Error message for the current time stamp. + :vartype errors: list[~azure.ai.anomalydetector.models.ErrorResponse] """ timestamp: datetime.datetime = rest_field() - """The timestamp for this anomaly. Required. """ + """Time stamp for this anomaly. Required.""" value: Optional["_models.AnomalyValue"] = rest_field() - """The detailed value of this anomalous timestamp. """ + """Detailed value of this anomalous time stamp.""" errors: Optional[List["_models.ErrorResponse"]] = rest_field() - """Error message for the current timestamp. """ + """Error message for the current time stamp.""" @overload def __init__( @@ -242,39 +230,37 @@ def __init__(self, mapping: Mapping[str, Any]): :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - ... - def __init__(self, *args, **kwargs): + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation super().__init__(*args, **kwargs) class AnomalyValue(_model_base.Model): - """Detailed information of the anomalous timestamp. + """Detailed information of the anomalous time stamp. All required parameters must be populated in order to send to Azure. - :ivar is_anomaly: True if an anomaly is detected at the current timestamp. Required. + :ivar is_anomaly: True if an anomaly is detected at the current time stamp. Required. :vartype is_anomaly: bool :ivar severity: Indicates the significance of the anomaly. The higher the severity, the more significant the anomaly is. Required. :vartype severity: float - :ivar score: Raw anomaly score of severity, will help indicate the degree of abnormality as - well. Required. + :ivar score: Raw anomaly score of severity, to help indicate the degree of abnormality. + Required. :vartype score: float - :ivar interpretation: Interpretation of this anomalous timestamp. - :vartype interpretation: list[~anomalydetector.models.AnomalyInterpretation] + :ivar interpretation: Interpretation of this anomalous time stamp. + :vartype interpretation: list[~azure.ai.anomalydetector.models.AnomalyInterpretation] """ is_anomaly: bool = rest_field(name="isAnomaly") - """True if an anomaly is detected at the current timestamp. Required. """ + """True if an anomaly is detected at the current time stamp. Required.""" severity: float = rest_field() """Indicates the significance of the anomaly. The higher the severity, the more -significant the anomaly is. Required. """ + significant the anomaly is. Required.""" score: float = rest_field() - """Raw anomaly score of severity, will help indicate the degree of abnormality as -well. Required. """ + """Raw anomaly score of severity, to help indicate the degree of abnormality. Required.""" interpretation: Optional[List["_models.AnomalyInterpretation"]] = rest_field() - """Interpretation of this anomalous timestamp. """ + """Interpretation of this anomalous time stamp.""" @overload def __init__( @@ -293,22 +279,20 @@ def __init__(self, mapping: Mapping[str, Any]): :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - ... - def __init__(self, *args, **kwargs): + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation super().__init__(*args, **kwargs) class CorrelationChanges(_model_base.Model): """Correlation changes among the anomalous variables. - :ivar changed_variables: The correlated variables that have correlation changes under an - anomaly. + :ivar changed_variables: Correlated variables that have correlation changes under an anomaly. :vartype changed_variables: list[str] """ changed_variables: Optional[List[str]] = rest_field(name="changedVariables") - """The correlated variables that have correlation changes under an anomaly. """ + """Correlated variables that have correlation changes under an anomaly.""" @overload def __init__( @@ -324,25 +308,24 @@ def __init__(self, mapping: Mapping[str, Any]): :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - ... - def __init__(self, *args, **kwargs): + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation super().__init__(*args, **kwargs) class DiagnosticsInfo(_model_base.Model): - """Diagnostics information to help inspect the states of model or variable. + """Diagnostics information to help inspect the states of a model or variable. :ivar model_state: Model status. - :vartype model_state: ~anomalydetector.models.ModelState - :ivar variable_states: Variable Status. - :vartype variable_states: list[~anomalydetector.models.VariableState] + :vartype model_state: ~azure.ai.anomalydetector.models.ModelState + :ivar variable_states: Variable status. + :vartype variable_states: list[~azure.ai.anomalydetector.models.VariableState] """ model_state: Optional["_models.ModelState"] = rest_field(name="modelState") - """Model status. """ + """Model status.""" variable_states: Optional[List["_models.VariableState"]] = rest_field(name="variableStates") - """Variable Status. """ + """Variable status.""" @overload def __init__( @@ -359,27 +342,26 @@ def __init__(self, mapping: Mapping[str, Any]): :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - ... - def __init__(self, *args, **kwargs): + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation super().__init__(*args, **kwargs) class ErrorResponse(_model_base.Model): - """ErrorResponse contains code and message that shows the error information. + """Error information that the API returned. All required parameters must be populated in order to send to Azure. - :ivar code: The error code. Required. + :ivar code: Error code. Required. :vartype code: str - :ivar message: The message explaining the error reported by the service. Required. + :ivar message: Message that explains the error that the service reported. Required. :vartype message: str """ code: str = rest_field() - """The error code. Required. """ + """Error code. Required.""" message: str = rest_field() - """The message explaining the error reported by the service. Required. """ + """Message that explains the error that the service reported. Required.""" @overload def __init__( @@ -396,79 +378,76 @@ def __init__(self, mapping: Mapping[str, Any]): :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - ... - def __init__(self, *args, **kwargs): + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation super().__init__(*args, **kwargs) class ModelInfo(_model_base.Model): - """Training result of a model including its status, errors and diagnostics + """Training result of a model, including its status, errors, and diagnostics information. Readonly variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. - :ivar data_source: Source link to the input data to indicate an accessible Azure storage Uri, - either pointed to an Azure blob storage folder, or pointed to a CSV file in - Azure blob storage based on you data schema selection. Required. + :ivar data_source: Source link to the input data to indicate an accessible Azure Storage URI. + It either points to an Azure Blob Storage folder or points to a CSV file in + Azure Blob Storage, based on your data schema selection. Required. :vartype data_source: str - :ivar data_schema: Data schema of input data source: OneTable or MultiTable. The default - DataSchema is OneTable. Known values are: "OneTable" and "MultiTable". - :vartype data_schema: str or ~anomalydetector.models.DataSchema - :ivar start_time: A required field, indicating the start time of training data, which should be - date-time of ISO 8601 format. Required. + :ivar data_schema: Data schema of the input data source. The default + is OneTable. Known values are: "OneTable" and "MultiTable". + :vartype data_schema: str or ~azure.ai.anomalydetector.models.DataSchema + :ivar start_time: Start date/time of training data, which should be + in ISO 8601 format. Required. :vartype start_time: ~datetime.datetime - :ivar end_time: A required field, indicating the end time of training data, which should be - date-time of ISO 8601 format. Required. + :ivar end_time: End date/time of training data, which should be + in ISO 8601 format. Required. :vartype end_time: ~datetime.datetime - :ivar display_name: An optional field. The display name of the model whose maximum length is 24 + :ivar display_name: Display name of the model. Maximum length is 24 characters. :vartype display_name: str - :ivar sliding_window: An optional field, indicating how many previous timestamps will be used - to - detect whether the timestamp is anomaly or not. + :ivar sliding_window: Number of previous time stamps that will be used to + detect whether the time stamp is an anomaly or not. :vartype sliding_window: int - :ivar align_policy: An optional field, indicating the manner to align multiple variables. - :vartype align_policy: ~anomalydetector.models.AlignPolicy - :ivar status: Model status. One of CREATED, RUNNING, READY, and FAILED. Known values are: - "CREATED", "RUNNING", "READY", and "FAILED". - :vartype status: str or ~anomalydetector.models.ModelStatus - :ivar errors: Error messages when failed to create a model. - :vartype errors: list[~anomalydetector.models.ErrorResponse] - :ivar diagnostics_info: Diagnostics information to help inspect the states of model or + :ivar align_policy: Manner of aligning multiple variables. + :vartype align_policy: ~azure.ai.anomalydetector.models.AlignPolicy + :ivar status: Model status. Known values are: "CREATED", "RUNNING", "READY", and "FAILED". + :vartype status: str or ~azure.ai.anomalydetector.models.ModelStatus + :ivar errors: Error messages after failure to create a model. + :vartype errors: list[~azure.ai.anomalydetector.models.ErrorResponse] + :ivar diagnostics_info: Diagnostics information to help inspect the states of a model or variable. - :vartype diagnostics_info: ~anomalydetector.models.DiagnosticsInfo + :vartype diagnostics_info: ~azure.ai.anomalydetector.models.DiagnosticsInfo """ data_source: str = rest_field(name="dataSource") - """Source link to the input data to indicate an accessible Azure storage Uri, -either pointed to an Azure blob storage folder, or pointed to a CSV file in -Azure blob storage based on you data schema selection. Required. """ + """Source link to the input data to indicate an accessible Azure Storage URI. + It either points to an Azure Blob Storage folder or points to a CSV file in + Azure Blob Storage, based on your data schema selection. Required.""" data_schema: Optional[Union[str, "_models.DataSchema"]] = rest_field(name="dataSchema") - """Data schema of input data source: OneTable or MultiTable. The default -DataSchema is OneTable. Known values are: \"OneTable\" and \"MultiTable\".""" + """Data schema of the input data source. The default + is OneTable. Known values are: \"OneTable\" and \"MultiTable\".""" start_time: datetime.datetime = rest_field(name="startTime") - """A required field, indicating the start time of training data, which should be -date-time of ISO 8601 format. Required. """ + """Start date/time of training data, which should be + in ISO 8601 format. Required.""" end_time: datetime.datetime = rest_field(name="endTime") - """A required field, indicating the end time of training data, which should be -date-time of ISO 8601 format. Required. """ + """End date/time of training data, which should be + in ISO 8601 format. Required.""" display_name: Optional[str] = rest_field(name="displayName") - """An optional field. The display name of the model whose maximum length is 24 -characters. """ + """Display name of the model. Maximum length is 24 + characters.""" sliding_window: Optional[int] = rest_field(name="slidingWindow") - """An optional field, indicating how many previous timestamps will be used to -detect whether the timestamp is anomaly or not. """ + """Number of previous time stamps that will be used to + detect whether the time stamp is an anomaly or not.""" align_policy: Optional["_models.AlignPolicy"] = rest_field(name="alignPolicy") - """An optional field, indicating the manner to align multiple variables. """ - status: Optional[Union[str, "_models.ModelStatus"]] = rest_field() - """Model status. One of CREATED, RUNNING, READY, and FAILED. Known values are: \"CREATED\", \"RUNNING\", \"READY\", and \"FAILED\".""" + """Manner of aligning multiple variables.""" + status: Optional[Union[str, "_models.ModelStatus"]] = rest_field(readonly=True) + """Model status. Known values are: \"CREATED\", \"RUNNING\", \"READY\", and \"FAILED\".""" errors: Optional[List["_models.ErrorResponse"]] = rest_field(readonly=True) - """Error messages when failed to create a model. """ - diagnostics_info: Optional["_models.DiagnosticsInfo"] = rest_field(name="diagnosticsInfo") - """Diagnostics information to help inspect the states of model or variable. """ + """Error messages after failure to create a model.""" + diagnostics_info: Optional["_models.DiagnosticsInfo"] = rest_field(name="diagnosticsInfo", readonly=True) + """Diagnostics information to help inspect the states of a model or variable.""" @overload def __init__( @@ -481,8 +460,6 @@ def __init__( display_name: Optional[str] = None, sliding_window: Optional[int] = None, align_policy: Optional["_models.AlignPolicy"] = None, - status: Optional[Union[str, "_models.ModelStatus"]] = None, - diagnostics_info: Optional["_models.DiagnosticsInfo"] = None, ): ... @@ -492,45 +469,15 @@ def __init__(self, mapping: Mapping[str, Any]): :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - ... - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - -class ModelList(_model_base.Model): - """Response of listing models. - - All required parameters must be populated in order to send to Azure. - - :ivar models: List of models. Required. - :vartype models: list[~anomalydetector.models.AnomalyDetectionModel] - :ivar current_count: Number of trained multivariate models. Required. - :vartype current_count: int - :ivar max_count: Maximum number of models that can be trained for this Anomaly Detector - resource. Required. - :vartype max_count: int - :ivar next_link: The link to fetch more models. - :vartype next_link: str - """ - - models: List["_models.AnomalyDetectionModel"] = rest_field() - """List of models. Required. """ - current_count: int = rest_field(name="currentCount") - """Number of trained multivariate models. Required. """ - max_count: int = rest_field(name="maxCount") - """Maximum number of models that can be trained for this Anomaly Detector resource. Required. """ - next_link: Optional[str] = rest_field(name="nextLink") - """The link to fetch more models. """ - - def __init__(self, *args, **kwargs): + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation super().__init__(*args, **kwargs) class ModelState(_model_base.Model): """Model status. - :ivar epoch_ids: This indicates the number of passes of the entire training dataset the + :ivar epoch_ids: Number of passes of the entire training dataset that the algorithm has completed. :vartype epoch_ids: list[int] :ivar train_losses: List of metrics used to assess how the model fits the training data for @@ -546,16 +493,16 @@ class ModelState(_model_base.Model): """ epoch_ids: Optional[List[int]] = rest_field(name="epochIds") - """This indicates the number of passes of the entire training dataset the -algorithm has completed. """ + """Number of passes of the entire training dataset that the + algorithm has completed.""" train_losses: Optional[List[float]] = rest_field(name="trainLosses") """List of metrics used to assess how the model fits the training data for each -epoch. """ + epoch.""" validation_losses: Optional[List[float]] = rest_field(name="validationLosses") """List of metrics used to assess how the model fits the validation set for each -epoch. """ + epoch.""" latencies_in_seconds: Optional[List[float]] = rest_field(name="latenciesInSeconds") - """Latency for each epoch. """ + """Latency for each epoch.""" @overload def __init__( @@ -574,61 +521,59 @@ def __init__(self, mapping: Mapping[str, Any]): :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - ... - def __init__(self, *args, **kwargs): + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation super().__init__(*args, **kwargs) class MultivariateBatchDetectionOptions(_model_base.Model): - """Detection request for batch inference. This is an asynchronous inference which + """Detection request for batch inference. This is an asynchronous inference that will need another API to get detection results. All required parameters must be populated in order to send to Azure. - :ivar data_source: Source link to the input data to indicate an accessible Azure storage Uri, - either pointed to an Azure blob storage folder, or pointed to a CSV file in - Azure blob storage based on you data schema selection. The data schema should - be exactly the same with those used in the training phase. Required. + :ivar data_source: Source link to the input data to indicate an accessible Azure Storage URI. + It either points to an Azure Blob Storage folder or points to a CSV file in + Azure Blob Storage, based on your data schema selection. The data schema should + be exactly the same as those used in the training phase. The input data must + contain at least slidingWindow entries preceding the start time of the data + to be detected. Required. :vartype data_source: str - :ivar top_contributor_count: An optional field, which is used to specify the number of top - contributed - variables for one anomalous timestamp in the response. The default number is - 10. Required. + :ivar top_contributor_count: Number of top contributed variables for one anomalous time stamp + in the response. :vartype top_contributor_count: int - :ivar start_time: A required field, indicating the start time of data for detection, which - should - be date-time of ISO 8601 format. Required. + :ivar start_time: Start date/time of data for detection, which should + be in ISO 8601 format. Required. :vartype start_time: ~datetime.datetime - :ivar end_time: A required field, indicating the end time of data for detection, which should - be date-time of ISO 8601 format. Required. + :ivar end_time: End date/time of data for detection, which should + be in ISO 8601 format. Required. :vartype end_time: ~datetime.datetime """ data_source: str = rest_field(name="dataSource") - """Source link to the input data to indicate an accessible Azure storage Uri, -either pointed to an Azure blob storage folder, or pointed to a CSV file in -Azure blob storage based on you data schema selection. The data schema should -be exactly the same with those used in the training phase. Required. """ - top_contributor_count: int = rest_field(name="topContributorCount") - """An optional field, which is used to specify the number of top contributed -variables for one anomalous timestamp in the response. The default number is -10. Required. """ + """Source link to the input data to indicate an accessible Azure Storage URI. + It either points to an Azure Blob Storage folder or points to a CSV file in + Azure Blob Storage, based on your data schema selection. The data schema should + be exactly the same as those used in the training phase. The input data must + contain at least slidingWindow entries preceding the start time of the data + to be detected. Required.""" + top_contributor_count: int = rest_field(name="topContributorCount", default=10) + """Number of top contributed variables for one anomalous time stamp in the response.""" start_time: datetime.datetime = rest_field(name="startTime") - """A required field, indicating the start time of data for detection, which should -be date-time of ISO 8601 format. Required. """ + """Start date/time of data for detection, which should + be in ISO 8601 format. Required.""" end_time: datetime.datetime = rest_field(name="endTime") - """A required field, indicating the end time of data for detection, which should -be date-time of ISO 8601 format. Required. """ + """End date/time of data for detection, which should + be in ISO 8601 format. Required.""" @overload def __init__( self, *, data_source: str, - top_contributor_count: int, start_time: datetime.datetime, end_time: datetime.datetime, + top_contributor_count: int = 10, ): ... @@ -638,9 +583,8 @@ def __init__(self, mapping: Mapping[str, Any]): :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - ... - def __init__(self, *args, **kwargs): + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation super().__init__(*args, **kwargs) @@ -649,28 +593,28 @@ class MultivariateBatchDetectionResultSummary(_model_base.Model): All required parameters must be populated in order to send to Azure. - :ivar status: Status of detection results. One of CREATED, RUNNING, READY, and FAILED. - Required. Known values are: "CREATED", "RUNNING", "READY", and "FAILED". - :vartype status: str or ~anomalydetector.models.MultivariateBatchDetectionStatus - :ivar errors: Error message when detection is failed. - :vartype errors: list[~anomalydetector.models.ErrorResponse] - :ivar variable_states: Variable Status. - :vartype variable_states: list[~anomalydetector.models.VariableState] - :ivar setup_info: Detection request for batch inference. This is an asynchronous inference - which + :ivar status: Status of detection results. Required. Known values are: "CREATED", "RUNNING", + "READY", and "FAILED". + :vartype status: str or ~azure.ai.anomalydetector.models.MultivariateBatchDetectionStatus + :ivar errors: Error message when detection fails. + :vartype errors: list[~azure.ai.anomalydetector.models.ErrorResponse] + :ivar variable_states: Variable status. + :vartype variable_states: list[~azure.ai.anomalydetector.models.VariableState] + :ivar setup_info: Detection request for batch inference. This is an asynchronous inference that will need another API to get detection results. Required. - :vartype setup_info: ~anomalydetector.models.MultivariateBatchDetectionOptions + :vartype setup_info: ~azure.ai.anomalydetector.models.MultivariateBatchDetectionOptions """ status: Union[str, "_models.MultivariateBatchDetectionStatus"] = rest_field() - """Status of detection results. One of CREATED, RUNNING, READY, and FAILED. Required. Known values are: \"CREATED\", \"RUNNING\", \"READY\", and \"FAILED\".""" + """Status of detection results. Required. Known values are: \"CREATED\", \"RUNNING\", \"READY\", + and \"FAILED\".""" errors: Optional[List["_models.ErrorResponse"]] = rest_field() - """Error message when detection is failed. """ + """Error message when detection fails.""" variable_states: Optional[List["_models.VariableState"]] = rest_field(name="variableStates") - """Variable Status. """ + """Variable status.""" setup_info: "_models.MultivariateBatchDetectionOptions" = rest_field(name="setupInfo") - """Detection request for batch inference. This is an asynchronous inference which -will need another API to get detection results. Required. """ + """Detection request for batch inference. This is an asynchronous inference that + will need another API to get detection results. Required.""" @overload def __init__( @@ -689,34 +633,33 @@ def __init__(self, mapping: Mapping[str, Any]): :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - ... - def __init__(self, *args, **kwargs): + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation super().__init__(*args, **kwargs) class MultivariateDetectionResult(_model_base.Model): - """Detection results for the given resultId. + """Detection results for the resultId value. Readonly variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. - :ivar result_id: Result identifier, which is used to fetch the results of an inference call. + :ivar result_id: Result identifier that's used to fetch the results of an inference call. Required. :vartype result_id: str :ivar summary: Multivariate anomaly detection status. Required. - :vartype summary: ~anomalydetector.models.MultivariateBatchDetectionResultSummary - :ivar results: Detection result for each timestamp. Required. - :vartype results: list[~anomalydetector.models.AnomalyState] + :vartype summary: ~azure.ai.anomalydetector.models.MultivariateBatchDetectionResultSummary + :ivar results: Detection result for each time stamp. Required. + :vartype results: list[~azure.ai.anomalydetector.models.AnomalyState] """ result_id: str = rest_field(name="resultId", readonly=True) - """Result identifier, which is used to fetch the results of an inference call. Required. """ + """Result identifier that's used to fetch the results of an inference call. Required.""" summary: "_models.MultivariateBatchDetectionResultSummary" = rest_field() - """Multivariate anomaly detection status. Required. """ + """Multivariate anomaly detection status. Required.""" results: List["_models.AnomalyState"] = rest_field() - """Detection result for each timestamp. Required. """ + """Detection result for each time stamp. Required.""" @overload def __init__( @@ -733,41 +676,39 @@ def __init__(self, mapping: Mapping[str, Any]): :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - ... - def __init__(self, *args, **kwargs): + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation super().__init__(*args, **kwargs) class MultivariateLastDetectionOptions(_model_base.Model): - """Request of last detection. + """Request of the last detection. All required parameters must be populated in order to send to Azure. - :ivar variables: This contains the inference data, including the name, timestamps(ISO 8601) and + :ivar variables: Contains the inference data, including the name, time stamps (ISO 8601), and values of variables. Required. - :vartype variables: list[~anomalydetector.models.VariableValues] - :ivar top_contributor_count: An optional field, which is used to specify the number of top - contributed - variables for one anomalous timestamp in the response. The default number is - 10. Required. + :vartype variables: list[~azure.ai.anomalydetector.models.VariableValues] + :ivar top_contributor_count: Number of top contributed + variables for one anomalous time stamp in the response. The default is + 10. :vartype top_contributor_count: int """ variables: List["_models.VariableValues"] = rest_field() - """This contains the inference data, including the name, timestamps(ISO 8601) and -values of variables. Required. """ - top_contributor_count: int = rest_field(name="topContributorCount") - """An optional field, which is used to specify the number of top contributed -variables for one anomalous timestamp in the response. The default number is -10. Required. """ + """Contains the inference data, including the name, time stamps (ISO 8601), and + values of variables. Required.""" + top_contributor_count: int = rest_field(name="topContributorCount", default=10) + """Number of top contributed + variables for one anomalous time stamp in the response. The default is + 10.""" @overload def __init__( self, *, variables: List["_models.VariableValues"], - top_contributor_count: int, + top_contributor_count: int = 10, ): ... @@ -777,25 +718,24 @@ def __init__(self, mapping: Mapping[str, Any]): :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - ... - def __init__(self, *args, **kwargs): + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation super().__init__(*args, **kwargs) class MultivariateLastDetectionResult(_model_base.Model): - """Results of last detection. + """Results of the last detection. - :ivar variable_states: Variable Status. - :vartype variable_states: list[~anomalydetector.models.VariableState] + :ivar variable_states: Variable status. + :vartype variable_states: list[~azure.ai.anomalydetector.models.VariableState] :ivar results: Anomaly status and information. - :vartype results: list[~anomalydetector.models.AnomalyState] + :vartype results: list[~azure.ai.anomalydetector.models.AnomalyState] """ variable_states: Optional[List["_models.VariableState"]] = rest_field(name="variableStates") - """Variable Status. """ + """Variable status.""" results: Optional[List["_models.AnomalyState"]] = rest_field() - """Anomaly status and information. """ + """Anomaly status and information.""" @overload def __init__( @@ -812,69 +752,26 @@ def __init__(self, mapping: Mapping[str, Any]): :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - ... - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - -class ResponseError(_model_base.Model): - """Error response. - - All required parameters must be populated in order to send to Azure. - - :ivar x_ms_error_code: Error code. - :vartype x_ms_error_code: str - :ivar code: The error code. Required. - :vartype code: str - :ivar message: The message explaining the error reported by the service. Required. - :vartype message: str - """ - - x_ms_error_code: Optional[str] = rest_field(name="x-ms-error-code") - """Error code. """ - code: str = rest_field() - """The error code. Required. """ - message: str = rest_field() - """The message explaining the error reported by the service. Required. """ - - @overload - def __init__( - self, - *, - code: str, - message: str, - x_ms_error_code: Optional[str] = None, - ): - ... - - @overload - def __init__(self, mapping: Mapping[str, Any]): - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - ... - def __init__(self, *args, **kwargs): + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation super().__init__(*args, **kwargs) class TimeSeriesPoint(_model_base.Model): - """The definition of input timeseries points. + """Definition of input time series points. All required parameters must be populated in order to send to Azure. - :ivar timestamp: Optional argument, timestamp of a data point (ISO8601 format). + :ivar timestamp: Argument that indicates the time stamp of a data point (ISO8601 format). :vartype timestamp: ~datetime.datetime - :ivar value: The measurement of that point, should be float. Required. + :ivar value: Measurement of that point. Required. :vartype value: float """ timestamp: Optional[datetime.datetime] = rest_field() - """Optional argument, timestamp of a data point (ISO8601 format). """ + """Argument that indicates the time stamp of a data point (ISO8601 format).""" value: float = rest_field() - """The measurement of that point, should be float. Required. """ + """Measurement of that point. Required.""" @overload def __init__( @@ -891,63 +788,64 @@ def __init__(self, mapping: Mapping[str, Any]): :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - ... - def __init__(self, *args, **kwargs): + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation super().__init__(*args, **kwargs) class UnivariateChangePointDetectionOptions(_model_base.Model): - """The request of change point detection. + """Request of change point detection. All required parameters must be populated in order to send to Azure. - :ivar series: Time series data points. Points should be sorted by timestamp in ascending + :ivar series: Time series data points. Points should be sorted by time stamp in ascending order to match the change point detection result. Required. - :vartype series: list[~anomalydetector.models.TimeSeriesPoint] - :ivar granularity: Can only be one of yearly, monthly, weekly, daily, hourly, minutely or - secondly. Granularity is used for verify whether input series is valid. Required. Known values - are: "yearly", "monthly", "weekly", "daily", "hourly", "minutely", "secondly", "microsecond", - and "none". - :vartype granularity: str or ~anomalydetector.models.TimeGranularity - :ivar custom_interval: Custom Interval is used to set non-standard time interval, for example, - if the - series is 5 minutes, request can be set as {"granularity":"minutely", + :vartype series: list[~azure.ai.anomalydetector.models.TimeSeriesPoint] + :ivar granularity: Granularity is used to verify whether the input series is valid. Required. + Known values are: "yearly", "monthly", "weekly", "daily", "hourly", "minutely", "secondly", + "microsecond", and "none". + :vartype granularity: str or ~azure.ai.anomalydetector.models.TimeGranularity + :ivar custom_interval: A custom interval is used to set a nonstandard time interval. For + example, if the + series is 5 minutes, the request can be set as {"granularity":"minutely", "customInterval":5}. :vartype custom_interval: int - :ivar period: Optional argument, periodic value of a time series. If the value is null or - does not present, the API will determine the period automatically. + :ivar period: Argument that indicates the periodic value of a time series. If the value is null + or + not present, the API will determine the period automatically. :vartype period: int - :ivar stable_trend_window: Optional argument, advanced model parameter, a default - stableTrendWindow will + :ivar stable_trend_window: Argument that indicates an advanced model parameter. A default + stableTrendWindow value will be used in detection. :vartype stable_trend_window: int - :ivar threshold: Optional argument, advanced model parameter, between 0.0-1.0, the lower the - value is, the larger the trend error will be which means less change point will + :ivar threshold: Argument that indicates an advanced model parameter between 0.0 and 1.0. The + lower the + value is, the larger the trend error is, which means less change point will be accepted. :vartype threshold: float """ series: List["_models.TimeSeriesPoint"] = rest_field() - """Time series data points. Points should be sorted by timestamp in ascending -order to match the change point detection result. Required. """ + """Time series data points. Points should be sorted by time stamp in ascending + order to match the change point detection result. Required.""" granularity: Union[str, "_models.TimeGranularity"] = rest_field() - """Can only be one of yearly, monthly, weekly, daily, hourly, minutely or -secondly. Granularity is used for verify whether input series is valid. Required. Known values are: \"yearly\", \"monthly\", \"weekly\", \"daily\", \"hourly\", \"minutely\", \"secondly\", \"microsecond\", and \"none\".""" + """Granularity is used to verify whether the input series is valid. Required. Known values are: + \"yearly\", \"monthly\", \"weekly\", \"daily\", \"hourly\", \"minutely\", \"secondly\", + \"microsecond\", and \"none\".""" custom_interval: Optional[int] = rest_field(name="customInterval") - """Custom Interval is used to set non-standard time interval, for example, if the -series is 5 minutes, request can be set as {\"granularity\":\"minutely\", -\"customInterval\":5}. """ + """A custom interval is used to set a nonstandard time interval. For example, if the + series is 5 minutes, the request can be set as {\"granularity\":\"minutely\", + \"customInterval\":5}.""" period: Optional[int] = rest_field() - """Optional argument, periodic value of a time series. If the value is null or -does not present, the API will determine the period automatically. """ + """Argument that indicates the periodic value of a time series. If the value is null or + not present, the API will determine the period automatically.""" stable_trend_window: Optional[int] = rest_field(name="stableTrendWindow") - """Optional argument, advanced model parameter, a default stableTrendWindow will -be used in detection. """ + """Argument that indicates an advanced model parameter. A default stableTrendWindow value will + be used in detection.""" threshold: Optional[float] = rest_field() - """Optional argument, advanced model parameter, between 0.0-1.0, the lower the -value is, the larger the trend error will be which means less change point will -be accepted. """ + """Argument that indicates an advanced model parameter between 0.0 and 1.0. The lower the + value is, the larger the trend error is, which means less change point will + be accepted.""" @overload def __init__( @@ -968,38 +866,36 @@ def __init__(self, mapping: Mapping[str, Any]): :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - ... - def __init__(self, *args, **kwargs): + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation super().__init__(*args, **kwargs) class UnivariateChangePointDetectionResult(_model_base.Model): - """The response of change point detection. + """Response of change point detection. Readonly variables are only populated by the server, and will be ignored when sending a request. - :ivar period: Frequency extracted from the series, zero means no recurrent pattern has been + :ivar period: Frequency extracted from the series. Zero means no recurrent pattern has been found. :vartype period: int - :ivar is_change_point: isChangePoint contains change point properties for each input point. - True means - an anomaly either negative or positive has been detected. The index of the + :ivar is_change_point: Change point properties for each input point. True means + an anomaly (either negative or positive) has been detected. The index of the array is consistent with the input series. :vartype is_change_point: list[bool] - :ivar confidence_scores: the change point confidence of each point. + :ivar confidence_scores: Change point confidence of each point. :vartype confidence_scores: list[float] """ period: Optional[int] = rest_field(readonly=True) - """Frequency extracted from the series, zero means no recurrent pattern has been -found. """ + """Frequency extracted from the series. Zero means no recurrent pattern has been + found.""" is_change_point: Optional[List[bool]] = rest_field(name="isChangePoint") - """isChangePoint contains change point properties for each input point. True means -an anomaly either negative or positive has been detected. The index of the -array is consistent with the input series. """ + """Change point properties for each input point. True means + an anomaly (either negative or positive) has been detected. The index of the + array is consistent with the input series.""" confidence_scores: Optional[List[float]] = rest_field(name="confidenceScores") - """the change point confidence of each point. """ + """Change point confidence of each point.""" @overload def __init__( @@ -1016,84 +912,84 @@ def __init__(self, mapping: Mapping[str, Any]): :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - ... - def __init__(self, *args, **kwargs): + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation super().__init__(*args, **kwargs) class UnivariateDetectionOptions(_model_base.Model): - """The request of entire or last anomaly detection. + """Request of the entire or last anomaly detection. All required parameters must be populated in order to send to Azure. - :ivar series: Time series data points. Points should be sorted by timestamp in ascending + :ivar series: Time series data points. Points should be sorted by time stamp in ascending order to match the anomaly detection result. If the data is not sorted - correctly or there is duplicated timestamp, the API will not work. In such - case, an error message will be returned. Required. - :vartype series: list[~anomalydetector.models.TimeSeriesPoint] - :ivar granularity: Optional argument, can be one of yearly, monthly, weekly, daily, hourly, - minutely, secondly, microsecond or none. If granularity is not present, it will - be none by default. If granularity is none, the timestamp property in time + correctly or there's a duplicated time stamp, the API won't work. In such + a case, an error message is returned. Required. + :vartype series: list[~azure.ai.anomalydetector.models.TimeSeriesPoint] + :ivar granularity: Argument that indicates time granularity. If granularity is not present, the + value + is none by default. If granularity is none, the time stamp property in the time series point can be absent. Known values are: "yearly", "monthly", "weekly", "daily", "hourly", "minutely", "secondly", "microsecond", and "none". - :vartype granularity: str or ~anomalydetector.models.TimeGranularity - :ivar custom_interval: Custom Interval is used to set non-standard time interval, for example, - if the - series is 5 minutes, request can be set as {"granularity":"minutely", + :vartype granularity: str or ~azure.ai.anomalydetector.models.TimeGranularity + :ivar custom_interval: A custom interval is used to set a nonstandard time interval. For + example, if the + series is 5 minutes, the request can be set as {"granularity":"minutely", "customInterval":5}. :vartype custom_interval: int - :ivar period: Optional argument, periodic value of a time series. If the value is null or - does not present, the API will determine the period automatically. + :ivar period: Argument that indicates the periodic value of a time series. If the value is null + or + is not present, the API determines the period automatically. :vartype period: int - :ivar max_anomaly_ratio: Optional argument, advanced model parameter, max anomaly ratio in a - time series. + :ivar max_anomaly_ratio: Argument that indicates an advanced model parameter. It's the maximum + anomaly ratio in a time series. :vartype max_anomaly_ratio: float - :ivar sensitivity: Optional argument, advanced model parameter, between 0-99, the lower the - value - is, the larger the margin value will be which means less anomalies will be + :ivar sensitivity: Argument that indicates an advanced model parameter between 0 and 99. The + lower the value + is, the larger the margin value is, which means fewer anomalies will be accepted. :vartype sensitivity: int - :ivar impute_mode: Used to specify how to deal with missing values in the input series, it's - used + :ivar impute_mode: Specifies how to deal with missing values in the input series. It's used when granularity is not "none". Known values are: "auto", "previous", "linear", "fixed", "zero", and "notFill". - :vartype impute_mode: str or ~anomalydetector.models.ImputeMode - :ivar impute_fixed_value: Used to specify the value to fill, it's used when granularity is not - "none" + :vartype impute_mode: str or ~azure.ai.anomalydetector.models.ImputeMode + :ivar impute_fixed_value: Specifies the value to fill. It's used when granularity is not "none" and imputeMode is "fixed". :vartype impute_fixed_value: float """ series: List["_models.TimeSeriesPoint"] = rest_field() - """Time series data points. Points should be sorted by timestamp in ascending -order to match the anomaly detection result. If the data is not sorted -correctly or there is duplicated timestamp, the API will not work. In such -case, an error message will be returned. Required. """ + """Time series data points. Points should be sorted by time stamp in ascending + order to match the anomaly detection result. If the data is not sorted + correctly or there's a duplicated time stamp, the API won't work. In such + a case, an error message is returned. Required.""" granularity: Optional[Union[str, "_models.TimeGranularity"]] = rest_field() - """Optional argument, can be one of yearly, monthly, weekly, daily, hourly, -minutely, secondly, microsecond or none. If granularity is not present, it will -be none by default. If granularity is none, the timestamp property in time -series point can be absent. Known values are: \"yearly\", \"monthly\", \"weekly\", \"daily\", \"hourly\", \"minutely\", \"secondly\", \"microsecond\", and \"none\".""" + """Argument that indicates time granularity. If granularity is not present, the value + is none by default. If granularity is none, the time stamp property in the time + series point can be absent. Known values are: \"yearly\", \"monthly\", \"weekly\", \"daily\", + \"hourly\", \"minutely\", \"secondly\", \"microsecond\", and \"none\".""" custom_interval: Optional[int] = rest_field(name="customInterval") - """Custom Interval is used to set non-standard time interval, for example, if the -series is 5 minutes, request can be set as {\"granularity\":\"minutely\", -\"customInterval\":5}. """ + """A custom interval is used to set a nonstandard time interval. For example, if the + series is 5 minutes, the request can be set as {\"granularity\":\"minutely\", + \"customInterval\":5}.""" period: Optional[int] = rest_field() - """Optional argument, periodic value of a time series. If the value is null or -does not present, the API will determine the period automatically. """ + """Argument that indicates the periodic value of a time series. If the value is null or + is not present, the API determines the period automatically.""" max_anomaly_ratio: Optional[float] = rest_field(name="maxAnomalyRatio") - """Optional argument, advanced model parameter, max anomaly ratio in a time series. """ + """Argument that indicates an advanced model parameter. It's the maximum anomaly ratio in a time + series.""" sensitivity: Optional[int] = rest_field() - """Optional argument, advanced model parameter, between 0-99, the lower the value -is, the larger the margin value will be which means less anomalies will be -accepted. """ + """Argument that indicates an advanced model parameter between 0 and 99. The lower the value + is, the larger the margin value is, which means fewer anomalies will be + accepted.""" impute_mode: Optional[Union[str, "_models.ImputeMode"]] = rest_field(name="imputeMode") - """Used to specify how to deal with missing values in the input series, it's used -when granularity is not \"none\". Known values are: \"auto\", \"previous\", \"linear\", \"fixed\", \"zero\", and \"notFill\".""" + """Specifies how to deal with missing values in the input series. It's used + when granularity is not \"none\". Known values are: \"auto\", \"previous\", \"linear\", + \"fixed\", \"zero\", and \"notFill\".""" impute_fixed_value: Optional[float] = rest_field(name="imputeFixedValue") - """Used to specify the value to fill, it's used when granularity is not \"none\" -and imputeMode is \"fixed\". """ + """Specifies the value to fill. It's used when granularity is not \"none\" + and imputeMode is \"fixed\".""" @overload def __init__( @@ -1116,96 +1012,90 @@ def __init__(self, mapping: Mapping[str, Any]): :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - ... - def __init__(self, *args, **kwargs): + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation super().__init__(*args, **kwargs) class UnivariateEntireDetectionResult(_model_base.Model): - """The response of entire anomaly detection. + """Response of the entire anomaly detection. All required parameters must be populated in order to send to Azure. - :ivar period: Frequency extracted from the series, zero means no recurrent pattern has been + :ivar period: Frequency extracted from the series. Zero means no recurrent pattern has been found. Required. :vartype period: int - :ivar expected_values: ExpectedValues contain expected value for each input point. The index of - the + :ivar expected_values: Expected value for each input point. The index of the array is consistent with the input series. Required. :vartype expected_values: list[float] - :ivar upper_margins: UpperMargins contain upper margin of each input point. UpperMargin is used - to - calculate upperBoundary, which equals to expectedValue + (100 - - marginScale)*upperMargin. Anomalies in response can be filtered by - upperBoundary and lowerBoundary. By adjusting marginScale value, less - significant anomalies can be filtered in client side. The index of the array is + :ivar upper_margins: Upper margin of each input point. UpperMargin is used to + calculate upperBoundary, which is equal to expectedValue + (100 - + marginScale)*upperMargin. Anomalies in the response can be filtered by + upperBoundary and lowerBoundary. Adjusting the marginScale value can help filter less + significant anomalies on the client side. The index of the array is consistent with the input series. Required. :vartype upper_margins: list[float] - :ivar lower_margins: LowerMargins contain lower margin of each input point. LowerMargin is used - to - calculate lowerBoundary, which equals to expectedValue - (100 - + :ivar lower_margins: Lower margin of each input point. LowerMargin is used to + calculate lowerBoundary, which is equal to expectedValue - (100 - marginScale)*lowerMargin. Points between the boundary can be marked as normal - ones in client side. The index of the array is consistent with the input + ones on the client side. The index of the array is consistent with the input series. Required. :vartype lower_margins: list[float] - :ivar is_anomaly: IsAnomaly contains anomaly properties for each input point. True means an - anomaly either negative or positive has been detected. The index of the array + :ivar is_anomaly: Anomaly properties for each input point. True means an + anomaly (either negative or positive) has been detected. The index of the array is consistent with the input series. Required. :vartype is_anomaly: list[bool] - :ivar is_negative_anomaly: IsNegativeAnomaly contains anomaly status in negative direction for - each input + :ivar is_negative_anomaly: Anomaly status in a negative direction for each input point. True means a negative anomaly has been detected. A negative anomaly means the point is detected as an anomaly and its real value is smaller than the expected one. The index of the array is consistent with the input series. Required. :vartype is_negative_anomaly: list[bool] - :ivar is_positive_anomaly: IsPositiveAnomaly contain anomaly status in positive direction for - each input + :ivar is_positive_anomaly: Anomaly status in a positive direction for each input point. True means a positive anomaly has been detected. A positive anomaly means the point is detected as an anomaly and its real value is larger than the expected one. The index of the array is consistent with the input series. Required. :vartype is_positive_anomaly: list[bool] - :ivar severity: The severity score for each input point. The larger the value is, the more - sever the anomaly is. For normal points, the "severity" is always 0. + :ivar severity: Severity score for each input point. The larger the value is, the more + severe the anomaly is. For normal points, the severity is always 0. :vartype severity: list[float] """ period: int = rest_field() - """Frequency extracted from the series, zero means no recurrent pattern has been -found. Required. """ + """Frequency extracted from the series. Zero means no recurrent pattern has been + found. Required.""" expected_values: List[float] = rest_field(name="expectedValues") - """ExpectedValues contain expected value for each input point. The index of the -array is consistent with the input series. Required. """ + """Expected value for each input point. The index of the + array is consistent with the input series. Required.""" upper_margins: List[float] = rest_field(name="upperMargins") - """UpperMargins contain upper margin of each input point. UpperMargin is used to -calculate upperBoundary, which equals to expectedValue + (100 - -marginScale)*upperMargin. Anomalies in response can be filtered by -upperBoundary and lowerBoundary. By adjusting marginScale value, less -significant anomalies can be filtered in client side. The index of the array is -consistent with the input series. Required. """ + """Upper margin of each input point. UpperMargin is used to + calculate upperBoundary, which is equal to expectedValue + (100 - + marginScale)*upperMargin. Anomalies in the response can be filtered by + upperBoundary and lowerBoundary. Adjusting the marginScale value can help filter less + significant anomalies on the client side. The index of the array is + consistent with the input series. Required.""" lower_margins: List[float] = rest_field(name="lowerMargins") - """LowerMargins contain lower margin of each input point. LowerMargin is used to -calculate lowerBoundary, which equals to expectedValue - (100 - -marginScale)*lowerMargin. Points between the boundary can be marked as normal -ones in client side. The index of the array is consistent with the input -series. Required. """ + """Lower margin of each input point. LowerMargin is used to + calculate lowerBoundary, which is equal to expectedValue - (100 - + marginScale)*lowerMargin. Points between the boundary can be marked as normal + ones on the client side. The index of the array is consistent with the input + series. Required.""" is_anomaly: List[bool] = rest_field(name="isAnomaly") - """IsAnomaly contains anomaly properties for each input point. True means an -anomaly either negative or positive has been detected. The index of the array -is consistent with the input series. Required. """ + """Anomaly properties for each input point. True means an + anomaly (either negative or positive) has been detected. The index of the array + is consistent with the input series. Required.""" is_negative_anomaly: List[bool] = rest_field(name="isNegativeAnomaly") - """IsNegativeAnomaly contains anomaly status in negative direction for each input -point. True means a negative anomaly has been detected. A negative anomaly -means the point is detected as an anomaly and its real value is smaller than -the expected one. The index of the array is consistent with the input series. Required. """ + """Anomaly status in a negative direction for each input + point. True means a negative anomaly has been detected. A negative anomaly + means the point is detected as an anomaly and its real value is smaller than + the expected one. The index of the array is consistent with the input series. Required.""" is_positive_anomaly: List[bool] = rest_field(name="isPositiveAnomaly") - """IsPositiveAnomaly contain anomaly status in positive direction for each input -point. True means a positive anomaly has been detected. A positive anomaly -means the point is detected as an anomaly and its real value is larger than the -expected one. The index of the array is consistent with the input series. Required. """ + """Anomaly status in a positive direction for each input + point. True means a positive anomaly has been detected. A positive anomaly + means the point is detected as an anomaly and its real value is larger than the + expected one. The index of the array is consistent with the input series. Required.""" severity: Optional[List[float]] = rest_field() - """The severity score for each input point. The larger the value is, the more -sever the anomaly is. For normal points, the \"severity\" is always 0. """ + """Severity score for each input point. The larger the value is, the more + severe the anomaly is. For normal points, the severity is always 0.""" @overload def __init__( @@ -1228,18 +1118,17 @@ def __init__(self, mapping: Mapping[str, Any]): :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - ... - def __init__(self, *args, **kwargs): + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation super().__init__(*args, **kwargs) class UnivariateLastDetectionResult(_model_base.Model): - """The response of last anomaly detection. + """Response of the last anomaly detection. All required parameters must be populated in order to send to Azure. - :ivar period: Frequency extracted from the series, zero means no recurrent pattern has been + :ivar period: Frequency extracted from the series. Zero means no recurrent pattern has been found. Required. :vartype period: int :ivar suggested_window: Suggested input series points needed for detecting the latest point. @@ -1248,58 +1137,59 @@ class UnivariateLastDetectionResult(_model_base.Model): :ivar expected_value: Expected value of the latest point. Required. :vartype expected_value: float :ivar upper_margin: Upper margin of the latest point. UpperMargin is used to calculate - upperBoundary, which equals to expectedValue + (100 - marginScale)*upperMargin. + upperBoundary, which is equal to expectedValue + (100 - marginScale)*upperMargin. If the value of latest point is between upperBoundary and lowerBoundary, it - should be treated as normal value. By adjusting marginScale value, anomaly - status of latest point can be changed. Required. + should be treated as a normal value. Adjusting the marginScale value enables the anomaly + status of the latest point to be changed. Required. :vartype upper_margin: float :ivar lower_margin: Lower margin of the latest point. LowerMargin is used to calculate - lowerBoundary, which equals to expectedValue - (100 - marginScale)*lowerMargin. Required. + lowerBoundary, which is equal to expectedValue - (100 - marginScale)*lowerMargin. Required. :vartype lower_margin: float - :ivar is_anomaly: Anomaly status of the latest point, true means the latest point is an anomaly - either in negative direction or positive direction. Required. + :ivar is_anomaly: Anomaly status of the latest point. True means the latest point is an + anomaly, + either in the negative direction or in the positive direction. Required. :vartype is_anomaly: bool - :ivar is_negative_anomaly: Anomaly status in negative direction of the latest point. True means - the latest + :ivar is_negative_anomaly: Anomaly status of the latest point in a negative direction. True + means the latest point is an anomaly and its real value is smaller than the expected one. Required. :vartype is_negative_anomaly: bool - :ivar is_positive_anomaly: Anomaly status in positive direction of the latest point. True means - the latest + :ivar is_positive_anomaly: Anomaly status of the latest point in a positive direction. True + means the latest point is an anomaly and its real value is larger than the expected one. Required. :vartype is_positive_anomaly: bool - :ivar severity: The severity score for the last input point. The larger the value is, the more - sever the anomaly is. For normal points, the "severity" is always 0. + :ivar severity: Severity score for the last input point. The larger the value is, the more + severe the anomaly is. For normal points, the severity is always 0. :vartype severity: float """ period: int = rest_field() - """Frequency extracted from the series, zero means no recurrent pattern has been -found. Required. """ + """Frequency extracted from the series. Zero means no recurrent pattern has been + found. Required.""" suggested_window: int = rest_field(name="suggestedWindow") - """Suggested input series points needed for detecting the latest point. Required. """ + """Suggested input series points needed for detecting the latest point. Required.""" expected_value: float = rest_field(name="expectedValue") - """Expected value of the latest point. Required. """ + """Expected value of the latest point. Required.""" upper_margin: float = rest_field(name="upperMargin") """Upper margin of the latest point. UpperMargin is used to calculate -upperBoundary, which equals to expectedValue + (100 - marginScale)*upperMargin. -If the value of latest point is between upperBoundary and lowerBoundary, it -should be treated as normal value. By adjusting marginScale value, anomaly -status of latest point can be changed. Required. """ + upperBoundary, which is equal to expectedValue + (100 - marginScale)*upperMargin. + If the value of latest point is between upperBoundary and lowerBoundary, it + should be treated as a normal value. Adjusting the marginScale value enables the anomaly + status of the latest point to be changed. Required.""" lower_margin: float = rest_field(name="lowerMargin") """Lower margin of the latest point. LowerMargin is used to calculate -lowerBoundary, which equals to expectedValue - (100 - marginScale)*lowerMargin. Required. """ + lowerBoundary, which is equal to expectedValue - (100 - marginScale)*lowerMargin. Required.""" is_anomaly: bool = rest_field(name="isAnomaly") - """Anomaly status of the latest point, true means the latest point is an anomaly -either in negative direction or positive direction. Required. """ + """Anomaly status of the latest point. True means the latest point is an anomaly, + either in the negative direction or in the positive direction. Required.""" is_negative_anomaly: bool = rest_field(name="isNegativeAnomaly") - """Anomaly status in negative direction of the latest point. True means the latest -point is an anomaly and its real value is smaller than the expected one. Required. """ + """Anomaly status of the latest point in a negative direction. True means the latest + point is an anomaly and its real value is smaller than the expected one. Required.""" is_positive_anomaly: bool = rest_field(name="isPositiveAnomaly") - """Anomaly status in positive direction of the latest point. True means the latest -point is an anomaly and its real value is larger than the expected one. Required. """ + """Anomaly status of the latest point in a positive direction. True means the latest + point is an anomaly and its real value is larger than the expected one. Required.""" severity: Optional[float] = rest_field() - """The severity score for the last input point. The larger the value is, the more -sever the anomaly is. For normal points, the \"severity\" is always 0. """ + """Severity score for the last input point. The larger the value is, the more + severe the anomaly is. For normal points, the severity is always 0.""" @overload def __init__( @@ -1323,37 +1213,36 @@ def __init__(self, mapping: Mapping[str, Any]): :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - ... - def __init__(self, *args, **kwargs): + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation super().__init__(*args, **kwargs) class VariableState(_model_base.Model): - """Variable Status. + """Variable status. :ivar variable: Variable name in variable states. :vartype variable: str :ivar filled_n_a_ratio: Proportion of missing values that need to be filled by fillNAMethod. :vartype filled_n_a_ratio: float - :ivar effective_count: Number of effective data points before applying fillNAMethod. + :ivar effective_count: Number of effective data points before fillNAMethod is applied. :vartype effective_count: int - :ivar first_timestamp: First valid timestamp with value of input data. + :ivar first_timestamp: First valid time stamp with a value of input data. :vartype first_timestamp: ~datetime.datetime - :ivar last_timestamp: Last valid timestamp with value of input data. + :ivar last_timestamp: Last valid time stamp with a value of input data. :vartype last_timestamp: ~datetime.datetime """ variable: Optional[str] = rest_field() - """Variable name in variable states. """ + """Variable name in variable states.""" filled_n_a_ratio: Optional[float] = rest_field(name="filledNARatio") - """Proportion of missing values that need to be filled by fillNAMethod. """ + """Proportion of missing values that need to be filled by fillNAMethod.""" effective_count: Optional[int] = rest_field(name="effectiveCount") - """Number of effective data points before applying fillNAMethod. """ + """Number of effective data points before fillNAMethod is applied.""" first_timestamp: Optional[datetime.datetime] = rest_field(name="firstTimestamp") - """First valid timestamp with value of input data. """ + """First valid time stamp with a value of input data.""" last_timestamp: Optional[datetime.datetime] = rest_field(name="lastTimestamp") - """Last valid timestamp with value of input data. """ + """Last valid time stamp with a value of input data.""" @overload def __init__( @@ -1373,9 +1262,8 @@ def __init__(self, mapping: Mapping[str, Any]): :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - ... - def __init__(self, *args, **kwargs): + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation super().__init__(*args, **kwargs) @@ -1384,20 +1272,20 @@ class VariableValues(_model_base.Model): All required parameters must be populated in order to send to Azure. - :ivar variable: Variable name of last detection request. Required. + :ivar variable: Variable name of the last detection request. Required. :vartype variable: str - :ivar timestamps: Timestamps of last detection request. Required. + :ivar timestamps: Time stamps of the last detection request. Required. :vartype timestamps: list[str] :ivar values: Values of variables. Required. :vartype values: list[float] """ variable: str = rest_field() - """Variable name of last detection request. Required. """ + """Variable name of the last detection request. Required.""" timestamps: List[str] = rest_field() - """Timestamps of last detection request. Required. """ + """Time stamps of the last detection request. Required.""" values: List[float] = rest_field() - """Values of variables. Required. """ + """Values of variables. Required.""" @overload def __init__( @@ -1415,7 +1303,6 @@ def __init__(self, mapping: Mapping[str, Any]): :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - ... - def __init__(self, *args, **kwargs): + def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation super().__init__(*args, **kwargs) diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/samples/sample_multivariate_detect.py b/sdk/anomalydetector/azure-ai-anomalydetector/samples/sample_multivariate_detect.py index dd976af798ed..7b7e3ea3d6a5 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/samples/sample_multivariate_detect.py +++ b/sdk/anomalydetector/azure-ai-anomalydetector/samples/sample_multivariate_detect.py @@ -114,7 +114,10 @@ def batch_detect(self, model_id, body): r = self.ad_client.get_multivariate_batch_detection_result(result_id) print("Get detection result...(it may take a few seconds)") - while r.summary.status != MultivariateBatchDetectionStatus.READY and r.summary.status != MultivariateBatchDetectionStatus.FAILED: + while ( + r.summary.status != MultivariateBatchDetectionStatus.READY + and r.summary.status != MultivariateBatchDetectionStatus.FAILED + ): r = self.ad_client.get_multivariate_batch_detection_result(result_id) print("Detection is {}".format(r.summary.status)) time.sleep(15) diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/setup.py b/sdk/anomalydetector/azure-ai-anomalydetector/setup.py index b07d314e17c5..809681d3e35a 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/setup.py +++ b/sdk/anomalydetector/azure-ai-anomalydetector/setup.py @@ -2,7 +2,7 @@ # -------------------------------------------------------------------------- # 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) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- # coding: utf-8 @@ -29,7 +29,7 @@ setup( name=PACKAGE_NAME, version=version, - description="Microsoft Cognitive Services Anomaly Detector Client Library for Python", + description="Microsoft {} Client Library for Python".format(PACKAGE_PPRINT_NAME), long_description=open("README.md", "r").read(), long_description_content_type="text/markdown", license="MIT License", @@ -38,7 +38,7 @@ url="https://github.com/Azure/azure-sdk-for-python/tree/main/sdk", keywords="azure, azure sdk", classifiers=[ - "Development Status :: 4 - Beta", + "Development Status :: 5 - Production/Stable", "Programming Language :: Python", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3", diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/tsp-location.yaml b/sdk/anomalydetector/azure-ai-anomalydetector/tsp-location.yaml new file mode 100644 index 000000000000..da852138a871 --- /dev/null +++ b/sdk/anomalydetector/azure-ai-anomalydetector/tsp-location.yaml @@ -0,0 +1,4 @@ +cleanup: false +commit: 324a5095c5b33493b59da70803a2e2e7f35034a9 +directory: specification/cognitiveservices/AnomalyDetector +repo: Azure/azure-rest-api-specs