Datasets:

ArXiv:
License:
dp-bench / scripts /infer_aws.py
mer9ury
refactor: Sync evaluation pipeline, scripts, and docs from private repo
1e9a6e5
raw
history blame
14.9 kB
"""
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)