Papa Programmer
Lesson 03 of 15

Loading and cleaning documents

8 min read

Optional

Why cleaning comes first

A retriever returns text exactly as it was stored. If a web page was stored with its menu, the menu words, "Home Shop Help", become part of that page's passages. They match questions they should not match. They also take up space in the prompt, and a model pays for every TokenA small piece of text that a model reads or writes as one unit, such as a short word, part of a longer word or a punctuation mark. In English, one token is about four characters. it reads.

Cleaning is cheap compared with the problems it prevents. A search that returns a footer instead of a policy looks like a search bug, and the cause is in the data.

  1. ExtractRead each file format and pull out the text.
  2. StripRemove menus, scripts, footers and other page furniture.
  3. Keep structureLeave headings, lists and tables readable.
  4. Remove repeatsDrop pages that say the same thing twice.
  5. LabelRecord where each document came from and when it changed.
The loading steps, in order

Extract the text

Each format needs its own reader. Markdown and plain text are already text. HTML needs the tags removed. A PDF that was made from a word processor holds text that a library can extract, but a scanned PDF holds only pictures of text, and it needs optical character recognition (OCR) first. Tables are the hardest case. Reading a table cell by cell can scramble the rows, so check a few tables by eye.

Strip the page furniture

Web pages carry a lot that is not content. The program below uses Python's built-in HTML parser to keep the text and skip anything inside a menu, a script or a footer.

python
from html.parser import HTMLParser

class TextExtractor(HTMLParser):
	skip = {"script", "style", "nav", "footer"}

	def __init__(self):
		super().__init__()
		self.depth = 0
		self.parts = []

	def handle_starttag(self, tag, attrs):
		if tag in self.skip:
			self.depth += 1
		elif tag in ("h1", "h2", "p", "li") and not self.depth:
			self.parts.append("\n")

	def handle_endtag(self, tag):
		if tag in self.skip:
			self.depth -= 1

	def handle_data(self, data):
		if not self.depth:
			self.parts.append(data.replace("\n", " "))

page = """<html><nav>Home | Shop | Help</nav>
<h1>Returns</h1><p>You can   return an unused bike
within 30 days.</p><script>track()</script>
<p>Refunds take 5 business days.</p><footer>Riverside Bikes</footer></html>"""

parser = TextExtractor()
parser.feed(page)
lines = [" ".join(line.split()) for line in "".join(parser.parts).split("\n")]
print([line for line in lines if line])

It prints:

text
['Returns', 'You can return an unused bike within 30 days.', 'Refunds take 5 business days.']

Three things happened. The menu, the script and the footer are gone. The extra spaces and the line break inside the first paragraph are now single spaces. And each heading and paragraph is its own line, so the structure survived. Real pages need real selectors for their own menus, but the idea does not change: decide what counts as content, and keep only that.

Keep the structure

Do not flatten everything into one block. A heading such as "Returns" tells the next step where one topic ends and the next begins, and the How to chunk documents Lesson uses it. A numbered list of steps should stay a list, because step 3 means nothing without step 2.

Remove repeats

Sites often hold the same text at several addresses, or the same policy in two versions. If both are indexed, a question about that policy returns the same passage twice and fills the prompt with a repeat. The simplest check is to normalise the text, which here means lower-casing it and collapsing spaces, and then compare a fingerprint of it.

python
import hashlib

pages = {
	"a": "Returns take 30 days.",
	"b": "returns   take 30 days.",
	"c": "Shipping takes 5 days.",
}

seen = {}
for name, text in pages.items():
	fingerprint = hashlib.sha256(" ".join(text.lower().split()).encode()).hexdigest()
	seen.setdefault(fingerprint, name)

print(sorted(seen.values()))

It prints:

text
['a', 'c']

Pages a and b differ only in capital letters and spaces, so they share one fingerprint and the second is dropped. This catches exact repeats. Near-repeats, such as two versions of a policy with one changed line, need a person to decide which to keep.

Treat documents as untrusted

A document is not an instruction, but a model cannot always tell the difference. Text that says "ignore your earlier instructions" can sit inside a web page or an uploaded file, and if it is retrieved, it reaches the model. This attack is called Prompt injectionAn attack that hides instructions in text the agent reads, such as a web page or an email. The model may treat the hidden text as a command and act on it.. Cleaning does not remove it, so decide which sources you trust before you index them, and treat the rest as untrusted input.

Read the result

Before you move on, open ten cleaned documents and read them as the model would. Look for leftover menu text, broken words, tables that read as nonsense and empty pages. Ten minutes here saves hours of confusion in later steps.

Clean before you indexWhatever stays in the text can be retrieved and read by the model.
Keep the structureHeadings and lists tell the next step where ideas begin and end.
Trust sources deliberatelyRetrieved text can carry instructions, so index only what you trust.

Your reading position is saved

0%

0 of 15 complete

Contents

Learning tools