I’ve been learning how RAG systems work, and I wanted to understand one part properly: loading and chunking a messy document. Every tutorial I saw makes it look like two steps. Use the right loader, apply a recursive text splitter, and boom, you have chunks.

So I tried that on a real PDF. With the tutorial setup (1000-character chunks, 200 overlap, page by page), 137 of the 193 chunks (71%) had the page header in them, and at least 16 page breaks cut straight through indented code. This was not the expected output, I must say. But it was clear enough that this approach will not work.

PDF LINK

Let’s analyze the PDF first. The document is a 142-page set of Python lecture notes, converted from Word to PDF. It has the same header and footer on every page, code that runs across page breaks, and no code fences at all. Scripts, their Output: sections and >>> REPL sessions all sit in the same stream of text as the prose. It also has tables and diagrams. I’m skipping those here and keeping only text, code and output. Even with that smaller scope, there was a lot more to do here than expected.

End goal of this exercise is simple. A list of chunks that:

  • are not broken in the middle. No half function, no if without its else
  • don’t have noise. No header, no footer, no page number in the text
  • still run as valid Python if they’re code
  • know where they came from, which pages and which unit

Basically no orphans. Each chunk should have close to complete meaning on its own.

let’s start with loading the pdf

from pypdf import PdfReader
from langchain_core.documents import Document

def load_pdf(path, start_page=0):
    reader = PdfReader(path)
    total = len(reader.pages)
    for i in range(start_page, total):
        yield Document(
            page_content=reader.pages[i].extract_text().rstrip(),
            metadata={"source": path, "page": i,
                      "page_label": reader.page_labels[i], "total_pages": total},
        )

pages = list(load_pdf("python_notes.pdf", start_page=5))  # skip syllabus + index

Now why this and not just use the library? I wanted control over the whitespace. I will strip extra whitespace only from the end of each page, not the start, because a page can start with Python code and We don’t want to lose its indentation. It’s part of the code.

There are three different page numbers floating around. page is the 0-based index, page_label is what the PDF reader shows, and the one printed on the page is something else again. I keep all of them in metadata so I can map back later.

Also, this is a lazy loader, so it gives back one page at a time. That doesn’t matter much yet, but it matters in Part 2.

Here’s what a raw page looks like:

PYTHON PROGRAMMING III YEAR/II SEM MRCET \n33 \n \nC:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py \nEnter a value 5 \nEnter b value-2 \nbig number= 5 \n#program to find biggest of two numbers using functions. (nested if) \n \ndef biggest(a,b,c): \n if a>b : \n if a>c : \n return a \n else : \n return c \n else : \n if b>c : \n return b \n else : \n return c \n \n \na=int(input("Enter a value")) \nb=int(input("Enter b value")) \nc=int(input("Enter c value")) \n #function call \nbig= biggest(a,b,c) \nprint("big number= ",big) \n \nOutput: \nC:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py \nEnter a value 5 \nEnter b value -6 \nEnter c value 7 \nbig number= 7 \n \n#Writer a program to read one subject mark and print pass or fail use single return \nvalues function with argument. \ndef result(a): \n if a>40: \n return "pass"'

One side note. The order you see in a PDF viewer and the order you get from the text extraction can be different. The extraction follows the order text was written into the PDF’s internal content stream, not where it sits on the page. That’s why the page number is the 2nd line in our output and not the last.

[issue] page 38-39

There is Python code that is partly on page 38 and partly on the next one. Since we load one document at a time, if we chunk document by document we will have orphaned code that doesn’t belong to anything, and it will lose its meaning. We have to keep the code together, otherwise the bottom half will be useless.

cleaning the pdf

For now let’s just clean the headers and footers. The idea is simple: take the top 2 and bottom 2 non-empty lines from each page, and count how many pages each of those lines shows up on. If a line shows up on 60% or more of the pages, it’s boilerplate, and it goes into a set we use for removal.

Why only the top and bottom lines? Why not count every line on the page?

[issue] Output: looks like boilerplate

Output: appears on 72 of 137 pages, which is 53%. If I counted lines across the whole page, it would get flagged like a header, and I’d delete 118 real lines along with it. Headers and footers live at the edges of the page, and Output: lives in the middle. So looking only at position takes care of it.

The 60% threshold: it separates the header, which appears on every page, from Output:, which I want to keep so each program gets chunked with its result.

The page number is different. It changes on every page, so frequency counting can never catch it. A simple regex does the job, without making it complicated. But I don’t throw it away: the printed page number goes into metadata, next to page and page_label.

