File size: 9,532 Bytes
165da3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
{
 "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
}