"""
Google Document AI layout inference.
Uses Google Cloud Document AI for document analysis.
"""
import asyncio
import io
import json
import os
from typing import Optional
import google
from google.api_core.client_options import ClientOptions
from google.cloud import documentai
from PIL import Image
from base import BaseInference, create_argument_parser, parse_args_with_extra
CATEGORY_MAP = {
"paragraph": "paragraph",
"footer": "footer",
"header": "header",
"heading-1": "heading1",
"heading-2": "heading1",
"heading-3": "heading1",
"table": "table",
"title": "heading1"
}
class GoogleInference(BaseInference):
"""Google Document AI layout inference."""
def __init__(
self,
save_path,
input_formats=None,
concurrent_limit=None,
sampling_rate=1.0,
request_timeout=600,
random_seed=None,
group_by_document=False,
file_ext_mapping=None
):
"""Initialize the GoogleInference class.
Args:
save_path (str): the json path to save the results
input_formats (list, optional): the supported file formats.
concurrent_limit (int, optional): maximum number of concurrent API requests
sampling_rate (float, optional): fraction of files to process (0.0-1.0)
request_timeout (float, optional): timeout in seconds for API requests
random_seed (int, optional): random seed for reproducible sampling
group_by_document (bool, optional): group per-page results into document-level
file_ext_mapping (str or dict, optional): file extension mapping for grouping
"""
super().__init__(
save_path,
input_formats,
concurrent_limit,
sampling_rate,
request_timeout,
random_seed,
group_by_document,
file_ext_mapping
)
self.project_id = os.getenv("GOOGLE_PROJECT_ID") or ""
self.processor_id = os.getenv("GOOGLE_PROCESSOR_ID") or ""
self.location = os.getenv("GOOGLE_LOCATION") or ""
self.endpoint = os.getenv("GOOGLE_ENDPOINT") or ""
if not all([self.project_id, self.processor_id, self.location, self.endpoint]):
raise ValueError("Please set the environment variables for Google Cloud")
self.processor_version = "rc"
@staticmethod
def convert_image_to_pdf_bytes(image_path: str) -> bytes:
"""Convert an image file to PDF bytes for Layout Parser compatibility.
Args:
image_path: Path to the image file
Returns:
PDF content as bytes
"""
with Image.open(image_path) as img:
# Convert to RGB if necessary (e.g., for RGBA or P mode images)
if img.mode in ('RGBA', 'P', 'LA'):
img = img.convert('RGB')
pdf_buffer = io.BytesIO()
img.save(pdf_buffer, format='PDF')
pdf_buffer.seek(0)
return pdf_buffer.read()
@staticmethod
def generate_html_table(table_data):
"""Generate HTML table from table data."""
html = "
\n"
for row in table_data["bodyRows"]:
html += " \n"
for cell in row["cells"]:
text = ""
if cell["blocks"]:
text = cell["blocks"][0].get("textBlock", {}).get("text", "")
row_span = f" rowspan='{cell['rowSpan']}'" if cell["rowSpan"] > 1 else ""
col_span = f" colspan='{cell['colSpan']}'" if cell["colSpan"] > 1 else ""
html += f" | {text} | \n"
html += "
\n"
html += "
"
return html
@staticmethod
def iterate_blocks(data):
"""Iterate through document blocks and extract content."""
block_sequence = []
def recurse_blocks(blocks):
for block in blocks:
block_id = block.get("blockId", "")
block_type = block.get("textBlock", {}).get("type", "")
block_text = block.get("textBlock", {}).get("text", "")
if block_type:
block_sequence.append((block_id, block_type, block_text))
block_table = block.get("tableBlock", {})
if block_table:
block_table_html = GoogleInference.generate_html_table(block_table)
block_sequence.append((block_id, "table", block_table_html))
if block.get("textBlock", {}).get("blocks", []):
recurse_blocks(block["textBlock"]["blocks"])
if "documentLayout" in data:
recurse_blocks(data["documentLayout"].get("blocks", []))
return block_sequence
def post_process(self, data):
"""Post-process Google Document AI API response to standard format."""
processed_dict = {}
for input_key in data.keys():
output_data = data[input_key]
processed_dict[input_key] = {"elements": []}
blocks = self.iterate_blocks(output_data)
id_counter = 0
for _, category, transcription in blocks:
category = CATEGORY_MAP.get(category, "paragraph")
data_dict = {
"coordinates": [{"x": 0, "y": 0}] * 4,
"category": category,
"id": id_counter,
"content": {
"text": transcription if category != "table" else "",
"html": transcription if category == "table" else "",
"markdown": ""
}
}
processed_dict[input_key]["elements"].append(data_dict)
id_counter += 1
return self._merge_processed_data(processed_dict)
def _process_document_layout_sample(self, file_path, mime_type, chunk_size=1000):
"""Process document with layout analysis."""
process_options = documentai.ProcessOptions(
layout_config=documentai.ProcessOptions.LayoutConfig(
chunking_config=documentai.ProcessOptions.LayoutConfig.ChunkingConfig(
chunk_size=chunk_size,
include_ancestor_headings=True,
)
)
)
document = self._process_document(file_path, mime_type, process_options=process_options)
return json.loads(google.cloud.documentai_v1.Document.to_json(document))
def _process_document(
self,
file_path,
mime_type: str,
process_options: Optional[documentai.ProcessOptions] = None,
) -> documentai.Document:
"""Process a single document."""
client = documentai.DocumentProcessorServiceClient(
client_options=ClientOptions(api_endpoint=self.endpoint)
)
# Convert image to PDF for Layout Parser compatibility
image_mime_types = ["image/jpeg", "image/png", "image/bmp", "image/tiff", "image/heic"]
if mime_type in image_mime_types:
file_content = self.convert_image_to_pdf_bytes(file_path)
mime_type = "application/pdf"
else:
with open(file_path, "rb") as f:
file_content = f.read()
name = client.processor_version_path(
self.project_id, self.location, self.processor_id, self.processor_version
)
request = documentai.ProcessRequest(
name=name,
raw_document=documentai.RawDocument(content=file_content, mime_type=mime_type),
process_options=process_options,
)
result = client.process_document(request=request)
return result.document
def _get_mime_type(self, filepath):
"""Get MIME type from file path."""
suffix = filepath.suffix.lower()
mime_types = {
".pdf": "application/pdf",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".png": "image/png",
".bmp": "image/bmp",
".tiff": "image/tiff",
".heic": "image/heic"
}
if suffix not in mime_types:
raise NotImplementedError(f"Unsupported file type: {suffix}")
return mime_types[suffix]
async def _call_api_async(self, filepath, *args, **kwargs):
"""Make the actual async API call for a file."""
mime_type = self._get_mime_type(filepath)
loop = asyncio.get_event_loop()
return await loop.run_in_executor(
None, self._process_document_layout_sample, filepath, mime_type
)
def _call_api_sync(self, filepath, *args, **kwargs):
"""Make the actual sync API call for a file."""
mime_type = self._get_mime_type(filepath)
return self._process_document_layout_sample(filepath, mime_type)
if __name__ == "__main__":
parser = create_argument_parser("Google Document AI layout inference")
args = parse_args_with_extra(parser)
google_inference = GoogleInference(
args.save_path,
input_formats=args.input_formats,
concurrent_limit=args.concurrent,
sampling_rate=args.sampling_rate,
request_timeout=args.request_timeout,
random_seed=args.random_seed,
group_by_document=args.group_by_document,
file_ext_mapping=args.file_ext_mapping
)
google_inference.infer(args.data_path)