import re
from collections import Counter

ZONE = 2          # only look at the first/last 2 non-blank lines of each page
THRESHOLD = 0.6   # a line is boilerplate if it sits in the zone on >= 60% of pages

def find_boilerplate(docs: list[Document]) -> set[str]:
    counts: Counter[str] = Counter()
    for d in docs:
        counts.update({norm(l) for l in zone_lines(d.page_content)})
    return {line for line, n in counts.items() if n / len(docs) >= THRESHOLD}

stitching it back together

We have a list of documents, one per page. But to make meaningful chunks, we need to cross the boundaries the pages impose. Half-cut code or half-cut text is not a useful chunk to work with, and we already saw code split across pages 38–39. So we join the loaded text into one complete piece, and then make the cuts at boundaries that come from the content.

Don’t let the container boundary interfere with the content boundary.

This only works because we cleaned first. If the header were still there, stitching would just put it in the middle of the code.

PAGE_JOIN = "\n"   # one newline, NOT "\n\n"

def stitch(docs):
    """Return (full_text, page_starts, page_meta).
    page_starts[k] = offset in full_text where the k-th page begins.
    page_meta[k]   = that page's metadata (page, page_label, printed_page)."""
    parts, page_starts, page_meta = [], [], []
    offset = 0
    for d in docs:
        page_starts.append(offset)
        page_meta.append(d.metadata)
        parts.append(d.page_content)
        offset += len(d.page_content) + len(PAGE_JOIN)
    return PAGE_JOIN.join(parts), page_starts, page_meta

Why "\n" and not "\n\n"? RecursiveCharacterTextSplitter tries "\n\n" first when it looks for a place to cut. If every page seam looked like a paragraph break, the splitter would happily cut there, and we’d be right back to page-shaped chunks. With a single "\n", the seam looks like any other line break, so it gets no special treatment.

Does this approach hold up on very large text? Say a 1000-page PDF, or many 1000-page PDFs, then what?

  1. If there are many PDFs, it makes sense to process them in parallel instead of combining them, and link them later with some form of group id or other cross link.
  2. 1000 pages of text still fits in memory, but when there are many, we can build a streaming pipeline that picks one page at a time and chunks it on a running buffer. We will explore that in a different post.

[issue] wrapped comments

Comments in Python start with #, and they only cover a single line. In the Word document, long comment lines just wrapped visually onto the next line. When it was converted to PDF, that wrap became a real line break. So now the end of the comment sits on its own line, without a #, and to Python it looks like code.

before: '#Program to find area of a circle using function use single return value function with \nargument.'
after:  '#Program to find area of a circle using function use single return value function with  argument.'

The solution is simple. A line is a wrapped comment if:

  • it starts with #
  • it’s long enough to have hit the wrap limit (70 characters; )
  • the next line is not empty, doesn’t start with #, and does not look like code

If all of that is true, we join the two lines.

How do we decide what looks like code? A few simple rules, based on this PDF:

  • It starts with >>>: a REPL line, so it’s code.
  • Its first word is a Python keyword (def, import, for…): code.
  • Otherwise, ast.parse(line) decides. x = 1 and print(x) parse. values function with argument. raises SyntaxError, so it’s prose.
import ast
import keyword
from dataclasses import dataclass

WRAP_MIN_LEN = 70

@dataclass(frozen=True)
class WrapRepair:
    offset: int        # position in the full text of the newline that was replaced
    comment_tail: str  # end of the comment line
    joined: str        # the line that got joined onto it

def is_wrapped(comment: str, nxt: str) -> bool:
    return (
        comment.lstrip().startswith("#")
        and len(comment.rstrip()) >= WRAP_MIN_LEN
        and bool(nxt.strip())
        and not nxt.lstrip().startswith("#")
        and not looks_like_code(nxt)
    )


def repair_wraps(full: str) -> tuple[str, list[WrapRepair]]:
    """Replace the newline after each wrapped comment with a space.

    '\\n' -> ' ' keeps the text the SAME LENGTH, so the page_starts
    from stitching stay valid; no offset needs recomputing.
    """
    chars = list(full)
    repairs: list[WrapRepair] = []
    lines = full.split("\n")
    pos = 0
    for cur, nxt in zip(lines, lines[1:]):
        newline_at = pos + len(cur)
        if is_wrapped(cur, nxt):
            chars[newline_at] = " "
            repairs.append(WrapRepair(newline_at, cur.strip()[-40:], nxt.strip()))
        pos = newline_at + 1
    return "".join(chars), repairs

