Skip to content

Commit 0cb07ea

Browse files
author
Chien Yuan Chang
committed
[SAMPLE-UPDATE] sample_delete_result
1 parent 9ba0557 commit 0cb07ea

File tree

4 files changed

+101
-157
lines changed

4 files changed

+101
-157
lines changed

sdk/contentunderstanding/azure-ai-contentunderstanding/samples/async_samples/sample_delete_result_async.py

Lines changed: 13 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -55,45 +55,29 @@ async def main() -> None:
5555

5656
async with ContentUnderstandingClient(endpoint=endpoint, credential=credential) as client:
5757
# [START analyze_and_delete_result]
58-
document_url = "https://github.com/Azure-Samples/azure-ai-content-understanding-assets/raw/refs/heads/main/docs/invoice.pdf"
58+
# You can replace this URL with your own invoice file URL
59+
document_url = "https://raw.githubusercontent.com/Azure-Samples/azure-ai-content-understanding-assets/main/document/invoice.pdf"
5960

60-
print("Document Analysis Workflow")
61-
print("=" * 60)
62-
print(f" Document URL: {document_url}")
63-
print(f" Analyzer: prebuilt-invoice")
64-
print("=" * 60)
65-
66-
# Step 1: Start the analysis operation
67-
print("\nStep 1: Starting document analysis...")
68-
poller = await client.begin_analyze(
61+
# Step 1: Analyze and wait for completion
62+
analyze_operation = await client.begin_analyze(
6963
analyzer_id="prebuilt-invoice",
7064
inputs=[AnalyzeInput(url=document_url)],
7165
)
7266

73-
# Get the operation ID from the poller
74-
operation_id = poller.operation_id
75-
76-
if not operation_id:
77-
print("Error: Could not extract operation ID from response")
78-
return
79-
80-
print(f" Operation ID: {operation_id}")
81-
82-
# Wait for completion
83-
print(" Waiting for analysis to complete...")
84-
result: AnalyzeResult = await poller.result()
67+
# Get the operation ID - this is needed to delete the result later
68+
operation_id = analyze_operation.operation_id
69+
print(f"Operation ID: {operation_id}")
70+
result: AnalyzeResult = await analyze_operation.result()
8571
print("Analysis completed successfully!")
8672

8773
# Display some sample results
8874
if result.contents and len(result.contents) > 0:
89-
doc_content: DocumentContent = result.contents[0] # type: ignore
90-
if doc_content.fields:
91-
print(f" Total fields extracted: {len(doc_content.fields)}")
92-
customer_name_field = doc_content.fields.get("CustomerName")
93-
if customer_name_field:
94-
print(f" Customer Name: {customer_name_field.value or '(not found)'}")
75+
document_content: DocumentContent = result.contents[0] # type: ignore
76+
if document_content.fields:
77+
print(f"Total fields extracted: {len(document_content.fields)}")
78+
9579
# Step 2: Delete the analysis result
96-
print(f"\nStep 2: Deleting analysis result (Operation ID: {operation_id})...")
80+
print(f"Deleting analysis result (Operation ID: {operation_id})...")
9781
await client.delete_result(operation_id=operation_id)
9882
print("Analysis result deleted successfully!")
9983

sdk/contentunderstanding/azure-ai-contentunderstanding/samples/sample_delete_result.py

Lines changed: 13 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -55,47 +55,31 @@ def main() -> None:
5555
client = ContentUnderstandingClient(endpoint=endpoint, credential=credential)
5656

5757
# [START analyze_and_delete_result]
58+
# You can replace this URL with your own invoice file URL
5859
document_url = (
59-
"https://github.com/Azure-Samples/azure-ai-content-understanding-assets/raw/refs/heads/main/docs/invoice.pdf"
60+
"https://raw.githubusercontent.com/Azure-Samples/azure-ai-content-understanding-assets/main/document/invoice.pdf"
6061
)
6162

62-
print("Document Analysis Workflow")
63-
print("=" * 60)
64-
print(f" Document URL: {document_url}")
65-
print(f" Analyzer: prebuilt-invoice")
66-
print("=" * 60)
67-
68-
# Step 1: Start the analysis operation
69-
print("\nStep 1: Starting document analysis...")
70-
poller = client.begin_analyze(
63+
# Step 1: Analyze and wait for completion
64+
analyze_operation = client.begin_analyze(
7165
analyzer_id="prebuilt-invoice",
7266
inputs=[AnalyzeInput(url=document_url)],
7367
)
7468

75-
# Get the operation ID from the poller
76-
operation_id = poller.operation_id
77-
78-
if not operation_id:
79-
print("Error: Could not extract operation ID from response")
80-
return
81-
82-
print(f" Operation ID: {operation_id}")
83-
84-
# Wait for completion
85-
print(" Waiting for analysis to complete...")
86-
result: AnalyzeResult = poller.result()
69+
# Get the operation ID - this is needed to delete the result later
70+
operation_id = analyze_operation.operation_id
71+
print(f"Operation ID: {operation_id}")
72+
result: AnalyzeResult = analyze_operation.result()
8773
print("Analysis completed successfully!")
8874

8975
# Display some sample results
9076
if result.contents and len(result.contents) > 0:
91-
doc_content: DocumentContent = result.contents[0] # type: ignore
92-
if doc_content.fields:
93-
print(f" Total fields extracted: {len(doc_content.fields)}")
94-
customer_name_field = doc_content.fields.get("CustomerName")
95-
if customer_name_field:
96-
print(f" Customer Name: {customer_name_field.value or '(not found)'}")
77+
document_content: DocumentContent = result.contents[0] # type: ignore
78+
if document_content.fields:
79+
print(f"Total fields extracted: {len(document_content.fields)}")
80+
9781
# Step 2: Delete the analysis result
98-
print(f"\nStep 2: Deleting analysis result (Operation ID: {operation_id})...")
82+
print(f"Deleting analysis result (Operation ID: {operation_id})...")
9983
client.delete_result(operation_id=operation_id)
10084
print("Analysis result deleted successfully!")
10185

sdk/contentunderstanding/azure-ai-contentunderstanding/tests/samples/test_sample_delete_result.py

Lines changed: 37 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import pytest
2222
from devtools_testutils import recorded_by_proxy
2323
from testpreparer import ContentUnderstandingPreparer, ContentUnderstandingClientTestBase
24+
from azure.ai.contentunderstanding.models import AnalyzeInput, AnalyzeResult, DocumentContent
2425

2526

2627
class TestSampleDeleteResult(ContentUnderstandingClientTestBase):
@@ -33,16 +34,17 @@ def test_sample_delete_result(self, azure_content_understanding_endpoint: str) -
3334
3435
This test validates:
3536
1. Document analysis to create a result
36-
2. Extracting result ID
37-
3. Deleting the result
37+
2. Extracting operation ID
38+
3. Deleting the result using operation ID
3839
39-
13_DeleteResult.DeleteResultAsync()
40+
Equivalent to: Sample13_DeleteResult.DeleteResultAsync()
4041
"""
4142
client = self.create_client(endpoint=azure_content_understanding_endpoint)
4243

4344
# First, analyze a document to create a result
44-
tests_dir = os.path.dirname(os.path.dirname(__file__))
45-
file_path = os.path.join(tests_dir, "test_data", "sample_invoice.pdf")
45+
current_dir = os.path.dirname(os.path.abspath(__file__))
46+
test_data_dir = os.path.join(os.path.dirname(current_dir), "test_data")
47+
file_path = os.path.join(test_data_dir, "sample_invoice.pdf")
4648

4749
assert os.path.exists(file_path), f"Sample file not found at {file_path}"
4850
print(f"[PASS] Sample file exists: {file_path}")
@@ -53,58 +55,44 @@ def test_sample_delete_result(self, azure_content_understanding_endpoint: str) -
5355
assert len(file_bytes) > 0, "File should not be empty"
5456
print(f"[PASS] File loaded: {len(file_bytes)} bytes")
5557

56-
# Analyze to get a result ID
57-
poller = client.begin_analyze_binary(
58-
analyzer_id="prebuilt-documentSearch", binary_input=file_bytes, content_type="application/pdf"
58+
# Analyze to get an operation ID
59+
analyze_operation = client.begin_analyze(
60+
analyzer_id="prebuilt-invoice", inputs=[AnalyzeInput(data=file_bytes)]
5961
)
6062

61-
result = poller.result()
63+
result: AnalyzeResult = analyze_operation.result()
6264

6365
# Assertions for analysis
64-
assert poller is not None, "Analysis operation should not be null"
65-
assert poller.done(), "Operation should be completed"
66+
assert analyze_operation is not None, "Analysis operation should not be null"
67+
assert analyze_operation.done(), "Operation should be completed"
6668
assert result is not None, "Analysis result should not be null"
6769
print("[PASS] Analysis completed successfully")
6870

69-
# Extract operation ID from the poller
70-
# The operation ID is needed to delete the result
71-
operation_id = None
71+
# Get operation ID - this is needed to delete the result
72+
operation_id = analyze_operation.operation_id
73+
assert operation_id is not None, "Operation ID should not be null"
74+
assert isinstance(operation_id, str), "Operation ID should be a string"
75+
assert operation_id.strip(), "Operation ID should not be empty"
76+
print(f"[PASS] Operation ID extracted: {operation_id[:50]}...")
77+
78+
# Verify we have analysis content
79+
assert hasattr(result, "contents"), "Result should contain contents"
80+
contents = getattr(result, "contents", None)
81+
assert contents is not None, "Result contents should not be null"
82+
assert len(contents) > 0, "Result should have at least one content"
83+
print(f"[PASS] Analysis result contains {len(contents)} content item(s)")
84+
85+
# Delete the result
7286
try:
73-
# Extract operation ID from polling URL
74-
if hasattr(poller, "_polling_method"):
75-
polling_method = getattr(poller, "_polling_method", None)
76-
if polling_method and hasattr(polling_method, "_operation"):
77-
operation = getattr(polling_method, "_operation", None) # type: ignore
78-
if operation and hasattr(operation, "get_polling_url"):
79-
polling_url = operation.get_polling_url() # type: ignore
80-
# Extract operation ID from URL (last segment before query string)
81-
operation_id = polling_url.split("/")[-1]
82-
if "?" in operation_id:
83-
operation_id = operation_id.split("?")[0]
87+
client.delete_result(operation_id=operation_id)
88+
print(f"[PASS] Result deleted successfully (operation ID: {operation_id[:50]}...)")
89+
print("[INFO] Deletion success verified by no exception thrown")
8490
except Exception as e:
85-
print(f"[WARN] Could not extract operation ID: {str(e)[:100]}")
86-
87-
# Assertion: Verify we have an operation ID
88-
if operation_id:
89-
assert operation_id is not None, "Operation ID should not be null"
90-
assert isinstance(operation_id, str), "Operation ID should be a string"
91-
assert operation_id.strip(), "Operation ID should not be empty"
92-
print(f"[PASS] Operation ID extracted: {operation_id[:50]}...")
93-
94-
# Delete the result
95-
try:
96-
client.delete_result(operation_id=operation_id)
97-
print(f"[PASS] Result deleted successfully (operation ID: {operation_id[:50]}...)")
98-
print("[INFO] Deletion success verified by no exception thrown")
99-
except Exception as e:
100-
error_msg = str(e)
101-
# Some implementations might not support result deletion or result might auto-expire
102-
if "not found" in error_msg.lower() or "404" in error_msg:
103-
print(f"[INFO] Result already deleted or not found: {error_msg[:100]}")
104-
else:
105-
print(f"[WARN] Delete result failed: {error_msg[:100]}")
106-
else:
107-
print("[INFO] Operation ID not available in response")
108-
print("[INFO] Delete result operation skipped - operation ID extraction not supported")
91+
error_msg = str(e)
92+
# Some implementations might not support result deletion or result might auto-expire
93+
if "not found" in error_msg.lower() or "404" in error_msg:
94+
print(f"[INFO] Result already deleted or not found: {error_msg[:100]}")
95+
else:
96+
raise
10997

11098
print("\n[SUCCESS] All test_sample_delete_result assertions passed")

sdk/contentunderstanding/azure-ai-contentunderstanding/tests/samples/test_sample_delete_result_async.py

Lines changed: 38 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
TEST FILE: test_sample_delete_result_async.py
1111
1212
DESCRIPTION:
13-
These tests validate the sample_delete_result.py sample code (async version).
13+
These tests validate the sample_delete_result_async.py sample code (async version).
1414
This sample demonstrates deleting analysis results for immediate cleanup.
1515
1616
USAGE:
@@ -21,6 +21,7 @@
2121
import pytest
2222
from devtools_testutils.aio import recorded_by_proxy_async
2323
from testpreparer_async import ContentUnderstandingPreparer, ContentUnderstandingClientTestBaseAsync
24+
from azure.ai.contentunderstanding.models import AnalyzeInput, AnalyzeResult
2425

2526

2627
class TestSampleDeleteResultAsync(ContentUnderstandingClientTestBaseAsync):
@@ -33,16 +34,17 @@ async def test_sample_delete_result_async(self, azure_content_understanding_endp
3334
3435
This test validates:
3536
1. Document analysis to create a result
36-
2. Extracting result ID
37-
3. Deleting the result
37+
2. Extracting operation ID
38+
3. Deleting the result using operation ID
3839
39-
13_DeleteResult.DeleteResultAsync()
40+
Equivalent to: Sample13_DeleteResult.DeleteResultAsync()
4041
"""
4142
client = self.create_async_client(endpoint=azure_content_understanding_endpoint)
4243

4344
# First, analyze a document to create a result
44-
tests_dir = os.path.dirname(os.path.dirname(__file__))
45-
file_path = os.path.join(tests_dir, "test_data", "sample_invoice.pdf")
45+
current_dir = os.path.dirname(os.path.abspath(__file__))
46+
test_data_dir = os.path.join(os.path.dirname(current_dir), "test_data")
47+
file_path = os.path.join(test_data_dir, "sample_invoice.pdf")
4648

4749
assert os.path.exists(file_path), f"Sample file not found at {file_path}"
4850
print(f"[PASS] Sample file exists: {file_path}")
@@ -53,59 +55,45 @@ async def test_sample_delete_result_async(self, azure_content_understanding_endp
5355
assert len(file_bytes) > 0, "File should not be empty"
5456
print(f"[PASS] File loaded: {len(file_bytes)} bytes")
5557

56-
# Analyze to get a result ID
57-
poller = await client.begin_analyze_binary(
58-
analyzer_id="prebuilt-documentSearch", binary_input=file_bytes, content_type="application/pdf"
58+
# Analyze to get an operation ID
59+
analyze_operation = await client.begin_analyze(
60+
analyzer_id="prebuilt-invoice", inputs=[AnalyzeInput(data=file_bytes)]
5961
)
6062

61-
result = await poller.result()
63+
result: AnalyzeResult = await analyze_operation.result()
6264

6365
# Assertions for analysis
64-
assert poller is not None, "Analysis operation should not be null"
65-
assert poller.done(), "Operation should be completed"
66+
assert analyze_operation is not None, "Analysis operation should not be null"
67+
assert analyze_operation.done(), "Operation should be completed"
6668
assert result is not None, "Analysis result should not be null"
6769
print("[PASS] Analysis completed successfully")
6870

69-
# Extract operation ID from the poller
70-
# The operation ID is needed to delete the result
71-
operation_id = None
71+
# Get operation ID - this is needed to delete the result
72+
operation_id = analyze_operation.operation_id
73+
assert operation_id is not None, "Operation ID should not be null"
74+
assert isinstance(operation_id, str), "Operation ID should be a string"
75+
assert operation_id.strip(), "Operation ID should not be empty"
76+
print(f"[PASS] Operation ID extracted: {operation_id[:50]}...")
77+
78+
# Verify we have analysis content
79+
assert hasattr(result, "contents"), "Result should contain contents"
80+
contents = getattr(result, "contents", None)
81+
assert contents is not None, "Result contents should not be null"
82+
assert len(contents) > 0, "Result should have at least one content"
83+
print(f"[PASS] Analysis result contains {len(contents)} content item(s)")
84+
85+
# Delete the result
7286
try:
73-
# Extract operation ID from polling URL
74-
if hasattr(poller, "_polling_method"):
75-
polling_method = getattr(poller, "_polling_method", None)
76-
if polling_method and hasattr(polling_method, "_operation"):
77-
operation = getattr(polling_method, "_operation", None) # type: ignore
78-
if operation and hasattr(operation, "get_polling_url"):
79-
polling_url = operation.get_polling_url() # type: ignore
80-
# Extract operation ID from URL (last segment before query string)
81-
operation_id = polling_url.split("/")[-1]
82-
if "?" in operation_id:
83-
operation_id = operation_id.split("?")[0]
87+
await client.delete_result(operation_id=operation_id)
88+
print(f"[PASS] Result deleted successfully (operation ID: {operation_id[:50]}...)")
89+
print("[INFO] Deletion success verified by no exception thrown")
8490
except Exception as e:
85-
print(f"[WARN] Could not extract operation ID: {str(e)[:100]}")
86-
87-
# Assertion: Verify we have an operation ID
88-
if operation_id:
89-
assert operation_id is not None, "Operation ID should not be null"
90-
assert isinstance(operation_id, str), "Operation ID should be a string"
91-
assert operation_id.strip(), "Operation ID should not be empty"
92-
print(f"[PASS] Operation ID extracted: {operation_id[:50]}...")
93-
94-
# Delete the result
95-
try:
96-
await client.delete_result(operation_id=operation_id)
97-
print(f"[PASS] Result deleted successfully (operation ID: {operation_id[:50]}...)")
98-
print("[INFO] Deletion success verified by no exception thrown")
99-
except Exception as e:
100-
error_msg = str(e)
101-
# Some implementations might not support result deletion or result might auto-expire
102-
if "not found" in error_msg.lower() or "404" in error_msg:
103-
print(f"[INFO] Result already deleted or not found: {error_msg[:100]}")
104-
else:
105-
print(f"[WARN] Delete result failed: {error_msg[:100]}")
106-
else:
107-
print("[INFO] Operation ID not available in response")
108-
print("[INFO] Delete result operation skipped - operation ID extraction not supported")
91+
error_msg = str(e)
92+
# Some implementations might not support result deletion or result might auto-expire
93+
if "not found" in error_msg.lower() or "404" in error_msg:
94+
print(f"[INFO] Result already deleted or not found: {error_msg[:100]}")
95+
else:
96+
raise
10997

11098
await client.close()
11199
print("\n[SUCCESS] All test_sample_delete_result_async assertions passed")

0 commit comments

Comments
 (0)