✦ GHINOVA

GHINOVA / Python PDF chatbot tutorial

FREE PYTHON TUTORIAL

Build a PDF chatbot in Python without an API key

By Ginwa Fakih, PhD in Computer Science ·

Ask a question about a PDF and get back the passage and page number that support the answer. This tutorial builds the retrieval part of retrieval-augmented generation (RAG). The example returns a direct quote, so you can check the evidence before adding a language model.

1. Extract passages and keep their page numbers

Choose a PDF with selectable text and save it as document.pdf. For a quick test, create a two-page PDF in a word processor. Put “Lab visitors must sign in at reception” on the first page and “Safety glasses are required when using the drill press” on the second.

Install the packages in your terminal. In a Colab code cell, use %pip in place of python -m pip and upload the PDF to the session.

python -m pip install pypdf scikit-learn

Run this Python code. Each record pairs an extracted line with its original page number. Line-based splitting keeps the example short and works best on PDFs with simple layouts.

from pypdf import PdfReader

passages = []
for page_number, page in enumerate(PdfReader("document.pdf").pages, start=1):
    for line in (page.extract_text() or "").splitlines():
        line = line.strip()
        if line:
            passages.append((page_number, line))

if not passages:
    raise ValueError("No selectable text found. Try a PDF with a text layer.")

2. Rank passages and cite the best match

TF-IDF gives more weight to words that help distinguish one passage from another. Cosine similarity then scores how closely a question matches each passage. Start with a score cutoff of 0.2 and adjust it using sample questions from your own document.

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

vectorizer = TfidfVectorizer(stop_words="english")
passage_vectors = vectorizer.fit_transform(text for _, text in passages)

def ask_pdf(question, min_score=0.2):
    query = vectorizer.transform([question])
    scores = cosine_similarity(query, passage_vectors)[0]
    best = scores.argmax()
    if scores[best] < min_score:
        return "I couldn't find enough evidence in this PDF."
    page_number, evidence = passages[best]
    return f'"{evidence}" (PDF page {page_number})'

print(ask_pdf("Are safety glasses required at the drill press?"))
print(ask_pdf("What is the Wi-Fi password?"))

3. Test questions the PDF can and cannot answer

For the two-page example, the first question should return the drill-press rule and cite page 2. The second should return the insufficient-evidence message. Now try asking for the price of safety glasses. It may retrieve the same rule because the terms overlap. Open the cited page and check whether the passage actually answers the question. A similarity score measures overlap and cannot establish that the answer is supported.

If a scanned PDF yields no text, run optical character recognition first. If a sentence wraps across multiple lines, try grouping nearby lines while retaining their page numbers.

Practice with a ready-to-run notebook

The €5 PDF chatbot workshop includes a guided Colab notebook, a sample PDF and a workbook with exercises. You can also try the free retrieval evaluation lab from the digital shop.

Preview the PDF chatbot workshop →

Learn how to evaluate a RAG chatbot in Python →