The repair replaces the \n after the comment with a space. That’s one character for one character, so the text stays exactly the same length, and the page_starts offsets from stitching are still correct. Nothing needs recomputing. The rules aren’t perfect. English words like for, if, and and in are also Python keywords, so a wrap starting with one of them would be treated as code and not joined. A one-word wrap like values also parses as valid Python.

splitting code and prose

Now the real problem. The splitter needs to know where code starts and where it ends, and this PDF just doesn’t tell you. No code fences, nothing. Code, its output, >>> sessions and the explanation text are all just lines. A normal splitter doesn’t care. It cuts wherever it hits the size limit, and if that’s in the middle of a function, too bad.

So I go through the text line by line and decide what each line is. There are 4 kinds:

  • PROSE: the explanation text
  • CODE: script lines, comments, indented lines
  • OUTPUT: whatever comes after an Output: line
  • REPL: >>> sessions and whatever they print

Why a state machine and not just a check on each line? Because of output. If you look at a line like 7 or Hello World on its own, you can’t tell what it is. It only makes sense because the line before it said Output:. So once we’re in OUTPUT or REPL, we stay there until something clearly ends it. That’s the state part.

The rules go in order, and the first one that matches wins:

  1. starts with >>> or ... → REPL
  2. the line is just Output: → OUTPUT
  3. a UNIT – I heading → PROSE
  4. already in OUTPUT or REPL → stay there, until a blank line, a comment, a keyword line, a heading or an English sentence shows up
  5. otherwise, is it code?
    • indented → code
    • starts with # → code
    • looks like an English sentence (6+ mostly alphabetic words that don’t parse as Python) → prose
    • starts with a Python keyword and has code characters (= ( ) [ ] { } :) or parses → code
    • no code characters at all → prose
    • otherwise → code only if ast.parse accepts it
import ast
import re
import keyword
from dataclasses import dataclass
from enum import Enum
from typing import Literal

Kind = Literal["code", "prose"]

HEADING = re.compile(r"UNIT\s+–\s+[IVX]+\b")   # en dash, not a hyphen
CODE_CHARS = set("=()[]{}:")

class State(Enum):
    PROSE = "prose"
    CODE = "code"
    OUTPUT = "output"
    REPL = "repl"

@dataclass(frozen=True)
class Block:
    kind: Kind
    start: int   # offset of the first character in the full text
    end: int


def segment(full: str) -> list[Block]:
    blocks: list[Block] = []
    state = State.PROSE
    block_kind: Kind | None = None
    block_start = 0
    last_end = 0           # end of the last non-blank line seen
    after_blank = False
    pos = 0

    def close() -> None:
        if block_kind is not None:
            blocks.append(Block(block_kind, block_start, last_end))

    for line in full.split("\n"):
        line_end = pos + len(line)
        if not line.strip():
            after_blank = True
        else:
            prev = state
            state = next_state(line, state, after_blank)
            kind: Kind = "prose" if state is State.PROSE else "code"
            # new example: code that starts after an Output/REPL section
            new_example = state is State.CODE and prev in (State.OUTPUT, State.REPL)
            if kind != block_kind or new_example:
                close()
                block_kind, block_start = kind, pos
            last_end = line_end
            after_blank = False
        pos = line_end + 1
    close()
    return blocks

def next_state(line: str, state: State, after_blank: bool) -> State:
    s = line.strip()
    if s.startswith(">>>") or s.startswith("..."):
        return State.REPL
    if s.rstrip(" :").lower() == "output":
        return State.OUTPUT
    if HEADING.match(s):
        return State.PROSE
    # output and REPL results continue until something ends them
    if state in (State.OUTPUT, State.REPL) and not ends_results(s, after_blank):
        return state
    return State.CODE if is_code_line(line) else State.PROSE

chunking

Now we know which lines are prose and which are code. But the blocks are still the wrong size for embedding. Some prose blocks are really long and some code blocks are just one line. And prose and code can’t be split the same way. A prose chunk can repeat a sentence from the previous chunk and it’s fine. A code chunk that repeats lines or loses its indentation is broken.

So three things happen here.

First, glue the lead-ins to their code. The notes introduce examples with a short line like Example: or Syntax:. The state machine correctly calls that prose, but on its own as a chunk it means nothing, and the code below it loses its label.

Second, use two splitters, one for each kind. Both go up to 1000 characters, but they behave differently:

