{ "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 }