-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
sample_recognize_custom_entities.py
78 lines (64 loc) · 2.92 KB
/
sample_recognize_custom_entities.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""
FILE: sample_recognize_custom_entities.py
DESCRIPTION:
This sample demonstrates how to recognize custom entities in documents.
Recognizing custom entities is also available as an action type through the begin_analyze_actions API.
For information on regional support of custom features and how to train a model to
recognize custom entities, see https://aka.ms/azsdk/textanalytics/customentityrecognition
USAGE:
python sample_recognize_custom_entities.py
Set the environment variables with your own values before running the sample:
1) AZURE_LANGUAGE_ENDPOINT - the endpoint to your Language resource.
2) AZURE_LANGUAGE_KEY - your Language subscription key
3) CUSTOM_ENTITIES_PROJECT_NAME - your Language Studio project name
4) CUSTOM_ENTITIES_DEPLOYMENT_NAME - your Language Studio deployment name
"""
def sample_recognize_custom_entities() -> None:
# [START recognize_custom_entities]
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient
endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
key = os.environ["AZURE_LANGUAGE_KEY"]
project_name = os.environ["CUSTOM_ENTITIES_PROJECT_NAME"]
deployment_name = os.environ["CUSTOM_ENTITIES_DEPLOYMENT_NAME"]
path_to_sample_document = os.path.abspath(
os.path.join(
os.path.abspath(__file__),
"..",
"./text_samples/custom_entities_sample.txt",
)
)
text_analytics_client = TextAnalyticsClient(
endpoint=endpoint,
credential=AzureKeyCredential(key),
)
with open(path_to_sample_document) as fd:
document = [fd.read()]
poller = text_analytics_client.begin_recognize_custom_entities(
document,
project_name=project_name,
deployment_name=deployment_name
)
document_results = poller.result()
for custom_entities_result in document_results:
if custom_entities_result.kind == "CustomEntityRecognition":
for entity in custom_entities_result.entities:
print(
"Entity '{}' has category '{}' with confidence score of '{}'".format(
entity.text, entity.category, entity.confidence_score
)
)
elif custom_entities_result.is_error is True:
print("...Is an error with code '{}' and message '{}'".format(
custom_entities_result.error.code, custom_entities_result.error.message
)
)
# [END recognize_custom_entities]
if __name__ == "__main__":
sample_recognize_custom_entities()