Skip to content

2.2 Loading Documents from Different Sources into a Unified Format

Document loading is the first and critically important stage of building a RAG system. Mistakes at this step inevitably affect the quality of the whole system. The extracted text directly determines the quality of retrieval and, as a consequence, the quality of the model's answers. Problems often arise precisely because of incorrect data loading.

In LangChain, a document is represented as a standard object with two main fields:

from langchain.schema import Document

doc = Document(
    page_content="Document text goes here...",
    metadata={
        "source": "docs/manual.pdf",
        "page": 5,
        "section": "Installation",
        "author": "Technical team"
    }
)

page_content holds the text, and metadata holds additional information. This standardized representation makes it possible to work with documents from different sources in a uniform way: they all look the same, and the subsequent components process them the same way.

Metadata matters for several reasons. - It lets you filter the search: find only documents from a certain author or source. - It provides attribution: the user sees which document the information came from. - It helps with debugging: when an answer is wrong, the metadata shows which fragments were used.

The general process of loading and bringing data to a unified format is shown in Fig. 12.

Figure 12. Loading documents.

Figure 12. Loading documents.

Loading PDFs

PDF is an ideal format for printing but a terrible one for text extraction. The format is oriented toward visual representation, that is, how the content looks on the page. Text can be split into fragments in arbitrary order, tables lose their structure, and columns merge into one unreadable mess.

LangChain provides several PDF loaders with different characteristics.

PyPDFLoader is the simplest and fastest option:

from langchain_community.document_loaders import PyPDFLoader

loader = PyPDFLoader("document.pdf")
pages = loader.load()

for page in pages:
    print(f"Page {page.metadata['page']}: {len(page.page_content)} characters")

PyPDFLoader uses the pypdf library and works quickly. It is ideal for documents with a simple structure. But on complex documents, the quality of extraction can be low.

PDFPlumberLoader is a more powerful option that handles tables better:

from langchain_community.document_loaders import PDFPlumberLoader

loader = PDFPlumberLoader("document_with_tables.pdf")
pages = loader.load()

PDFPlumber preserves the structure of tables and complex layouts better, but it runs more slowly. The choice between them depends on what matters more: speed or quality.

Often you need to combine different loaders. If you load a large set of PDF files, some simple and some with a complex structure, it makes sense to analyze each file and choose a suitable loader.

The algorithm is simple: look at the first page of the document and check for signs of complexity (tables, multi-column text, embedded code). If the document is simple, use the fast PyPDFLoader. If it is complex, use PDFPlumber.

def classify_and_load(pdf_path):
    with open(pdf_path, 'rb') as f:
        pdf = pypdf.PdfReader(f)
        first_page_text = pdf.pages[0].extract_text()

    has_tables = detect_table_markers(first_page_text)
    has_code = detect_code_blocks(first_page_text)

    if has_tables:
        loader = PDFPlumberLoader(pdf_path)
    else:
        loader = PyPDFLoader(pdf_path)

    return loader.load()

def detect_table_markers(text):
    table_indicators = ['|', '─', '┌', '┐', '└', '┘']
    return any(ind in text for ind in table_indicators)

def detect_code_blocks(text):
    code_patterns = [
        r'```',
        r'def\s+\w+\(',
        r'class\s+\w+:',
        r'\{\s*"[^"]+"\s*:'
    ]
    return any(re.search(pattern, text) for pattern in code_patterns)

This approach automates the choice: each document is processed in the way that is optimal for it. Fast documents are processed quickly, complex ones with quality.

Loading Web Pages

Web pages are another common source of information. Web content contains useful text mixed with navigation, advertising, scripts, and service elements. The basic LangChain loader strips the HTML markup, but the result often contains noise.

from langchain_community.document_loaders import WebBaseLoader

loader = WebBaseLoader("https://example.com/article")
documents = loader.load()

A cleaner result requires additional processing. Remove the navigation, header, sidebars, scripts, and styles. Then extract the main content:

from langchain_community.document_loaders import WebBaseLoader
from bs4 import BeautifulSoup
import requests

def load_article_content(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.content, 'html.parser')

    for element in soup.find_all(['nav', 'header', 'footer', 'aside', 'script', 'style']):
        element.decompose()

    article = soup.find('article') or soup.find('main') or soup.find('body')

    text = article.get_text(separator='\n', strip=True)

    return Document(
        page_content=text,
        metadata={
            "source": url,
            "title": soup.title.string if soup.title else None,
            "loaded_at": datetime.utcnow().isoformat()
        }
    )

Documentation in Notion and Other Services

Many teams keep their documentation in Notion, Google Docs, or Confluence. LangChain provides loaders for popular platforms.

For Notion, the simplest way is to export the documentation to Markdown and use the loader:

from langchain_community.document_loaders import NotionDirectoryLoader

loader = NotionDirectoryLoader("notion_export")
documents = loader.load()

NotionDirectoryLoader works with the Markdown export. If you need direct integration through the Notion API, there is NotionDBLoader, but it requires additional setup.

