Read a document with Content Understanding in Fabric
On Fabric, ContentUnderstanding can analyze documents without an Azure resource endpoint or key. It uses the workspace's managed Content Understanding endpoint and the notebook's identity. This quickstart reads a generated PDF with prebuilt-read, saves the operation handle, and then polls for the result.
Setting an endpoint on the stage, or in AIDefaults().for_api("content_understanding"), switches to your own resource instead. Credentials need that endpoint. Without one, they fail before any request is sent.
Prerequisites
- A Fabric notebook with an attached lakehouse.
- A SynapseML version that includes keyless Content Understanding.
- Fabric-managed Content Understanding available for your capacity and region.
The managed endpoint supports analysis and polling. It doesn't support creating or reading analyzers, so this example uses prebuilt-read. For custom analyzers and field extraction, use your own Foundry resource as shown in the semantic quickstart. Analysis requests are billable.
import uuid
from synapse.ml.services.contentunderstanding import ContentUnderstanding
run_root = "Files/content-understanding/fabric-read-" + uuid.uuid4().hex[:12]
# No endpoint or credentials: on Fabric the stage uses the managed endpoint
# and the notebook's identity.
analyzer = (
ContentUnderstanding()
.setAnalyzerId("prebuilt-read")
.setDocumentBytesCol("body")
.setMimeType("application/pdf")
.setOutputCol("analysis")
.setErrorCol("error")
)
Create a sample PDF
The document is generated here, so it contains no customer data and needs no extra packages.
def example_pdf():
text = b"BT /F1 16 Tf 50 730 Td (SynapseML Content Understanding example) Tj ET"
objects = [
b"<< /Type /Catalog /Pages 2 0 R >>",
b"<< /Type /Pages /Kids [4 0 R] /Count 1 >>",
b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] "
b"/Resources << /Font << /F1 3 0 R >> >> /Contents 5 0 R >>",
f"<< /Length {len(text)} >>\nstream\n".encode("ascii") + text + b"\nendstream",
]
data = bytearray(b"%PDF-1.4\n")
offsets = [0]
for number, obj in enumerate(objects, 1):
offsets.append(len(data))
data.extend(f"{number} 0 obj\n".encode("ascii") + obj + b"\nendobj\n")
xref = len(data)
data.extend(f"xref\n0 {len(offsets)}\n0000000000 65535 f \n".encode("ascii"))
for offset in offsets[1:]:
data.extend(f"{offset:010d} 00000 n \n".encode("ascii"))
data.extend(
f"trailer\n<< /Size {len(offsets)} /Root 1 0 R >>\n"
f"startxref\n{xref}\n%%EOF\n".encode("ascii")
)
return data
documents = spark.createDataFrame(
[("synthetic-document-1", example_pdf())], "documentId string, body binary"
)
Submit and save the handle
Submit mode sends each document once and returns its operation handle. Save the handles before polling, so a lost session can resume from them without sending the documents again. Spark reruns the plan for every action, so write the output once and read it back. Keep the printed handles_path. You need it to recover.
handles_path = run_root + "/handles"
submitted = analyzer.copy().setOperationMode("submit").transform(documents)
submitted.drop("body").write.mode("errorifexists").parquet(handles_path)
print("Saved handles to", handles_path)
handles = spark.read.parquet(handles_path)
columns = ["documentId", "analysis.status", "analysis.operationLocation"]
handles.select(*columns).show(truncate=False)
Poll for the result
Poll mode sends only GET requests for the saved handles. This cell needs only handles_path. It reads the saved handles and writes the results next to them, at handles_path plus -results. Each run replaces those results. The saved handles don't change.
If a document is still running, run this cell again. If the session ends, start a new one and set handles_path to the printed path. Then run this cell and the next one. Don't rerun the submit cell, because it sends the documents again. Service handles expire after a while, so poll soon.
from synapse.ml.services.contentunderstanding import ContentUnderstanding
# After a lost session, set handles_path to the printed path before this cell.
results_path = handles_path.rstrip("/") + "-results"
handles = spark.read.parquet(handles_path)
pending = handles.where("analysis.operationLocation IS NOT NULL").select(
"documentId", "analysis.operationLocation"
)
poller = (
ContentUnderstanding()
.setOperationMode("poll")
.setOperationLocationCol("operationLocation")
.setOutputCol("result")
.setErrorCol("pollError")
)
# Overwrite replaces only earlier poll results. The saved handles don't change.
poller.transform(pending).write.mode("overwrite").parquet(results_path)
results = spark.read.parquet(results_path)
results.select("documentId", "result.status", "result.error").show(truncate=False)
completed = results.where("result.status = 'Succeeded'")
assert completed.count() == 1, "Check result.error, and poll running handles again."
completed.selectExpr(
"documentId",
"get_json_object(result.rawResponse, '$.result.contents[0].markdown') AS text",
).show(truncate=False)
The last cell reads saved results and doesn't call the service. To analyze many documents in one pass, use analyze mode with transform and a higher setConcurrency, and save the results before displaying them. The Content Understanding guide covers the options and recovery.