-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
textAnalyticsClient.ts
1124 lines (1056 loc) · 43.8 KB
/
textAnalyticsClient.ts
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import type { CommonClientOptions } from "@azure/core-client";
import type { InternalPipelineOptions } from "@azure/core-rest-pipeline";
import { bearerTokenAuthenticationPolicy } from "@azure/core-rest-pipeline";
import type { KeyCredential, TokenCredential } from "@azure/core-auth";
import { isTokenCredential } from "@azure/core-auth";
import { SDK_VERSION } from "./constants.js";
import { GeneratedClient } from "./generated/generatedClient.js";
import { logger } from "./logger.js";
import type {
DetectLanguageInput,
JobManifestTasks as GeneratedActions,
SentimentOptionalParams as GeneratedAnalyzeSentimentOptions,
LanguagesOptionalParams as GeneratedDetectLanguageOptions,
KeyPhrasesOptionalParams as GeneratedExtractKeyPhrasesOptions,
EntitiesRecognitionGeneralOptionalParams as GeneratedRecognizeCategorizedEntitiesOptions,
EntitiesLinkingOptionalParams as GeneratedRecognizeLinkedEntitiesOptions,
EntitiesRecognitionPiiOptionalParams as GeneratedRecognizePiiEntitiesOptions,
PiiCategory,
TextDocumentInput,
} from "./generated/models/index.js";
import type { DetectLanguageResultArray } from "./detectLanguageResultArray.js";
import { makeDetectLanguageResultArray } from "./detectLanguageResultArray.js";
import type { RecognizeCategorizedEntitiesResultArray } from "./recognizeCategorizedEntitiesResultArray.js";
import { makeRecognizeCategorizedEntitiesResultArray } from "./recognizeCategorizedEntitiesResultArray.js";
import type { AnalyzeSentimentResultArray } from "./analyzeSentimentResultArray.js";
import { makeAnalyzeSentimentResultArray } from "./analyzeSentimentResultArray.js";
import type { ExtractKeyPhrasesResultArray } from "./extractKeyPhrasesResultArray.js";
import { makeExtractKeyPhrasesResultArray } from "./extractKeyPhrasesResultArray.js";
import type { RecognizePiiEntitiesResultArray } from "./recognizePiiEntitiesResultArray.js";
import { makeRecognizePiiEntitiesResultArray } from "./recognizePiiEntitiesResultArray.js";
import type { RecognizeLinkedEntitiesResultArray } from "./recognizeLinkedEntitiesResultArray.js";
import { makeRecognizeLinkedEntitiesResultArray } from "./recognizeLinkedEntitiesResultArray.js";
import type { TracingClient } from "@azure/core-tracing";
import { createTracingClient } from "@azure/core-tracing";
import { textAnalyticsAzureKeyCredentialPolicy } from "./azureKeyCredentialPolicy.js";
import {
StringIndexType,
addParamsToTask,
compose,
setCategoriesFilter,
setOpinionMining,
setStrEncodingParam,
setStrEncodingParamValue,
throwError,
} from "./util.js";
import {
AnalyzeHealthcareEntitiesPollerLike,
BeginAnalyzeHealthcarePoller,
PollerLikeWithCancellation,
} from "./lro/health/poller.js";
import {
AnalyzeHealthcareOperationState,
BeginAnalyzeHealthcareEntitiesOptions,
} from "./lro/health/operation.js";
import type { TextAnalyticsOperationOptions } from "./textAnalyticsOperationOptions.js";
import { AnalyzeActionsPollerLike, BeginAnalyzeActionsPoller } from "./lro/analyze/poller.js";
import {
AnalyzeActionsOperationMetadata,
AnalyzeActionsOperationState,
BeginAnalyzeActionsOptions,
} from "./lro/analyze/operation.js";
import { AnalysisPollOperationState, OperationMetadata } from "./lro/poller.js";
import type { TextAnalyticsAction } from "./textAnalyticsAction.js";
export {
BeginAnalyzeActionsOptions,
AnalyzeActionsPollerLike,
AnalyzeActionsOperationState,
BeginAnalyzeHealthcareEntitiesOptions,
PollerLikeWithCancellation,
AnalyzeHealthcareEntitiesPollerLike,
AnalyzeHealthcareOperationState,
AnalysisPollOperationState,
OperationMetadata,
AnalyzeActionsOperationMetadata,
StringIndexType,
};
const DEFAULT_COGNITIVE_SCOPE = "https://cognitiveservices.azure.com/.default";
/**
* Client options used to configure TextAnalytics API requests.
*/
export interface TextAnalyticsClientOptions extends CommonClientOptions {
/**
* The default country hint to use. Defaults to "us".
*/
defaultCountryHint?: string;
/**
* The default language to use. Defaults to "en".
*/
defaultLanguage?: string;
}
/**
* Options for the detect languages operation.
*/
export interface DetectLanguageOptions extends TextAnalyticsOperationOptions {}
/**
* Options for the recognize entities operation.
*/
export interface RecognizeCategorizedEntitiesOptions extends TextAnalyticsOperationOptions {
/**
* Specifies the measurement unit used to calculate the offset and length properties.
* Possible units are "TextElements_v8", "UnicodeCodePoint", and "Utf16CodeUnit".
* The default is the JavaScript's default which is "Utf16CodeUnit".
*/
stringIndexType?: StringIndexType;
}
/**
* Options for the analyze sentiment operation.
*/
export interface AnalyzeSentimentOptions extends TextAnalyticsOperationOptions {
/**
* Whether to mine the opinions of a sentence and conduct more granular
* analysis around the aspects of a product or service (also known as
* aspect-based sentiment analysis). If set to true, the returned
* `SentenceSentiment` objects will have property `opinions` containing
* the result of this analysis.
* More information about the feature can be found here: {@link https://docs.microsoft.com/azure/cognitive-services/text-analytics/how-tos/text-analytics-how-to-sentiment-analysis?tabs=version-3-1#opinion-mining}
*/
includeOpinionMining?: boolean;
/**
* Specifies the measurement unit used to calculate the offset and length properties.
* Possible units are "TextElements_v8", "UnicodeCodePoint", and "Utf16CodeUnit".
* The default is the JavaScript's default which is "Utf16CodeUnit".
*/
stringIndexType?: StringIndexType;
}
/**
* The types of PII domains the user can choose from.
*/
export enum PiiEntityDomain {
/**
* @see {@link https://aka.ms/tanerpii} for more information.
*/
PROTECTED_HEALTH_INFORMATION = "PHI",
}
/**
* Options for the recognize PII entities operation.
*/
export interface RecognizePiiEntitiesOptions extends TextAnalyticsOperationOptions {
/**
* Filters entities to ones only included in the specified domain (e.g., if
* set to 'PHI', entities in the Protected Healthcare Information domain will
* only be returned). @see {@link https://aka.ms/tanerpii} for more information.
*/
domainFilter?: PiiEntityDomain;
/**
* Specifies the measurement unit used to calculate the offset and length properties.
* Possible units are "TextElements_v8", "UnicodeCodePoint", and "Utf16CodeUnit".
* The default is the JavaScript's default which is "Utf16CodeUnit".
*/
stringIndexType?: StringIndexType;
/**
* Filters entities to ones only included in the specified array of categories
*/
categoriesFilter?: PiiCategory[];
}
/**
* Options for the extract key phrases operation.
*/
export interface ExtractKeyPhrasesOptions extends TextAnalyticsOperationOptions {}
/**
* Options for the recognize linked entities operation.
*/
export interface RecognizeLinkedEntitiesOptions extends TextAnalyticsOperationOptions {
/**
* Specifies the measurement unit used to calculate the offset and length properties.
* Possible units are "TextElements_v8", "UnicodeCodePoint", and "Utf16CodeUnit".
* The default is the JavaScript's default which is "Utf16CodeUnit".
*/
stringIndexType?: StringIndexType;
}
/**
* Options for an entities recognition action.
*/
export interface RecognizeCategorizedEntitiesAction extends TextAnalyticsAction {
/**
* Specifies the measurement unit used to calculate the offset and length properties.
* Possible units are "TextElements_v8", "UnicodeCodePoint", and "Utf16CodeUnit".
* The default is the JavaScript's default which is "Utf16CodeUnit".
*/
stringIndexType?: StringIndexType;
/**
* If set to true, you opt-out of having your text input logged for troubleshooting. By default, Text Analytics
* logs your input text for 48 hours, solely to allow for troubleshooting issues. Setting this parameter to true,
* disables input logging and may limit our ability to remediate issues that occur.
*/
disableServiceLogs?: boolean;
}
/**
* Options for a Pii entities recognition action.
*/
export interface RecognizePiiEntitiesAction extends TextAnalyticsAction {
/**
* Filters entities to ones only included in the specified domain (e.g., if
* set to 'PHI', entities in the Protected Healthcare Information domain will
* only be returned). @see {@link https://aka.ms/tanerpii} for more information.
*/
domainFilter?: PiiEntityDomain;
/**
* Filters entities to ones only included in the specified array of categories
*/
categoriesFilter?: PiiCategory[];
/**
* Specifies the measurement unit used to calculate the offset and length properties.
* Possible units are "TextElements_v8", "UnicodeCodePoint", and "Utf16CodeUnit".
* The default is the JavaScript's default which is "Utf16CodeUnit".
*/
stringIndexType?: StringIndexType;
/**
* If set to false, you opt-in to have your text input logged for troubleshooting. By default, Text Analytics
* will not log your input text for pii entities recognition. Setting this parameter to false,
* enables input logging.
*/
disableServiceLogs?: boolean;
}
/**
* Options for a key phrases recognition action.
*/
export interface ExtractKeyPhrasesAction extends TextAnalyticsAction {
/**
* If set to false, you opt-in to have your text input logged for troubleshooting. By default, Text Analytics
* will not log your input text for pii entities recognition. Setting this parameter to false,
* enables input logging.
*/
disableServiceLogs?: boolean;
}
/**
* Options for an entities linking action.
*/
export interface RecognizeLinkedEntitiesAction extends TextAnalyticsAction {
/**
* Specifies the measurement unit used to calculate the offset and length properties.
* Possible units are "TextElements_v8", "UnicodeCodePoint", and "Utf16CodeUnit".
* The default is the JavaScript's default which is "Utf16CodeUnit".
*/
stringIndexType?: StringIndexType;
/**
* If set to true, you opt-out of having your text input logged for troubleshooting. By default, Text Analytics
* logs your input text for 48 hours, solely to allow for troubleshooting issues. Setting this parameter to true,
* disables input logging and may limit our ability to remediate issues that occur.
*/
disableServiceLogs?: boolean;
}
/**
* Options for an analyze sentiment action.
*/
export interface AnalyzeSentimentAction extends TextAnalyticsAction {
/**
* Specifies the measurement unit used to calculate the offset and length properties.
* Possible units are "TextElements_v8", "UnicodeCodePoint", and "Utf16CodeUnit".
* The default is the JavaScript's default which is "Utf16CodeUnit".
*/
stringIndexType?: StringIndexType;
/**
* If set to true, you opt-out of having your text input logged for troubleshooting. By default, Text Analytics
* logs your input text for 48 hours, solely to allow for troubleshooting issues. Setting this parameter to true,
* disables input logging and may limit our ability to remediate issues that occur.
*/
disableServiceLogs?: boolean;
/**
* Whether to mine the opinions of a sentence and conduct more granular
* analysis around the aspects of a product or service (also known as
* aspect-based sentiment analysis). If set to true, the returned
* `SentenceSentiment` objects will have property `opinions` containing
* the result of this analysis.
* More information about the feature can be found here: {@link https://docs.microsoft.com/azure/cognitive-services/text-analytics/how-tos/text-analytics-how-to-sentiment-analysis?tabs=version-3-1#opinion-mining}
*/
includeOpinionMining?: boolean;
}
/**
* Description of collection of actions for the analyze API to perform on input documents. However, currently, the service can accept up to one action only per action type.
*/
export interface TextAnalyticsActions {
/**
* A collection of descriptions of entities recognition actions. However, currently, the service can accept up to one action only for `recognizeEntities`.
*/
recognizeEntitiesActions?: RecognizeCategorizedEntitiesAction[];
/**
* A collection of descriptions of Pii entities recognition actions. However, currently, the service can accept up to one action only for `recognizePiiEntities`.
*/
recognizePiiEntitiesActions?: RecognizePiiEntitiesAction[];
/**
* A collection of descriptions of key phrases recognition actions. However, currently, the service can accept up to one action only for `extractKeyPhrases`.
*/
extractKeyPhrasesActions?: ExtractKeyPhrasesAction[];
/**
* A collection of descriptions of entities linking actions. However, currently, the service can accept up to one action only for `recognizeLinkedEntities`.
*/
recognizeLinkedEntitiesActions?: RecognizeLinkedEntitiesAction[];
/**
* A collection of descriptions of sentiment analysis actions. However, currently, the service can accept up to one action only for `analyzeSentiment`.
*/
analyzeSentimentActions?: AnalyzeSentimentAction[];
}
/**
* Client class for interacting with Azure Text Analytics.
*/
export class TextAnalyticsClient {
/**
* The URL to the TextAnalytics endpoint
*/
public readonly endpointUrl: string;
/**
* The default country hint to use. Defaults to "us".
*/
public defaultCountryHint: string;
/**
* The default language to use. Defaults to "en".
*/
public defaultLanguage: string;
/**
* @internal
* A reference to the auto-generated TextAnalytics HTTP client.
*/
private readonly client: GeneratedClient;
private readonly _tracing: TracingClient;
/**
* Creates an instance of TextAnalyticsClient.
*
* Example usage:
* ```ts
* import { TextAnalyticsClient, AzureKeyCredential } from "@azure/ai-text-analytics";
*
* const client = new TextAnalyticsClient(
* "<service endpoint>",
* new AzureKeyCredential("<api key>")
* );
* ```
* @param endpointUrl - The URL to the TextAnalytics endpoint
* @param credential - Used to authenticate requests to the service.
* @param options - Used to configure the TextAnalytics client.
*/
constructor(
endpointUrl: string,
credential: TokenCredential | KeyCredential,
options: TextAnalyticsClientOptions = {},
) {
this.endpointUrl = endpointUrl;
const { defaultCountryHint = "us", defaultLanguage = "en", ...pipelineOptions } = options;
this.defaultCountryHint = defaultCountryHint;
this.defaultLanguage = defaultLanguage;
const libInfo = `azsdk-js-ai-textanalytics/${SDK_VERSION}`;
if (!pipelineOptions.userAgentOptions) {
pipelineOptions.userAgentOptions = {};
}
if (pipelineOptions.userAgentOptions.userAgentPrefix) {
pipelineOptions.userAgentOptions.userAgentPrefix = `${pipelineOptions.userAgentOptions.userAgentPrefix} ${libInfo}`;
} else {
pipelineOptions.userAgentOptions.userAgentPrefix = libInfo;
}
const internalPipelineOptions: InternalPipelineOptions = {
...pipelineOptions,
...{
loggingOptions: {
logger: logger.info,
additionalAllowedHeaderNames: ["x-ms-correlation-request-id", "x-ms-request-id"],
},
},
};
this.client = new GeneratedClient(this.endpointUrl, internalPipelineOptions);
const authPolicy = isTokenCredential(credential)
? bearerTokenAuthenticationPolicy({ credential, scopes: DEFAULT_COGNITIVE_SCOPE })
: textAnalyticsAzureKeyCredentialPolicy(credential);
this.client.pipeline.addPolicy(authPolicy);
this._tracing = createTracingClient({
packageName: "@azure/ai-text-analytics",
packageVersion: SDK_VERSION,
namespace: "Microsoft.CognitiveServices",
});
}
/**
* Runs a predictive model to determine the language that the passed-in
* input strings are written in, and returns, for each one, the detected
* language as well as a score indicating the model's confidence that the
* inferred language is correct. Scores close to 1 indicate high certainty in
* the result. 120 languages are supported.
* @param documents - A collection of input strings to analyze.
* @param countryHint - Indicates the country of origin for all of
* the input strings to assist the text analytics model in predicting
* the language they are written in. If unspecified, this value will be
* set to the default country hint in `TextAnalyticsClientOptions`.
* If set to an empty string, or the string "none", the service will apply a
* model where the country is explicitly unset.
* The same country hint is applied to all strings in the input collection.
* @param options - Optional parameters for the operation.
*/
public async detectLanguage(
documents: string[],
countryHint?: string,
options?: DetectLanguageOptions,
): Promise<DetectLanguageResultArray>;
/**
* Runs a predictive model to determine the language that the passed-in
* input document are written in, and returns, for each one, the detected
* language as well as a score indicating the model's confidence that the
* inferred language is correct. Scores close to 1 indicate high certainty in
* the result. 120 languages are supported.
* @param documents - A collection of input documents to analyze.
* @param options - Optional parameters for the operation.
*/
public async detectLanguage(
documents: DetectLanguageInput[],
options?: DetectLanguageOptions,
): Promise<DetectLanguageResultArray>;
public async detectLanguage(
documents: string[] | DetectLanguageInput[],
countryHintOrOptions?: string | DetectLanguageOptions,
options?: DetectLanguageOptions,
): Promise<DetectLanguageResultArray> {
let realOptions: DetectLanguageOptions;
let realInputs: DetectLanguageInput[];
if (!Array.isArray(documents) || documents.length === 0) {
throw new Error("'documents' must be a non-empty array");
}
if (isStringArray(documents)) {
const countryHint = (countryHintOrOptions as string) || this.defaultCountryHint;
realInputs = convertToDetectLanguageInput(documents, countryHint);
realOptions = options || {};
} else {
// Replace "none" hints with ""
realInputs = documents.map((input) => ({
...input,
countryHint: input.countryHint === "none" ? "" : input.countryHint,
}));
realOptions = (countryHintOrOptions as DetectLanguageOptions) || {};
}
return this._tracing.withSpan(
"TextAnalyticsClient-detectLanguages",
makeGeneratedDetectLanguageOptions(realOptions),
(finalOptions) =>
this.client
.languages(
{
documents: realInputs,
},
finalOptions,
)
.then((result) => makeDetectLanguageResultArray(realInputs, result)),
);
}
/**
* Runs a predictive model to identify a collection of named entities
* in the passed-in input strings, and categorize those entities into types
* such as person, location, or organization. For more information on
* available categories, @see
* {@link https://docs.microsoft.com/azure/cognitive-services/Text-Analytics/named-entity-types}.
* For a list of languages supported by this operation, @see
* {@link https://docs.microsoft.com/azure/cognitive-services/text-analytics/language-support}.
* @param documents - The input strings to analyze.
* @param language - The language that all the input strings are
written in. If unspecified, this value will be set to the default
language in `TextAnalyticsClientOptions`.
If set to an empty string, the service will apply a model
where the language is explicitly set to "None".
* @param options - Optional parameters for the operation.
*/
public async recognizeEntities(
documents: string[],
language?: string,
// eslint-disable-next-line @azure/azure-sdk/ts-naming-options
options?: RecognizeCategorizedEntitiesOptions,
): Promise<RecognizeCategorizedEntitiesResultArray>;
/**
* Runs a predictive model to identify a collection of named entities
* in the passed-in input documents, and categorize those entities into types
* such as person, location, or organization. For more information on
* available categories, @see
* {@link https://docs.microsoft.com/azure/cognitive-services/Text-Analytics/named-entity-types}.
* For a list of languages supported by this operation, @see
* {@link https://docs.microsoft.com/azure/cognitive-services/text-analytics/language-support}.
* @param documents - The input documents to analyze.
* @param options - Optional parameters for the operation.
*/
public async recognizeEntities(
documents: TextDocumentInput[],
// eslint-disable-next-line @azure/azure-sdk/ts-naming-options
options?: RecognizeCategorizedEntitiesOptions,
): Promise<RecognizeCategorizedEntitiesResultArray>;
public async recognizeEntities(
documents: string[] | TextDocumentInput[],
languageOrOptions?: string | RecognizeCategorizedEntitiesOptions,
// eslint-disable-next-line @azure/azure-sdk/ts-naming-options
options?: RecognizeCategorizedEntitiesOptions,
): Promise<RecognizeCategorizedEntitiesResultArray> {
let realOptions: RecognizeCategorizedEntitiesOptions;
let realInputs: TextDocumentInput[];
if (!Array.isArray(documents) || documents.length === 0) {
throw new Error("'documents' must be a non-empty array");
}
if (isStringArray(documents)) {
const language = (languageOrOptions as string) || this.defaultLanguage;
realInputs = convertToTextDocumentInput(documents, language);
realOptions = options || {};
} else {
realInputs = documents;
realOptions = (languageOrOptions as RecognizeCategorizedEntitiesOptions) || {};
}
return this._tracing.withSpan(
"TextAnalyticsClient-recognizeEntities",
makeGeneratedRecognizeCategorizedEntitiesOptions(realOptions),
(finalOptions) =>
throwError(
this.client.entitiesRecognitionGeneral(
{
documents: realInputs,
},
finalOptions,
),
).then((result) => makeRecognizeCategorizedEntitiesResultArray(realInputs, result)),
);
}
/**
* Runs a predictive model to identify the positive, negative, neutral, or mixed
* sentiment contained in the input strings, as well as scores indicating
* the model's confidence in each of the predicted sentiments. Optionally it
* can also identify targets in the text and assessments about it through
* opinion mining. For a list of languages supported by this operation, @see
* {@link https://docs.microsoft.com/azure/cognitive-services/text-analytics/language-support}.
* @param documents - The input strings to analyze.
* @param language - The language that all the input strings are
written in. If unspecified, this value will be set to the default
language in `TextAnalyticsClientOptions`.
If set to an empty string, the service will apply a model
where the lanuage is explicitly set to "None".
* @param options - Optional parameters that includes enabling opinion mining.
*/
public async analyzeSentiment(
documents: string[],
language?: string,
options?: AnalyzeSentimentOptions,
): Promise<AnalyzeSentimentResultArray>;
/**
* Runs a predictive model to identify the positive, negative or neutral, or mixed
* sentiment contained in the input documents, as well as scores indicating
* the model's confidence in each of the predicted sentiments.Optionally it
* can also identify targets in the text and assessments about it through
* opinion mining. For a list of languages supported by this operation, @see
* {@link https://docs.microsoft.com/azure/cognitive-services/text-analytics/language-support}.
* @param documents - The input documents to analyze.
* @param options - Optional parameters that includes enabling opinion mining.
*/
public async analyzeSentiment(
documents: TextDocumentInput[],
options?: AnalyzeSentimentOptions,
): Promise<AnalyzeSentimentResultArray>;
public async analyzeSentiment(
documents: string[] | TextDocumentInput[],
languageOrOptions?: string | AnalyzeSentimentOptions,
options?: AnalyzeSentimentOptions,
): Promise<AnalyzeSentimentResultArray> {
let realOptions: AnalyzeSentimentOptions;
let realInputs: TextDocumentInput[];
if (!Array.isArray(documents) || documents.length === 0) {
throw new Error("'documents' must be a non-empty array");
}
if (isStringArray(documents)) {
const language = (languageOrOptions as string) || this.defaultLanguage;
realInputs = convertToTextDocumentInput(documents, language);
realOptions = options || {};
} else {
realInputs = documents;
realOptions = (languageOrOptions as AnalyzeSentimentOptions) || {};
}
return this._tracing.withSpan(
"TextAnalyticsClient-analyzeSentiment",
makeGeneratedAnalyzeSentimentOptions(realOptions),
(finalOptions) =>
this.client
.sentiment(
{
documents: realInputs,
},
finalOptions,
)
.then((result) => makeAnalyzeSentimentResultArray(realInputs, result)),
);
}
/**
* Runs a model to identify a collection of significant phrases
* found in the passed-in input strings.
* For a list of languages supported by this operation, @see
* {@link https://docs.microsoft.com/azure/cognitive-services/text-analytics/language-support}.
* @param documents - The input strings to analyze.
* @param language - The language that all the input strings are
written in. If unspecified, this value will be set to the default
language in `TextAnalyticsClientOptions`.
If set to an empty string, the service will apply a model
where the language is explicitly set to "None".
* @param options - Options for the operation.
*/
public async extractKeyPhrases(
documents: string[],
language?: string,
options?: ExtractKeyPhrasesOptions,
): Promise<ExtractKeyPhrasesResultArray>;
/**
* Runs a model to identify a collection of significant phrases
* found in the passed-in input documents.
* For a list of languages supported by this operation, @see
* {@link https://docs.microsoft.com/azure/cognitive-services/text-analytics/language-support}.
* @param documents - The input documents to analyze.
* @param options - Options for the operation.
*/
public async extractKeyPhrases(
documents: TextDocumentInput[],
options?: ExtractKeyPhrasesOptions,
): Promise<ExtractKeyPhrasesResultArray>;
public async extractKeyPhrases(
documents: string[] | TextDocumentInput[],
languageOrOptions?: string | ExtractKeyPhrasesOptions,
options?: ExtractKeyPhrasesOptions,
): Promise<ExtractKeyPhrasesResultArray> {
let realOptions: ExtractKeyPhrasesOptions;
let realInputs: TextDocumentInput[];
if (!Array.isArray(documents) || documents.length === 0) {
throw new Error("'documents' must be a non-empty array");
}
if (isStringArray(documents)) {
const language = (languageOrOptions as string) || this.defaultLanguage;
realInputs = convertToTextDocumentInput(documents, language);
realOptions = options || {};
} else {
realInputs = documents;
realOptions = (languageOrOptions as ExtractKeyPhrasesOptions) || {};
}
return this._tracing.withSpan(
"TextAnalyticsClient-extractKeyPhrases",
makeGeneratedExtractKeyPhrasesOptions(realOptions),
(finalOptions) =>
this.client
.keyPhrases(
{
documents: realInputs,
},
finalOptions,
)
.then((result) => makeExtractKeyPhrasesResultArray(realInputs, result)),
);
}
/**
* Runs a predictive model to identify a collection of entities containing
* personally identifiable information found in the passed-in input strings,
* and categorize those entities into types such as US social security
* number, drivers license number, or credit card number.
* For a list of languages supported by this operation, @see
* {@link https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/language-support}.
* @param inputs - The input strings to analyze.
* @param language - The language that all the input strings are
written in. If unspecified, this value will be set to the default
language in `TextAnalyticsClientOptions`.
If set to an empty string, the service will apply a model
where the language is explicitly set to "None".
* @param options - Options for the operation.
*/
public async recognizePiiEntities(
inputs: string[],
language?: string,
options?: RecognizePiiEntitiesOptions,
): Promise<RecognizePiiEntitiesResultArray>;
/**
* Runs a predictive model to identify a collection of entities containing
* personally identifiable information found in the passed-in input documents,
* and categorize those entities into types such as US social security
* number, drivers license number, or credit card number.
* For a list of languages supported by this operation, @see
* {@link https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/language-support}.
* @param inputs - The input documents to analyze.
* @param options - Optional parameters for the operation.
*/
public async recognizePiiEntities(
inputs: TextDocumentInput[],
options?: RecognizePiiEntitiesOptions,
): Promise<RecognizePiiEntitiesResultArray>;
public async recognizePiiEntities(
inputs: string[] | TextDocumentInput[],
languageOrOptions?: string | RecognizePiiEntitiesOptions,
options?: RecognizePiiEntitiesOptions,
): Promise<RecognizePiiEntitiesResultArray> {
let realOptions: RecognizePiiEntitiesOptions;
let realInputs: TextDocumentInput[];
if (isStringArray(inputs)) {
const language = (languageOrOptions as string) || this.defaultLanguage;
realInputs = convertToTextDocumentInput(inputs, language);
realOptions = options || {};
} else {
realInputs = inputs;
realOptions = (languageOrOptions as RecognizePiiEntitiesOptions) || {};
}
return this._tracing.withSpan(
"TextAnalyticsClient-recognizePiiEntities",
makeGeneratedRecognizePiiEntitiesOptions(realOptions),
(finalOptions) =>
this.client
.entitiesRecognitionPii(
{
documents: realInputs,
},
finalOptions,
)
.then((result) => makeRecognizePiiEntitiesResultArray(realInputs, result)),
);
}
/**
* Runs a predictive model to identify a collection of entities
* found in the passed-in input strings, and include information linking the
* entities to their corresponding entries in a well-known knowledge base.
* For a list of languages supported by this operation, @see
* {@link https://docs.microsoft.com/azure/cognitive-services/text-analytics/language-support}.
* @param documents - The input strings to analyze.
* @param language - The language that all the input strings are
written in. If unspecified, this value will be set to the default
language in `TextAnalyticsClientOptions`.
If set to an empty string, the service will apply a model
where the language is explicitly set to "None".
* @param options - Options for the operation.
*/
public async recognizeLinkedEntities(
documents: string[],
language?: string,
options?: RecognizeLinkedEntitiesOptions,
): Promise<RecognizeLinkedEntitiesResultArray>;
/**
* Runs a predictive model to identify a collection of entities
* found in the passed-in input documents, and include information linking the
* entities to their corresponding entries in a well-known knowledge base.
* For a list of languages supported by this operation, @see
* {@link https://docs.microsoft.com/azure/cognitive-services/text-analytics/language-support}.
* @param documents - The input documents to analyze.
* @param options - Options for the operation.
*/
public async recognizeLinkedEntities(
documents: TextDocumentInput[],
options?: RecognizeLinkedEntitiesOptions,
): Promise<RecognizeLinkedEntitiesResultArray>;
public async recognizeLinkedEntities(
documents: string[] | TextDocumentInput[],
languageOrOptions?: string | RecognizeLinkedEntitiesOptions,
options?: RecognizeLinkedEntitiesOptions,
): Promise<RecognizeLinkedEntitiesResultArray> {
let realOptions: RecognizeLinkedEntitiesOptions;
let realInputs: TextDocumentInput[];
if (!Array.isArray(documents) || documents.length === 0) {
throw new Error("'documents' must be a non-empty array");
}
if (isStringArray(documents)) {
const language = (languageOrOptions as string) || this.defaultLanguage;
realInputs = convertToTextDocumentInput(documents, language);
realOptions = options || {};
} else {
realInputs = documents;
realOptions = (languageOrOptions as RecognizeLinkedEntitiesOptions) || {};
}
return this._tracing.withSpan(
"TextAnalyticsClient-recognizeLinkedEntities",
makeGeneratedRecognizeLinkingEntitiesOptions(realOptions),
(finalOptions) =>
this.client
.entitiesLinking(
{
documents: realInputs,
},
finalOptions,
)
.then((result) => makeRecognizeLinkedEntitiesResultArray(realInputs, result)),
);
}
/**
* Start a healthcare analysis operation to recognize healthcare related entities (drugs, conditions,
* symptoms, etc) and their relations.
* @param documents - Collection of documents to analyze.
* @param language - The language that all the input strings are
written in. If unspecified, this value will be set to the default
language in `TextAnalyticsClientOptions`.
If set to an empty string, the service will apply a model
where the language is explicitly set to "None".
* @param options - Options for the operation.
*/
async beginAnalyzeHealthcareEntities(
documents: string[],
language?: string,
options?: BeginAnalyzeHealthcareEntitiesOptions,
): Promise<AnalyzeHealthcareEntitiesPollerLike>;
/**
* Start a healthcare analysis operation to recognize healthcare related entities (drugs, conditions,
* symptoms, etc) and their relations.
* @param documents - Collection of documents to analyze.
* @param options - Options for the operation.
*/
async beginAnalyzeHealthcareEntities(
documents: TextDocumentInput[],
options?: BeginAnalyzeHealthcareEntitiesOptions,
): Promise<AnalyzeHealthcareEntitiesPollerLike>;
async beginAnalyzeHealthcareEntities(
documents: string[] | TextDocumentInput[],
languageOrOptions?: string | BeginAnalyzeHealthcareEntitiesOptions,
options?: BeginAnalyzeHealthcareEntitiesOptions,
): Promise<AnalyzeHealthcareEntitiesPollerLike> {
let realOptions: BeginAnalyzeHealthcareEntitiesOptions;
let realInputs: TextDocumentInput[];
if (isStringArray(documents)) {
const language = (languageOrOptions as string) || this.defaultLanguage;
realInputs = convertToTextDocumentInput(documents, language);
realOptions = options || {};
} else {
realInputs = documents;
realOptions = (languageOrOptions as BeginAnalyzeHealthcareEntitiesOptions) || {};
}
const { updateIntervalInMs, resumeFrom, ...restOptions } = realOptions;
const poller = new BeginAnalyzeHealthcarePoller({
client: this.client,
tracing: this._tracing,
documents: realInputs,
options: restOptions,
updateIntervalInMs: updateIntervalInMs,
resumeFrom: resumeFrom,
});
await poller.poll();
return poller;
}
/**
* Submit a collection of text documents for analysis. Specify one or more unique actions to be executed.
* @param documents - Collection of documents to analyze
* @param actions - TextAnalyticsActions to execute.
* @param language - The language that all the input strings are
written in. If unspecified, this value will be set to the default
language in `TextAnalyticsClientOptions`.
If set to an empty string, the service will apply a model
where the language is explicitly set to "None".
* @param options - Options for the operation.
*/
public async beginAnalyzeActions(
documents: string[],
actions: TextAnalyticsActions,
language?: string,
options?: BeginAnalyzeActionsOptions,
): Promise<AnalyzeActionsPollerLike>;
/**
* Submit a collection of text documents for analysis. Specify one or more unique actions to be executed.
* @param documents - Collection of documents to analyze
* @param actions - TextAnalyticsActions to execute.
* @param options - Options for the operation.
*/
public async beginAnalyzeActions(
documents: TextDocumentInput[],
actions: TextAnalyticsActions,
options?: BeginAnalyzeActionsOptions,
): Promise<AnalyzeActionsPollerLike>;
public async beginAnalyzeActions(
documents: string[] | TextDocumentInput[],
actions: TextAnalyticsActions,
languageOrOptions?: string | BeginAnalyzeActionsOptions,
options?: BeginAnalyzeActionsOptions,
): Promise<AnalyzeActionsPollerLike> {
let realOptions: BeginAnalyzeActionsOptions;
let realInputs: TextDocumentInput[];
if (!Array.isArray(documents) || documents.length === 0) {
throw new Error("'documents' must be a non-empty array");
}
if (isStringArray(documents)) {
const language = (languageOrOptions as string) || this.defaultLanguage;
realInputs = convertToTextDocumentInput(documents, language);
realOptions = options || {};
} else {
realInputs = documents;
realOptions = (languageOrOptions as BeginAnalyzeActionsOptions) || {};
}
const compiledActions = compileAnalyzeInput(actions);
const { updateIntervalInMs, resumeFrom, ...restOptions } = realOptions;
const poller = new BeginAnalyzeActionsPoller({
client: this.client,
tracing: this._tracing,
documents: realInputs,
actions: compiledActions,
options: restOptions,
resumeFrom: resumeFrom,
updateIntervalInMs: updateIntervalInMs,
});
await poller.poll();
return poller;
}
}
/**
* @internal
*/
function compileAnalyzeInput(actions: TextAnalyticsActions): GeneratedActions {
return {
entityRecognitionPiiTasks: actions.recognizePiiEntitiesActions?.map(
compose(setStrEncodingParam, compose(setCategoriesFilter, addParamsToTask)),
),
entityRecognitionTasks: actions.recognizeEntitiesActions?.map(
compose(setStrEncodingParam, addParamsToTask),
),
keyPhraseExtractionTasks: actions.extractKeyPhrasesActions?.map(addParamsToTask),
entityLinkingTasks: actions.recognizeLinkedEntitiesActions?.map(
compose(setStrEncodingParam, addParamsToTask),
),
sentimentAnalysisTasks: actions.analyzeSentimentActions?.map(
compose(setStrEncodingParam, compose(setOpinionMining, addParamsToTask)),
),
};
}
function isStringArray(documents: any[]): documents is string[] {
return typeof documents[0] === "string";
}
/**
* @internal
*/
function convertToDetectLanguageInput(
inputs: string[],
countryHint: string,
): DetectLanguageInput[] {
if (countryHint === "none") {
countryHint = "";
}
return inputs.map((text: string, index): DetectLanguageInput => {
return {
id: String(index),
countryHint,
text,
};
});
}
/**
* @internal
*/
function convertToTextDocumentInput(inputs: string[], language: string): TextDocumentInput[] {
return inputs.map((text: string, index): TextDocumentInput => {
return {
id: String(index),
language,
text,
};
});
}
/**
* Creates the options the service expects for the analyze sentiment API from the user friendly ones.