Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

[textanalytics] adds dynamic classification #26404

Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions sdk/textanalytics/azure-ai-textanalytics/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
`TemporalSpanResolution`, `VolumeResolution`, `WeightResolution`, `AgeUnit`, `AreaUnit`, `TemporalModifier`,
`InformationUnit`, `LengthUnit`, `NumberKind`, `RangeKind`, `RelativeTo`, `SpeedUnit`, `TemperatureUnit`,
`VolumeUnit`, and `WeightUnit`.
- Added the `dynamic_classification` client method to perform dynamic classification on documents without needing to train a model.

### Breaking Changes

Expand Down
5 changes: 5 additions & 0 deletions sdk/textanalytics/azure-ai-textanalytics/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ The Azure Cognitive Service for Language is a cloud-based service that provides
- Custom Named Entity Recognition
- Custom Text Classification
- Extractive Text Summarization
- Dynamic Classification

[Source code][source_code] | [Package (PyPI)][ta_pypi] | [API reference documentation][ta_ref_docs] | [Product documentation][language_product_documentation] | [Samples][ta_samples]

Expand Down Expand Up @@ -256,6 +257,7 @@ The following section provides several code snippets covering some of the most c
- [Custom Single Label Classification][single_label_classify_sample]
- [Custom Multi Label Classification][multi_label_classify_sample]
- [Extractive Summarization][extract_summary_sample]
- [Dynamic Classification][dynamic_classification_sample]

### Analyze sentiment

Expand Down Expand Up @@ -668,6 +670,7 @@ Common scenarios
- Custom Single Label Classification: [sample_single_label_classify.py][single_label_classify_sample] ([async_version][single_label_classify_sample_async])
- Custom Multi Label Classification: [sample_multi_label_classify.py][multi_label_classify_sample] ([async_version][multi_label_classify_sample_async])
- Extractive text summarization: [sample_extract_summary.py][extract_summary_sample] ([async version][extract_summary_sample_async])
- Dynamic Classification: [sample_dynamic_classification.py][dynamic_classification_sample] ([async_version][dynamic_classification_sample_async])

Advanced scenarios

