Datasets:
Size:
1M<n<10M
ArXiv:
Tags:
Document_Understanding
Document_Packet_Splitting
Document_Comprehension
Document_Classification
Document_Recognition
Document_Segmentation
DOI:
License:
Release dataset generator
Browse filesFiles changed (27)
- notebooks/01_create_assets.ipynbAdded+131
- notebooks/02_create_benchmarks.ipynbAdded+226
- notebooks/03_analyze_benchmarks.ipynbAdded+321
- src/assets/__init__.pyAdded+2
- src/assets/models.pyAdded+14
- src/assets/run.pyAdded+123
- src/assets/services/__init__.pyAdded+2
- src/assets/services/asset_creator.pyAdded+114
- src/assets/services/asset_writer.pyAdded+63
- src/assets/services/deepseek_ocr.pyAdded+151
- src/assets/services/pdf_loader.pyAdded+131
- src/assets/services/textract_ocr.pyAdded+51
- src/benchmarks/__init__.pyAdded+2
- src/benchmarks/models.pyAdded+61
- src/benchmarks/run.pyAdded+148
- src/benchmarks/services/__init__.pyAdded+2
- src/benchmarks/services/asset_loader.pyAdded+117
- src/benchmarks/services/benchmark_generator.pyAdded+77
- src/benchmarks/services/benchmark_writer.pyAdded+177
- src/benchmarks/services/shuffle_strategies/__init__.pyAdded+25
- src/benchmarks/services/shuffle_strategies/base_strategy.pyAdded+90
- src/benchmarks/services/shuffle_strategies/mono_rand.pyAdded+89
- src/benchmarks/services/shuffle_strategies/mono_seq.pyAdded+93
- src/benchmarks/services/shuffle_strategies/poly_int.pyAdded+111
- src/benchmarks/services/shuffle_strategies/poly_rand.pyAdded+111
- src/benchmarks/services/shuffle_strategies/poly_seq.pyAdded+94
- src/benchmarks/services/split_manager.pyAdded+110
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Step 1: Create Assets from Raw PDFs\n", "\n", "This notebook processes raw PDFs and creates structured assets:\n", "- Page images (PNG at 300 DPI)\n", "- OCR text (AWS Textract)\n", "\n", "**Output**: Structured assets for benchmark creation" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import sys\n", "sys.path.append(\"../src/assets\")\n", "\n", "from services.pdf_loader import PdfLoader\n", "from services.textract_ocr import TextractOcr\n", "from services.asset_writer import AssetWriter\n", "from services.asset_creator import AssetCreator" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Configuration" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "RAW_DATA_PATH = '../data/raw_pdfs'\n", "OUTPUT_PATH = '../data/assets'\n", "WORKERS = 10\n", "LIMIT = None # Set to number to limit processing" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Load PDFs" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "loader = PdfLoader(raw_data_path=RAW_DATA_PATH)\n", "documents = loader.get_all_documents()\n", "\n", "print(f\"Loaded {len(documents)} documents\")\n", "print(f\"Sample: {documents[0]}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Create Assets" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ocr = TextractOcr()\n", "writer = AssetWriter(output_base_path=OUTPUT_PATH)\n", "creator = AssetCreator(writer, ocr)\n", "\n", "results = creator.create_all(\n", " documents=documents,\n", " workers=WORKERS,\n", " limit=LIMIT\n", ")\n", "\n", "print(f\"\\nResults: {results}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Save Document Mapping (Optional)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "loader.save_document_mapping(\n", " documents,\n", " output_path='../data/document_mapping.csv'\n", ")\n", "\n", "print(\"Document mapping saved!\")" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.8.0" } }, "nbformat": 4, "nbformat_minor": 4}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Step 2: Create Benchmarks from Assets\n", "\n", "This notebook generates document splitting benchmarks using all strategies.\n", "\n", "**Prerequisites**: Assets created from notebook 01\n", "\n", "**Output**: Benchmark datasets with ground truth for train/test/validation splits" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import sys\n", "sys.path.append('../src/benchmarks')\n", "\n", "from services.asset_loader import AssetLoader\n", "from services.split_manager import SplitManager\n", "from services.benchmark_generator import BenchmarkGenerator\n", "from services.benchmark_writer import BenchmarkWriter\n", "from services.shuffle_strategies import get_strategy, STRATEGIES" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Configuration" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ASSETS_PATH = '../data/assets'\n", "OUTPUT_PATH = '../data/benchmarks'\n", "SPLIT_MAPPING_PATH = '../data/metadata/split_mapping.json'\n", "\n", "# Number of spliced documents per split\n", "NUM_TRAIN = 800\n", "NUM_TEST = 200\n", "NUM_VAL = 500\n", "\n", "# Size: small (5-20 pages) or large (20-500 pages)\n", "SIZE = 'small'\n", "MIN_PAGES = 5 if SIZE == 'small' else 20\n", "MAX_PAGES = 20 if SIZE == 'small' else 500\n", "\n", "RANDOM_SEED = 42\n", "\n", "print(f\"Configuration:\")\n", "print(f\" Size: {SIZE} ({MIN_PAGES}-{MAX_PAGES} pages)\")\n", "print(f\" Train: {NUM_TRAIN}, Test: {NUM_TEST}, Val: {NUM_VAL}\")\n", "print(f\" Strategies: {list(STRATEGIES.keys())}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Load Assets" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "loader = AssetLoader(assets_path=ASSETS_PATH)\n", "documents_by_type = loader.load_all_documents()\n", "\n", "print(f\"Loaded {loader.total_documents} documents across {len(documents_by_type)} types\")\n", "for doc_type, docs in documents_by_type.items():\n", " print(f\" {doc_type}: {len(docs)} documents\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Create Train/Test/Validation Split" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "split_manager = SplitManager(random_seed=RANDOM_SEED)\n", "splits = split_manager.create_split(documents_by_type)\n", "\n", "# Save split mapping\n", "split_manager.save_split(splits, SPLIT_MAPPING_PATH)\n", "\n", "print(f\"\\nSplit statistics:\")\n", "for split_name in ['train', 'test', 'validation']:\n", " total = sum(len(docs) for docs in splits[split_name].values())\n", " print(f\" {split_name}: {total} documents\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Generate All Benchmarks" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "all_strategies = ['mono_seq', 'mono_rand', 'poly_seq', 'poly_int', 'poly_rand']\n", "\n", "for strategy_name in all_strategies:\n", " print(f\"\\n{'='*60}\")\n", " print(f\"Processing strategy: {strategy_name}\")\n", " print(f\"{'='*60}\")\n", " \n", " # Initialize strategy\n", " strategy = get_strategy(\n", " strategy_name,\n", " min_pages=MIN_PAGES,\n", " max_pages=MAX_PAGES,\n", " random_seed=RANDOM_SEED\n", " )\n", " \n", " generator = BenchmarkGenerator(strategy=strategy)\n", " output_path = f'{OUTPUT_PATH}/{strategy_name}/{SIZE}'\n", " writer = BenchmarkWriter(output_base_path=output_path, assets_path=ASSETS_PATH)\n", " \n", " # Generate train\n", " print(f\"Generating train...\")\n", " train_benchmark = generator.generate_for_split(\n", " documents_by_type=documents_by_type,\n", " doc_names_for_split=splits['train'],\n", " num_spliced_docs=NUM_TRAIN,\n", " split_name='train',\n", " benchmark_name=strategy_name\n", " )\n", " writer.save_benchmark_set(train_benchmark, 'train')\n", " \n", " # Generate test\n", " print(f\"Generating test...\")\n", " test_benchmark = generator.generate_for_split(\n", " documents_by_type=documents_by_type,\n", " doc_names_for_split=splits['test'],\n", " num_spliced_docs=NUM_TEST,\n", " split_name='test',\n", " benchmark_name=strategy_name\n", " )\n", " writer.save_benchmark_set(test_benchmark, 'test')\n", " \n", " # Generate validation\n", " print(f\"Generating validation...\")\n", " val_benchmark = generator.generate_for_split(\n", " documents_by_type=documents_by_type,\n", " doc_names_for_split=splits['validation'],\n", " num_spliced_docs=NUM_VAL,\n", " split_name='validation',\n", " benchmark_name=strategy_name\n", " )\n", " writer.save_benchmark_set(val_benchmark, 'validation')\n", " \n", " print(f\"✅ Completed {strategy_name}\")\n", "\n", "print(f\"\\n{'='*60}\")\n", "print(f\"✅ All benchmarks generated!\")\n", "print(f\"{'='*60}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Summary" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(f\"\\n✅ Benchmark creation complete!\")\n", "print(f\"\\nOutput structure:\")\n", "for strategy_name in all_strategies:\n", " print(f\"\\n{OUTPUT_PATH}/{strategy_name}/{SIZE}/\")\n", " print(f\" ├── train.csv ({NUM_TRAIN} documents)\")\n", " print(f\" ├── test.csv ({NUM_TEST} documents)\")\n", " print(f\" ├── validation.csv ({NUM_VAL} documents)\")\n", " print(f\" └── ground_truth_json/\")\n", " print(f\" ├── train/ (JSON per document)\")\n", " print(f\" ├── test/ (JSON per document)\")\n", " print(f\" └── validation/ (JSON per document)\")\n", "print(f\"\\nSplit mapping: {SPLIT_MAPPING_PATH}\")" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.8.0" } }, "nbformat": 4, "nbformat_minor": 4}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Step 3: Analyze Benchmarks\n", "\n", "This notebook analyzes generated benchmarks:\n", "- Load and inspect benchmark CSV and ground truth JSON\n", "- Visualize statistics\n", "- Validate ground truth consistency\n", "\n", "**Prerequisites**: Benchmarks created from notebook 02" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import json\n", "import os\n", "from PIL import Image\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "from pathlib import Path\n", "from collections import Counter\n", "from datasets import load_dataset" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Configuration" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "STRATEGY = 'poly_seq' # mono_seq, mono_rand, poly_seq, poly_int, poly_rand\n", "SIZE = 'small' # small or large\n", "SPLIT = 'train' # train, test, or validation\n", "\n", "BENCHMARK_PATH = f'../data/benchmarks/{STRATEGY}/{SIZE}'\n", "CSV_FILE = f'{BENCHMARK_PATH}/{SPLIT}.csv'\n", "JSON_DIR = f'{BENCHMARK_PATH}/ground_truth_json/{SPLIT}'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Load CSV Benchmark" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Load dataset using HuggingFace datasets library\n", "dataset = load_dataset('csv', data_files=CSV_FILE)['train']\n", "\n", "print(f\"Loaded {len(dataset)} rows from {CSV_FILE}\")\n", "print(f\"\\nColumns: {dataset.column_names}\")\n", "print(\"\\nFirst 5 rows:\")\n", "# Display first 5 rows\n", "for i in range(min(5, len(dataset))):\n", " print(dataset[i])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Basic Statistics" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Count unique parent documents\n", "unique_parents = set(dataset['parent_doc_name'])\n", "num_parent_docs = len(unique_parents)\n", "total_pages = len(dataset)\n", "unique_doc_types = set(dataset['doc_type'])\n", "num_doc_types = len(unique_doc_types)\n", "\n", "print(\"📊 Benchmark Statistics\")\n", "print(\"=\"*50)\n", "print(f\"Strategy: {STRATEGY}\")\n", "print(f\"Size: {SIZE}\")\n", "print(f\"Split: {SPLIT}\")\n", "print(f\"\\nTotal parent documents: {num_parent_docs}\")\n", "print(f\"Total pages: {total_pages}\")\n", "print(f\"Unique document types: {num_doc_types}\")\n", "print(f\"Average pages per document: {total_pages / num_parent_docs:.2f}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Pages per Parent Document" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Group by parent_doc_name and count pages\n", "\n", "pages_per_doc = Counter(dataset['parent_doc_name'])\n", "pages_counts = list(pages_per_doc.values())\n", "\n", "plt.figure(figsize=(10, 6))\n", "plt.hist(pages_counts, bins=30, edgecolor='black')\n", "plt.xlabel('Total Pages')\n", "plt.ylabel('Frequency')\n", "plt.title(f'Distribution of Pages per Parent Document ({STRATEGY}/{SIZE}/{SPLIT})')\n", "plt.grid(axis='y', alpha=0.3)\n", "plt.show()\n", "\n", "print(\"\\nPages per document statistics:\")\n", "\n", "print(f\"count {len(pages_counts)}\")\n", "print(f\"mean {np.mean(pages_counts):.6f}\")\n", "print(f\"std {np.std(pages_counts):.6f}\")\n", "print(f\"min {np.min(pages_counts):.6f}\")\n", "print(f\"25% {np.percentile(pages_counts, 25):.6f}\")\n", "print(f\"50% {np.percentile(pages_counts, 50):.6f}\")\n", "print(f\"75% {np.percentile(pages_counts, 75):.6f}\")\n", "print(f\"max {np.max(pages_counts):.6f}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Document Type Distribution" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Count document types\n", "type_counts = Counter(dataset['doc_type'])\n", "\n", "plt.figure(figsize=(12, 6))\n", "plt.bar(type_counts.keys(), type_counts.values(), edgecolor='black')\n", "plt.xlabel('Document Type')\n", "plt.ylabel('Number of Pages')\n", "plt.title(f'Document Type Distribution ({STRATEGY}/{SIZE}/{SPLIT})')\n", "plt.xticks(rotation=45, ha='right')\n", "plt.grid(axis='y', alpha=0.3)\n", "plt.tight_layout()\n", "plt.show()\n", "\n", "print(\"\\nDocument type page counts:\")\n", "for doc_type, count in sorted(type_counts.items(), key=lambda x: x[1], reverse=True):\n", " print(f\" {doc_type}: {count} pages\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Inspect Sample Parent Document" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Get first parent document\n", "sample_parent = dataset['parent_doc_name'][0]\n", "# Filter dataset for this parent\n", "sample_indices = [i for i, parent in enumerate(dataset['parent_doc_name']) if parent == sample_parent]\n", "sample_data = dataset.select(sample_indices)\n", "\n", "print(f\"Parent Document: {sample_parent}\")\n", "print(f\"Total Pages: {len(sample_data)}\")\n", "print(\"\\nSubdocuments (by group_id):\")\n", "unique_groups = set(sample_data['group_id'])\n", "for group_id in sorted(unique_groups):\n", " group_indices = [i for i, g in enumerate(sample_data['group_id']) if g == group_id]\n", " group_data = sample_data.select(group_indices)\n", " doc_type = group_data['doc_type'][0]\n", " original_doc = group_data['original_doc_name'][0]\n", " pages = group_data['page']\n", " print(f\" {group_id}: {doc_type}/{original_doc} - Pages: {pages[:5]}{'...' if len(pages) > 5 else ''}\")\n", "\n", "print(\"\\nFirst 10 pages:\")\n", "for i in range(min(10, len(sample_data))):\n", " row = sample_data[i]\n", " print(f\" Page {row['page']}: {row['doc_type']}/{row['original_doc_name']} (group: {row['group_id']}, ordinal: {row['local_doc_id_page_ordinal']})\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## View Sample Images" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Display all pages vertically (scrollable)\n", "for i in range(len(sample_data)):\n", " row = sample_data[i]\n", " img_path = f\"../{row['image_path']}\"\n", " \n", " if os.path.exists(img_path):\n", " img = Image.open(img_path)\n", " \n", " plt.figure(figsize=(8, 10))\n", " plt.imshow(img)\n", " plt.title(f\"Page {row['page']} | {row['doc_type']} | Group: {row['group_id']}\", fontsize=12)\n", " plt.axis('off')\n", " plt.tight_layout()\n", " plt.show()\n", " \n", " print(f\"Page {row['page']}: {row['original_doc_name']}\")\n", " print(f\"Group: {row['group_id']} | Ordinal: {row['local_doc_id_page_ordinal']}\")\n", " print(\"-\" * 80)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Load and Inspect Ground Truth JSON" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Load ground truth JSON for sample parent document\n", "json_file = f'{JSON_DIR}/{sample_parent}.json'\n", "\n", "with open(json_file, 'r') as f:\n", " gt_json = json.load(f)\n", "\n", "print(f\"Ground Truth JSON for: {gt_json['doc_id']}\")\n", "print(f\"Total Pages: {gt_json['total_pages']}\")\n", "print(f\"Number of Subdocuments: {len(gt_json['subdocuments'])}\")\n", "print(f\"\\nFull JSON structure:\")\n", "print(json.dumps(gt_json, indent=2))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Summary" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"\\n📊 Final Summary\")\n", "print(\"=\"*50)\n", "print(f\"Strategy: {STRATEGY}\")\n", "print(f\"Size: {SIZE}\")\n", "print(f\"Split: {SPLIT}\")\n", "print(f\"\\nParent documents: {num_parent_docs}\")\n", "print(f\"Total pages: {total_pages}\")\n", "print(f\"Unique document types: {num_doc_types}\")\n", "print(f\"\\nAverage pages per document: {total_pages / num_parent_docs:.2f}\")" ] } ], "metadata": { "kernelspec": { "display_name": "idplabs", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.11" } }, "nbformat": 4, "nbformat_minor": 4}12# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.# SPDX-License-Identifier: CC-BY-NC-4.01234567891011121314# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.# SPDX-License-Identifier: CC-BY-NC-4.0
from pydantic import BaseModel, Field
class Document(BaseModel): """Represents a document in the dataset."""
doc_type: str = Field(..., description="Document category/type") doc_name: str = Field(..., description="Unique document identifier") filename: str = Field(..., description="PDF filename") absolute_filepath: str = Field(..., description="Full path to PDF file") page_count: int = Field(..., gt=0, description="Number of pages in document")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.# SPDX-License-Identifier: CC-BY-NC-4.0
"""Create Assets from Raw PDFs
Processes raw PDFs and creates structured assets:- Page images (PNG at 300 DPI)- OCR text (AWS Textract)
Usage: python main.py python main.py --workers 20 --limit 100"""import osimport argparsefrom loguru import logger
from services.pdf_loader import PdfLoaderfrom services.textract_ocr import TextractOcrfrom services.deepseek_ocr import DeepSeekOcrfrom services.asset_writer import AssetWriterfrom services.asset_creator import AssetCreator
def main(): parser = argparse.ArgumentParser(description='Create assets from raw PDFs') parser.add_argument('--raw-data-path', default='../raw_data') parser.add_argument('--output-path', default='../processed_assets') parser.add_argument('--metadata-path', default='../metadata') parser.add_argument('--workers', type=int, default=10) parser.add_argument('--limit', type=int, default=None) parser.add_argument('--save-mapping', action='store_true') parser.add_argument('--use-deepseek-for-language', action='store_true', help='Use DeepSeek OCR for language docs (default: Textract)') parser.add_argument('--s3-bucket', default=os.getenv('DOCSPLIT_S3_BUCKET'), help='S3 bucket for Textract temporary uploads') parser.add_argument('--s3-prefix', default='textract-temp', help='S3 prefix for uploads')
args = parser.parse_args()
logger.info("Creating assets from PDFs")
# Load all PDFs loader = PdfLoader(raw_data_path=args.raw_data_path) documents = loader.get_all_documents()
successful_docs = []
if args.use_deepseek_for_language: # Separate language documents for DeepSeek processing language_docs = [doc for doc in documents if doc.doc_type == 'language'] other_docs = [doc for doc in documents if doc.doc_type != 'language']
# Process non-language documents with Textract if other_docs: logger.info(f"Processing {len(other_docs)} non-language documents with Textract") ocr = TextractOcr(s3_bucket=args.s3_bucket, s3_prefix=args.s3_prefix) writer = AssetWriter(output_base_path=args.output_path) creator = AssetCreator(writer, ocr)
results = creator.create_all( documents=other_docs, workers=args.workers, limit=args.limit )
logger.info(f"Textract completed: {results}") if results['failed'] > 0: logger.warning(f"Textract failed: {results['failed_docs']}")
failed_names = set(results['failed_docs']) successful_docs.extend([doc for doc in other_docs if doc.doc_name not in failed_names])
# Process language documents with DeepSeek if language_docs: logger.info(f"Processing {len(language_docs)} language documents with DeepSeek OCR") try: deepseek_ocr = DeepSeekOcr() writer = AssetWriter(output_base_path=args.output_path) creator = AssetCreator(writer, deepseek_ocr)
results = creator.create_all( documents=language_docs, workers=args.workers, limit=args.limit )
logger.info(f"DeepSeek completed: {results}") if results['failed'] > 0: logger.warning(f"DeepSeek failed: {results['failed_docs']}")
failed_names = set(results['failed_docs']) successful_docs.extend([doc for doc in language_docs if doc.doc_name not in failed_names]) except Exception as e: logger.error(f"DeepSeek OCR initialization failed: {e}") else: # Process ALL documents with Textract logger.info(f"Processing {len(documents)} documents with Textract") ocr = TextractOcr(s3_bucket=args.s3_bucket, s3_prefix=args.s3_prefix) writer = AssetWriter(output_base_path=args.output_path) creator = AssetCreator(writer, ocr)
results = creator.create_all( documents=documents, workers=args.workers, limit=args.limit )
logger.info(f"Textract completed: {results}") if results['failed'] > 0: logger.warning(f"Textract failed: {results['failed_docs']}")
failed_names = set(results['failed_docs']) successful_docs.extend([doc for doc in documents if doc.doc_name not in failed_names])
# Save mapping AFTER processing with only successful documents if args.save_mapping: mapping_path = f"{args.metadata_path}/document_mapping.csv" loader.save_document_mapping(successful_docs, output_path=mapping_path) logger.info(f"Saved mapping for {len(successful_docs)} successful documents")
if __name__ == '__main__': main()12# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.# SPDX-License-Identifier: CC-BY-NC-4.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.# SPDX-License-Identifier: CC-BY-NC-4.0
import osfrom concurrent.futures import ThreadPoolExecutor, as_completedfrom typing import List, Optionalfrom loguru import loggerfrom tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type
from models import Documentfrom services.textract_ocr import TextractOcrfrom services.deepseek_ocr import DeepSeekOcrfrom services.asset_writer import AssetWriter
class AssetCreator: """Creates assets from PDFs: extracts images and OCR text."""
def __init__(self, writer: AssetWriter, ocr): """Initialize AssetCreator. Args: writer: AssetWriter instance ocr: OCR service (TextractOcr or DeepSeekOcr) """ self.writer = writer self.ocr = ocr self.is_deepseek = isinstance(ocr, DeepSeekOcr)
@retry( stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10), retry=retry_if_exception_type((Exception,)), reraise=True, ) def create_assets(self, doc: Document) -> None: """Create assets for a single document with retry logic.""" try: logger.trace(f"Processing: {doc.doc_name}") # Read PDF with open(doc.absolute_filepath, 'rb') as f: pdf_bytes = f.read() # Extract text via OCR if self.is_deepseek: # DeepSeek needs images, extract them first from src.idp_labs.core.util.pdf_util import PdfUtil images = PdfUtil.get_pages_images_from_pdf(pdf_path=doc.absolute_filepath) text_pages = self.ocr.extract_text_from_images(images) else: # Textract uses PDF bytes text_pages = self.ocr.extract_text_from_pdf(pdf_bytes) # Write all assets self.writer.save_document_assets( doc_type=doc.doc_type, doc_name=doc.doc_name, filename=doc.filename, pdf_bytes=pdf_bytes, text_pages=text_pages ) logger.trace(f"Completed: {doc.doc_name}") except Exception as e: logger.exception(f"Error processing {doc.doc_name}: {e}") raise
def create_all( self, documents: List[Document], workers: Optional[int] = None, limit: Optional[int] = None ) -> dict: """Create assets for all documents with concurrent execution. Returns: Dict with 'successful', 'failed', and 'failed_docs' keys. """ if workers is None: workers = os.cpu_count() or 1 docs_to_process = documents[:limit] if limit and limit > 0 else documents logger.info(f"Processing {len(docs_to_process)} documents with {workers} workers") successful = 0 failed = 0 failed_docs = [] with ThreadPoolExecutor(max_workers=workers) as executor: future_to_doc = { executor.submit(self.create_assets, doc): doc for doc in docs_to_process } for future in as_completed(future_to_doc): doc = future_to_doc[future] try: future.result() successful += 1 except Exception as e: failed += 1 failed_docs.append(doc.doc_name) logger.error(f"Failed: {doc.doc_name} - {e}") logger.info(f"Completed: {successful} successful, {failed} failed") return { 'successful': successful, 'failed': failed, 'failed_docs': failed_docs }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.# SPDX-License-Identifier: CC-BY-NC-4.0
import osfrom pathlib import Pathfrom typing import Listfrom PIL import Imageimport fitzfrom loguru import logger
class AssetWriter: """Writes document assets (PDF, images, OCR text) to disk."""
def __init__(self, output_base_path: str = ".data/rvl-cdip-nmp-hf/rvl-cdip-nmp-assets"): self.output_base_path = Path(output_base_path)
def save_document_assets( self, doc_type: str, doc_name: str, filename: str, pdf_bytes: bytes, text_pages: List[str] ): """Save all assets for a document: original PDF, page images, and OCR text.""" # Create directory structure: {doc_type}/{filename}/ doc_dir = self.output_base_path / doc_type / filename original_dir = doc_dir / "original" pages_dir = doc_dir / "pages" original_dir.mkdir(parents=True, exist_ok=True) # Save original PDF original_pdf_path = original_dir / filename with open(original_pdf_path, 'wb') as f: f.write(pdf_bytes) # Extract and save page images pdf_doc = fitz.open(stream=pdf_bytes, filetype="pdf") for page_num in range(len(pdf_doc)): page = pdf_doc[page_num] page_num_str = f"{page_num + 1:04d}" # Create page directory page_dir = pages_dir / page_num_str page_dir.mkdir(parents=True, exist_ok=True) # Save page image pix = page.get_pixmap(dpi=300) img_path = page_dir / f"page-{page_num_str}.png" pix.save(str(img_path)) # Save OCR text if page_num < len(text_pages): text_path = page_dir / f"page-{page_num_str}-textract.md" with open(text_path, 'w', encoding='utf-8') as f: f.write(text_pages[page_num]) pdf_doc.close() logger.debug(f"Saved assets for {doc_type}/{doc_name}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.# SPDX-License-Identifier: CC-BY-NC-4.0
import osimport sysimport ioimport tempfileimport shutilimport refrom typing import List, Optionalfrom contextlib import redirect_stdoutfrom loguru import loggerfrom PIL import Image
# Pin model revision for reproducibility and supply chain security# Update README.md 9f30c71 commited on Nov 3, 2025# False positive, high entropy string is acutally a commit hash required to remediate B615MODEL_REVISION = "9f30c71f441d010e5429c532364a86705536c53a" # nosec SECRET-HEX-HIGH-ENTROPY-STRING
class DeepSeekOcr: """DeepSeek OCR for language documents."""
def __init__( self, model_name: str = "deepseek-ai/DeepSeek-OCR", device: str = "cuda", cache_dir: Optional[str] = None ): """Initialize DeepSeek OCR from Hugging Face. Args: model_name: Hugging Face model name device: Device to run model on ('cuda' or 'cpu') cache_dir: Optional cache directory for model downloads (use larger disk if needed) """ try: from transformers import AutoModel, AutoTokenizer import torch # Verify CUDA availability if device == "cuda" and not torch.cuda.is_available(): logger.warning("CUDA requested but not available. Falling back to CPU. Performance will be significantly slower.") device = "cpu" logger.info(f"Loading DeepSeek model: {model_name} on {device}") self.tokenizer = AutoTokenizer.from_pretrained( # nosec B615 - False positive, see MODEL_REVISION is set to a specific version hash model_name, trust_remote_code=True, cache_dir=cache_dir, revision=MODEL_REVISION ) self.model = AutoModel.from_pretrained( # nosec B615 - False positive, see MODEL_REVISION is set to a specific version hash model_name, _attn_implementation='flash_attention_2', trust_remote_code=True, use_safetensors=True, torch_dtype=torch.bfloat16, cache_dir=cache_dir, revision=MODEL_REVISION ) self.model = self.model.eval() if device == "cuda": self.model = self.model.cuda() self.device = device logger.info(f"DeepSeek model loaded successfully on {device}") except ImportError as e: logger.error(f"Failed to import dependencies: {e}") raise except Exception as e: logger.error(f"Failed to load DeepSeek model: {e}") raise
def extract_text_from_images(self, images: List[Image.Image]) -> List[str]: """Extract text from page images using DeepSeek OCR. Args: images: List of PIL Images Returns: List of markdown text per page """ texts = [] temp_dir = tempfile.mkdtemp(prefix='deepseek_ocr_') try: for idx, image in enumerate(images): if not isinstance(image, Image.Image): logger.warning(f"Page {idx + 1} is not a valid PIL Image, skipping") texts.append("") continue try: # Suppress model debug output with redirect_stdout(io.StringIO()): self.model.infer( self.tokenizer, prompt="<image>\n<|grounding|>Convert the document to markdown.", image_file=image, output_path=temp_dir, base_size=1024, image_size=640, crop_mode=True, save_results=True ) # Read result from saved file result_file = os.path.join(temp_dir, 'result.mmd') if os.path.exists(result_file): with open(result_file, 'r', encoding='utf-8') as f: result = f.read() # Clean markup tags clean_text = re.sub(r'<\|ref\|>text<\|/ref\|>', '', result) clean_text = re.sub(r'<\|det\|>\[\[.*?\]\]<\|/det\|>', '', clean_text) clean_text = clean_text.strip() texts.append(clean_text) # Delete all output files after reading for item in os.listdir(temp_dir): item_path = os.path.join(temp_dir, item) try: if os.path.isfile(item_path): os.remove(item_path) elif os.path.isdir(item_path): shutil.rmtree(item_path) except Exception as e: logger.debug(f"Failed to clean up {item_path}: {e}") logger.info(f"DeepSeek OCR completed for page {idx + 1}") else: logger.warning(f"No result file found for page {idx + 1}") texts.append("") except Exception as e: logger.error(f"DeepSeek OCR error on page {idx + 1}: {e}") texts.append("") finally: # Cleanup temp directory if os.path.exists(temp_dir): shutil.rmtree(temp_dir, ignore_errors=True) logger.debug(f"Cleaned up temp directory: {temp_dir}") return texts
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.# SPDX-License-Identifier: CC-BY-NC-4.0
import osfrom pathlib import Pathfrom typing import List, Optionalimport csvfrom loguru import loggerimport fitz
from models import Document
class PdfLoader: """Loads PDF files from raw data directory."""
def __init__(self, raw_data_path: str = ".data/rvl-cdip-mp/raw_data", max_file_size_mb: float = 150): """Initialize PDF loader. Args: raw_data_path: Path to raw data directory max_file_size_mb: Maximum file size in MB for valid PDFs """ self.raw_data_path = Path(raw_data_path) self.max_file_size_mb = max_file_size_mb
def validate_pdf(self, file_path: Path) -> tuple[bool, str, int]: """Validate if a PDF is readable and within size limits. Args: file_path: Path to PDF file Returns: Tuple of (is_valid, status_message, page_count) """ try: # Check file size size_bytes = file_path.stat().st_size size_mb = size_bytes / (1024 * 1024) if size_bytes == 0: return False, "ZERO_SIZE", 0 if size_mb > self.max_file_size_mb: return False, f"TOO_LARGE ({size_mb:.1f}MB)", 0 # Check PDF header with open(file_path, "rb") as f: header = f.read(4) if header != b"%PDF": return False, "INVALID_PDF_HEADER", 0 # Test readability with PyMuPDF doc = fitz.open(str(file_path)) if doc.is_encrypted: doc.close() return False, "ENCRYPTED_PDF", 0 page_count = doc.page_count if page_count == 0: doc.close() return False, "NO_PAGES", 0 # Try to access first page page = doc[0] page.get_text() doc.close() return True, "VALID", page_count except Exception as e: return False, f"ERROR: {str(e)[:50]}", 0
def get_all_documents(self, exclude_types: Optional[List[str]] = None) -> List[Document]: """Get all valid PDF documents from raw data directory. Args: exclude_types: List of document types to exclude (e.g., ['language']) """ if exclude_types is None: exclude_types = [] documents = [] for doc_type_dir in self.raw_data_path.iterdir(): if not doc_type_dir.is_dir(): continue doc_type = doc_type_dir.name if doc_type in exclude_types: logger.info(f"Skipping excluded type: {doc_type}") continue for pdf_file in doc_type_dir.glob("*.pdf"): is_valid, status, page_count = self.validate_pdf(pdf_file) if not is_valid: logger.warning(f"Skipping invalid PDF {pdf_file}: {status}") continue doc = Document( doc_type=doc_type, doc_name=pdf_file.stem, filename=pdf_file.name, absolute_filepath=str(pdf_file.absolute()), page_count=page_count ) documents.append(doc) logger.info(f"Loaded {len(documents)} valid documents") return documents
def save_document_mapping(self, documents: List[Document], output_path: str): """Save document mapping to CSV.""" os.makedirs(os.path.dirname(output_path), exist_ok=True) with open(output_path, 'w', newline='') as f: writer = csv.DictWriter(f, fieldnames=['type', 'doc_name', 'filename', 'pages', 'validation_status']) writer.writeheader() for doc in documents: writer.writerow({ 'type': doc.doc_type, 'doc_name': doc.doc_name, 'filename': doc.filename, 'pages': doc.page_count, 'validation_status': 'VALID' }) logger.info(f"Saved document mapping to {output_path}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.# SPDX-License-Identifier: CC-BY-NC-4.0
from typing import Listfrom loguru import loggerfrom textractor import Textractorfrom textractor.data.constants import TextractFeatures
class TextractOcr: """Extracts text from PDFs using AWS Textract with S3 upload."""
def __init__(self, s3_bucket: str, s3_prefix: str = 'textract-temp'): """Initialize Textract OCR. Args: s3_bucket: S3 bucket for temporary uploads s3_prefix: S3 prefix for uploads """ self.textractor = Textractor() self.s3_upload_path = f"s3://{s3_bucket}/{s3_prefix}" logger.info(f"Textract S3 upload path: {self.s3_upload_path}")
def extract_text_from_pdf(self, pdf_bytes: bytes) -> List[str]: """Extract text from PDF using Textract with S3 upload. Returns: List of markdown text, one per page. """ # Use start_document_analysis with S3 upload lazy_document = self.textractor.start_document_analysis( file_source=pdf_bytes, s3_upload_path=self.s3_upload_path, features=[TextractFeatures.LAYOUT], save_image=False, ) # Wait for completion _ = lazy_document.response pages = lazy_document.document.pages # Convert to markdown page_texts = [] for page in pages: try: page_content = page.to_markdown() except Exception: page_content = page.get_text() page_texts.append(page_content) return page_texts if page_texts else ['']12# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.# SPDX-License-Identifier: CC-BY-NC-4.012345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.# SPDX-License-Identifier: CC-BY-NC-4.0
from typing import List, Dict, Optionalfrom pydantic import BaseModel, Field
class SourceDocument(BaseModel): """Represents a source document used in splicing."""
doc_type: str = Field(..., description="Document category/type") doc_name: str = Field(..., description="Source document identifier") pages: List[int] = Field(..., description="Page numbers used from this document")
class GroundTruthPage(BaseModel): """Ground truth for a single page in spliced document."""
page_num: int = Field(..., ge=1, description="Page number in spliced document") doc_type: str = Field(..., description="Document category/type") source_doc: str = Field(..., description="Source document identifier") source_page: int = Field(..., ge=1, description="Page number in source document")
class SplicedDocument(BaseModel): """Represents a spliced benchmark document."""
spliced_doc_id: str = Field(..., description="Unique identifier for spliced document") source_documents: List[SourceDocument] = Field(..., description="Source documents used") ground_truth: List[GroundTruthPage] = Field(..., description="Ground truth page mappings") total_pages: int = Field(..., gt=0, description="Total pages in spliced document")
class BenchmarkSet(BaseModel): """Collection of spliced documents for a benchmark."""
benchmark_name: str = Field(..., description="Benchmark identifier") strategy: str = Field(..., description="Shuffling strategy used") split: str = Field(..., description="Dataset split: train, test, or validation") created_at: str = Field(..., description="Creation timestamp") documents: List[SplicedDocument] = Field(..., description="Spliced documents") statistics: Dict[str, int] = Field(default_factory=dict, description="Benchmark statistics")
class DocumentAsset(BaseModel): """Represents a loaded document asset."""
doc_type: str = Field(..., description="Document category/type") doc_name: str = Field(..., description="Document identifier") filename: str = Field(..., description="PDF filename") page_count: int = Field(..., gt=0, description="Number of pages") pages: List['PageAsset'] = Field(default_factory=list, description="Page assets")
class PageAsset(BaseModel): """Represents a single page asset."""
page_num: int = Field(..., ge=1, description="Page number") image_path: str = Field(..., description="Path to page image") text_path: str = Field(..., description="Path to OCR text") text_content: Optional[str] = Field(None, description="Loaded text content")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.# SPDX-License-Identifier: CC-BY-NC-4.0
"""Create Benchmarks from Assets
Generates document splitting benchmarks from structured assets.
Usage: python main.py --strategy multi_category_concat python main.py --strategy single_category_concat --num-docs-train 500"""
import argparsefrom pathlib import Pathfrom loguru import logger
from services.asset_loader import AssetLoaderfrom services.split_manager import SplitManagerfrom services.benchmark_generator import BenchmarkGeneratorfrom services.benchmark_writer import BenchmarkWriterfrom services.shuffle_strategies import get_strategy, STRATEGIES
def main(): parser = argparse.ArgumentParser(description='Create benchmarks from assets')
# Paths parser.add_argument('--assets-path', default='data/assets', help='Path to assets from create_assets') parser.add_argument('--output-path', default='data/benchmarks', help='Output path for benchmarks') parser.add_argument('--split-mapping', default='data/metadata/split_mapping.json', help='Path to split mapping JSON (created if not exists)')
# Strategy parser.add_argument('--strategy', choices=list(STRATEGIES.keys()) + ['all'], default='all', help='Shuffle strategy to use (default: all strategies)')
# Split configuration parser.add_argument('--num-docs-train', type=int, default=800, help='Number of spliced documents for training') parser.add_argument('--num-docs-test', type=int, default=500, help='Number of spliced documents for testing') parser.add_argument('--num-docs-val', type=int, default=200, help='Number of spliced documents for validation')
# Strategy parameters parser.add_argument('--size', choices=['small', 'large'], default='small', help='Benchmark size: small (5-20 pages) or large (20-500 pages)') parser.add_argument('--random-seed', type=int, default=42, help='Random seed for reproducibility')
args = parser.parse_args()
# Set page ranges based on size if args.size == 'small': min_pages, max_pages = 5, 20 else: # large min_pages, max_pages = 20, 500
# Determine which strategies to run if args.strategy == 'all': strategies_to_run = list(STRATEGIES.keys()) logger.info(f"Creating benchmarks for all strategies: {strategies_to_run}") else: strategies_to_run = [args.strategy] logger.info(f"Creating benchmark with strategy: {args.strategy}")
logger.info(f"Size: {args.size} ({min_pages}-{max_pages} pages)")
# Load assets loader = AssetLoader(assets_path=args.assets_path) documents_by_type = loader.load_all_documents()
if not documents_by_type: logger.error("No documents loaded. Check assets path.") return
# Create or load split split_manager = SplitManager(random_seed=args.random_seed)
if args.split_mapping and Path(args.split_mapping).exists(): logger.info(f"Loading existing split from {args.split_mapping}") splits = split_manager.load_split(args.split_mapping) else: logger.info("Creating new split") splits = split_manager.create_split(documents_by_type)
# Save split mapping to metadata folder split_path = Path(args.split_mapping) split_path.parent.mkdir(parents=True, exist_ok=True) split_manager.save_split(splits, str(split_path))
# Run for each strategy for strategy_name in strategies_to_run: logger.info(f"\n{'='*60}") logger.info(f"Processing strategy: {strategy_name}") logger.info(f"{'='*60}\n")
# Initialize strategy strategy = get_strategy( strategy_name, min_pages=min_pages, max_pages=max_pages, random_seed=args.random_seed )
# Initialize generator and writer generator = BenchmarkGenerator(strategy=strategy) writer = BenchmarkWriter( output_base_path=str(Path(args.output_path) / strategy_name / args.size), assets_path=args.assets_path )
# Generate benchmarks for each split split_configs = [ ('train', args.num_docs_train), ('test', args.num_docs_test), ('validation', args.num_docs_val) ]
for split_name, num_docs in split_configs: if num_docs <= 0: logger.info(f"Skipping {split_name} (num_docs=0)") continue
logger.info(f"Generating {split_name} benchmark...")
benchmark_set = generator.generate_for_split( documents_by_type=documents_by_type, doc_names_for_split=splits[split_name], num_spliced_docs=num_docs, split_name=split_name, benchmark_name=strategy_name )
writer.save_benchmark_set(benchmark_set, split_name)
logger.info(f"Completed {split_name}: {benchmark_set.statistics}")
logger.info("\n" + "="*60) logger.info("All benchmark creation complete!") logger.info("="*60)
if __name__ == '__main__': main()12# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.# SPDX-License-Identifier: CC-BY-NC-4.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.# SPDX-License-Identifier: CC-BY-NC-4.0
import osimport csvfrom pathlib import Pathfrom typing import List, Dict, Optionalfrom loguru import logger
from models import DocumentAsset, PageAsset
class AssetLoader: """Loads document assets from create_assets output using document_mapping.csv."""
def __init__(self, assets_path: str, mapping_csv: str = None): """Initialize asset loader. Args: assets_path: Path to assets directory mapping_csv: Path to document_mapping.csv (default: data/metadata/document_mapping.csv) """ self.assets_path = Path(assets_path) if mapping_csv is None: mapping_csv = "data/metadata/document_mapping.csv" self.mapping_csv = Path(mapping_csv) if not self.mapping_csv.exists(): raise FileNotFoundError(f"Document mapping not found: {self.mapping_csv}")
def load_all_documents(self, doc_types: List[str] = None) -> Dict[str, List[DocumentAsset]]: """Load all document assets grouped by type from CSV. Args: doc_types: Optional list of document types to load. If None, loads all. Returns: Dict mapping doc_type to list of DocumentAsset objects. """ documents_by_type = {} # Read document mapping CSV with open(self.mapping_csv, 'r', encoding='utf-8') as f: reader = csv.DictReader(f) for row in reader: doc_type = row['type'] doc_name = row['doc_name'] filename = row['filename'] page_count = int(row['pages']) # Filter by doc_types if specified if doc_types and doc_type not in doc_types: continue # Build document asset doc_asset = self._create_document_asset( doc_type=doc_type, doc_name=doc_name, filename=filename, page_count=page_count ) if doc_type not in documents_by_type: documents_by_type[doc_type] = [] documents_by_type[doc_type].append(doc_asset) total = sum(len(docs) for docs in documents_by_type.values()) logger.info(f"Loaded {total} documents across {len(documents_by_type)} types from CSV") return documents_by_type
def _create_document_asset( self, doc_type: str, doc_name: str, filename: str, page_count: int ) -> DocumentAsset: """Create DocumentAsset with page information. Args: doc_type: Document category doc_name: Document identifier filename: PDF filename page_count: Number of pages Returns: DocumentAsset with populated pages """ pages = [] for page_num in range(1, page_count + 1): page_num_str = f"{page_num:04d}" # Construct paths based on known structure page_dir = self.assets_path / doc_type / filename / "pages" / page_num_str image_path = page_dir / f"page-{page_num_str}.png" text_path = page_dir / f"page-{page_num_str}-textract.md" page_asset = PageAsset( page_num=page_num, image_path=str(image_path), text_path=str(text_path), text_content=None # Loaded on demand ) pages.append(page_asset) return DocumentAsset( doc_type=doc_type, doc_name=doc_name, filename=filename, page_count=page_count, pages=pages )1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.# SPDX-License-Identifier: CC-BY-NC-4.0
from typing import Dict, Listfrom datetime import datetimefrom loguru import logger
from models import DocumentAsset, BenchmarkSetfrom services.shuffle_strategies.base_strategy import BaseStrategy
class BenchmarkGenerator: """Orchestrates benchmark generation."""
def __init__(self, strategy: BaseStrategy): self.strategy = strategy
def generate_for_split( self, documents_by_type: Dict[str, List[DocumentAsset]], doc_names_for_split: Dict[str, List[str]], num_spliced_docs: int, split_name: str, benchmark_name: str ) -> BenchmarkSet: """Generate benchmark set for a specific split. Args: documents_by_type: All available documents grouped by type doc_names_for_split: Document names to use for this split num_spliced_docs: Number of spliced documents to generate split_name: Name of the split (train, test, validation) benchmark_name: Name of the benchmark Returns: BenchmarkSet object """ logger.info(f"Generating {num_spliced_docs} documents for {split_name} split") spliced_documents = self.strategy.generate( documents_by_type=documents_by_type, doc_names_for_split=doc_names_for_split, num_spliced_docs=num_spliced_docs ) # Calculate statistics statistics = self._calculate_statistics(spliced_documents) benchmark_set = BenchmarkSet( benchmark_name=benchmark_name, strategy=self.strategy.__class__.__name__, split=split_name, created_at=datetime.now().isoformat(), documents=spliced_documents, statistics=statistics ) logger.info(f"Generated benchmark set with {len(spliced_documents)} documents") return benchmark_set
def _calculate_statistics(self, spliced_documents: List) -> Dict[str, int]: """Calculate statistics for the benchmark set.""" total_pages = sum(doc.total_pages for doc in spliced_documents) total_source_docs = sum(len(doc.source_documents) for doc in spliced_documents) doc_types = set() for doc in spliced_documents: for source in doc.source_documents: doc_types.add(source.doc_type) return { 'total_spliced_documents': len(spliced_documents), 'total_pages': total_pages, 'total_source_documents': total_source_docs, 'unique_doc_types': len(doc_types), 'avg_pages_per_document': int(total_pages / len(spliced_documents)) if spliced_documents else 0 }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.# SPDX-License-Identifier: CC-BY-NC-4.0
import csvimport jsonfrom pathlib import Pathfrom loguru import logger
from models import BenchmarkSet
class BenchmarkWriter: """Writes benchmark datasets to disk as CSV files."""
def __init__(self, output_base_path: str, assets_path: str = "data/assets"): self.output_base_path = Path(output_base_path) self.assets_path = Path(assets_path)
def save_benchmark_set( self, benchmark_set: BenchmarkSet, split: str ): """Save a benchmark set to CSV and ground truth JSON files. Args: benchmark_set: The benchmark set to save split: Split name (train, test, or validation) """ self.output_base_path.mkdir(parents=True, exist_ok=True) output_path = self.output_base_path / f"{split}.csv" json_dir = self.output_base_path / "ground_truth_json" / split json_dir.mkdir(parents=True, exist_ok=True) # Generate group IDs (AA, AB, AC, etc.) def generate_group_id(index): """Generate group_id like AA, AB, AC, ..., AZ, BA, BB, etc.""" alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" first_char = alphabet[index // 26 % 26] second_char = alphabet[index % 26] return first_char + second_char # Flatten ground truth pages into CSV rows rows = [] # Track unique source documents across all packets for group_id assignment source_doc_to_group_id = {} group_id_counter = 0 for doc_idx, doc in enumerate(benchmark_set.documents): # Track page ordinal per source document source_doc_ordinals = {} # Track local_doc_id per source document within this packet source_doc_to_local_id = {} local_id_counter = {} for gt_page in doc.ground_truth: source_key = gt_page.source_doc # Assign group_id per unique source document if source_key not in source_doc_to_group_id: source_doc_to_group_id[source_key] = generate_group_id(group_id_counter) group_id_counter += 1 group_id = source_doc_to_group_id[source_key] # Increment ordinal for this source document if source_key not in source_doc_ordinals: source_doc_ordinals[source_key] = 0 source_doc_ordinals[source_key] += 1 # Assign local_doc_id per source document if source_key not in source_doc_to_local_id: doc_type_prefix = gt_page.doc_type.replace(" ", "-").lower() if doc_type_prefix not in local_id_counter: local_id_counter[doc_type_prefix] = 0 local_id_counter[doc_type_prefix] += 1 source_doc_to_local_id[source_key] = f"{doc_type_prefix}-{local_id_counter[doc_type_prefix]:02d}" local_doc_id = source_doc_to_local_id[source_key] # Build paths image_path = f"{self.assets_path}/{gt_page.doc_type}/{gt_page.source_doc}.pdf/pages/{gt_page.source_page:04d}/page-{gt_page.source_page:04d}.png" text_path = f"{self.assets_path}/{gt_page.doc_type}/{gt_page.source_doc}.pdf/pages/{gt_page.source_page:04d}/page-{gt_page.source_page:04d}-textract.md" rows.append({ 'doc_type': gt_page.doc_type, 'original_doc_name': gt_page.source_doc, 'parent_doc_name': doc.spliced_doc_id, 'local_doc_id': local_doc_id, 'page': gt_page.page_num, 'image_path': image_path, 'text_path': text_path, 'group_id': group_id, 'local_doc_id_page_ordinal': source_doc_ordinals[source_key] }) # Generate ground truth JSON for this parent document self._save_ground_truth_json(doc, json_dir) # Write CSV if rows: fieldnames = ['doc_type', 'original_doc_name', 'parent_doc_name', 'local_doc_id', 'page', 'image_path', 'text_path', 'group_id', 'local_doc_id_page_ordinal'] with open(output_path, 'w', newline='', encoding='utf-8') as f: writer = csv.DictWriter(f, fieldnames=fieldnames) writer.writeheader() writer.writerows(rows) logger.info(f"Saved {len(benchmark_set.documents)} spliced documents ({len(rows)} pages) to {output_path}") logger.info(f"Saved {len(benchmark_set.documents)} ground truth JSON files to {json_dir}") def _save_ground_truth_json(self, doc, json_dir: Path): """Generate ground truth JSON for a single parent document.""" # Group pages by source document (doc_type, source_doc) subdocs = {} for gt_page in doc.ground_truth: key = (gt_page.doc_type, gt_page.source_doc) if key not in subdocs: subdocs[key] = [] subdocs[key].append(gt_page) # Build subdocuments structure subdocuments = [] for subdoc_idx, ((doc_type, source_doc), pages) in enumerate(subdocs.items()): group_id = self._generate_group_id(subdoc_idx) # Count occurrences of this doc_type so far doc_type_count = sum(1 for s in subdocuments if s['doc_type_id'] == doc_type) + 1 local_doc_id = f"{doc_type}-{doc_type_count:02d}" page_ordinals = [p.page_num for p in pages] subdoc_pages = [] for idx, gt_page in enumerate(pages, 1): image_path = f"{self.assets_path}/{gt_page.doc_type}/{gt_page.source_doc}.pdf/pages/{gt_page.source_page:04d}/page-{gt_page.source_page:04d}.png" text_path = f"{self.assets_path}/{gt_page.doc_type}/{gt_page.source_doc}.pdf/pages/{gt_page.source_page:04d}/page-{gt_page.source_page:04d}-textract.md" subdoc_pages.append({ "page": gt_page.page_num, "original_doc_name": gt_page.source_doc, "image_path": image_path, "text_path": text_path, "local_doc_id_page_ordinal": idx }) subdocuments.append({ "doc_type_id": doc_type, "page_ordinals": page_ordinals, "local_doc_id": local_doc_id, "group_id": group_id, "pages": subdoc_pages }) # Build final JSON structure ground_truth = { "doc_id": doc.spliced_doc_id, "total_pages": doc.total_pages, "subdocuments": subdocuments } # Write JSON file json_path = json_dir / f"{doc.spliced_doc_id}.json" with open(json_path, 'w', encoding='utf-8') as f: json.dump(ground_truth, f, indent=2) def _generate_group_id(self, index): """Generate group_id like AA, AB, AC, ..., AZ, BA, BB, etc.""" result = "" index += 1 while index > 0: index -= 1 result = chr(65 + (index % 26)) + result index //= 26 return result or "A"12345678910111213141516171819202122232425# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.# SPDX-License-Identifier: CC-BY-NC-4.0
from .base_strategy import BaseStrategyfrom .mono_seq import MonoSeqfrom .mono_rand import MonoRandfrom .poly_seq import PolySeqfrom .poly_int import PolyIntfrom .poly_rand import PolyRand
STRATEGIES = { 'mono_seq': MonoSeq, 'mono_rand': MonoRand, 'poly_seq': PolySeq, 'poly_int': PolyInt, 'poly_rand': PolyRand,}
def get_strategy(name: str, **kwargs) -> BaseStrategy: """Get a strategy instance by name.""" if name not in STRATEGIES: raise ValueError(f"Unknown strategy: {name}. Available: {list(STRATEGIES.keys())}") return STRATEGIES[name](**kwargs)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.# SPDX-License-Identifier: CC-BY-NC-4.0
from abc import ABC, abstractmethodfrom typing import List, Dictimport random
from models import DocumentAsset, SplicedDocument
class BaseStrategy(ABC): """Abstract base class for shuffle strategies."""
def __init__( self, min_pages: int = 17, max_pages: int = 20, random_seed: int = 42 ): self.min_pages = min_pages self.max_pages = max_pages self.random_seed = random_seed self.rng = random.Random(random_seed) # nosec B311 - non-cryptographic use for benchmark shuffling
@abstractmethod def generate( self, documents_by_type: Dict[str, List[DocumentAsset]], doc_names_for_split: Dict[str, List[str]], num_spliced_docs: int ) -> List[SplicedDocument]: """Generate spliced documents using this strategy. Args: documents_by_type: All available documents grouped by type doc_names_for_split: Document names to use for this split num_spliced_docs: Number of spliced documents to generate Returns: List of SplicedDocument objects """ pass
def _get_available_docs( self, documents_by_type: Dict[str, List[DocumentAsset]], doc_names_for_split: Dict[str, List[str]] ) -> Dict[str, List[DocumentAsset]]: """Filter documents to only those in the split.""" available = {} for doc_type, doc_names in doc_names_for_split.items(): if doc_type not in documents_by_type: continue doc_name_set = set(doc_names) available[doc_type] = [ doc for doc in documents_by_type[doc_type] if doc.doc_name in doc_name_set ] return available
def _get_random_doc( self, available_docs: Dict[str, List[DocumentAsset]], doc_type: str = None ) -> DocumentAsset: """Get a random document, optionally from a specific type.""" if doc_type: if doc_type not in available_docs or not available_docs[doc_type]: raise ValueError(f"No documents available for type: {doc_type}") return self.rng.choice(available_docs[doc_type]) else: all_docs = [doc for docs in available_docs.values() for doc in docs] if not all_docs: raise ValueError("No documents available") return self.rng.choice(all_docs)
def _get_random_pages( self, doc: DocumentAsset, num_pages: int = None ) -> List[int]: """Get random page numbers from a document.""" if num_pages is None: num_pages = self.rng.randint(self.min_pages, self.max_pages) num_pages = min(num_pages, doc.page_count) return self.rng.sample(range(1, doc.page_count + 1), num_pages)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.# SPDX-License-Identifier: CC-BY-NC-4.0
from typing import List, Dictimport uuidfrom loguru import logger
from models import DocumentAsset, SplicedDocument, SourceDocument, GroundTruthPagefrom services.shuffle_strategies.base_strategy import BaseStrategy
class MonoRand(BaseStrategy): """DocSplit-Mono-Rand: Single category document pages randomization. Similar to Mono-Seq but shuffles pages from concatenated documents. Tests models' robustness to page-level disruptions common in manual document assembly, requiring boundary detection and page sequence reconstruction. """
def generate( self, documents_by_type: Dict[str, List[DocumentAsset]], doc_names_for_split: Dict[str, List[str]], num_spliced_docs: int ) -> List[SplicedDocument]: available_docs = self._get_available_docs(documents_by_type, doc_names_for_split) # Filter out language category for large datasets (min_pages >= 20) if self.min_pages >= 20 and "language" in available_docs: del available_docs["language"] spliced_documents = [] for i in range(num_spliced_docs): # Pick a random document type doc_type = self.rng.choice(list(available_docs.keys())) # Set target page count target_pages = self.rng.randint(self.min_pages, self.max_pages) # Keep adding entire documents until reaching target source_documents = [] ground_truth = [] current_page = 1 used_docs = set() while current_page - 1 < target_pages: available = [d for d in available_docs[doc_type] if d.doc_name not in used_docs and d.page_count <= self.max_pages] if not available: break doc = self.rng.choice(available) used_docs.add(doc.doc_name) if current_page - 1 + doc.page_count > self.max_pages: continue # Add all pages but shuffle their order pages = list(range(1, doc.page_count + 1)) self.rng.shuffle(pages) source_documents.append(SourceDocument( doc_type=doc.doc_type, doc_name=doc.doc_name, pages=pages )) for source_page in pages: ground_truth.append(GroundTruthPage( page_num=current_page, doc_type=doc.doc_type, source_doc=doc.doc_name, source_page=source_page )) current_page += 1 if current_page - 1 >= self.min_pages: spliced_doc = SplicedDocument( spliced_doc_id=str(uuid.uuid4()), source_documents=source_documents, ground_truth=ground_truth, total_pages=current_page - 1 ) spliced_documents.append(spliced_doc) logger.info(f"Generated {len(spliced_documents)} DocSplit-Mono-Rand documents") return spliced_documents123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.# SPDX-License-Identifier: CC-BY-NC-4.0
from typing import List, Dictimport uuidfrom loguru import logger
from models import DocumentAsset, SplicedDocument, SourceDocument, GroundTruthPagefrom services.shuffle_strategies.base_strategy import BaseStrategy
class MonoSeq(BaseStrategy): """DocSplit-Mono-Seq: Single category document concatenation sequentially. Creates document packets by concatenating entire documents from the same category while preserving original page order. Tests boundary detection without category transitions as discriminative signals. """
def generate( self, documents_by_type: Dict[str, List[DocumentAsset]], doc_names_for_split: Dict[str, List[str]], num_spliced_docs: int ) -> List[SplicedDocument]: available_docs = self._get_available_docs(documents_by_type, doc_names_for_split) # Filter out language category for large datasets (min_pages >= 20) if self.min_pages >= 20 and "language" in available_docs: del available_docs["language"] spliced_documents = [] for i in range(num_spliced_docs): # Pick a random document type doc_type = self.rng.choice(list(available_docs.keys())) # Set target page count target_pages = self.rng.randint(self.min_pages, self.max_pages) # Keep adding entire documents until reaching target source_documents = [] ground_truth = [] current_page = 1 used_docs = set() while current_page - 1 < target_pages: # Get available docs of this type that haven't been used available = [d for d in available_docs[doc_type] if d.doc_name not in used_docs and d.page_count <= self.max_pages] if not available: break # Pick a random document doc = self.rng.choice(available) used_docs.add(doc.doc_name) # Check if adding this doc would exceed max_pages if current_page - 1 + doc.page_count > self.max_pages: continue # Add all pages from this document in original order pages = list(range(1, doc.page_count + 1)) source_documents.append(SourceDocument( doc_type=doc.doc_type, doc_name=doc.doc_name, pages=pages )) # Add ground truth for each page for source_page in pages: ground_truth.append(GroundTruthPage( page_num=current_page, doc_type=doc.doc_type, source_doc=doc.doc_name, source_page=source_page )) current_page += 1 # Only add if we have at least min_pages if current_page - 1 >= self.min_pages: spliced_doc = SplicedDocument( spliced_doc_id=str(uuid.uuid4()), source_documents=source_documents, ground_truth=ground_truth, total_pages=current_page - 1 ) spliced_documents.append(spliced_doc) logger.info(f"Generated {len(spliced_documents)} DocSplit-Mono-Seq documents") return spliced_documents123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.# SPDX-License-Identifier: CC-BY-NC-4.0
from typing import List, Dictimport uuidfrom loguru import logger
from models import DocumentAsset, SplicedDocument, SourceDocument, GroundTruthPagefrom services.shuffle_strategies.base_strategy import BaseStrategy
class PolyInt(BaseStrategy): """DocSplit-Poly-Int: Multi category document pages interleaving. Similar to Poly-Seq but interleaves pages in a round-robin fashion. Simulates batch processing scenarios such as mortgage processing where property deeds, tax records, and legal notices are interspersed. """
def generate( self, documents_by_type: Dict[str, List[DocumentAsset]], doc_names_for_split: Dict[str, List[str]], num_spliced_docs: int ) -> List[SplicedDocument]: available_docs = self._get_available_docs(documents_by_type, doc_names_for_split) doc_types = list(available_docs.keys()) if len(doc_types) < 2: raise ValueError("Need at least 2 document types for multi-category strategy") spliced_documents = [] for i in range(num_spliced_docs): # Set target page count target_pages = self.rng.randint(self.min_pages, self.max_pages) # Collect entire documents from different types selected_docs = [] used_types = set() total_pages = 0 while total_pages < target_pages: available_types = [t for t in doc_types if t not in used_types] if not available_types: break doc_type = self.rng.choice(available_types) used_types.add(doc_type) available = [d for d in available_docs[doc_type] if d.page_count <= self.max_pages] if not available: continue doc = self.rng.choice(available) if total_pages + doc.page_count > self.max_pages: continue selected_docs.append(doc) total_pages += doc.page_count # Collect all pages from selected documents all_pages = [] for doc in selected_docs: for page_num in range(1, doc.page_count + 1): all_pages.append({ 'doc_type': doc.doc_type, 'doc_name': doc.doc_name, 'source_page': page_num }) # Interleave pages (shuffle them) self.rng.shuffle(all_pages) # Build source documents and ground truth source_docs_dict = {} ground_truth = [] for idx, page_info in enumerate(all_pages, start=1): doc_key = (page_info['doc_type'], page_info['doc_name']) if doc_key not in source_docs_dict: source_docs_dict[doc_key] = [] source_docs_dict[doc_key].append(page_info['source_page']) ground_truth.append(GroundTruthPage( page_num=idx, doc_type=page_info['doc_type'], source_doc=page_info['doc_name'], source_page=page_info['source_page'] )) source_documents = [ SourceDocument(doc_type=doc_type, doc_name=doc_name, pages=pages) for (doc_type, doc_name), pages in source_docs_dict.items() ] if len(all_pages) >= self.min_pages: spliced_doc = SplicedDocument( spliced_doc_id=str(uuid.uuid4()), source_documents=source_documents, ground_truth=ground_truth, total_pages=len(all_pages) ) spliced_documents.append(spliced_doc) logger.info(f"Generated {len(spliced_documents)} DocSplit-Poly-Int documents") return spliced_documents123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.# SPDX-License-Identifier: CC-BY-NC-4.0
from typing import List, Dictimport uuidfrom loguru import logger
from models import DocumentAsset, SplicedDocument, SourceDocument, GroundTruthPagefrom services.shuffle_strategies.base_strategy import BaseStrategy
class PolyRand(BaseStrategy): """DocSplit-Poly-Rand: Multi category document pages randomization. Similar to Poly-Seq but applies complete randomization across all pages, representing maximum entropy scenarios. Stress-tests model robustness under worst-case conditions where no structural assumptions hold. """
def generate( self, documents_by_type: Dict[str, List[DocumentAsset]], doc_names_for_split: Dict[str, List[str]], num_spliced_docs: int ) -> List[SplicedDocument]: available_docs = self._get_available_docs(documents_by_type, doc_names_for_split) doc_types = list(available_docs.keys()) if len(doc_types) < 2: raise ValueError("Need at least 2 document types for multi-category strategy") spliced_documents = [] for i in range(num_spliced_docs): # Set target page count target_pages = self.rng.randint(self.min_pages, self.max_pages) # Collect entire documents from different types selected_docs = [] used_types = set() total_pages = 0 while total_pages < target_pages: available_types = [t for t in doc_types if t not in used_types] if not available_types: break doc_type = self.rng.choice(available_types) used_types.add(doc_type) available = [d for d in available_docs[doc_type] if d.page_count <= self.max_pages] if not available: continue doc = self.rng.choice(available) if total_pages + doc.page_count > self.max_pages: continue selected_docs.append(doc) total_pages += doc.page_count # Collect all pages from selected documents all_pages = [] for doc in selected_docs: for page_num in range(1, doc.page_count + 1): all_pages.append({ 'doc_type': doc.doc_type, 'doc_name': doc.doc_name, 'source_page': page_num }) # Fully shuffle all pages self.rng.shuffle(all_pages) # Build source documents and ground truth source_docs_dict = {} ground_truth = [] for idx, page_info in enumerate(all_pages, start=1): doc_key = (page_info['doc_type'], page_info['doc_name']) if doc_key not in source_docs_dict: source_docs_dict[doc_key] = [] source_docs_dict[doc_key].append(page_info['source_page']) ground_truth.append(GroundTruthPage( page_num=idx, doc_type=page_info['doc_type'], source_doc=page_info['doc_name'], source_page=page_info['source_page'] )) source_documents = [ SourceDocument(doc_type=doc_type, doc_name=doc_name, pages=pages) for (doc_type, doc_name), pages in source_docs_dict.items() ] if len(all_pages) >= self.min_pages: spliced_doc = SplicedDocument( spliced_doc_id=str(uuid.uuid4()), source_documents=source_documents, ground_truth=ground_truth, total_pages=len(all_pages) ) spliced_documents.append(spliced_doc) logger.info(f"Generated {len(spliced_documents)} DocSplit-Poly-Rand documents") return spliced_documents12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.# SPDX-License-Identifier: CC-BY-NC-4.0
from typing import List, Dictimport uuidfrom loguru import logger
from models import DocumentAsset, SplicedDocument, SourceDocument, GroundTruthPagefrom services.shuffle_strategies.base_strategy import BaseStrategy
class PolySeq(BaseStrategy): """DocSplit-Poly-Seq: Multi category documents concatenation sequentially. Creates document packets by concatenating documents from different categories without repetition while preserving page ordering. Simulates heterogeneous document assembly scenarios such as medical claims processing. """
def generate( self, documents_by_type: Dict[str, List[DocumentAsset]], doc_names_for_split: Dict[str, List[str]], num_spliced_docs: int ) -> List[SplicedDocument]: available_docs = self._get_available_docs(documents_by_type, doc_names_for_split) doc_types = list(available_docs.keys()) if len(doc_types) < 2: raise ValueError("Need at least 2 document types for multi-category strategy") spliced_documents = [] for i in range(num_spliced_docs): # Set target page count target_pages = self.rng.randint(self.min_pages, self.max_pages) # Keep adding entire documents from different types until reaching target source_documents = [] ground_truth = [] current_page = 1 used_types = set() while current_page - 1 < target_pages: # Get available types not yet used available_types = [t for t in doc_types if t not in used_types] if not available_types: break # Pick a random type doc_type = self.rng.choice(available_types) used_types.add(doc_type) # Pick a random document from this type available = [d for d in available_docs[doc_type] if d.page_count <= self.max_pages] if not available: continue doc = self.rng.choice(available) if current_page - 1 + doc.page_count > self.max_pages: continue # Add all pages in original order pages = list(range(1, doc.page_count + 1)) source_documents.append(SourceDocument( doc_type=doc.doc_type, doc_name=doc.doc_name, pages=pages )) for source_page in pages: ground_truth.append(GroundTruthPage( page_num=current_page, doc_type=doc.doc_type, source_doc=doc.doc_name, source_page=source_page )) current_page += 1 if current_page - 1 >= self.min_pages: spliced_doc = SplicedDocument( spliced_doc_id=str(uuid.uuid4()), source_documents=source_documents, ground_truth=ground_truth, total_pages=current_page - 1 ) spliced_documents.append(spliced_doc) logger.info(f"Generated {len(spliced_documents)} DocSplit-Poly-Seq documents") return spliced_documents123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.# SPDX-License-Identifier: CC-BY-NC-4.0
import jsonimport randomfrom pathlib import Pathfrom typing import Dict, Listfrom datetime import datetimefrom loguru import logger
from models import DocumentAsset
class SplitManager: """Manages train/test/validation splits for documents."""
def __init__( self, train_ratio: float = 0.6, test_ratio: float = 0.25, validation_ratio: float = 0.15, random_seed: int = 42 ): self.train_ratio = train_ratio self.test_ratio = test_ratio self.validation_ratio = validation_ratio self.random_seed = random_seed
if abs(train_ratio + test_ratio + validation_ratio - 1.0) > 0.001: raise ValueError("Split ratios must sum to 1.0")
def create_split( self, documents_by_type: Dict[str, List[DocumentAsset]] ) -> Dict[str, Dict[str, List[str]]]: """Create stratified train/test/validation split.
Returns: Dict with structure: {split_name: {doc_type: [doc_names]}} """ random.seed(self.random_seed)
splits = { 'train': {}, 'test': {}, 'validation': {} }
for doc_type, documents in documents_by_type.items(): doc_names = [doc.doc_name for doc in documents] random.shuffle(doc_names)
total = len(doc_names) train_end = int(total * self.train_ratio) test_end = train_end + int(total * self.test_ratio)
splits['train'][doc_type] = doc_names[:train_end] splits['test'][doc_type] = doc_names[train_end:test_end] splits['validation'][doc_type] = doc_names[test_end:]
logger.info(f"Created split: train={self._count_docs(splits['train'])}, " f"test={self._count_docs(splits['test'])}, " f"val={self._count_docs(splits['validation'])}")
return splits
def save_split(self, splits: Dict, output_path: str): """Save split mapping to JSON.""" Path(output_path).parent.mkdir(parents=True, exist_ok=True)
split_data = { 'created_at': datetime.now().isoformat(), 'split_config': { 'train_ratio': self.train_ratio, 'test_ratio': self.test_ratio, 'validation_ratio': self.validation_ratio, 'random_seed': self.random_seed, 'stratified': True }, 'splits': splits, 'statistics': { 'train': self._get_statistics(splits['train']), 'test': self._get_statistics(splits['test']), 'validation': self._get_statistics(splits['validation']) } }
with open(output_path, 'w') as f: json.dump(split_data, f, indent=2)
logger.info(f"Saved split mapping to {output_path}")
def load_split(self, split_path: str) -> Dict[str, Dict[str, List[str]]]: """Load split mapping from JSON.""" with open(split_path, 'r') as f: split_data = json.load(f)
logger.info(f"Loaded split mapping from {split_path}") return split_data['splits']
def _count_docs(self, split: Dict[str, List[str]]) -> int: """Count total documents in a split.""" return sum(len(docs) for docs in split.values())
def _get_statistics(self, split: Dict[str, List[str]]) -> Dict[str, int]: """Get statistics for a split.""" stats = {'total': self._count_docs(split)} for doc_type, docs in split.items(): stats[doc_type] = len(docs) return statsnotebooks/01_create_assets.ipynbAdded+131
notebooks/02_create_benchmarks.ipynbAdded+226
notebooks/03_analyze_benchmarks.ipynbAdded+321
src/assets/__init__.pyAdded+2
src/assets/models.pyAdded+14
src/assets/run.pyAdded+123
src/assets/services/__init__.pyAdded+2
src/assets/services/asset_creator.pyAdded+114
src/assets/services/asset_writer.pyAdded+63
src/assets/services/deepseek_ocr.pyAdded+151
src/assets/services/pdf_loader.pyAdded+131
src/assets/services/textract_ocr.pyAdded+51
src/benchmarks/__init__.pyAdded+2
src/benchmarks/models.pyAdded+61
src/benchmarks/run.pyAdded+148
src/benchmarks/services/__init__.pyAdded+2
src/benchmarks/services/asset_loader.pyAdded+117
src/benchmarks/services/benchmark_generator.pyAdded+77
src/benchmarks/services/benchmark_writer.pyAdded+177
src/benchmarks/services/shuffle_strategies/__init__.pyAdded+25
src/benchmarks/services/shuffle_strategies/base_strategy.pyAdded+90
src/benchmarks/services/shuffle_strategies/mono_rand.pyAdded+89
src/benchmarks/services/shuffle_strategies/mono_seq.pyAdded+93
src/benchmarks/services/shuffle_strategies/poly_int.pyAdded+111
src/benchmarks/services/shuffle_strategies/poly_rand.pyAdded+111
src/benchmarks/services/shuffle_strategies/poly_seq.pyAdded+94
src/benchmarks/services/split_manager.pyAdded+110