File size: 9,539 Bytes
1e9a6e5 b837da3 1e9a6e5 b837da3 1e9a6e5 b837da3 1e9a6e5 b837da3 1e9a6e5 b837da3 1e9a6e5 b837da3 1e9a6e5 b837da3 1e9a6e5 b837da3 1e9a6e5 b837da3 1e9a6e5 b837da3 cb40a1c b837da3 1e9a6e5 b837da3 1e9a6e5 b837da3 1e9a6e5 b837da3 1e9a6e5 b837da3 1e9a6e5 b837da3 1e9a6e5 b837da3 1e9a6e5 b837da3 1e9a6e5 b837da3 1e9a6e5 b837da3 1e9a6e5 b837da3 1e9a6e5 b837da3 1e9a6e5 b837da3 1e9a6e5 b837da3 1e9a6e5 b837da3 1e9a6e5 b837da3 1e9a6e5 b837da3 1e9a6e5 b837da3 1e9a6e5 b837da3 1e9a6e5 b837da3 1e9a6e5 b837da3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 | """
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 = "<table border='1'>\n"
for row in table_data["bodyRows"]:
html += " <tr>\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" <td{row_span}{col_span}>{text}</td>\n"
html += " </tr>\n"
html += "</table>"
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)
|