File size: 14,871 Bytes
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 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 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 | """
AWS Textract document layout inference.
Uses AWS Textract API for document analysis.
"""
import asyncio
import os
import boto3
from base import BaseInference, create_argument_parser, parse_args_with_extra
CATEGORY_MAP = {
"LAYOUT_TEXT": "paragraph",
"LAYOUT_LIST": "list",
"LAYOUT_HEADER": "header",
"LAYOUT_FOOTER": "footer",
"LAYOUT_PAGE_NUMBER": "paragraph",
"LAYOUT_FIGURE": "figure",
"LAYOUT_TABLE": "table",
"LAYOUT_TITLE": "heading1",
"LAYOUT_SECTION_HEADER": "heading1",
"TABLE": "table"
}
class AWSInference(BaseInference):
"""AWS Textract document 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 AWSInference 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
)
AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID") or ""
AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY") or ""
AWS_REGION = os.getenv("AWS_REGION") or ""
AWS_S3_BUCKET_NAME = os.getenv("AWS_S3_BUCKET_NAME") or ""
if not all([AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION, AWS_S3_BUCKET_NAME]):
raise ValueError("Please set the environment variables for AWS")
self.client = boto3.client(
"textract",
region_name=AWS_REGION,
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY
)
self.s3 = boto3.resource(
"s3",
region_name=AWS_REGION,
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY
)
self.s3_bucket_name = AWS_S3_BUCKET_NAME
def _get_text(self, result, blocks_map):
"""Extract text from a block using its relationships."""
text = ""
if "Relationships" in result:
for relationship in result["Relationships"]:
if relationship["Type"] == "CHILD":
for child_id in relationship["Ids"]:
word = blocks_map[child_id]
if word["BlockType"] == "WORD":
text += " " + word["Text"]
return text[1:] if text else ""
def post_process(self, data):
"""Post-process AWS Textract API response to standard format."""
processed_dict = {}
for input_key in data.keys():
output_data = data[input_key]
# Normalize output_data to always be a list of pages
if isinstance(output_data, dict) and "Blocks" in output_data:
output_data = [output_data]
# Handle time_sec if present
time_sec = None
if isinstance(output_data, dict) and "time_sec" in output_data:
time_sec = output_data["time_sec"]
if "Blocks" in output_data:
output_data = [output_data]
elif isinstance(output_data.get("data"), list):
output_data = output_data["data"]
processed_dict[input_key] = {"elements": []}
if time_sec is not None:
processed_dict[input_key]["time_sec"] = time_sec
all_elems = {}
for page_data in output_data:
for elem in page_data["Blocks"]:
all_elems[elem["Id"]] = elem
for page_data in output_data:
for idx, elem in enumerate(page_data["Blocks"]):
if elem["BlockType"] == "LAYOUT_LIST":
continue
if "LAYOUT" in elem["BlockType"] and elem["BlockType"] != "LAYOUT_TABLE":
bbox = elem["Geometry"]["BoundingBox"]
x, y, w, h = bbox["Left"], bbox["Top"], bbox["Width"], bbox["Height"]
coord = [[x, y], [x + w, y], [x + w, y + h], [x, y + h]]
xy_coord = [{"x": x, "y": y} for x, y in coord]
category = CATEGORY_MAP.get(elem["BlockType"], "paragraph")
transcription = ""
if elem["BlockType"] not in ["LAYOUT_FIGURE", "LAYOUT_KEY_VALUE"]:
for item in all_elems[elem["Id"]].get("Relationships", []):
for id_ in item["Ids"]:
if all_elems[id_]["BlockType"] == "LINE":
transcription += all_elems[id_]["Text"] + "\n"
data_dict = {
"coordinates": xy_coord,
"category": category,
"id": idx,
"content": {"text": transcription, "html": "", "markdown": ""}
}
processed_dict[input_key]["elements"].append(data_dict)
elif elem["BlockType"] == "TABLE":
bbox = elem["Geometry"]["BoundingBox"]
x, y, w, h = bbox["Left"], bbox["Top"], bbox["Width"], bbox["Height"]
coord = [[x, y], [x + w, y], [x + w, y + h], [x, y + h]]
xy_coord = [{"x": x, "y": y} for x, y in coord]
category = CATEGORY_MAP.get(elem["BlockType"], "paragraph")
table_cells = {}
for relationship in elem["Relationships"]:
if relationship["Type"] == "CHILD":
for cell_id in relationship["Ids"]:
cell_block = next((b for b in page_data["Blocks"] if b["Id"] == cell_id), None)
if cell_block and cell_block["BlockType"] == "CELL":
row_index = cell_block["RowIndex"] - 1
column_index = cell_block["ColumnIndex"] - 1
table_cells[(row_index, column_index)] = {
"block": cell_block,
"span": (cell_block["RowSpan"], cell_block["ColumnSpan"]),
"text": self._get_text(cell_block, all_elems),
}
if not table_cells:
continue
max_row = max(c[0] for c in table_cells.keys())
max_col = max(c[1] for c in table_cells.keys())
for relationship in elem["Relationships"]:
if relationship["Type"] == "MERGED_CELL":
for cell_id in relationship["Ids"]:
cell_block = next((b for b in page_data["Blocks"] if b["Id"] == cell_id), None)
if cell_block and cell_block["BlockType"] == "MERGED_CELL":
row_index = cell_block["RowIndex"] - 1
column_index = cell_block["ColumnIndex"] - 1
row_span = cell_block["RowSpan"]
column_span = cell_block["ColumnSpan"]
for i in range(row_span):
for j in range(column_span):
table_cells.pop((row_index + i, column_index + j), None)
text = ""
for child_ids in cell_block.get("Relationships", [{}])[0].get("Ids", []):
child_cell = next((b for b in page_data["Blocks"] if b["Id"] == child_ids), None)
text += " " + self._get_text(child_cell, all_elems) if child_cell else ""
table_cells[(row_index, column_index)] = {
"block": cell_block,
"span": (row_span, column_span),
"text": text[1:] if text else "",
}
html_table = "<table>"
for row_index in range(max_row + 1):
html_table += "<tr>"
for column_index in range(max_col + 1):
cell_data = table_cells.get((row_index, column_index))
if cell_data:
row_span, column_span = cell_data["span"]
html_table += f"<td rowspan='{row_span}' colspan='{column_span}'>{cell_data['text']}</td>"
html_table += "</tr>"
html_table += "</table>"
data_dict = {
"coordinates": xy_coord,
"category": category,
"id": idx,
"content": {"text": "", "html": html_table, "markdown": ""}
}
processed_dict[input_key]["elements"].append(data_dict)
return self._merge_processed_data(processed_dict)
def _start_job(self, object_name):
"""Start a Textract job for PDF processing."""
import time
filename_with_ext = os.path.basename(object_name)
print(f"uploading {filename_with_ext} to s3")
self.s3.Bucket(self.s3_bucket_name).upload_file(object_name, filename_with_ext)
response = self.client.start_document_analysis(
DocumentLocation={
"S3Object": {"Bucket": self.s3_bucket_name, "Name": filename_with_ext}
},
FeatureTypes=["LAYOUT", "TABLES"]
)
return response["JobId"]
def _is_job_complete(self, job_id):
"""Check if Textract job is complete."""
import time
time.sleep(1)
response = self.client.get_document_analysis(JobId=job_id)
status = response["JobStatus"]
print(f"Job status: {status}")
while status == "IN_PROGRESS":
time.sleep(1)
response = self.client.get_document_analysis(JobId=job_id)
status = response["JobStatus"]
print(f"Job status: {status}")
return status
def _get_job_results(self, job_id):
"""Get all pages of Textract job results."""
import time
pages = []
time.sleep(1)
response = self.client.get_document_analysis(JobId=job_id)
pages.append(response)
print(f"Resultset page received: {len(pages)}")
next_token = response.get("NextToken")
while next_token:
time.sleep(1)
response = self.client.get_document_analysis(JobId=job_id, NextToken=next_token)
pages.append(response)
print(f"Resultset page received: {len(pages)}")
next_token = response.get("NextToken")
return pages
async def _call_api_async(self, filepath, *args, **kwargs):
"""Make the actual async API call for a file."""
loop = asyncio.get_event_loop()
if filepath.suffix.lower() == ".pdf":
job_id = await loop.run_in_executor(None, self._start_job, str(filepath))
print(f"Started job with id: {job_id}")
status = await loop.run_in_executor(None, self._is_job_complete, job_id)
if status == "SUCCEEDED":
result = await loop.run_in_executor(None, self._get_job_results, job_id)
else:
raise Exception(f"Job {job_id} failed with status: {status}")
else:
with open(filepath, "rb") as file:
img_test = file.read()
bytes_test = bytearray(img_test)
result = await loop.run_in_executor(
None,
lambda: self.client.analyze_document(
Document={"Bytes": bytes_test},
FeatureTypes=["LAYOUT", "TABLES"]
)
)
return result
def _call_api_sync(self, filepath, *args, **kwargs):
"""Make the actual sync API call for a file."""
if filepath.suffix.lower() == ".pdf":
job_id = self._start_job(str(filepath))
print(f"Started job with id: {job_id}")
status = self._is_job_complete(job_id)
if status == "SUCCEEDED":
result = self._get_job_results(job_id)
else:
raise Exception(f"Job {job_id} failed with status: {status}")
else:
with open(filepath, "rb") as file:
bytes_test = bytearray(file.read())
result = self.client.analyze_document(
Document={"Bytes": bytes_test},
FeatureTypes=["LAYOUT", "TABLES"]
)
return result
if __name__ == "__main__":
parser = create_argument_parser("AWS Textract document layout inference")
args = parse_args_with_extra(parser)
aws_inference = AWSInference(
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
)
aws_inference.infer(args.data_path)
|