-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
DocumentAnalysisAsyncClient.java
670 lines (645 loc) · 40.2 KB
/
DocumentAnalysisAsyncClient.java
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.ai.formrecognizer.documentanalysis;
import com.azure.ai.formrecognizer.documentanalysis.administration.models.OperationStatus;
import com.azure.ai.formrecognizer.documentanalysis.implementation.DocumentClassifiersImpl;
import com.azure.ai.formrecognizer.documentanalysis.implementation.DocumentModelsImpl;
import com.azure.ai.formrecognizer.documentanalysis.implementation.FormRecognizerClientImpl;
import com.azure.ai.formrecognizer.documentanalysis.implementation.models.AnalyzeDocumentRequest;
import com.azure.ai.formrecognizer.documentanalysis.implementation.models.AnalyzeResultOperation;
import com.azure.ai.formrecognizer.documentanalysis.implementation.models.ClassifyDocumentRequest;
import com.azure.ai.formrecognizer.documentanalysis.implementation.models.StringIndexType;
import com.azure.ai.formrecognizer.documentanalysis.implementation.util.Transforms;
import com.azure.ai.formrecognizer.documentanalysis.models.AnalyzeDocumentOptions;
import com.azure.ai.formrecognizer.documentanalysis.models.AnalyzeResult;
import com.azure.ai.formrecognizer.documentanalysis.models.OperationResult;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceClient;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.exception.HttpResponseException;
import com.azure.core.http.HttpPipeline;
import com.azure.core.http.rest.Response;
import com.azure.core.util.BinaryData;
import com.azure.core.util.Context;
import com.azure.core.util.CoreUtils;
import com.azure.core.util.logging.ClientLogger;
import com.azure.core.util.polling.LongRunningOperationStatus;
import com.azure.core.util.polling.PollResponse;
import com.azure.core.util.polling.PollerFlux;
import com.azure.core.util.polling.PollingContext;
import reactor.core.publisher.Mono;
import java.io.InputStream;
import java.util.Objects;
import java.util.function.Function;
import static com.azure.ai.formrecognizer.documentanalysis.implementation.util.Constants.DEFAULT_POLL_INTERVAL;
import static com.azure.ai.formrecognizer.documentanalysis.implementation.util.Utility.activationOperation;
import static com.azure.ai.formrecognizer.documentanalysis.implementation.util.Utility.getAnalyzeDocumentOptions;
import static com.azure.core.util.FluxUtil.monoError;
/**
* <p>This class provides an asynchronous client to connect to the Form Recognizer Azure Cognitive Service.</p>
* <p>This client provides asynchronous methods to perform:</p>
*
* <ol>
* <li>Custom Document Analysis: Classification, extraction and analysis of data from forms and documents specific
* to distinct business data and use cases. Use the custom trained model by passing its modelId into the
* {@link com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisAsyncClient#beginAnalyzeDocument(String, BinaryData)}
* method.</li>
* <li>General Document Analysis: Extract text, tables, structure, and key-value pairs. Use general document model
* provided by the Form Recognizer service by passing modelId="rebuilt-document" into the
* {@link com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisAsyncClient#beginAnalyzeDocument(String, BinaryData)}
* method.</li>
* <li>Prebuilt Model Analysis: Analyze receipts, business cards, invoices, ID's, W2's and other documents with
* <a href="https://aka.ms/azsdk/formrecognizer/models">supported prebuilt models. Use the prebuilt receipt model
* provided by passing modelId="prebuilt-receipt" into the
* {@link com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisAsyncClient#beginAnalyzeDocument(String, BinaryData)}
* method.</a></li>
* <li>Layout Analysis: Extract text, selection marks, and tables structures, along with their bounding box
* coordinates, from forms and documents. Use the layout analysis model provided the service by passing
* modelId="prebuilt-layout" into the
* {@link com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisAsyncClient#beginAnalyzeDocument(String, BinaryData)}
* method.</li>
* <li>Polling and Callbacks: It includes mechanisms for polling the service to check the status of an analysis
* operation or registering callbacks to receive notifications when the analysis is complete.</li>
* </ol>
*
* <p>This client also provides different methods based on inputs from a URL and inputs from a stream.</p>
*
* <p><strong>Note: </strong>This client only supports
* {@link com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisServiceVersion#V2022_08_31} and newer.
* To use an older service version, {@link com.azure.ai.formrecognizer.FormRecognizerClient} and {@link com.azure.ai
* .formrecognizer.training.FormTrainingClient}.</p>
*
* <p>Service clients are the point of interaction for developers to use Azure Form Recognizer.
* {@link com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisClient} is the synchronous service client and
* {@link com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisAsyncClient} is the asynchronous service client.
* The examples shown in this document use a credential object named DefaultAzureCredential for authentication, which is
* appropriate for most scenarios, including local development and production environments. Additionally, we
* recommend using
* <a href="https://learn.microsoft.com/azure/active-directory/managed-identities-azure-resources/">managed identity</a>
* for authentication in production environments.
* You can find more information on different ways of authenticating and their corresponding credential types in the
* <a href="https://learn.microsoft.com/java/api/overview/azure/identity-readme">Azure Identity documentation"</a>.
* </p>
*
* <p><strong>Sample: Construct a DocumentAnalysisAsyncClient with DefaultAzureCredential</strong></p>
*
* <p>The following code sample demonstrates the creation of a
* {@link com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisAsyncClient}, using
* the `DefaultAzureCredentialBuilder` to configure it.</p>
*
* <!-- src_embed readme-sample-createDocumentAnalysisAsyncClientWithAAD -->
* <pre>
* DocumentAnalysisAsyncClient documentAnalysisAsyncClient = new DocumentAnalysisClientBuilder()
* .endpoint("{endpoint}")
* .credential(new DefaultAzureCredentialBuilder().build())
* .buildAsyncClient();
* </pre>
* <!-- end readme-sample-createDocumentAnalysisAsyncClientWithAAD -->
*
* <p>Further, see the code sample below to use
* {@link com.azure.core.credential.AzureKeyCredential AzureKeyCredential} for client creation.</p>
*
* <!-- src_embed readme-sample-asyncClient -->
* <pre>
* DocumentAnalysisAsyncClient documentAnalysisAsyncClient = new DocumentAnalysisClientBuilder()
* .credential(new AzureKeyCredential("{key}"))
* .endpoint("{endpoint}")
* .buildAsyncClient();
* </pre>
* <!-- end readme-sample-asyncClient -->
*
* @see com.azure.ai.formrecognizer.documentanalysis
* @see DocumentAnalysisClientBuilder
* @see DocumentAnalysisClient
*/
@ServiceClient(builder = DocumentAnalysisClientBuilder.class, isAsync = true)
public final class DocumentAnalysisAsyncClient {
private final ClientLogger logger = new ClientLogger(DocumentAnalysisAsyncClient.class);
private final DocumentModelsImpl documentModelsImpl;
private final DocumentClassifiersImpl documentClassifiersImpl;
private final DocumentAnalysisServiceVersion serviceVersion;
/**
* Create a {@link DocumentAnalysisAsyncClient} that sends requests to the Form recognizer service's endpoint. Each
* service call goes through the {@link DocumentAnalysisClientBuilder#pipeline(HttpPipeline)} http pipeline.
*
* @param formRecognizerClientImpl The proxy service used to perform REST calls.
* @param serviceVersion The versions of Azure Form Recognizer service supported by this client library.
*/
DocumentAnalysisAsyncClient(FormRecognizerClientImpl formRecognizerClientImpl, DocumentAnalysisServiceVersion serviceVersion) {
this.documentModelsImpl = formRecognizerClientImpl.getDocumentModels();
this.documentClassifiersImpl = formRecognizerClientImpl.getDocumentClassifiers();
this.serviceVersion = serviceVersion;
}
/**
* Analyzes data from documents with optical character recognition (OCR) and semantic values from a given document
* using any of the prebuilt models or a custom-built analysis model.
* <p>The service does not support cancellation of the long running operation and returns with an
* error message indicating absence of cancellation support.</p>
*
* <p><strong>Code sample</strong></p>
* <p> Analyze a document using the URL of the document. </p>
* <!-- src_embed com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisAsyncClient.beginAnalyzeDocumentFromUrl#string-string -->
* <pre>
* String documentUrl = "{document_url}";
* String modelId = "{model_id}";
* documentAnalysisAsyncClient.beginAnalyzeDocumentFromUrl(modelId, documentUrl)
* // if polling operation completed, retrieve the final result.
* .flatMap(AsyncPollResponse::getFinalResult)
* .subscribe(analyzeResult ->
* analyzeResult.getDocuments()
* .forEach(document ->
* document.getFields()
* .forEach((key, documentField) -> {
* System.out.printf("Field text: %s%n", key);
* System.out.printf("Field value data content: %s%n", documentField.getContent());
* System.out.printf("Confidence score: %.2f%n", documentField.getConfidence());
* })));
* </pre>
* <!-- end com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisAsyncClient.beginAnalyzeDocumentFromUrl#string-string -->
*
* @param modelId The unique model ID to be used. Use this to specify the custom model ID or prebuilt model ID.
* Prebuilt model IDs supported can be found <a href="https://aka.ms/azsdk/formrecognizer/models">here</a>
* @param documentUrl The URL of the document to analyze.
*
* @return A {@link PollerFlux} that polls the progress of the analyze document operation until it has completed, has failed,
* or has been cancelled. The completed operation returns an {@link AnalyzeResult}.
* @throws HttpResponseException If analyze operation fails and the {@link AnalyzeResultOperation} returns
* with an {@link OperationStatus#FAILED}..
* @throws IllegalArgumentException If {@code documentUrl} or {@code modelId} is null.
*/
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION)
public PollerFlux<OperationResult, AnalyzeResult>
beginAnalyzeDocumentFromUrl(String modelId, String documentUrl) {
return beginAnalyzeDocumentFromUrl(modelId, documentUrl, null);
}
/**
* Analyzes data from documents with optical character recognition (OCR) and semantic values from a given document
* using any of the prebuilt models or a custom-built analysis model.
* <p>The service does not support cancellation of the long running operation and returns with an
* error message indicating absence of cancellation support.</p>
*
* <p><strong>Code sample</strong></p>
* <p> Analyze a document using the URL of the document with configurable options. </p>
* <!-- src_embed com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisAsyncClient.beginAnalyzeDocumentFromUrl#string-string-Options -->
* <pre>
* String documentUrl = "{document_url}";
* // analyze a receipt using prebuilt model
* String modelId = "prebuilt-receipt";
*
* documentAnalysisAsyncClient.beginAnalyzeDocumentFromUrl(modelId, documentUrl,
* new AnalyzeDocumentOptions().setPages(Arrays.asList("1", "3")))
* // if polling operation completed, retrieve the final result.
* .flatMap(AsyncPollResponse::getFinalResult)
* .subscribe(analyzeResult -> {
* System.out.println(analyzeResult.getModelId());
* analyzeResult.getDocuments()
* .forEach(document ->
* document.getFields()
* .forEach((key, documentField) -> {
* System.out.printf("Field text: %s%n", key);
* System.out.printf("Field value data content: %s%n", documentField.getContent());
* System.out.printf("Confidence score: %.2f%n", documentField.getConfidence());
* }));
* });
*
* </pre>
* <!-- end com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisAsyncClient.beginAnalyzeDocumentFromUrl#string-string-Options -->
*
* @param modelId The unique model ID to be used. Use this to specify the custom model ID or prebuilt model ID.
* Prebuilt model IDs supported can be found <a href="https://aka.ms/azsdk/formrecognizer/models">here</a>
* @param documentUrl The source URL to the input form.
* @param analyzeDocumentOptions The additional configurable {@link AnalyzeDocumentOptions options}
* that may be passed when analyzing documents.
* @return A {@link PollerFlux} that polls progress of the analyze document operation until it has completed,
* has failed, or has been cancelled. The completed operation returns an {@link AnalyzeResult}.
* @throws HttpResponseException If analyze operation fails and the {@link AnalyzeResultOperation} returns
* with an {@link OperationStatus#FAILED}.
* @throws IllegalArgumentException If {@code documentUrl} or {@code modelId} is null.
*/
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION)
public PollerFlux<OperationResult, AnalyzeResult>
beginAnalyzeDocumentFromUrl(String modelId, String documentUrl,
AnalyzeDocumentOptions analyzeDocumentOptions) {
return beginAnalyzeDocumentFromUrl(documentUrl, modelId, analyzeDocumentOptions, Context.NONE);
}
private PollerFlux<OperationResult, AnalyzeResult>
beginAnalyzeDocumentFromUrl(String documentUrl, String modelId,
AnalyzeDocumentOptions analyzeDocumentOptions,
Context context) {
try {
if (CoreUtils.isNullOrEmpty(documentUrl)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'documentUrl' is required and cannot"
+ " be null or empty"));
}
if (CoreUtils.isNullOrEmpty(modelId)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'modelId' is required and cannot"
+ " be null or empty"));
}
final AnalyzeDocumentOptions finalAnalyzeDocumentOptions
= getAnalyzeDocumentOptions(analyzeDocumentOptions);
return new PollerFlux<>(
DEFAULT_POLL_INTERVAL,
activationOperation(() ->
documentModelsImpl.analyzeDocumentWithResponseAsync(modelId,
CoreUtils.isNullOrEmpty(finalAnalyzeDocumentOptions.getPages())
? null : String.join(",", finalAnalyzeDocumentOptions.getPages()),
finalAnalyzeDocumentOptions.getLocale() == null ? null
: finalAnalyzeDocumentOptions.getLocale(),
StringIndexType.UTF16CODE_UNIT,
finalAnalyzeDocumentOptions.getDocumentAnalysisFeatures(),
new AnalyzeDocumentRequest().setUrlSource(documentUrl),
context)
.map(analyzeDocumentResponse ->
Transforms.toDocumentOperationResult(
analyzeDocumentResponse.getDeserializedHeaders().getOperationLocation())),
logger),
pollingOperation(resultId ->
documentModelsImpl.getAnalyzeResultWithResponseAsync(modelId, resultId, context)),
(activationResponse, pollingContext) ->
Mono.error(new RuntimeException("Cancellation is not supported")),
fetchingOperation(resultId ->
documentModelsImpl.getAnalyzeResultWithResponseAsync(
modelId,
resultId,
context))
.andThen(after -> after
.map(modelSimpleResponse ->
Transforms.toAnalyzeResultOperation(modelSimpleResponse.getValue().getAnalyzeResult()))
.onErrorMap(Transforms::mapToHttpResponseExceptionIfExists)));
} catch (RuntimeException ex) {
return PollerFlux.error(ex);
}
}
/**
* Analyzes data from documents with optical character recognition (OCR) and semantic values from a given document
* using any of the prebuilt models or a custom-built analysis model.
* <p>The service does not support cancellation of the long running operation and returns with an
* error message indicating absence of cancellation support.</p>
* <p>
* Note that the {@code data} passed must be replayable if retries are enabled (the default). In other words, the
* {@code Flux} must produce the same data each time it is subscribed to.
*
* <p><strong>Code sample</strong></p>
* <p> Analyze a document. </p>
* <!-- src_embed com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisAsyncClient.beginAnalyzeDocument#string-BinaryData -->
* <pre>
* File document = new File("{local/file_path/fileName.jpg}");
* String modelId = "{model_id}";
* // Utility method to convert input stream to Binary Data
* BinaryData buffer = BinaryData.fromStream(new ByteArrayInputStream(Files.readAllBytes(document.toPath())));
*
* documentAnalysisAsyncClient.beginAnalyzeDocument(modelId, buffer)
* // if polling operation completed, retrieve the final result.
* .flatMap(AsyncPollResponse::getFinalResult)
* .subscribe(analyzeResult ->
* analyzeResult.getDocuments()
* .forEach(analyzedDocument ->
* analyzedDocument.getFields()
* .forEach((key, documentField) -> {
* System.out.printf("Field text: %s%n", key);
* System.out.printf("Field value data content: %s%n", documentField.getContent());
* System.out.printf("Confidence score: %.2f%n", documentField.getConfidence());
* })));
* </pre>
* <!-- end com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisAsyncClient.beginAnalyzeDocument#string-BinaryData -->
*
* @param modelId The unique model ID to be used. Use this to specify the custom model ID or prebuilt model ID.
* Prebuilt model IDs supported can be found <a href="https://aka.ms/azsdk/formrecognizer/models">here</a>
* @param document The data of the document to analyze information from.
* @return A {@link PollerFlux} that polls the progress of the analyze document operation until it has completed,
* has failed, or has been cancelled. The completed operation returns an {@link AnalyzeResult}.
* @throws HttpResponseException If analyze operation fails and returns with an {@link OperationStatus#FAILED}.
* @throws IllegalArgumentException If {@code document} or {@code modelId} is null.
*/
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION)
public PollerFlux<OperationResult, AnalyzeResult>
beginAnalyzeDocument(String modelId, BinaryData document) {
return beginAnalyzeDocument(modelId, document, null);
}
/**
* Analyzes data from documents with optical character recognition (OCR) and semantic values from a given document
* using any of the prebuilt models or a custom-built analysis model.
* <p>The service does not support cancellation of the long running operation and returns with an
* error message indicating absence of cancellation support.</p>
* <p>
* Note that the {@code data} passed must be replayable if retries are enabled (the default). In other words, the
* {@code Flux} must produce the same data each time it is subscribed to.
*
* <p><strong>Code sample</strong></p>
* <p> Analyze a document with configurable options. . </p>
* <!-- src_embed com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisAsyncClient.beginAnalyzeDocument#string-BinaryData-Options -->
* <pre>
* File document = new File("{local/file_path/fileName.jpg}");
* String modelId = "{model_id}";
* final AnalyzeDocumentOptions analyzeDocumentOptions =
* new AnalyzeDocumentOptions().setPages(Arrays.asList("1", "3")).setDocumentAnalysisFeatures(
* Collections.singletonList(
* DocumentAnalysisFeature.FORMULAS));
*
* // Utility method to convert input stream to Binary Data
* BinaryData buffer = BinaryData.fromStream(new ByteArrayInputStream(Files.readAllBytes(document.toPath())));
*
* documentAnalysisAsyncClient.beginAnalyzeDocument(modelId, buffer, analyzeDocumentOptions)
* // if polling operation completed, retrieve the final result.
* .flatMap(AsyncPollResponse::getFinalResult)
* .subscribe(analyzeResult -> {
* System.out.println(analyzeResult.getModelId());
* analyzeResult.getDocuments()
* .forEach(analyzedDocument ->
* analyzedDocument.getFields()
* .forEach((key, documentField) -> {
* System.out.printf("Field text: %s%n", key);
* System.out.printf("Field value data content: %s%n", documentField.getContent());
* System.out.printf("Confidence score: %.2f%n", documentField.getConfidence());
* }));
* });
* </pre>
* <!-- end com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisAsyncClient.beginAnalyzeDocument#string-BinaryData-Options -->
*
* @param modelId The unique model ID to be used. Use this to specify the custom model ID or prebuilt model ID.
* Prebuilt model IDs supported can be found <a href="https://aka.ms/azsdk/formrecognizer/models">here</a>
* @param document The data of the document to analyze information from.
* @param analyzeDocumentOptions The additional configurable {@link AnalyzeDocumentOptions options} that may be
* passed when analyzing documents.
* @return A {@link PollerFlux} that polls the progress of the analyze document operation until it has completed,
* has failed, or has been cancelled. The completed operation returns an {@link AnalyzeResult}.
* @throws HttpResponseException If analyze operation fails and returns with an {@link OperationStatus#FAILED}.
* @throws IllegalArgumentException If {@code document} or {@code modelId} is null.
* @throws IllegalArgumentException If {@code document} length is null or unspecified.
* Use {@link BinaryData#fromStream(InputStream, Long)} to create an instance of the {@code document}
* from given {@link InputStream} with length.
*/
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION)
public PollerFlux<OperationResult, AnalyzeResult>
beginAnalyzeDocument(String modelId, BinaryData document,
AnalyzeDocumentOptions analyzeDocumentOptions) {
return beginAnalyzeDocument(modelId, document, analyzeDocumentOptions, Context.NONE);
}
private PollerFlux<OperationResult, AnalyzeResult>
beginAnalyzeDocument(String modelId, BinaryData document,
AnalyzeDocumentOptions analyzeDocumentOptions, Context context) {
try {
Objects.requireNonNull(document, "'document' is required and cannot be null.");
if (CoreUtils.isNullOrEmpty(modelId)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'modelId' is required and cannot"
+ " be null or empty"));
}
if (document.getLength() == null) {
throw logger.logExceptionAsError(new IllegalArgumentException("'document length' is required and cannot"
+ " be null"));
}
final AnalyzeDocumentOptions finalAnalyzeDocumentOptions
= getAnalyzeDocumentOptions(analyzeDocumentOptions);
return new PollerFlux<>(
DEFAULT_POLL_INTERVAL,
activationOperation(() ->
documentModelsImpl.analyzeDocumentWithResponseAsync(modelId,
null,
CoreUtils.isNullOrEmpty(finalAnalyzeDocumentOptions.getPages())
? null : String.join(",", finalAnalyzeDocumentOptions.getPages()),
finalAnalyzeDocumentOptions.getLocale() == null ? null
: finalAnalyzeDocumentOptions.getLocale(),
StringIndexType.UTF16CODE_UNIT,
finalAnalyzeDocumentOptions.getDocumentAnalysisFeatures(),
document,
document.getLength(),
context)
.map(analyzeDocumentResponse -> Transforms.toDocumentOperationResult(
analyzeDocumentResponse.getDeserializedHeaders().getOperationLocation())),
logger),
pollingOperation(
resultId -> documentModelsImpl.getAnalyzeResultWithResponseAsync(
modelId, resultId, context)),
(activationResponse, pollingContext) ->
Mono.error(new RuntimeException("Cancellation is not supported")),
fetchingOperation(resultId -> documentModelsImpl.getAnalyzeResultWithResponseAsync(
modelId, resultId, context))
.andThen(after -> after.map(modelSimpleResponse ->
Transforms.toAnalyzeResultOperation(modelSimpleResponse.getValue().getAnalyzeResult()))
.onErrorMap(Transforms::mapToHttpResponseExceptionIfExists)));
} catch (RuntimeException ex) {
return PollerFlux.error(ex);
}
}
/**
* Classify a given document using a document classifier.
* For more information on how to build a custom classifier model,
* see <a href="https://aka.ms/azsdk/formrecognizer/buildclassifiermodel"></a>
* <p>The service does not support cancellation of the long running operation and returns with an
* error message indicating absence of cancellation support.</p>
*
* <p><strong>Code sample</strong></p>
* <p> Analyze a document using the URL of the document. </p>
* <!-- src_embed com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisAsyncClient.beginClassifyDocumentFromUrl#string-string -->
* <pre>
* String documentUrl = "{document_url}";
* String classifierId = "custom-trained-classifier-id";
*
* documentAnalysisAsyncClient.beginClassifyDocumentFromUrl(classifierId, documentUrl)
* // if polling operation completed, retrieve the final result.
* .flatMap(AsyncPollResponse::getFinalResult)
* .subscribe(analyzeResult -> {
* System.out.println(analyzeResult.getModelId());
* analyzeResult.getDocuments()
* .forEach(analyzedDocument -> System.out.printf("Doc Type: %s%n", analyzedDocument.getDocType()));
* });
*
* </pre>
* <!-- end com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisAsyncClient.beginClassifyDocumentFromUrl#string-string -->
*
* @param classifierId The unique classifier ID to be used. Use this to specify the custom classifier ID.
* @param documentUrl The URL of the document to analyze.
*
* @return A {@link PollerFlux} that polls the progress of the analyze document operation until it has completed, has failed,
* or has been cancelled. The completed operation returns an {@link AnalyzeResult}.
* @throws HttpResponseException If analyze operation fails and the {@link AnalyzeResultOperation} returns
* with an {@link OperationStatus#FAILED}..
* @throws IllegalArgumentException If {@code documentUrl} or {@code classifierId} is null.
*/
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION)
public PollerFlux<OperationResult, AnalyzeResult>
beginClassifyDocumentFromUrl(String classifierId, String documentUrl) {
return beginClassifyDocumentFromUrl(classifierId, documentUrl, Context.NONE);
}
private PollerFlux<OperationResult, AnalyzeResult>
beginClassifyDocumentFromUrl(String documentUrl, String classifierId,
Context context) {
try {
if (CoreUtils.isNullOrEmpty(documentUrl)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'documentUrl' is required and cannot"
+ " be null or empty"));
}
if (CoreUtils.isNullOrEmpty(classifierId)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'classifierId' is required and cannot"
+ " be null or empty"));
}
return new PollerFlux<>(
DEFAULT_POLL_INTERVAL,
activationOperation(() ->
documentClassifiersImpl.classifyDocumentWithResponseAsync(classifierId,
StringIndexType.UTF16CODE_UNIT,
new ClassifyDocumentRequest().setUrlSource(documentUrl),
context)
.map(analyzeDocumentResponse ->
Transforms.toDocumentOperationResult(
analyzeDocumentResponse.getDeserializedHeaders().getOperationLocation())),
logger),
pollingOperation(resultId ->
documentClassifiersImpl.getClassifyResultWithResponseAsync(classifierId, resultId, context)),
(activationResponse, pollingContext) ->
Mono.error(new RuntimeException("Cancellation is not supported")),
fetchingOperation(resultId ->
documentClassifiersImpl.getClassifyResultWithResponseAsync(
classifierId,
resultId,
context))
.andThen(after -> after
.map(modelSimpleResponse ->
Transforms.toAnalyzeResultOperation(modelSimpleResponse.getValue().getAnalyzeResult()))
.onErrorMap(Transforms::mapToHttpResponseExceptionIfExists)));
} catch (RuntimeException ex) {
return PollerFlux.error(ex);
}
}
/**
* Classify a given document using a document classifier.
* For more information on how to build a custom classifier model,
* see <a href="https://aka.ms/azsdk/formrecognizer/buildclassifiermodel"></a>
* <p>The service does not support cancellation of the long running operation and returns with an
* error message indicating absence of cancellation support.</p>
* <p>
* Note that the {@code data} passed must be replayable if retries are enabled (the default). In other words, the
* {@code Flux} must produce the same data each time it is subscribed to.
*
* <p><strong>Code sample</strong></p>
* <p> Analyze a document with configurable options.</p>
* <!-- src_embed com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisAsyncClient.beginClassifyDocument#string-BinaryData -->
* <pre>
* File document = new File("{local/file_path/fileName.jpg}");
* String classifierId = "{model_id}";
*
* // Utility method to convert input stream to Binary Data
* BinaryData buffer = BinaryData.fromStream(new ByteArrayInputStream(Files.readAllBytes(document.toPath())));
*
* documentAnalysisAsyncClient.beginClassifyDocument(classifierId, buffer)
* // if polling operation completed, retrieve the final result.
* .flatMap(AsyncPollResponse::getFinalResult)
* .subscribe(analyzeResult -> {
* System.out.println(analyzeResult.getModelId());
* analyzeResult.getDocuments()
* .forEach(analyzedDocument -> System.out.printf("Doc Type: %s%n", analyzedDocument.getDocType()));
* });
* </pre>
* <!-- end com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisAsyncClient.beginClassifyDocument#string-BinaryData -->
*
* @param classifierId The unique classifier ID to be used. Use this to specify the custom classifier ID.
* @param document The data of the document to analyze information from. For service supported file types, see:
* <a href="https://aka.ms/azsdk/formrecognizer/supportedfiles"></a>
* @return A {@link PollerFlux} that polls the progress of the analyze document operation until it has completed,
* has failed, or has been cancelled. The completed operation returns an {@link AnalyzeResult}.
* @throws HttpResponseException If analyze operation fails and returns with an {@link OperationStatus#FAILED}.
* @throws IllegalArgumentException If {@code document} or {@code classifierId} is null.
* @throws IllegalArgumentException If {@code document} length is null or unspecified.
* Use {@link BinaryData#fromStream(InputStream, Long)} to create an instance of the {@code document}
* from given {@link InputStream} with length.
*/
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION)
public PollerFlux<OperationResult, AnalyzeResult>
beginClassifyDocument(String classifierId, BinaryData document) {
return beginClassifyDocument(classifierId, document, Context.NONE);
}
private PollerFlux<OperationResult, AnalyzeResult>
beginClassifyDocument(String classifierId, BinaryData document, Context context) {
try {
Objects.requireNonNull(document, "'document' is required and cannot be null.");
if (CoreUtils.isNullOrEmpty(classifierId)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'classifierId' is required and cannot"
+ " be null or empty"));
}
if (document.getLength() == null) {
throw logger.logExceptionAsError(new IllegalArgumentException("'document length' is required and cannot"
+ " be null"));
}
return new PollerFlux<>(
DEFAULT_POLL_INTERVAL,
activationOperation(() ->
documentClassifiersImpl.classifyDocumentWithResponseAsync(classifierId,
null,
StringIndexType.UTF16CODE_UNIT,
document,
document.getLength(),
context)
.map(analyzeDocumentResponse -> Transforms.toDocumentOperationResult(
analyzeDocumentResponse.getDeserializedHeaders().getOperationLocation())),
logger),
pollingOperation(
resultId -> documentClassifiersImpl.getClassifyResultWithResponseAsync(
classifierId, resultId, context)),
(activationResponse, pollingContext) ->
Mono.error(new RuntimeException("Cancellation is not supported")),
fetchingOperation(resultId -> documentClassifiersImpl.getClassifyResultWithResponseAsync(
classifierId, resultId, context))
.andThen(after -> after.map(modelSimpleResponse ->
Transforms.toAnalyzeResultOperation(modelSimpleResponse.getValue().getAnalyzeResult()))
.onErrorMap(Transforms::mapToHttpResponseExceptionIfExists)));
} catch (RuntimeException ex) {
return PollerFlux.error(ex);
}
}
/*
* Poller's POLLING operation.
*/
private Function<PollingContext<OperationResult>, Mono<PollResponse<OperationResult>>>
pollingOperation(
Function<String, Mono<Response<AnalyzeResultOperation>>> pollingFunction) {
return pollingContext -> {
try {
final PollResponse<OperationResult> operationResultPollResponse
= pollingContext.getLatestResponse();
final String resultId = operationResultPollResponse.getValue().getOperationId();
return pollingFunction.apply(resultId)
.flatMap(modelResponse -> processAnalyzeModelResponse(modelResponse, operationResultPollResponse))
.onErrorMap(Transforms::mapToHttpResponseExceptionIfExists);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
};
}
/*
* Poller's FETCHING operation.
*/
private Function<PollingContext<OperationResult>, Mono<Response<AnalyzeResultOperation>>>
fetchingOperation(
Function<String, Mono<Response<AnalyzeResultOperation>>> fetchingFunction) {
return pollingContext -> {
try {
final String resultId = pollingContext.getLatestResponse().getValue().getOperationId();
return fetchingFunction.apply(resultId);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
};
}
private Mono<PollResponse<OperationResult>> processAnalyzeModelResponse(
Response<AnalyzeResultOperation> analyzeResultOperationResponse,
PollResponse<OperationResult> operationResultPollResponse) {
LongRunningOperationStatus status;
switch (analyzeResultOperationResponse.getValue().getStatus()) {
case NOT_STARTED:
case RUNNING:
status = LongRunningOperationStatus.IN_PROGRESS;
break;
case SUCCEEDED:
status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED;
break;
case FAILED:
throw logger.logExceptionAsError(Transforms
.mapResponseErrorToHttpResponseException(analyzeResultOperationResponse.getValue().getError()));
default:
status = LongRunningOperationStatus.fromString(
analyzeResultOperationResponse.getValue().getStatus().toString(), true);
break;
}
return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue()));
}
}