Demo: Azure Implementation
PDF Layout Extraction with Azure AI Document Intelligence Supporting Multiple Document Versions with Visual Selection Cues (full-code approach)
Azure Storage + Document Intelligence + AI Vision + Azure Open AI (LLMs) + Function App + Cosmos DB
Costa Rica
Last updated: 2025-08-07
This solution is designed to be flexible and robust, supporting multiple versions of PDF documents with varying layouts, including those that use visual selection cues such as gray fills, hand-drawn Xs, checkmarks, or circles. By building on the PDFs-Layouts-Processing-Fapp-DocIntelligence repository, modular approach aiming to:
- Table structure and text are extracted using Azure Document Intelligence (Layout model).
- Visual selection cues are detected using Azure AI Vision or image preprocessing.
- Visual indicators are mapped to structured data, returning only the selected values in a clean JSON format.
- Advanced semantic understanding is provided by Azure OpenAI to analyze document content and context.
- Multiple file formats are supported, including PDFs and various image formats.
- The logic is abstracted to support multiple layout variations, so the system adapts easily to new document formats and selection styles.
Important
This example is based on a public network site and is intended for demonstration purposes only
. It showcases how several Azure resources can work together to achieve the desired result. Consider the section below about Important Considerations for Production Environment. Please note that these demos are intended as a guide and are based on my personal experiences. For official guidance, support, or more detailed information, please refer to Microsoft's official documentation or contact Microsoft directly
: Microsoft Sales and Support
List of References (Click to expand)
- Solution Accelerator for AI Document Processor (ADP) - AI Factory
Category | Details |
---|---|
Purpose | Automate document processing using Azure services and LLMs. Extracts data from files (PDF, Word, MP3), processes via Azure OpenAI, and outputs structured insights (JSON/CSV) to blob storage. |
Infrastructure Provisioning | Uses Bicep templates to deploy all required Azure resources. Automates setup of networking, identity, and access controls using RBAC and managed identities to ensure secure and scalable deployment. |
Main Azure Resources | - Azure Function App: Hosts the orchestrator and activity functions using Durable Functions to manage the document processing workflow. - Azure Storage Account: Stores input documents (bronze container) and output results (gold container). Also holds prompt configurations if UI is not deployed. - Azure Static Web App: Provides a user-friendly interface for uploading files, editing prompts, and triggering workflows. - Azure OpenAI: Processes extracted text using LLMs to generate structured summaries or insights. - Azure Cognitive Services: Specifically uses Document Intelligence for OCR and text extraction from uploaded files. - Cosmos DB: Stores prompt configurations when the frontend UI is enabled, allowing dynamic updates from the web interface. - Key Vault: Securely stores secrets, keys, and credentials used by the Function App and other services. - Application Insights: Enables monitoring, logging, and diagnostics for the Function App and other components. - App Service Plan: Provides the compute resources for running the Function App. |
Pipeline Components | - function_app.py : Main orchestrator using Durable Functions chaining pattern.- activities/runDocIntel.py : Extracts text from documents using Azure Document Intelligence.- activities/callAoai.py : Sends extracted text and prompt to Azure OpenAI and receives structured JSON.- activities/writeToBlob.py : Writes the final output to the gold container in blob storage. |
Data Flow | 1. Upload document to bronze container 2. OCR via Document Intelligence 3. Send extracted text + prompt to Azure OpenAI 4. Receive structured JSON 5. Write output to gold container |
Frontend UI (Optional) | - Allows business users to upload files and edit prompts - Prompts are stored in Cosmos DB - Users can trigger workflows and view job status directly from the interface |
Prompt Configuration | - Without UI: Prompts are stored in prompts.yaml file in blob storage- With UI: Prompts are stored and managed in Cosmos DB via the web interface |
Deployment Steps | 1. Fork and clone the GitHub repo 2. Run az login , azd auth login , azd up 3. Provide User Principal ID for RBAC setup 4. Choose whether to deploy frontend UI |
Execution (Without UI) | - Update prompts.yaml with desired instructions- Send POST request to http_start endpoint with blob metadata- Monitor pipeline execution via Log Stream |
Execution (With UI) | - Upload files via web interface - Edit system and user prompts - Click "Start Workflow" to trigger pipeline - View success/failure messages and job status |
Monitoring & Troubleshooting | - Use Log Stream for real-time logs - Use Log Analytics Workspace to query exceptions and performance metrics - Use SSH console in Development Tools to inspect deployment logs and file system |
Pre-Requisites | - Azure CLI - Azure Developer CLI (azd) - Node.js 18.x.x - npm 9.x.x - Python 3.11 |
License | MIT License – Free to use, modify, and distribute with attribution. No warranty provided. |
- Use Azure AI services with SynapseML in Microsoft Fabric
- Plan and manage costs for Azure AI Foundry
- Azure AI Document Intelligence documentation
- Get started with the Document Intelligence Sample Labeling tool
- Document Intelligence Sample Labeling tool
- Assign an Azure role for access to blob data
- Build and train a custom extraction model
- Compose custom models - Document Intelligence
- Deploy the Sample Labeling tool
- Train a custom model using the Sample Labeling tool
- Train models with the sample-labeling tool
- Azure Cosmos DB - Database for the AI Era
- Consistency levels in Azure Cosmos DB
- Azure Cosmos DB SQL API client library for Python
- CosmosClient class documentation
- Cosmos AAD Authentication
- Cosmos python examples
- Use control plane role-based access control with Azure Cosmos DB for NoSQL
- Use data plane role-based access control with Azure Cosmos DB for NoSQL
- Create or update Azure custom roles using Azure CLI
- Document Intelligence query field extraction
- What's new in Azure AI Document Intelligence
- Managed identities for Document Intelligence
Table of Content (Click to expand)
How can you extract layout, text, visual, and other elements
fromPDFs
stored in an Azure Storage Account, process them using Azure AI services, andstore the results
in Cosmos DB forfurther analysis?
This solution isdesigned to accelerate the process
of building your own implementation. Pleasefeel free to use any of the provided reference.
I'm happy to contribute. Once this solution is deployed:
- Upload your documents: Just
drop your PDFs or images into an Azure Storage container
and the system takes over from there.- Automated intelligent processing: Behind the scenes,
Azure Functions orchestrates a powerful AI workflow
:
- Document Intelligence pulls out tables, text, and form data
- AI Vision spots visual cues like checkmarks and highlights
- Azure OpenAI understands what the document actually means
- Centralized information management:
All extracted data is stored in Cosmos DB
, organized and accessible. The systemadapts to differents document layouts without requiring custom code for each format.
Note
Advantages of Document Intelligence for organizations handling with large volumes of documents:
- Utilizes natural language processing, computer vision, deep learning, and machine learning.
- Handles structured, semi-structured, and unstructured documents.
- Automates the extraction and transformation of layout data into usable formats like JSON or CSV.
Note
Azure Event Grid System Topics are free to create and manage, a System Topic is automatically created and managed by Azure for certain Azure services that emit events. It represents a source of events from an Azure resource (like a Storage Account, Key Vault, or Azure Maps). You don't need to create or manage the topic yourself, Azure does it for you when you enable event publishing on a supported resource.
- Emits predefined event types (e.g., Microsoft.Storage.BlobCreated, Microsoft.Resources.ResourceWriteSuccess).
- You can attach event handlers (like Azure Functions, Logic Apps, Webhooks) to respond to these events.
- Works seamlessly with serverless architectures for real-time automation.
For example: Suppose you have a Storage Account and want to trigger a function every time a new blob is uploaded: - Azure automatically creates a System Topic for the Storage Account.
- You subscribe to the BlobCreated event.
- When a blob is uploaded, Event Grid routes the event to your Azure Function.
Private Network Configuration
For enhanced security, consider configuring your Azure resources to operate within a private network. This can be achieved using Azure Virtual Network (VNet) to isolate your resources and control inbound and outbound traffic. Implementing private endpoints for services like Azure Blob Storage and Azure Functions can further secure your data by restricting access to your VNet.
Security
Ensure that you implement appropriate security measures when deploying this solution in a production environment. This includes:
- Securing Access: Use Azure Entra ID (formerly known as Azure Active Directory or Azure AD) for authentication and role-based access control (RBAC) to manage permissions.
- Managing Secrets: Store sensitive information such as connection strings and API keys in Azure Key Vault.
- Data Encryption: Enable encryption for data at rest and in transit to protect sensitive information.
Scalability
While this example provides a basic setup, you may need to scale the resources based on your specific requirements. Azure services offer various scaling options to handle increased workloads. Consider using:
- Auto-scaling: Configure auto-scaling for Azure Functions and other services to automatically adjust based on demand.
- Load Balancing: Use Azure Load Balancer or Application Gateway to distribute traffic and ensure high availability.
Cost Management
Monitor and manage the costs associated with your Azure resources. Use Azure Cost Management and Billing to track usage and optimize resource allocation.
Compliance
Ensure that your deployment complies with relevant regulations and standards. Use Azure Policy to enforce compliance and governance policies across your resources.
Disaster Recovery
Implement a disaster recovery plan to ensure business continuity in case of failures. Use Azure Site Recovery and backup solutions to protect your data and applications.
- An
Azure subscription is required
. All other resources, including instructions for creating a Resource Group, are provided in this workshop. Contributor role assigned or any custom role that allows
: access to manage all resources, and the ability to deploy resources within subscription.- If you choose to use the Terraform approach, please ensure that:
- Terraform is installed on your local machine.
- Install the Azure CLI to work with both Terraform and Azure commands.
- Please follow the Terraform guide to deploy the necessary Azure resources for the workshop.
- Next, as this method
skips the creation of each resource
manually. Proceed with the configuration from Configure/Validate the Environment variables.
Important
Regarding Networking
, this example will cover Public access configuration
, and system-managed identity
. However, please ensure you review your privacy requirements and adjust network and access settings as necessary for your specific case
.
Using Cosmos DB provides you with a flexible, scalable, and globally distributed database solution that can handle both structured and semi-structured data efficiently.
Azure Blob Storage
: Store the PDF invoices.Azure Functions
: Trigger on new PDF uploads, extract data, and process it.Azure SQL Database or Cosmos DB
: Store the extracted data for querying and analytics.
Resource | Recommendation |
---|---|
Azure Blob Storage | Use for storing the PDF files. This keeps your file storage separate from your data storage, which is a common best practice. |
Azure SQL Database | Use if your data is highly structured and you need complex queries and transactions. |
Azure Cosmos DB | Use if you need a globally distributed database with low latency and the ability to handle semi-structured data. |
In the context of Azure Function Apps, a
hosting option refers to the plan you choose to run your function app
. This choice affects how your function app is scaled, the resources available to each function app instance, and the support for advanced functionalities like virtual network connectivity and container support.
Tip
Scale to Zero
: Indicates whether the service can automatically scale down to zero instances when idle.- IDLE stands for:
- I – Inactive
- D – During
- L – Low
- E – Engagement
- In other words, when the application is not actively handling requests or events (it's in a low-activity or paused state).
- IDLE stands for:
Scale Behavior
: Describes how the service scales (e.g.,event-driven
,dedicated
, orcontainerized
).Virtual Networking
: Whether the service supports integration with virtual networks for secure communication.Dedicated Compute & Reserved Cold Start
: Availability of always-on compute to avoid cold starts and ensure low latency.Max Scale Out (Instances)
: Maximum number of instances the service can scale out to.Example AI Use Cases
: Real-world scenarios where each plan excels.
Flex Consumption
Feature | Description |
---|---|
Scale to Zero | Yes |
Scale Behavior | Fast event-driven |
Virtual Networking | Optional |
Dedicated Compute & Reserved Cold Start | Optional (Always Ready) |
Max Scale Out (Instances) | 1000 |
Example AI Use Cases | Real-time data processing for AI models, high-traffic AI-powered APIs , event-driven AI microservices . Ideal for fraud detection, real-time recommendations, NLP, and computer vision services. |
Consumption
Feature | Description |
---|---|
Scale to Zero | Yes |
Scale Behavior | Event-driven |
Virtual Networking | Optional |
Dedicated Compute & Reserved Cold Start | No |
Max Scale Out (Instances) | 200 |
Example AI Use Cases | Lightweight AI APIs , scheduled AI tasks , low-traffic AI event processing . Great for sentiment analysis, simple image recognition, and batch ML tasks. |
Functions Premium
Feature | Description |
---|---|
Scale to Zero | No |
Scale Behavior | Event-driven with premium options |
Virtual Networking | Yes |
Dedicated Compute & Reserved Cold Start | Yes |
Max Scale Out (Instances) | 100 |
Example AI Use Cases | Enterprise AI applications , low-latency AI APIs , VNet integration . Ideal for secure, high-performance AI services like customer support and analytics. |
App Service
Feature | Description |
---|---|
Scale to Zero | No |
Scale Behavior | Dedicated VMs |
Virtual Networking | Yes |
Dedicated Compute & Reserved Cold Start | Yes |
Max Scale Out (Instances) | Varies |
Example AI Use Cases | AI-powered web applications , dedicated resources . Great for chatbots, personalized content, and intensive AI inference. |
Container Apps Env.
Feature | Description |
---|---|
Scale to Zero | No |
Scale Behavior | Containerized microservices environment |
Virtual Networking | Yes |
Dedicated Compute & Reserved Cold Start | Yes |
Max Scale Out (Instances) | Varies |
Example AI Use Cases | AI microservices architecture , containerized AI workloads , complex AI workflows . Ideal for orchestrating AI services like image processing, text analysis, and real-time analytics. |
Important
All environment variable names must exactly match between
your Terraform deployment configuration
(in main.tf
) and your Function App environment settings
. Any mismatch will cause runtime failures when the application tries to access Azure resources.
Note
This example is using system-assigned managed identity to assign RBACs (Role-based Access Control).
-
Under
Settings
, go toEnvironment variables
. And+ Add
the following variables. For example: -
Click on
Apply
to save your configuration. -
Here are a few examples of how to get those values.
If a Terraform deployment template was used, these are linked automatically
, so please remember to review them.
These values depend on the specific you choose and deploy, like the AI models
, you can also adjustLLM_MAX_TOKENS
based on your model's capabilities andLLM_TEMPERATURE
based on your use case requirements.
FUNCTIONS_EXTENSION_VERSION
:~4
🡢Review the existence of this, if not create it
WEBSITE_RUN_FROM_PACKAGE
:1
🡢Review the existence of this, if not create it
FUNCTIONS_WORKER_RUNTIME
:python
🡢Review the existence of this, if not create it
FUNCTIONS_NODE_BLOCK_ON_ENTRY_POINT_ERROR
:true
(This setting ensures that all entry point errors are visible in your application insights logs) 🡢Review the existence of this, if not create it
COSMOS_DB_ENDPOINT
: Your Cosmos DB account endpoint 🡢Review the existence of this, if not create it
Click to see more
COSMOS_DB_KEY
: Your Cosmos DB account key 🡢Review the existence of this, if not create it
COSMOS_DB_CONNECTION_STRING
: Your Cosmos DB connection string 🡢Review the existence of this, if not create it
invoicecontosostorage_STORAGE
: Your Storage Account connection string 🡢Review the existence of this, if not create it
FORM_RECOGNIZER_ENDPOINT
: For example:https://<your-form-recognizer-endpoint>.cognitiveservices.azure.com/
🡢Review the existence of this, if not create it
FORM_RECOGNIZER_KEY
: Your Document Intelligence Key (Form Recognizer) 🡢Review the existence of this, if not create it
APPINSIGHTS_INSTRUMENTATIONKEY
: Your Application Insights instrumentation key 🡢Review the existence of this, if not create it
APPLICATIONINSIGHTS_CONNECTION_STRING
: Your Application Insights connection string 🡢Review the existence of this, if not create it
VISION_API_ENDPOINT
: Your Azure AI Vision endpoint for visual cue detection 🡢Review the existence of this, if not create it
VISION_API_KEY
: Your Azure AI Vision API key 🡢Review the existence of this, if not create it
VISION_API_VERSION
:2024-02-01
(Latest stable API version) 🡢Review the existence of this, if not create it
. These values depend on the specific you choose and deployAZURE_OPENAI_ENDPOINT
: Your Azure OpenAI service endpoint 🡢Review the existence of this, if not create it
AZURE_OPENAI_KEY
: Your Azure OpenAI API key 🡢Review the existence of this, if not create it
AZURE_OPENAI_API_VERSION
: e.g2025-04-14
🡢Review the existence of this, if not create it
. These values depend on the specific you choose and deployAZURE_OPENAI_GPT4_DEPLOYMENT
: Your e.g GPT-4 deployment name for complex reasoning and analysis 🡢Review the existence of this, if not create it
. These values depend on the specific you choose and deployAZURE_OPENAI_GPT4O_DEPLOYMENT
: Your e.g GPT-4o deployment name for advanced multimodal processing 🡢Review the existence of this, if not create it
. These values depend on the specific you choose and deployAZURE_OPENAI_EMBEDDING_DEPLOYMENT
: Your text embedding deployment name for semantic search 🡢Review the existence of this, if not create it
AI_HUB_NAME
: Your AI Studio Hub name for model management 🡢Review the existence of this, if not create it
AI_PROJECT_NAME
: Your AI Studio Project name 🡢Review the existence of this, if not create it
AI_HUB_WORKSPACE_URL
: Your AI Hub workspace URL 🡢Review the existence of this, if not create it
AI_PROJECT_WORKSPACE_URL
: Your AI Project workspace URL 🡢Review the existence of this, if not create it
AI_STORAGE_ACCOUNT_NAME
: Your AI storage account name for model artifacts 🡢Review the existence of this, if not create it
AI_STORAGE_CONNECTION
: Your AI storage connection string 🡢Review the existence of this, if not create it
ENABLE_LLM_PROCESSING
:true
(Enable LLM-powered PDF processing features) 🡢Review the existence of this, if not create it
LLM_MAX_TOKENS
:4000
(Maximum tokens per request - adjust based on your model choice) 🡢Review the existence of this, if not create it
LLM_TEMPERATURE
:0.1
(Low temperature for consistent extraction - adjust based on use case) 🡢Review the existence of this, if not create it
LLM_TIMEOUT_SECONDS
:120
(Timeout for LLM requests - may need adjustment depending on model response time) 🡢Review the existence of this, if not create it
-
You need to install VSCode
-
Install python from Microsoft store:
-
Open VSCode, and install some extensions:
python
, andAzure Tools
. -
Click on the
Azure
icon, andsign in
into your account. Allow the extensionAzure Resources
to sign in using Microsoft, it will open a browser window. After doing so, you will be able to see your subscription and resources. -
Under Workspace, click on
Create Function Project
, and choose a path in your local computer to develop your function. -
Choose the language, in this case is
python
: -
Select the model version, for this example let's use
v2
: -
For the python interpreter, let's use the one installed via
Microsoft Store
: -
Choose a template (e.g., Blob trigger) and configure it to trigger on new PDF uploads in your Blob container.
-
Provide a function name, like
BlobTriggerPDFsMultiLayoutsDocIntelligence
: -
Next, it will prompt you for the path of the blob container where you expect the function to be triggered after a file is uploaded. In this case is
pdfinvoices
as was previously created. -
Click on
Create new local app settings
, and then choose your subscription. -
Choose
Azure Storage Account for remote storage
, and select one. I'll be using theinvoicecontosostorage
. -
Then click on
Open in the current window
. You will see something like this: -
Now we need to update the function code to extract data from PDFs and store it in Cosmos DB, use this an example:
- PDF Upload: A PDF file is uploaded to the Azure Blob Storage container (
pdfinvoices
). - Trigger Azure Function: The upload triggers the Azure Function
BlobTriggerPDFsMultiLayoutsAIDocIntelligence
. - Initialize Clients: Sets up connections to Azure Document Intelligence, AI Vision, OpenAI, and Cosmos DB.
- Initializes the
DocumentAnalysisClient
using theFORM_RECOGNIZER_ENDPOINT
andFORM_RECOGNIZER_KEY
environment variables. - Initializes the
AzureOpenAI
client for LLM analysis using OpenAI deployment details. - Configures the Vision API for visual cue detection.
- Sets up the
CosmosClient
for data storage.
- Initializes the
- Read PDF from Blob Storage: Reads the PDF content from the blob into a byte stream.
- Analyze PDF: Uses Azure Document Intelligence to analyze the layout of the PDF.
- Calls
begin_analyze_document
with theprebuilt-layout
model. - Waits for the analysis to complete and retrieves the layout result.
- Calls
- Extract Layout Data: Parses and structures the layout data from the analysis result.
- Extracts lines, tables, and selection marks from each page.
- Identifies visual selection cues using AI Vision for enhanced form recognition.
- Logs styles (e.g., handwritten content) and organizes data into a structured dictionary.
- Enhance with AI Vision: Analyzes visual elements for additional insights.
- Detects and processes visual selection cues that Document Intelligence might miss.
- Combines visual analysis with document structure understanding.
- Apply LLM Analysis: Uses Azure OpenAI for semantic understanding of document content.
- Prepares structured content for the LLM with meaningful context.
- Analyzes content relationships and extracts high-level insights.
- Save Data to Cosmos DB: Saves the structured layout data to Cosmos DB.
- Ensures the database (
DocumentAnalysisDB
) and container (ProcessedDocuments
) exist or creates them. - Prepares document for storage with metadata and timestamps.
- Inserts or updates the layout data using
upsert_item
.
- Ensures the database (
- Logging (Process and Errors): Logs each step of the process, including success messages and detailed error handling for debugging and monitoring.
- Uses structured logging for better traceability.
- Includes processing time metrics for performance analysis.
- Provides comprehensive error handling with meaningful diagnostics.
-
Update the function_app.py, for example see the code used in this demo:
Template Blob Trigger Function Code updated -
Now, let's update the
requirements.txt
, see the code used in this demo:Template requirements.txt
Updated requirements.txt
-
Since this function has already been tested, you can deploy your code to the function app in your subscription. If you want to test, you can use run your function locally for testing.
- PDF Upload: A PDF file is uploaded to the Azure Blob Storage container (
Important
If you need further assistance with the code, please click here to view all the function code.
Note
Please ensure that all specified roles are assigned to the Function App. The provided example used System assigned
for the Function App to facilitate the role assignment.
Important
Please ensure that the user/system admin responsible for uploading the PDFs to the blob container has the necessary permissions. The error below illustrates what might occur if these roles are missing.
In that case, go to Access Control (IAM)
, click on + Add
, and Add role assignment
:
Search for Storage Blob Data Contributor
, click Next
.
Then, click on select members
and search for your user/systen admin. Finally click on Review + assign
.
Upload sample PDF invoices to the Blob container and verify that data is correctly ingested and stored in Cosmos DB.
-
Click on
Upload
, then selectBrowse for files
and choose your PDF invoices to be stored in the blob container, which will trigger the function app to parse them. -
Check the logs, and traces from your function with
Application Insights
: -
Under
Investigate
, click onPerformance
. Filter by time range, anddrill into the samples
. Sort the results by date (if you have many, like in my case) and click on the last one. -
Click on
View all
: -
Check all the logs, and traces generated. Also review the information parsed:
-
Validate that the information was uploaded to the Cosmos DB. Under
Data Explorer
, check yourDatabase
.