Skip to content

Commit 5196c22

Browse files
author
Yalin Li
authored
[DI] Add samples for getting raw json result (Azure#37725)
1 parent cfc9b85 commit 5196c22

File tree

6 files changed

+375
-1
lines changed

6 files changed

+375
-1
lines changed

sdk/documentintelligence/azure-ai-documentintelligence/README.md

Lines changed: 70 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,8 @@ The following section provides several code snippets covering some of the most c
202202
* [Build a Custom Model](#build-a-custom-model "Build a custom model")
203203
* [Analyze Documents Using a Custom Model](#analyze-documents-using-a-custom-model "Analyze Documents Using a Custom Model")
204204
* [Manage Your Models](#manage-your-models "Manage Your Models")
205-
* [Add-on capabilities](#add-on-capabilities "Add-on Capabilities")
205+
* [Add-on Capabilities](#add-on-capabilities "Add-on Capabilities")
206+
* [Get Raw JSON Result](#get-raw-json-result "Get Raw JSON Result")
206207

207208
### Extract Layout
208209

@@ -896,6 +897,74 @@ The following add-on capabilities are available in this SDK:
896897

897898
Note that some add-on capabilities will incur additional charges. See pricing: https://azure.microsoft.com/pricing/details/ai-document-intelligence/.
898899

900+
### Get Raw JSON Result
901+
902+
Can get the HTTP response by passing parameter `raw_response_hook` to any client method.
903+
<!-- SNIPPET:sample_get_raw_response.raw_response_hook -->
904+
905+
```python
906+
import os
907+
from azure.core.credentials import AzureKeyCredential
908+
from azure.ai.documentintelligence import DocumentIntelligenceAdministrationClient
909+
910+
endpoint = os.environ["DOCUMENTINTELLIGENCE_ENDPOINT"]
911+
key = os.environ["DOCUMENTINTELLIGENCE_API_KEY"]
912+
913+
client = DocumentIntelligenceAdministrationClient(endpoint=endpoint, credential=AzureKeyCredential(key))
914+
915+
responses = {}
916+
917+
def callback(response):
918+
responses["status_code"] = response.http_response.status_code
919+
responses["response_body"] = response.http_response.json()
920+
921+
client.get_resource_info(raw_response_hook=callback)
922+
923+
print(f"Response status code is: {responses["status_code"]}")
924+
response_body = responses["response_body"]
925+
print(
926+
f"Our resource has {response_body['customDocumentModels']['count']} custom models, "
927+
f"and we can have at most {response_body['customDocumentModels']['limit']} custom models."
928+
f"The quota limit for custom neural document models is {response_body['customNeuralDocumentModelBuilds']['quota']} and the resource has"
929+
f"used {response_body['customNeuralDocumentModelBuilds']['used']}. The resource quota will reset on {response_body['customNeuralDocumentModelBuilds']['quotaResetDateTime']}"
930+
)
931+
```
932+
933+
<!-- END SNIPPET -->
934+
935+
Also, can use the `send_request` method to send custom HTTP requests and get raw JSON result from HTTP responses.
936+
937+
<!-- SNIPPET:sample_send_request.send_request -->
938+
939+
```python
940+
import os
941+
from azure.core.credentials import AzureKeyCredential
942+
from azure.core.rest import HttpRequest
943+
from azure.ai.documentintelligence import DocumentIntelligenceAdministrationClient
944+
945+
endpoint = os.environ["DOCUMENTINTELLIGENCE_ENDPOINT"]
946+
key = os.environ["DOCUMENTINTELLIGENCE_API_KEY"]
947+
948+
client = DocumentIntelligenceAdministrationClient(endpoint=endpoint, credential=AzureKeyCredential(key))
949+
950+
# The `send_request` method can send custom HTTP requests that share the client's existing pipeline,
951+
# Now let's use the `send_request` method to make a resource details fetching request.
952+
# The URL of the request should be absolute, and append the API version used for the request.
953+
request = HttpRequest(method="GET", url=f"{endpoint}/documentintelligence/info?api-version=2024-07-31-preview")
954+
response = client.send_request(request)
955+
response.raise_for_status()
956+
response_body = response.json()
957+
print(
958+
f"Our resource has {response_body['customDocumentModels']['count']} custom models, "
959+
f"and we can have at most {response_body['customDocumentModels']['limit']} custom models."
960+
f"The quota limit for custom neural document models is {response_body['customNeuralDocumentModelBuilds']['quota']} and the resource has"
961+
f"used {response_body['customNeuralDocumentModelBuilds']['used']}. The resource quota will reset on {response_body['customNeuralDocumentModelBuilds']['quotaResetDateTime']}"
962+
)
963+
```
964+
965+
<!-- END SNIPPET -->
966+
967+
899968
## Troubleshooting
900969

901970
### General

sdk/documentintelligence/azure-ai-documentintelligence/azure/ai/documentintelligence/_operations/_patch.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ def _parse_operation_id(operation_location_header):
3939
regex = "[^:]+://[^/]+/documentintelligence/.+/([^?/]+)"
4040
return re.match(regex, operation_location_header).group(1)
4141

42+
4243
def _finished(status) -> bool:
4344
if hasattr(status, "value"):
4445
status = status.value
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
# coding: utf-8
2+
3+
# -------------------------------------------------------------------------
4+
# Copyright (c) Microsoft Corporation. All rights reserved.
5+
# Licensed under the MIT License. See License.txt in the project root for
6+
# license information.
7+
# --------------------------------------------------------------------------
8+
9+
"""
10+
FILE: sample_raw_response_hook_async.py
11+
12+
DESCRIPTION:
13+
This sample demonstrates how to get raw response via "raw_response_hook".
14+
15+
USAGE:
16+
python sample_raw_response_hook_async.py
17+
18+
Set the environment variables with your own values before running the sample:
19+
1) DOCUMENTINTELLIGENCE_ENDPOINT - the endpoint to your Document Intelligence resource.
20+
2) DOCUMENTINTELLIGENCE_API_KEY - your Document Intelligence API key.
21+
"""
22+
23+
import asyncio
24+
import os
25+
from azure.core.credentials import AzureKeyCredential
26+
from azure.ai.documentintelligence.aio import DocumentIntelligenceAdministrationClient
27+
28+
29+
async def sample_raw_response_hook():
30+
endpoint = os.environ["DOCUMENTINTELLIGENCE_ENDPOINT"]
31+
key = os.environ["DOCUMENTINTELLIGENCE_API_KEY"]
32+
33+
client = DocumentIntelligenceAdministrationClient(endpoint=endpoint, credential=AzureKeyCredential(key))
34+
35+
responses = {}
36+
37+
def callback(response):
38+
responses["status_code"] = response.http_response.status_code
39+
responses["response_body"] = response.http_response.json()
40+
41+
async with client:
42+
await client.get_resource_info(raw_response_hook=callback)
43+
44+
print(f"Response status code is: {responses['status_code']}")
45+
response_body = responses["response_body"]
46+
print(
47+
f"Our resource has {response_body['customDocumentModels']['count']} custom models, "
48+
f"and we can have at most {response_body['customDocumentModels']['limit']} custom models."
49+
f"The quota limit for custom neural document models is {response_body['customNeuralDocumentModelBuilds']['quota']} and the resource has"
50+
f"used {response_body['customNeuralDocumentModelBuilds']['used']}. The resource quota will reset on {response_body['customNeuralDocumentModelBuilds']['quotaResetDateTime']}"
51+
)
52+
53+
54+
async def main():
55+
await sample_raw_response_hook()
56+
57+
58+
if __name__ == "__main__":
59+
from azure.core.exceptions import HttpResponseError
60+
from dotenv import find_dotenv, load_dotenv
61+
62+
try:
63+
load_dotenv(find_dotenv())
64+
asyncio.run(main())
65+
except HttpResponseError as error:
66+
# Examples of how to check an HttpResponseError
67+
# Check by error code:
68+
if error.error is not None:
69+
if error.error.code == "InvalidImage":
70+
print(f"Received an invalid image error: {error.error}")
71+
if error.error.code == "InvalidRequest":
72+
print(f"Received an invalid request error: {error.error}")
73+
# Raise the error again after printing it
74+
raise
75+
# If the inner error is None and then it is possible to check the message to get more information:
76+
if "Invalid request".casefold() in error.message.casefold():
77+
print(f"Uh-oh! Seems there was an invalid request: {error}")
78+
# Raise the error again
79+
raise
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
# coding: utf-8
2+
3+
# -------------------------------------------------------------------------
4+
# Copyright (c) Microsoft Corporation. All rights reserved.
5+
# Licensed under the MIT License. See License.txt in the project root for
6+
# license information.
7+
# --------------------------------------------------------------------------
8+
9+
"""
10+
FILE: sample_send_request_async.py
11+
12+
DESCRIPTION:
13+
This sample demonstrates how to make custom HTTP requests through a client pipeline.
14+
15+
USAGE:
16+
python sample_send_request_async.py
17+
18+
Set the environment variables with your own values before running the sample:
19+
1) DOCUMENTINTELLIGENCE_ENDPOINT - the endpoint to your Form Recognizer resource.
20+
2) DOCUMENTINTELLIGENCE_API_KEY - your Form Recognizer API key
21+
"""
22+
23+
import asyncio
24+
import os
25+
from azure.core.credentials import AzureKeyCredential
26+
from azure.core.rest import HttpRequest
27+
from azure.ai.documentintelligence.aio import DocumentIntelligenceAdministrationClient
28+
29+
30+
async def sample_send_request():
31+
endpoint = os.environ["DOCUMENTINTELLIGENCE_ENDPOINT"]
32+
key = os.environ["DOCUMENTINTELLIGENCE_API_KEY"]
33+
34+
client = DocumentIntelligenceAdministrationClient(endpoint=endpoint, credential=AzureKeyCredential(key))
35+
36+
async with client:
37+
# The `send_request` method can send custom HTTP requests that share the client's existing pipeline,
38+
# Now let's use the `send_request` method to make a resource details fetching request.
39+
# The URL of the request should be absolute, and append the API version used for the request.
40+
request = HttpRequest(method="GET", url=f"{endpoint}/documentintelligence/info?api-version=2024-07-31-preview")
41+
response = await client.send_request(request)
42+
response.raise_for_status()
43+
response_body = response.json()
44+
print(
45+
f"Our resource has {response_body['customDocumentModels']['count']} custom models, "
46+
f"and we can have at most {response_body['customDocumentModels']['limit']} custom models."
47+
f"The quota limit for custom neural document models is {response_body['customNeuralDocumentModelBuilds']['quota']} and the resource has"
48+
f"used {response_body['customNeuralDocumentModelBuilds']['used']}. The resource quota will reset on {response_body['customNeuralDocumentModelBuilds']['quotaResetDateTime']}"
49+
)
50+
51+
52+
async def main():
53+
await sample_send_request()
54+
55+
56+
if __name__ == "__main__":
57+
from azure.core.exceptions import HttpResponseError
58+
from dotenv import find_dotenv, load_dotenv
59+
60+
try:
61+
load_dotenv(find_dotenv())
62+
asyncio.run(main())
63+
except HttpResponseError as error:
64+
# Examples of how to check an HttpResponseError
65+
# Check by error code:
66+
if error.error is not None:
67+
if error.error.code == "InvalidImage":
68+
print(f"Received an invalid image error: {error.error}")
69+
if error.error.code == "InvalidRequest":
70+
print(f"Received an invalid request error: {error.error}")
71+
# Raise the error again after printing it
72+
raise
73+
# If the inner error is None and then it is possible to check the message to get more information:
74+
if "Invalid request".casefold() in error.message.casefold():
75+
print(f"Uh-oh! Seems there was an invalid request: {error}")
76+
# Raise the error again
77+
raise
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
# coding: utf-8
2+
3+
# -------------------------------------------------------------------------
4+
# Copyright (c) Microsoft Corporation. All rights reserved.
5+
# Licensed under the MIT License. See License.txt in the project root for
6+
# license information.
7+
# --------------------------------------------------------------------------
8+
9+
"""
10+
FILE: sample_get_raw_response.py
11+
12+
DESCRIPTION:
13+
This sample demonstrates how to get raw response via "raw_response_hook".
14+
15+
USAGE:
16+
python sample_get_raw_response.py
17+
18+
Set the environment variables with your own values before running the sample:
19+
1) DOCUMENTINTELLIGENCE_ENDPOINT - the endpoint to your Document Intelligence resource.
20+
2) DOCUMENTINTELLIGENCE_API_KEY - your Document Intelligence API key.
21+
"""
22+
23+
24+
def sample_raw_response_hook():
25+
# [START raw_response_hook]
26+
import os
27+
from azure.core.credentials import AzureKeyCredential
28+
from azure.ai.documentintelligence import DocumentIntelligenceAdministrationClient
29+
30+
endpoint = os.environ["DOCUMENTINTELLIGENCE_ENDPOINT"]
31+
key = os.environ["DOCUMENTINTELLIGENCE_API_KEY"]
32+
33+
client = DocumentIntelligenceAdministrationClient(endpoint=endpoint, credential=AzureKeyCredential(key))
34+
35+
responses = {}
36+
37+
def callback(response):
38+
responses["status_code"] = response.http_response.status_code
39+
responses["response_body"] = response.http_response.json()
40+
41+
client.get_resource_info(raw_response_hook=callback)
42+
43+
print(f"Response status code is: {responses['status_code']}")
44+
response_body = responses["response_body"]
45+
print(
46+
f"Our resource has {response_body['customDocumentModels']['count']} custom models, "
47+
f"and we can have at most {response_body['customDocumentModels']['limit']} custom models."
48+
f"The quota limit for custom neural document models is {response_body['customNeuralDocumentModelBuilds']['quota']} and the resource has"
49+
f"used {response_body['customNeuralDocumentModelBuilds']['used']}. The resource quota will reset on {response_body['customNeuralDocumentModelBuilds']['quotaResetDateTime']}"
50+
)
51+
# [END raw_response_hook]
52+
53+
54+
if __name__ == "__main__":
55+
from azure.core.exceptions import HttpResponseError
56+
from dotenv import find_dotenv, load_dotenv
57+
58+
try:
59+
load_dotenv(find_dotenv())
60+
sample_raw_response_hook()
61+
except HttpResponseError as error:
62+
# Examples of how to check an HttpResponseError
63+
# Check by error code:
64+
if error.error is not None:
65+
if error.error.code == "InvalidImage":
66+
print(f"Received an invalid image error: {error.error}")
67+
if error.error.code == "InvalidRequest":
68+
print(f"Received an invalid request error: {error.error}")
69+
# Raise the error again after printing it
70+
raise
71+
# If the inner error is None and then it is possible to check the message to get more information:
72+
if "Invalid request".casefold() in error.message.casefold():
73+
print(f"Uh-oh! Seems there was an invalid request: {error}")
74+
# Raise the error again
75+
raise

0 commit comments

Comments
 (0)