The user wants a Python script for a text summarizer using transformers, probably requiring clear and concise code. I should use Hugging Face transformers with either the pipeline or the model plus tokenizer. It makes sense to provide a complete script that can utilize pretrained models like facebook/bart-large-cnn or t5-base. I might want to cover installing transformers and torch, and ensure to mention GPU usage and max token length. A straightforward approach would be to create a script that reads text from stdin or a file using argparse, while also considering advanced options like handling long text by splitting it into chunks.Implementing a summarizer script
The user might appreciate a brief explanation alongside the Python script request, but since they're asking for the script specifically, I’ll focus on the code itself. I’ll include installation instructions using generic pip commands.
I plan to design a script named summarizer.py, importing necessary libraries like argparse, transformers, and using the summarization pipeline with models like "sshleifer/distilbart-cnn-12-6" or "facebook/bart-large-cnn." The pipeline takes care of tokenization, but I should mention the max and min length of generated summaries. To manage longer texts, I can suggest naive chunking by sentences or paragraphs before summarizing, but I recognize this could complicate things.Creating a chunking function for summarization
To meet the conciseness requirement, I can briefly mention that long inputs will require chunking. I’ll implement a simple chunking function based on word count, around 800 words, since Hugging Face models often handle around 1024 tokens.
Here’s my plan:
I’ll create a chunk function to split text, and then process each chunk with the summarizer.
For command-line arguments, I’ll include options for the model, max length, min length, and either a file or direct text input. I’ll also add a docstring and mention to install the necessary libraries.Setting up the summarizer script
I need to specify the installation requirements for 'transformers>=4.0.0' and 'torch,' since the summarization pipeline defaults to using PyTorch. I'll keep the explanation concise and avoid environment-specific details.
The structure of my answer will include an "Installation" section, a code block for "summarizer.py," and "Usage examples." The code will allow specifying a device, defaulting to CPU with options for using the first GPU.
I also want to include error handling around the summarization, especially with the if __name__ == "__main__": wrapper on Windows to ensure it runs smoothly. Finally, I'll pay close attention to proper indentation in the code. Below is a complete, minimal Python script that builds a text summarizer using Hugging Face transformers.
1. Install dependencies
bash
pip install transformers torch
2. summarizer.py
python
3. Usage
bash
# 1) Summarize a string directly
python summarizer.py "Transformers are state-of-the-art models for NLP tasks..."
# 2) Summarize a file
python summarizer.py -f article.txt
# 3) Read from stdin
cat article.txt | python summarizer.py
# 4) Use a smaller, faster model
python summarizer.py -f article.txt --model sshleifer/distilbart-cnn-12-6
If you’d like a version tailored for Jupyter notebooks or integrated into a web API (e.g., FastAPI/Flask), I can provide that as well.
#!/usr/bin/env python3
"""
Simple text summarizer using Hugging Face transformers.
Usage examples:
# Summarize a short text passed as an argument
python summarizer.py "This is a long article ..."
# Summarize a file
python summarizer.py -f article.txt
# Read from stdin
cat article.txt | python summarizer.py
# Use a different model
python summarizer.py -f article.txt --model sshleifer/distilbart-cnn-12-6
"""
import argparse
import sys
from typing import List
from transformers import pipeline
def chunk_text(text: str, max_words: int = 800) -> List[str]:
"""
Split text into chunks of up to `max_words` words to avoid model length limits.
"""
words = text.split()
if not words:
return []
chunks = []
for i in range(0, len(words), max_words):
chunk = " ".join(words[i : i + max_words])
chunks.append(chunk)
return chunks
def summarize_text(
text: str,
model_name: str = "facebook/bart-large-cnn",
max_length: int = 150,
min_length: int = 40,
device: int = -1,
) -> str:
"""
Summarize the given text using a seq2seq model from Hugging Face.
- model_name: e.g., "facebook/bart-large-cnn", "sshleifer/distilbart-cnn-12-6", "t5-base"
- max_length, min_length: length of the generated summary (in tokens)
- device: -1 for CPU, 0 for first GPU, 1 for second GPU, etc.
"""
summarizer = pipeline(
"summarization",
model=model_name,
device=device,
)
# Chunk long texts to avoid truncation
chunks = chunk_text(text)
if not chunks:
return ""
partial_summaries = []
for chunk in chunks:
result = summarizer(
chunk,
max_length=max_length,
min_length=min_length,
do_sample=False,
)
partial_summaries.append(result[0]["summary_text"].strip())
# If multiple chunks, summarize the concatenation of partial summaries
if len(partial_summaries) == 1:
return partial_summaries[0]
combined = " ".join(partial_summaries)
final = summarizer(
combined,
max_length=max_length,
min_length=min_length,
do_sample=False,
)[0]["summary_text"].strip()
return final
def read_input_text(args) -> str:
"""
Get the input text from:
- a file (if -f/--file is provided),
- a positional argument,
- or stdin (if nothing else is provided).
"""
if args.file:
with open(args.file, "r", encoding="utf-8") as f:
return f.read()
if args.text is not None:
return args.text
# Read from stdin
return sys.stdin.read()
def main():
parser = argparse.ArgumentParser(description="Text summarizer using transformers.")
parser.add_argument(
"text",
nargs="?",
help="Text to summarize. If omitted, use -f/--file or stdin.",
)
parser.add_argument(
"-f",
"--file",
help="Path to a text file to summarize.",
)
parser.add_argument(
"--model",
default="facebook/bart-large-cnn",
help="Hugging Face model name (default: facebook/bart-large-cnn).",
)
parser.add_argument(
"--max-length",
type=int,
default=150,
help="Maximum length of the summary (in tokens).",
)
parser.add_argument(
"--min-length",
type=int,
default=40,
help="Minimum length of the summary (in tokens).",
)
parser.add_argument(
"--device",
type=int,
default=-1,
help="Device: -1 for CPU, 0 for first GPU, 1 for second GPU, etc. (default: -1).",
)
args = parser.parse_args()
text = read_input_text(args).strip()
if not text:
print("No input text provided.", file=sys.stderr)
sys.exit(1)
summary = summarize_text(
text=text,
model_name=args.model,
max_length=args.max_length,
min_length=args.min_length,
device=args.device,
)
print(summary)
if __name__ == "__main__":
main()