AIForum.

How to Automate Document Summarization with Local AI and Python

On this page

THE SHORT ANSWER

Local document summarization in Python splits into two practical routes: extractive scoring with TF-IDF or LexRank, which needs no language model and cannot hallucinate, and abstractive summarization with a locally hosted model, which reads better but can invent details. This guide covers both, including batching, long-document chunking, memory limits, and verification checks.
Quick facts

Automating document summarization with local AI means writing a Python pipeline that reads documents from disk, produces a shorter version, and writes the result back out — without sending the text to a hosted API. Two families of techniques cover almost every case: extractive summarization, which selects the most important existing sentences and needs no language model at all, and abstractive summarization, which asks a locally hosted model to write a new summary in its own words.

This guide is for technically curious beginners and intermediate practitioners who want a working pipeline rather than a survey. It covers the extractive path with runnable Python, the abstractive path as documented by Microsoft’s Foundry Local document summarizer tutorial, and the practical limits — memory, hallucination risk, and context length — that decide which one to reach for.

Extractive versus abstractive: choose the failure mode you can tolerate

Extractive summarization selects existing sentences from the document. As the runlocalai.co course material puts it, it “works without LLMs and runs fast,” and because every sentence is copied verbatim it cannot hallucinate. The cost is readability: selected sentences may not flow together, and the method cannot paraphrase or merge ideas spread across paragraphs.

Abstractive summarization generates new text that paraphrases the content. It produces more coherent output but “requires LLMs and may introduce hallucinations,” according to the same source. That single tradeoff drives most design decisions in a local pipeline. If the summary feeds a compliance record or a search index where a wrong figure is expensive, start extractive. If a human reads the summary before acting, abstractive output is usually acceptable and considerably more pleasant to read.

Prerequisites and environment

Both paths assume Python 3 with pip, and a document collection you are allowed to process. Everything else differs.

  • Extractive path: PyMuPDF (imported as fitz) for PDF text extraction, scikit-learn for TF-IDF scoring, NumPy for array handling, and optionally sumy for LexRank (pip install sumy).
  • Abstractive path: a local inference runtime plus enough memory. Microsoft’s Foundry Local tutorial lists a Windows, macOS, or Linux computer with at least 8 GB of RAM, and .NET 8.0 SDK or later for the C# samples it ships.

One documentation gap matters if you work in Python: the Microsoft tutorial’s sample code is C#. The tutorial pairs the Foundry Local SDK with the OpenAI client package, and Python users should confirm the current Python surface in the Foundry Local SDK reference, or point the openai Python client at a local server that exposes an OpenAI-compatible endpoint. Treat the setup below as documented rather than independently benchmarked.

Step 1: Get clean text out of the document

Summary quality is bounded by extraction quality. For PDFs, PyMuPDF is a compact starting point:

import fitz

doc = fitz.open("document.pdf")
text = doc[0].get_text()
doc.close()
print(len(text), text[:500])

Inspect that output before continuing. Headers, footers, page numbers, and hyphenated line breaks are common contamination, and a summarizer will happily treat them as content. Loop over every page for multi-page documents, and join pages with a blank line so sentence splitting does not merge the last sentence of one page with the first of the next.

Step 2: Score sentences with TF-IDF

The extractive baseline splits the text into sentences, scores each sentence by the sum of its TF-IDF values, and keeps the highest-scoring ones. Sorting the winners by their original position — not by score — is what makes the result read in document order.

import re
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer

def extractive_summarize(text, num_sentences=5):
    sentences = re.split(r'(?<=[.!?])s+', text)
    sentences = [s for s in sentences if len(s) > 20]
    if len(sentences) <= num_sentences:
        return text

    vectorizer = TfidfVectorizer(stop_words='english')
    tfidf_matrix = vectorizer.fit_transform(sentences)
    sentence_scores = np.array(tfidf_matrix.sum(axis=1)).flatten()

    top_indices = sentence_scores.argsort()[-num_sentences:]
    top_indices.sort()
    return ' '.join(sentences[i] for i in top_indices)

The short-sentence filter (dropping anything 20 characters or fewer) removes fragments that would otherwise score deceptively well. The num_sentences parameter is your compression dial: five sentences from a two-page memo is aggressive, five from a 40-page report is closer to a table of contents.

Step 3: Try LexRank when TF-IDF output feels disjointed

LexRank applies graph-based ranking, similar in spirit to PageRank, to decide which sentences are central to the document. The runlocalai.co material notes it “often produces more coherent summaries” than raw TF-IDF scoring. It arrives via sumy:

from sumy.parsers.plaintext import PlaintextParser
from sumy.nlp.tokenizers import Tokenizer
from sumy.summarizers.lex_rank import LexRankSummarizer

parser = PlaintextParser.from_string(text, Tokenizer("english"))
summarizer = LexRankSummarizer()
summary = summarizer(parser.document, 5)
print(" ".join(str(sentence) for sentence in summary))

Run both scorers on the same document and compare. On structured material such as contracts or technical specifications, TF-IDF frequently wins because repeated domain terms genuinely mark importance. On narrative or discursive prose, LexRank usually reads better.

Step 4: Add a local model for abstractive summaries

Microsoft’s Foundry Local tutorial frames the abstractive workflow as six stages: set up the project and install the SDK, read a text document from the file system, load a model and generate a summary, control summary output with system prompts, process multiple documents in a batch, and clean up resources. The C# project installs Microsoft.AI.Foundry.Local.WinML plus the OpenAI package on Windows, or Microsoft.AI.Foundry.Local plus OpenAI cross-platform; the WinML package is described as integrating with the Windows ML runtime, providing the same API surface with a wider breadth of hardware acceleration.

