-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild_time_bootstrap.py
More file actions
2069 lines (1560 loc) · 71.7 KB
/
Copy pathbuild_time_bootstrap.py
File metadata and controls
2069 lines (1560 loc) · 71.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Bootstrap the ENT RAG build-time implementation.
Run from the project root:
python bootstrap_build_time_v2.py
This script creates:
build_time/scripts/ Python implementation files
build_time/rag_digest/ Generated artifact folders
Unlike the earlier scaffold-only script, this version writes executable module code
adapted from the working rapid-development notebook.
"""
from __future__ import annotations
from pathlib import Path
from textwrap import dedent
import shutil
import subprocess
import sys
PROJECT_ROOT = Path(__file__).resolve().parent
BUILD_TIME_DIR = PROJECT_ROOT / "build_time"
RAG_DIGEST_SCRIPT_DIR = BUILD_TIME_DIR / "scripts"
RAG_DIGEST_ARTIFACTS_DIR = BUILD_TIME_DIR / "rag_digest"
# Do you want to reset the directory every run?
RESET_BUILD_TIME_DIR = True
# Do you want to overwrite the existing modules every run?
OVERWRITE_MODULES = True
# RAG Digest Main File
RAG_DIGEST_SCRIPT_EXEC_PY_PATH = RAG_DIGEST_SCRIPT_DIR / "rag_digest.py"
DIRECTORIES = [
BUILD_TIME_DIR,
RAG_DIGEST_SCRIPT_DIR,
RAG_DIGEST_ARTIFACTS_DIR,
RAG_DIGEST_SCRIPT_DIR / "subsection_chunking_utilities",
RAG_DIGEST_SCRIPT_DIR / "semantic_chunking_utilities",
RAG_DIGEST_SCRIPT_DIR / "indexing_utilities",
RAG_DIGEST_ARTIFACTS_DIR / "raw_images",
RAG_DIGEST_ARTIFACTS_DIR / "lookup_tables",
RAG_DIGEST_ARTIFACTS_DIR / "metadata",
RAG_DIGEST_ARTIFACTS_DIR / "faiss_indexes",
RAG_DIGEST_ARTIFACTS_DIR / "embedding_matrices",
RAG_DIGEST_ARTIFACTS_DIR / "reports",
]
FILES = {}
FILES[RAG_DIGEST_SCRIPT_DIR / "__init__.py"] = ""
FILES[RAG_DIGEST_SCRIPT_DIR / "subsection_chunking_utilities" / "__init__.py"] = ""
FILES[RAG_DIGEST_SCRIPT_DIR / "semantic_chunking_utilities" / "__init__.py"] = ""
FILES[RAG_DIGEST_SCRIPT_DIR / "indexing_utilities" / "__init__.py"] = ""
FILES[RAG_DIGEST_SCRIPT_DIR / "config.py"] = dedent(r'''
"""Configuration values for the build-time RAG digest pipeline."""
from pathlib import Path
PROJECT_ROOT = Path(__file__).resolve().parents[2]
# 1. PDF Source
PDF_PATH = PROJECT_ROOT / "pdfs" / "SFO_UK_Handbook_for_ENT_Reformat.pdf"
# 2. Build Time Path
BUILD_TIME_DIR = PROJECT_ROOT / "build_time"
# 2.1. Artifact Script
SCRIPT_DIR = BUILD_TIME_DIR / "scripts"
# 2.2. Artifact Directory
ARTIFACTS_DIR = BUILD_TIME_DIR / "rag_digest"
RAW_IMAGES_DIR = ARTIFACTS_DIR / "raw_images"
LOOKUP_TABLES_DIR = ARTIFACTS_DIR / "lookup_tables"
METADATA_DIR = ARTIFACTS_DIR / "metadata"
FAISS_INDEXES_DIR = ARTIFACTS_DIR / "faiss_indexes"
EMBEDDING_MATRICES_DIR = ARTIFACTS_DIR / "embedding_matrices"
REPORTS_DIR = ARTIFACTS_DIR / "reports"
# Encoder Model Names
BGE_MODEL_NAME = "BAAI/bge-small-en-v1.5"
CLIP_MODEL_NAME = "openai/clip-vit-base-patch32"
# Semantic Chunker Parameters
SEMANTIC_BUFFER_SIZE = 1
SEMANTIC_BREAKPOINT_PERCENTILE_THRESHOLD = 95
''').strip() + "\n"
FILES[RAG_DIGEST_SCRIPT_DIR / "subsection_chunking_utilities" / "data_models.py"] = dedent(r'''
"""Dataclasses used by the subsection chunking stage."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Optional, Tuple
@dataclass
class HeaderRecord:
header_id: int
hierarchy: int
title: str
page_index: int
page_number: int
@dataclass
class TableRecord:
table_id: int
page_index: int
bbox: Tuple[float, float, float, float]
text: str
@dataclass
class ImageRecord:
image_id: int
page_index: int
bbox: Tuple[float, float, float, float]
image_path: Optional[str]
''').strip() + "\n"
FILES[RAG_DIGEST_SCRIPT_DIR / "subsection_chunking_utilities" / "text_reconstruction.py"] = dedent(r'''
"""Text-block reconstruction and subsection passage normalization utilities."""
from __future__ import annotations
import re
from typing import List
def normalize_space(text: str) -> str:
"""Normalize whitespace while preserving paragraph boundaries."""
text = text.replace("\r\n", "\n").replace("\r", "\n")
text = text.replace("\u200b", "")
text = re.sub(r"[ \t]+", " ", text)
text = re.sub(r"\n{3,}", "\n\n", text)
return text.strip()
BULLET_PATTERN = re.compile(r"^[●•▪▫◦]\s*$")
BULLET_ITEM_PATTERN = re.compile(r"^[●•▪▫◦]\s+")
def clean_text_line(line: str) -> str:
line = line.replace("\u200b", "")
line = re.sub(r"[ \t]+", " ", line)
return line.strip()
def is_empty_line(line: str) -> bool:
return clean_text_line(line) == ""
def is_bullet_line(line: str) -> bool:
return bool(BULLET_PATTERN.fullmatch(clean_text_line(line)))
def is_bullet_item_line(line: str) -> bool:
return bool(BULLET_ITEM_PATTERN.match(clean_text_line(line)))
def construct_text_block(raw_text: str) -> str:
"""
Repair PyMuPDF bullet extraction within one text block.
Common pattern:
●
item line 1
item line 2
Becomes:
● item line 1 item line 2
"""
raw_text = raw_text.replace("\r\n", "\n").replace("\r", "\n")
raw_text = raw_text.replace("\u200b", "")
lines = raw_text.split("\n")
if not any(clean_text_line(line) for line in lines):
return "\n"
constructed_lines: List[str] = []
i = 0
while i < len(lines):
line = clean_text_line(lines[i])
if line == "":
constructed_lines.append("")
i += 1
continue
if is_bullet_line(line):
bullet_symbol = line
if i + 1 >= len(lines) or is_empty_line(lines[i + 1]):
constructed_lines.append(bullet_symbol)
i += 1
continue
item_lines = []
j = i + 1
while j < len(lines):
next_line = clean_text_line(lines[j])
if next_line == "":
break
if is_bullet_line(next_line):
break
item_lines.append(next_line)
j += 1
bullet_text = " ".join(item_lines).strip()
constructed_lines.append(f"{bullet_symbol} {bullet_text}" if bullet_text else bullet_symbol)
i = j
continue
constructed_lines.append(line)
i += 1
text = "\n".join(constructed_lines)
text = re.sub(r"\n{3,}", "\n\n", text)
return text.strip("\n")
def is_img_marker_line(line: str) -> bool:
return bool(re.fullmatch(r"<img\s+\d+>", clean_text_line(line)))
def is_table_block(paragraph: str) -> bool:
paragraph = paragraph.strip()
return bool(re.fullmatch(r"<t\s+\d+>\n.*?\n</t>", paragraph, flags=re.DOTALL))
def protect_hard_markers(text: str) -> str:
"""Force image/table markers to become hard paragraph boundaries."""
text = re.sub(r"\n*\s*(<img\s+\d+>)\s*\n*", r"\n\n\1\n\n", text)
text = re.sub(r"\n*(<t\s+\d+>\n.*?\n</t>)\n*", r"\n\n\1\n\n", text, flags=re.DOTALL)
return text
def merge_single_newline_paragraph(paragraph: str) -> str:
"""Merge line-wrapped captions/paragraphs while preserving bullet items."""
paragraph = paragraph.strip()
if not paragraph:
return ""
if is_img_marker_line(paragraph):
return paragraph
if is_table_block(paragraph):
return paragraph
lines = [clean_text_line(line) for line in paragraph.split("\n") if clean_text_line(line) != ""]
if not lines:
return ""
merged_lines = []
buffer = []
def flush_buffer() -> None:
nonlocal buffer
if buffer:
merged_lines.append(" ".join(buffer).strip())
buffer = []
for idx, line in enumerate(lines):
next_line = lines[idx + 1] if idx + 1 < len(lines) else ""
if is_bullet_item_line(line):
flush_buffer()
merged_lines.append(line)
continue
if next_line and is_bullet_item_line(next_line):
flush_buffer()
merged_lines.append(line)
continue
if is_img_marker_line(line):
flush_buffer()
merged_lines.append(line)
continue
buffer.append(line)
flush_buffer()
return "\n".join(line for line in merged_lines if line.strip())
def normalize_subsection_passage(text: str) -> str:
"""Final subsection-level cleanup after all page blocks have been appended."""
text = text.replace("\r\n", "\n").replace("\r", "\n")
text = text.replace("\u200b", "")
text = re.sub(r"[ \t]+\n", "\n", text)
text = re.sub(r"\n[ \t]+", "\n", text)
text = re.sub(r"[ \t]+", " ", text)
text = protect_hard_markers(text)
text = re.sub(r"\n{3,}", "\n\n", text)
paragraphs = text.split("\n\n")
normalized_paragraphs = []
for paragraph in paragraphs:
normalized = merge_single_newline_paragraph(paragraph)
if normalized.strip():
normalized_paragraphs.append(normalized)
text = "\n\n".join(normalized_paragraphs)
text = re.sub(r"\n{3,}", "\n\n", text)
return text.strip()
''').strip() + "\n"
FILES[RAG_DIGEST_SCRIPT_DIR / "subsection_chunking_utilities" / "pdf_outline.py"] = dedent(r'''
"""PDF outline and header extraction utilities."""
from __future__ import annotations
from typing import List
import fitz
from subsection_chunking_utilities.data_models import HeaderRecord
from subsection_chunking_utilities.text_reconstruction import normalize_space
def flatten_headers(doc: fitz.Document) -> List[HeaderRecord]:
"""Flatten all PDF outline entries into sequential subsection-level headers."""
raw_toc = doc.get_toc(simple=True)
headers: List[HeaderRecord] = []
for idx, item in enumerate(raw_toc):
level, title, page_number = item
headers.append(
HeaderRecord(
header_id=idx,
hierarchy=int(level),
title=normalize_space(str(title)),
page_index=int(page_number) - 1,
page_number=int(page_number),
)
)
return headers
''').strip() + "\n"
FILES[RAG_DIGEST_SCRIPT_DIR / "subsection_chunking_utilities" / "block_detection.py"] = dedent(r'''
"""PyMuPDF block detection helpers."""
from __future__ import annotations
from typing import Any, Dict, List, Tuple
import fitz
from subsection_chunking_utilities.text_reconstruction import construct_text_block
def find_bbox_centroid(bbox: Tuple[float, float, float, float]) -> Tuple[float, float]:
x0, y0, x1, y1 = bbox
return ((x0 + x1) / 2, (y0 + y1) / 2)
def text_block_centroid_inside_tbl_bbox(
centroid: Tuple[float, float],
ref_tbl: Tuple[float, float, float, float],
margin: float = 1.0,
) -> bool:
x, y = centroid
x0, y0, x1, y1 = ref_tbl
return (x0 - margin) <= x <= (x1 + margin) and (y0 - margin) <= y <= (y1 + margin)
def extract_block_text(block: Dict[str, Any]) -> str:
"""Extract visible text from a PyMuPDF text block."""
if block.get("type") != 0:
return ""
raw_lines = []
for line in block.get("lines", []):
spans = line.get("spans", [])
line_text = "".join(span.get("text", "") for span in spans)
raw_lines.append(line_text)
raw_text = "\n".join(raw_lines)
return construct_text_block(raw_text)
def preprocess_block_detection(page: fitz.Page) -> List[Dict[str, Any]]:
"""Return text/image blocks in a deterministic top-down, left-right order."""
try:
data = page.get_text("dict", sort=True)
except TypeError:
data = page.get_text("dict")
blocks = sorted(
data.get("blocks", []),
key=lambda block: (
round(block.get("bbox", [0, 0, 0, 0])[1], 1),
round(block.get("bbox", [0, 0, 0, 0])[0], 1),
),
)
return blocks
''').strip() + "\n"
FILES[RAG_DIGEST_SCRIPT_DIR / "subsection_chunking_utilities" / "table_processing.py"] = dedent(r'''
"""Table detection, normalization, and suppression utilities."""
from __future__ import annotations
# Intended to suppress: "Consider using the pymupdf_layout package for a greatly improved page layout analysis."
import io
from contextlib import redirect_stdout, redirect_stderr
from typing import Any, List, Optional, Tuple
import fitz
from subsection_chunking_utilities.block_detection import (
find_bbox_centroid,
text_block_centroid_inside_tbl_bbox,
)
from subsection_chunking_utilities.data_models import TableRecord
from subsection_chunking_utilities.text_reconstruction import normalize_space
def normalize_table_cells(table_cells: List[List[Any]]) -> str:
"""Convert extracted table cells into a compact text form."""
rows = []
for row in table_cells:
clean_cells = []
for cell in row:
clean_cells.append("" if cell is None else normalize_space(str(cell)))
row_text = " | ".join(clean_cells).strip()
if row_text:
rows.append(row_text)
return "\n".join(rows).strip()
def detect_tables_on_page(
page: fitz.Page,
page_index: int,
starting_table_id: int = 0,
) -> Tuple[List[TableRecord], int]:
"""Detect tables on a page and return normalized table records."""
table_records: List[TableRecord] = []
table_counter = starting_table_id
if not hasattr(page, "find_tables"):
return table_records, table_counter
try:
# Tries to extract table embeddings while suppressing the PyMuPDF warning
with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
table_finder = page.find_tables()
tables = getattr(table_finder, "tables", [])
except Exception as exc:
print(f"[WARN] Table detection failed on page {page_index + 1}: {exc}")
return table_records, table_counter
for table in tables:
table_counter += 1
try:
cells = table.extract()
table_text = normalize_table_cells(cells)
except Exception:
table_text = ""
if not table_text:
table_text = "[table detected but text extraction failed]"
table_records.append(
TableRecord(
table_id=table_counter,
page_index=page_index,
bbox=tuple(table.bbox),
text=table_text,
)
)
return table_records, table_counter
def find_containing_table(
block_bbox: Tuple[float, float, float, float],
table_records: List[TableRecord],
) -> Optional[TableRecord]:
"""Return the table whose bbox contains the block centroid, if any."""
center = find_bbox_centroid(block_bbox)
for table in table_records:
if text_block_centroid_inside_tbl_bbox(center, table.bbox):
return table
return None
''').strip() + "\n"
FILES[RAG_DIGEST_SCRIPT_DIR / "subsection_chunking_utilities" / "image_extraction.py"] = dedent(r'''
"""PDF image extraction utilities."""
from __future__ import annotations
from pathlib import Path
from typing import Any, Dict
import fitz
from subsection_chunking_utilities.data_models import ImageRecord
def save_image_block(
page: fitz.Page,
block: Dict[str, Any],
image_id: int,
doc_stem: str,
image_dir: Path,
) -> ImageRecord:
"""Save one PyMuPDF image block and return its image record."""
page_index = page.number
bbox = tuple(block.get("bbox", (0, 0, 0, 0)))
ext = block.get("ext", "png")
ext = ext.lower().replace(".", "")
image_filename = f"{doc_stem}_p{page_index + 1:03d}_img{image_id:04d}.{ext}"
image_path = image_dir / image_filename
image_bytes = block.get("image", None)
if image_bytes:
image_path.write_bytes(image_bytes)
else:
pix = page.get_pixmap(clip=fitz.Rect(bbox), dpi=200)
image_path = image_path.with_suffix(".png")
pix.save(image_path)
return ImageRecord(
image_id=image_id,
page_index=page_index,
bbox=bbox,
image_path=str(image_path),
)
''').strip() + "\n"
FILES[RAG_DIGEST_SCRIPT_DIR / "subsection_chunking_utilities" / "page_extraction.py"] = dedent(r'''
"""Subsection-level page traversal and passage construction."""
from __future__ import annotations
import re
from dataclasses import asdict
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
import fitz
from subsection_chunking_utilities.block_detection import extract_block_text, preprocess_block_detection
from subsection_chunking_utilities.data_models import HeaderRecord
from subsection_chunking_utilities.image_extraction import save_image_block
from subsection_chunking_utilities.pdf_outline import flatten_headers
from subsection_chunking_utilities.table_processing import detect_tables_on_page, find_containing_table
from subsection_chunking_utilities.text_reconstruction import normalize_subsection_passage
def make_subsection_key(header: HeaderRecord) -> str:
return f"{header.header_id:03d}::{header.title}"
def finalize_subsection_builder(
subsection_chunk: Dict[str, Dict[str, Any]],
current_header: Optional[HeaderRecord],
page_blocks_string_builder: List[str],
) -> List[str]:
if current_header is None:
return []
subsection_key = make_subsection_key(current_header)
passage = "\n".join(part for part in page_blocks_string_builder if part is not None)
passage = normalize_subsection_passage(passage)
subsection_chunk[subsection_key] = {
**asdict(current_header),
"subsection_key": subsection_key,
"char_count": len(passage),
"image_marker_count": len(re.findall(r"<img\s+\d+>", passage)),
"table_marker_count": len(re.findall(r"<t\s+\d+>", passage)),
"passage": passage,
}
return []
def header_iteration_logic(
page_index: int,
headers: List[HeaderRecord],
h_index: int,
current_header: Optional[HeaderRecord],
subsection_chunk: Dict[str, Dict[str, Any]],
page_blocks_string_builder: List[str],
) -> Tuple[Optional[HeaderRecord], int, List[str]]:
"""
Page-boundary header transition logic.
Assumption:
Each next flattened section/subsection begins on a new page.
"""
while h_index < len(headers) and page_index >= headers[h_index].page_index:
page_blocks_string_builder = finalize_subsection_builder(
subsection_chunk=subsection_chunk,
current_header=current_header,
page_blocks_string_builder=page_blocks_string_builder,
)
current_header = headers[h_index]
h_index += 1
return current_header, h_index, page_blocks_string_builder
def build_subsection_passages(
doc_path: Path,
image_dir: Path,
) -> Tuple[Dict[str, Dict[str, Any]], Dict[int, Dict[str, Any]], Dict[int, Dict[str, Any]]]:
"""
Build subsection-level passages and records for extracted images/tables.
Returns:
subsection_chunk: {subsection_key: subsection metadata and passage}
image_records: {image_id: image metadata}
table_records: {table_id: table metadata}
"""
image_dir.mkdir(parents=True, exist_ok=True)
doc = fitz.open(doc_path)
doc_stem = doc_path.stem
try:
headers = flatten_headers(doc)
if not headers:
raise ValueError("No PDF outline / TOC entries found.")
headers = sorted(headers, key=lambda h: (h.page_index, h.header_id))
subsection_chunk: Dict[str, Dict[str, Any]] = {}
image_records: Dict[int, Dict[str, Any]] = {}
table_records: Dict[int, Dict[str, Any]] = {}
figure_tracker = {"img": 0, "tbl": 0}
h_index = 0
current_header: Optional[HeaderRecord] = None
page_blocks_string_builder: List[str] = []
first_outline_page = headers[0].page_index
for page_index in range(first_outline_page, len(doc)):
page = doc[page_index]
current_header, h_index, page_blocks_string_builder = header_iteration_logic(
page_index=page_index,
headers=headers,
h_index=h_index,
current_header=current_header,
subsection_chunk=subsection_chunk,
page_blocks_string_builder=page_blocks_string_builder,
)
if current_header is None:
continue
page_tables, figure_tracker["tbl"] = detect_tables_on_page(
page=page,
page_index=page_index,
starting_table_id=figure_tracker["tbl"],
)
for table in page_tables:
table_records[table.table_id] = {
**asdict(table),
"subsection_key": make_subsection_key(current_header),
}
emitted_table_ids_on_page = set()
blocks = preprocess_block_detection(page)
for block in blocks:
block_type = block.get("type")
block_bbox = tuple(block.get("bbox", (0, 0, 0, 0)))
if block_type == 0:
containing_table = find_containing_table(
block_bbox=block_bbox,
table_records=page_tables,
)
if containing_table is not None:
table_id = containing_table.table_id
if table_id not in emitted_table_ids_on_page:
table_markup = f"\n\n<t {table_id}>\n{containing_table.text}\n</t>\n\n"
page_blocks_string_builder.append(table_markup)
emitted_table_ids_on_page.add(table_id)
continue
text = extract_block_text(block)
if text.strip() == "":
page_blocks_string_builder.append("\n")
continue
page_blocks_string_builder.append(text)
elif block_type == 1:
figure_tracker["img"] += 1
image_id = figure_tracker["img"]
try:
img_record = save_image_block(
page=page,
block=block,
image_id=image_id,
doc_stem=doc_stem,
image_dir=image_dir,
)
image_records[image_id] = {
**asdict(img_record),
"subsection_key": make_subsection_key(current_header),
"error": None,
}
except Exception as exc:
print(f"[WARN] Failed to save img_{image_id} on page {page_index + 1}: {exc}")
image_records[image_id] = {
"image_id": image_id,
"page_index": page_index,
"bbox": block_bbox,
"image_path": None,
"subsection_key": make_subsection_key(current_header),
"error": str(exc),
}
page_blocks_string_builder.append(f"\n<img {image_id}>\n")
page_blocks_string_builder = finalize_subsection_builder(
subsection_chunk=subsection_chunk,
current_header=current_header,
page_blocks_string_builder=page_blocks_string_builder,
)
finally:
doc.close()
return subsection_chunk, image_records, table_records
''').strip() + "\n"
# Subsection-level chunking orchestrator
FILES[RAG_DIGEST_SCRIPT_DIR / "subsection_chunking_module.py"] = dedent(r'''
"""Subsection-level PDF chunking orchestrator."""
from __future__ import annotations
from pathlib import Path
from typing import Any, Dict, Tuple
from config import PDF_PATH, RAW_IMAGES_DIR
from subsection_chunking_utilities.page_extraction import build_subsection_passages
def run_subsection_chunking(
pdf_path: Path = PDF_PATH,
image_dir: Path = RAW_IMAGES_DIR,
) -> Tuple[Dict[str, Dict[str, Any]], Dict[int, Dict[str, Any]], Dict[int, Dict[str, Any]]]:
"""Run the first loop: PDF -> subsection passages + image/table records."""
print("[1/4] Running subsection chunking")
subsection_chunk, image_records, table_records = build_subsection_passages(
doc_path=Path(pdf_path),
image_dir=Path(image_dir),
)
print(f"\tSubsection records: {len(subsection_chunk)}")
print(f"\tImage records: {len(image_records)}")
print(f"\tTable records: {len(table_records)}")
return subsection_chunk, image_records, table_records
''').strip() + "\n"
FILES[RAG_DIGEST_SCRIPT_DIR / "semantic_chunking_utilities" / "passage_preprocessing.py"] = dedent(r'''
"""Passage preprocessing utilities before semantic chunking."""
from __future__ import annotations
import re
IMAGE_MARKER_RE = re.compile(r"<img\s+(\d+)>")
def clean_text(text: str) -> str:
text = text.replace("\r\n", "\n").replace("\r", "\n")
text = text.replace("\u200b", "")
text = re.sub(r"[ \t]+", " ", text)
text = re.sub(r"\n{3,}", "\n\n", text)
return text.strip()
def prepare_text_for_semantic_chunking(s_passage: str) -> str:
"""
Prepare subsection passage before semantic chunking.
Policy:
- remove <img N> markers
- keep figure captions
- preserve table text but remove <t N> wrappers
"""
text = IMAGE_MARKER_RE.sub("", s_passage)
text = re.sub(r"<t\s+\d+>\n", "", text).replace("\n</t>", "")
text = re.sub(r"\n{3,}", "\n\n", text)
return clean_text(text)
''').strip() + "\n"
FILES[RAG_DIGEST_SCRIPT_DIR / "semantic_chunking_utilities" / "image_contexts.py"] = dedent(r'''
"""Image marker, caption, antecedent, and subsequent passage utilities."""
from __future__ import annotations
import re
from typing import Any, Dict, List, Optional, Tuple
from semantic_chunking_utilities.passage_preprocessing import IMAGE_MARKER_RE, clean_text
FIGURE_CAPTION_RE = re.compile(
r"^\s*(Figure\s+\d+[A-Za-z]?\s*:\s*.*?)(?=\n\n|<img\s+\d+>|$)",
flags=re.DOTALL,
)
TABLE_BLOCK_RE = re.compile(r"<t\s+\d+>\n.*?\n</t>", flags=re.DOTALL)
def paragraph_is_image_marker(paragraph: str) -> bool:
return bool(re.fullmatch(r"<img\s+\d+>", paragraph.strip()))
def paragraph_is_figure_caption(paragraph: str) -> bool:
return bool(re.match(r"^Figure\s+\d+[A-Za-z]?\s*:", paragraph.strip()))
def paragraph_is_table_block(paragraph: str) -> bool:
return bool(TABLE_BLOCK_RE.fullmatch(paragraph.strip()))
def extract_image_caption(after_img_text: str) -> Tuple[Optional[str], str]:
"""Extract immediate Figure caption after an <img N> marker."""
after_img_text = after_img_text.lstrip()
match = FIGURE_CAPTION_RE.match(after_img_text)
if not match:
return None, after_img_text
caption = clean_text(match.group(1))
remaining = after_img_text[match.end():].lstrip()
return caption, remaining
def get_last_antecedent_passage(before_img_text: str) -> Optional[str]:
"""Get nearest paragraph before image marker, skipping image markers/captions."""
paragraphs = [clean_text(p) for p in before_img_text.split("\n\n") if clean_text(p)]
for paragraph in reversed(paragraphs):
if paragraph_is_image_marker(paragraph) or paragraph_is_figure_caption(paragraph):
continue
return paragraph
return None
def get_first_subsequent_passage(after_caption_text: str) -> Optional[str]:
"""Get nearest paragraph after image caption, skipping image markers/captions."""
paragraphs = [clean_text(p) for p in after_caption_text.split("\n\n") if clean_text(p)]
for paragraph in paragraphs:
if paragraph_is_image_marker(paragraph) or paragraph_is_figure_caption(paragraph):
continue
return paragraph
return None
def extract_image_contexts_from_subsection(
s_passage: str,
image_records: Dict[Any, Dict[str, Any]],
) -> List[Dict[str, Any]]:
"""Extract all <img N> contexts from one subsection passage."""
image_contexts = []
for match in IMAGE_MARKER_RE.finditer(s_passage):
fig_id = int(match.group(1))
before_img_text = s_passage[:match.start()]
after_img_text = s_passage[match.end():]
caption, after_caption_text = extract_image_caption(after_img_text)
antecedent_passage = get_last_antecedent_passage(before_img_text)
subsequent_passage = get_first_subsequent_passage(after_caption_text)
img_record = image_records.get(fig_id)
image_path = img_record.get("image_path") if img_record is not None else None
image_contexts.append({
"figure_id": fig_id,
"caption": caption,
"neighbor_passages": {
"antecedent": antecedent_passage,
"subsequent": subsequent_passage,
},
"image_path": image_path,
})
return image_contexts
''').strip() + "\n"
FILES[RAG_DIGEST_SCRIPT_DIR / "semantic_chunking_utilities" / "semantic_splitter.py"] = dedent(r'''
"""LlamaIndex semantic splitter wrapper utilities."""
from __future__ import annotations
from typing import List
from llama_index.core import Document
from llama_index.core.node_parser import SemanticSplitterNodeParser
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
def build_semantic_splitter(
model_name: str,
device: str,
buffer_size: int = 1,
breakpoint_percentile_threshold: int = 95,
) -> SemanticSplitterNodeParser:
return SemanticSplitterNodeParser(
buffer_size=buffer_size,
breakpoint_percentile_threshold=breakpoint_percentile_threshold,
embed_model=HuggingFaceEmbedding(model_name=model_name, device=device),
)
def semantic_chunk_passage(
passage: str,
semantic_splitter: SemanticSplitterNodeParser,
) -> List[str]:
document = Document(text=passage)
nodes = semantic_splitter.get_nodes_from_documents([document])
return [node.get_content().strip() for node in nodes if node.get_content().strip()]
''').strip() + "\n"
FILES[RAG_DIGEST_SCRIPT_DIR / "semantic_chunking_utilities" / "token_audit.py"] = dedent(r'''
"""BGE tokenizer audit utilities for semantic chunks."""
from __future__ import annotations
from sentence_transformers import SentenceTransformer
def count_bge_tokens(text: str, encoder: SentenceTransformer) -> int:
tokenized = encoder.tokenizer(
text,
add_special_tokens=True,
truncation=False,
return_attention_mask=False,
verbose=False, # Some semantic chunks from the subsection passage will still exceed BGE's limit of 512 tokens
)
return len(tokenized["input_ids"])
''').strip() + "\n"
# Semantic Chunking Subsection Passages Orchestrator
FILES[RAG_DIGEST_SCRIPT_DIR / "semantic_chunking_module.py"] = dedent(r'''
"""Semantic chunking and metadata construction orchestrator."""
from __future__ import annotations
import gc
from typing import Any, Dict, List, Optional, Tuple
import torch
from sentence_transformers import SentenceTransformer