The simplest approach is to export data from Notion regularly and store the export in a version control system. This gives you reproducibility and lets you track changes in the documentation.

Video and Audio

Video and audio files need to be transcribed before they can be used in a RAG system.

For YouTube, LangChain integrates with transcription services:

from langchain_community.document_loaders import YoutubeLoader

loader = YoutubeLoader.from_youtube_url(
    "https://www.youtube.com/watch?v=example",
    add_video_info=True
)

documents = loader.load()

YoutubeLoader can use the video's built-in subtitles if they are available, or external services. The quality depends on the availability and quality of the source subtitles.

For local audio and video files, Whisper is used for transcription:

import whisper

def transcribe_audio(audio_path):
    model = whisper.load_model("base")
    result = model.transcribe(audio_path)

    return Document(
        page_content=result["text"],
        metadata={
            "source": audio_path,
            "language": result.get("language"),
            "duration": result.get("duration")
        }
    )

Whisper detects the language automatically and produces a transcript. The result becomes an ordinary document, which can be indexed like any other content.

Normalizing and Cleaning Text

After extraction, the text often needs cleaning. Extra spaces, odd characters, and conversion artifacts all degrade the quality of embeddings and search.

import re
import unicodedata

def normalize_text(text):
    text = unicodedata.normalize('NFKC', text)

    text = re.sub(r'\s+', ' ', text)

    text = re.sub(r'[^\w\s.,!?;:\-\'\"()\[\]{}]', '', text)

    text = text.strip()

    return text

def clean_document(doc):
    cleaned_content = normalize_text(doc.page_content)

    return Document(
        page_content=cleaned_content,
        metadata=doc.metadata
    )

The normalize_text function performs several standard transformations: it normalizes Unicode, removes repeated spaces, deletes strange characters, and trims the edges.

Enriching Metadata

The metadata that loaders add automatically is often insufficient. It is useful to add extra attributes depending on the type of content.

def enrich_metadata(doc, additional_metadata=None):
    enriched = doc.metadata.copy()

    enriched["content_length"] = len(doc.page_content)
    enriched["word_count"] = len(doc.page_content.split())
    enriched["indexed_at"] = datetime.utcnow().isoformat()

    if additional_metadata:
        enriched.update(additional_metadata)

    return Document(
        page_content=doc.page_content,
        metadata=enriched
    )

Add the content length, the word count, and the indexing date. This helps with filtering and debugging. You can also add a domain (for web content), a language, or a document category: anything that may be useful for your system.

Batch Loading

When loading a large number of documents, errors happen. The network may drop, the API may return an error, or the document format may be corrupted. It is important to handle such situations and save progress.

def load_documents_with_recovery(file_paths, loader_factory, progress_file="progress.json"):
    progress = load_progress(progress_file)

    results = []
    errors = []

    for path in file_paths:
        if path in progress.get("completed", []):
            continue

        try:
            loader = loader_factory(path)
            docs = loader.load()
            results.extend(docs)

            progress.setdefault("completed", []).append(path)
            save_progress(progress_file, progress)

        except Exception as e:
            errors.append({
                "path": path,
                "error": str(e)
            })
            progress.setdefault("errors", []).append(path)
            save_progress(progress_file, progress)

    return results, errors

The function saves progress to a file between iterations. If the process is interrupted, it can resume from the same place instead of starting over. Errors are logged, so you can later figure out why a particular document failed to load.

Questions for Reflection and Practice

Theoretical questions

  1. Explain why loading and processing documents is a critical stage in a RAG system, and how the quality of text extraction affects the final results.

  2. What differences exist between loaders for structured and unstructured data, and how do you choose the right one for a given type of content?

  3. What typical problems arise when extracting text from PDF documents with a complex structure (tables, multi-column layouts)?

  4. Explain the trade-offs between PyPDFLoader (fast) and PDFPlumberLoader (high quality), and when a hybrid approach is justified.

  5. How do you organize the extraction of clean content from web pages, excluding navigation, advertising, and service elements?

  6. What role do document metadata play in a RAG system, and how do you use it to filter search results?

  7. What stages does normalizing and cleaning text include after extraction from different sources?

  8. How do you organize batch loading of documents with progress saving and error handling?

  9. Describe the approach to enriching document metadata with additional attributes useful for search and analytics.

  10. What strategies are used for working with video and audio content in RAG systems?

Practical exercises

  1. Implement a PDF loading function that analyzes the content and automatically selects the optimal loader based on the detected features.

  2. Create a function that loads and cleans web pages, removing navigation elements and keeping the main content as a Document.

  3. Implement a metadata enrichment function that adds the word count, character count, language detection, and indexing date.

  4. Build a batch document loading system with progress logging and error handling in JSON format.

  5. Implement a text normalization function that removes HTML artifacts, repeated spaces, and strange characters.

  6. Create a loader for YouTube videos with transcription error handling and a fallback to built-in subtitles.

  7. Implement a converter from a Notion Markdown export to a standard Document that preserves the heading structure.