The stages translate directly to Python. The example below is illustrative rather than copied from a tested run — the base URL and model identifier depend on the runtime you install:

from openai import OpenAI

client = OpenAI(base_url="http://localhost:PORT/v1", api_key="not-needed")

SYSTEM_PROMPT = (
    "You summarize documents. Use only facts present in the source text. "
    "Do not add background knowledge. If the source is ambiguous, say so."
)

def summarize(text, max_words=150):
    response = client.chat.completions.create(
        model="your-local-model-id",
        messages=[
            {"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user", "content": f"Summarize in {max_words} words or fewer:nn{text}"},
        ],
        temperature=0.2,
    )
    return response.choices[0].message.content

The system prompt is doing real work here. Telling the model to use only source facts and to flag ambiguity is the cheapest available defense against the hallucination risk that abstractive summarization carries. A low temperature reduces variation between runs, which matters when you compare summaries over time.

Step 5: Batch the pipeline and handle long documents

Once a single document works, wrap the call in a loop over a folder. Writing Markdown next to the source keeps the pipeline inspectable:

from pathlib import Path

Path("summaries").mkdir(exist_ok=True)

for path in sorted(Path("inbox").glob("*.txt")):
    source = path.read_text(encoding="utf-8")
    summary = summarize(source)
    Path("summaries", f"{path.stem}.md").write_text(summary, encoding="utf-8")
    print(f"{path.name}: {len(source)} chars -> {len(summary)} chars")

Documents longer than the model’s context window need chunking. The standard pattern is map-reduce: split the text into overlapping chunks, summarize each chunk, then summarize the concatenated chunk summaries. Overlap prevents a sentence that straddles a boundary from being lost. Be aware of the compounding risk — each abstractive pass can introduce an error, and the reduce pass has no way to detect an error introduced upstream. For very long documents, an extractive first pass is often the safer choice, or a hybrid where extractive scoring decides which chunks reach the model at all.

Step 6: Verify before you trust the output

  • Extract named entities, numbers, and dates from both the source and the summary, and flag anything in the summary that does not appear in the source. This is the highest-value automated check for abstractive output.
  • For extractive output, confirm every selected sentence appears verbatim in the source. It is nearly free and catches tokenizer or encoding bugs.
  • Log the prompt, model identifier, and a hash of the input alongside each summary so a bad result can be reproduced.
  • Keep a human review step for anything published, filed, or used in a decision.

Limitations, memory, and licensing

Memory. The 8 GB figure in the Microsoft tutorial is a documented floor for that tutorial, not a guarantee for every model. Actual headroom depends on parameter count, quantization, context length, and runtime overhead. Weight file size alone is a poor estimate of memory use, because the KV cache grows with the context you feed in and the runtime consumes memory on top of the weights.

Quality. Extractive summaries are choppy and can repeat near-identical sentences. Abstractive summaries can state things the document never says. Neither failure disappears with a bigger model; they change shape.

Platform. Hardware acceleration is platform-dependent. The WinML package in the Microsoft tutorial is the Windows-specific option; cross-platform installs use a different package with a narrower acceleration story.

Licensing. Open weights, open source, and permission for commercial use are three separate things. Check the license attached to the specific model you download before shipping anything that depends on it.

Where to take it next

Scheduling is the last mile. A cron job on Linux or macOS, or Task Scheduler on Windows, can run the batch loop over a watched folder and drop summaries beside the originals. If the destination is a CMS such as WordPress, write summaries as drafts and keep the approval step — abstractive output should not be published unreviewed.

If you build this pipeline and hit a specific failure — a model that will not load, a summary that drops key figures, or PDF extraction that mangles a layout — describe your operating system, runtime, model identifier, and the exact error in the community so others can reproduce it.

FAQ

Can I summarize documents locally without a GPU?

The extractive path needs no model at all and runs on CPU. For abstractive summaries, Microsoft's Foundry Local tutorial lists 8 GB of RAM as the minimum, and the Windows package is described as integrating with the Windows ML runtime for hardware acceleration. Actual speed depends on your hardware and the model you choose.

How do I stop a local summarizer from inventing facts?

Instruct the model in the system prompt to use only facts present in the source text and to flag ambiguity, keep the temperature low, and add an automated check that flags numbers, dates, or names in the summary that do not appear in the source.

What should I do when a document exceeds the model's context window?

Split it into overlapping chunks, summarize each chunk, then summarize the combined chunk summaries — the map-reduce pattern. Overlap reduces the chance that a sentence spanning a boundary is lost, but each abstractive pass adds another opportunity for an error to enter.

Is extractive summarization always the weaker option?

No. It runs without a language model, is fast, and cannot hallucinate, which makes it a reasonable default for indexing, compliance records, or preprocessing long documents before an abstractive pass. Its weakness is readability, not accuracy.

References

  1. https://learn.microsoft.com/en-us/azure/foundry-local/tutorials/tutorial-build-document-summarizer
  2. https://www.runlocalai.co/learn/courses/document-processing/chapter-8-document-summarization

Related terms

Extractive summarization
Selecting existing sentences from a document, typically by scoring them, rather than generating new text.
Abstractive summarization
Generating new text that paraphrases a document's content; more coherent than extraction but capable of hallucinating.
TF-IDF
Term frequency–inverse document frequency, a weighting scheme that scores how distinctive a term is within a collection of documents or sentences.
LexRank
A graph-based ranking method, similar in spirit to PageRank, used to identify sentences that are central to a document.
Foundry Local
Microsoft's on-device model runtime and SDK, documented in a tutorial that builds a document summarizer that runs locally.
KV cache
Memory a language model uses to store attention keys and values for the tokens in its context; it grows with context length and adds to total memory use beyond the model weights.

Leave a Reply

Your email address will not be published. Required fields are marked *