Prose uses the plain text splitter:

  • cuts at paragraphs first, then lines, then words
  • 200 characters of overlap
  • leading whitespace stripped

Code uses the Python-aware splitter:

  • cuts at class first, then def, then blank lines, then lines
  • no overlap
  • leading whitespace kept

Overlap is good for prose because the repeated sentence carries context across the cut. In code it just duplicates lines of the program. And whitespace has to stay, because a chunk that starts with an indented line needs that indentation or it’s not valid Python anymore.

Each splitter only ever sees one block. So apart from the short lead-ins we glued on, a chunk never mixes explanation and code.

So that if/else that got cut in half at the start? Now it’s one chunk, tagged with both pages.

Overall: 472 chunks, 0 with the page header in them, 118 that span 2 or more pages.

from bisect import bisect_right
from langchain_text_splitters import Language, RecursiveCharacterTextSplitter

CHUNK_SIZE = 1000
PROSE_OVERLAP = 200
LEAD_IN_MAX = 80      # "Example:", "Syntax:" and similar short labels


@dataclass(frozen=True)
class DocIndex:
    """Everything stitching produced, needed to turn offsets into citations."""
    source: str
    page_starts: list[int]
    page_labels: list[str]
    printed_pages: list[int | None]
    unit_starts: list[int]
    unit_names: list[str]
    unit_titles: list[str]


def chunk(full: str, blocks: list[Block], idx: DocIndex) -> list[Document]:
    splitters = make_splitters()
    chunks: list[Document] = []
    for b in attach_lead_ins(full, blocks):
        text = full[b.start:b.end]
        for piece in splitters[b.kind].split_documents([Document(page_content=text)]):
            if not piece.page_content.strip():
                continue
            start = b.start + int(piece.metadata["start_index"])   # block-relative -> absolute
            end = start + len(piece.page_content)
            pages = _span(idx.page_starts, start, end)
            units = _span(idx.unit_starts, start, end)
            chunks.append(Document(
                page_content=piece.page_content,
                metadata={
                    "source": idx.source,
                    "kind": b.kind,
                    "start": start,
                    "end": end,
                    "pages": [idx.page_labels[k] for k in pages],
                    "printed_pages": [idx.printed_pages[k] for k in pages],
                    "unit": idx.unit_names[units[0]] if units else None,
                    "unit_title": idx.unit_titles[units[0]] if units else None,
                },
            ))
    return chunks


# putting it all together
pages = list(load_pdf("python_notes.pdf", start_page=5))
boilerplate = find_boilerplate(pages)
pages = [clean_page(p, boilerplate) for p in pages]
full, page_starts, page_meta = stitch(pages)
full, repairs = repair_wraps(full)
idx = build_index("python_notes.pdf", full, page_starts, page_meta)
chunks = chunk(full, segment(full), idx)

Would any of this work on a different PDF? Mostly no for the specific fixes, yes for the method. The en dash and the wrapped comments were particular to this PDF. Finding them, by looking at the raw output, measuring, fixing and checking, works for any loader.

rules of thumb

These come from one PDF, so take them as that. The first few I learned the hard way. The rest are things I’d watch for next time.

What this PDF taught me:

  1. Look at the raw output before writing any code, with repr(), not print(). print() hides trailing spaces and odd characters. That’s how I saw the space before every \n, the header on line 1 and the page number on line 2.
  2. Don’t let the container boundary interfere with the content boundary. A page is about storage, not meaning. Join first, then chunk.
  3. Find noise by position and frequency, not by hard-coding text. The header was noise because it sat in the top 2 lines of every page, well over the 60% threshold. Output: repeats a lot too (53% of pages), but it sits in the middle of the page and it’s content.
  4. Don’t strip whitespace blindly. In code it means something. That’s the whole .strip() vs .rstrip() thing. Same for characters that look alike: the units use an en dash (UNIT – I), not a hyphen, and exact matching on a hyphen finds nothing.
  5. Keep the offsets right through every step. Either a change keeps the length the same (like the \n → " " swap for wrapped comments), or it updates the offsets.
  6. Log every repair. The wrapped-comment fix keeps a list of what it changed. Heuristics are tuned to one document, and the log is how you notice when they misfire on the next one.

Every issue in this post comes back to rules 2 and 4: what does the format lose, and what is noise?

Full Code Github Link also repo has requirements file with same name in same folder.

Thanks for reading.

Feel free to connect with me on (rahuldsoni2001@gmail.com)