Expand Down Expand Up @@ -772,6 +775,8 @@ This project has adopted the [Microsoft Open Source Code of Conduct][code_of_con
[healthcare_action_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_analyze_healthcare_action.py
[extract_summary_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_extract_summary.py
[extract_summary_sample_async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_extract_summary_async.py
[dynamic_classification_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_dynamic_classification.py
[dynamic_classification_sample_async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_dynamic_classification_async.py
[cla]: https://cla.microsoft.com
[code_of_conduct]: https://opensource.microsoft.com/codeofconduct/
[coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
ExtractSummaryAction,
ExtractSummaryResult,
SummarySentence,
DynamicClassificationResult,
)
from ._generated.models import (
HealthcareDocumentType,
Expand Down Expand Up @@ -92,6 +93,7 @@
TemperatureUnit,
VolumeUnit,
WeightUnit,
ClassificationType,
)
from ._lro import AnalyzeHealthcareEntitiesLROPoller, AnalyzeActionsLROPoller, TextAnalysisLROPoller

Expand Down Expand Up @@ -184,6 +186,8 @@
"TemperatureUnit",
"VolumeUnit",
"WeightUnit",
"ClassificationType",
"DynamicClassificationResult",
]

__version__ = VERSION
Original file line number Diff line number Diff line change
Expand Up @@ -1209,6 +1209,7 @@ def __getattr__(self, attr):
+ RecognizeCustomEntitiesResult().keys()
+ ClassifyDocumentResult().keys()
+ ExtractSummaryResult().keys()
+ DynamicClassificationResult().keys()
)
result_attrs = result_set.difference(DocumentError().keys())
if attr in result_attrs:
Expand Down Expand Up @@ -2464,7 +2465,7 @@ def _to_generated(self, api_version, task_id): # pylint: disable=unused-argumen
class ClassificationCategory(DictMixin):
"""ClassificationCategory represents a classification of the input document.

:ivar str category: Custom classification category for the document.
:ivar str category: Classification category for the document.
:ivar float confidence_score: Confidence score between 0 and 1 of the recognized classification.
"""

Expand Down Expand Up @@ -2759,3 +2760,65 @@ def _from_generated(cls, sentence):
offset=sentence.offset,
length=sentence.length,
)

class DynamicClassificationResult(DictMixin):
"""DynamicClassificationResult is a result object which contains
the classifications for a particular document.

:ivar str id: Unique, non-empty document identifier.
:ivar classifications: Recognized classification results in the document.
:vartype classifications: list[~azure.ai.textanalytics.ClassificationCategory]
:ivar warnings: Warnings encountered while processing document.
:vartype warnings: list[~azure.ai.textanalytics.TextAnalyticsWarning]
:ivar statistics: If `show_stats=True` was specified in the request this
field will contain information about the document payload.
:vartype statistics: Optional[~azure.ai.textanalytics.TextDocumentStatistics]
:ivar bool is_error: Boolean check for error item when iterating over list of
results. Always False for an instance of a DynamicClassificationResult.
:ivar str kind: The text analysis kind - "DynamicClassification".

.. versionadded:: 2022-10-01-preview
The *DynamicClassificationResult* model.
"""

def __init__(
self,
**kwargs
):
self.id = kwargs.get('id', None)
self.classifications = kwargs.get('classifications', None)
self.warnings = kwargs.get('warnings', [])
self.statistics = kwargs.get('statistics', None)
self.is_error: Literal[False] = False
self.kind: Literal["DynamicClassification"] = "DynamicClassification"

def __repr__(self):
return "DynamicClassificationResult(id={}, classifications={}, warnings={}, statistics={}, " \
"is_error={})".format(
self.id,
repr(self.classifications),
repr(self.warnings),
repr(self.statistics),
self.is_error,
)[
:1024
]

@classmethod
def _from_generated(cls, result):
return cls(
id=result.id,
classifications=[
ClassificationCategory._from_generated(e) # pylint: disable=protected-access
for e in result.class_property
],
warnings=[
TextAnalyticsWarning._from_generated( # pylint: disable=protected-access
w
)
for w in result.warnings
],
statistics=TextDocumentStatistics._from_generated( # pylint: disable=protected-access
result.statistics
),
)
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
ClassifyDocumentResult,
ActionPointerKind,
ExtractSummaryResult,
DynamicClassificationResult,
)


Expand Down Expand Up @@ -289,6 +290,15 @@ def classify_document_result(
)


@prepare_result
def dynamic_classification_result(
categories, results, *args, **kwargs
): # pylint: disable=unused-argument
return DynamicClassificationResult._from_generated( # pylint: disable=protected-access
categories
)


def healthcare_extract_page_data(
doc_id_order, obj, health_job_state
): # pylint: disable=unused-argument
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@
pii_entities_result,
healthcare_paged_result,
analyze_paged_result,
_get_result_from_continuation_token
_get_result_from_continuation_token,
dynamic_classification_result,
)

from ._lro import (
Expand Down Expand Up @@ -67,6 +68,7 @@
_AnalyzeActionsType,
ExtractSummaryAction,
ExtractSummaryResult,
DynamicClassificationResult,
)
from ._check import is_language_api, string_index_type_compatibility

Expand Down Expand Up @@ -1652,3 +1654,100 @@ def begin_multi_label_classify(

except HttpResponseError as error:
return process_http_response_error(error)

@distributed_trace
@validate_multiapi_args(
version_method_added="2022-10-01-preview",
)
def dynamic_classification(
self,
documents: Union[List[str], List[TextDocumentInput], List[Dict[str, str]]],
categories: List[str],
**kwargs: Any,
) -> List[Union[DynamicClassificationResult, DocumentError]]:
"""Perform dynamic classification on a batch of documents.

On the fly classification of the input documents into one or multiple categories.
Assigns either one or multiple categories per document. This type of classification
doesn't require model training.

See https://aka.ms/azsdk/textanalytics/data-limits for service data limits.

:param documents: The set of documents to process as part of this batch.
If you wish to specify the ID and language on a per-item basis you must
use as input a list[:class:`~azure.ai.textanalytics.TextDocumentInput`] or a list
of dict representations of :class:`~azure.ai.textanalytics.TextDocumentInput`,
like `{"id": "1", "language": "en", "text": "hello world"}`.
:type documents:
list[str] or list[~azure.ai.textanalytics.TextDocumentInput] or list[dict[str, str]]
:param list[str] categories: A list of categories to which input is classified to.
:keyword classification_type: Specifies either one or multiple categories per document. Defaults
to multi classification which may return more than one class for each document. Known values
are: "Single" and "Multi".
:paramtype classification_type: str or ~azure.ai.textanalytics.ClassificationType
:keyword str language: The 2 letter ISO 639-1 representation of language for the
entire batch. For example, use "en" for English; "es" for Spanish etc.
If not set, uses "en" for English as default. Per-document language will
take precedence over whole batch language. See https://aka.ms/talangs for
supported languages in Language API.
:keyword str model_version: This value indicates which model will
be used for scoring, e.g. "latest", "2019-10-01". If a model-version
is not specified, the API will default to the latest, non-preview version.
See here for more info: https://aka.ms/text-analytics-model-versioning
:keyword bool show_stats: If set to true, response will contain document
level statistics in the `statistics` field of the document-level response.
:keyword bool disable_service_logs: If set to true, you opt-out of having your text input
logged on the service side for troubleshooting. By default, the Language service logs your
input text for 48 hours, solely to allow for troubleshooting issues in providing you with
the service's natural language processing functions. Setting this parameter to true,
disables input logging and may limit our ability to remediate issues that occur. Please see
Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for
additional details, and Microsoft Responsible AI principles at
https://www.microsoft.com/ai/responsible-ai.
:return: The combined list of :class:`~azure.ai.textanalytics.DynamicClassificationResult` and
:class:`~azure.ai.textanalytics.DocumentError` in the order the original documents
were passed in.
:rtype: list[~azure.ai.textanalytics.DynamicClassificationResult or ~azure.ai.textanalytics.DocumentError]
:raises ~azure.core.exceptions.HttpResponseError:

.. versionadded:: 2022-10-01-preview
The *dynamic_classification* client method.

.. admonition:: Example:

.. literalinclude:: ../samples/sample_dynamic_classification.py
:start-after: [START dynamic_classification]
:end-before: [END dynamic_classification]
:language: python
:dedent: 4
:caption: Perform dynamic classification on a batch of documents.
"""
language_arg = kwargs.pop("language", None)
language = language_arg if language_arg is not None else self._default_language
docs = _validate_input(documents, "language", language)
model_version = kwargs.pop("model_version", None)
show_stats = kwargs.pop("show_stats", None)
disable_service_logs = kwargs.pop("disable_service_logs", None)
classification_type = kwargs.pop("classification_type", None)

try:
models = self._client.models(api_version=self._api_version)
return cast(
List[Union[DynamicClassificationResult, DocumentError]],
self._client.analyze_text(
body=models.AnalyzeTextDynamicClassificationInput(
analysis_input={"documents": docs},
parameters=models.DynamicClassificationTaskParameters(
categories=categories,
logging_opt_out=disable_service_logs,
model_version=model_version,
classification_type=classification_type,
)
),
show_stats=show_stats,
cls=kwargs.pop("cls", dynamic_classification_result),
**kwargs
)
)
except HttpResponseError as error:
return process_http_response_error(error)
Loading