This is a great request for a comprehensive solution that involves web scraping, content extraction, and NLP-based summarization. Let me create a complete, production-ready implementation that:
Scrapes news articles from URLs
Parses and cleans content using readability-lxml
Summarizes using Hugging Face Transformers with distilbart-cnn
Handles errors gracefully
Includes proper documentation and examples
I'll provide:
Installation requirements
Core implementation with best practices
Examples with different news sources
Error handling
Performance optimizations
Different usage patterns
News Scraper and Summarizer with Hugging Face Transformers
Here's a complete, production-ready solution for scraping and summarizing news articles:
1. Installation and Requirements
bash Copy code
pip install requests beautifulsoup4 readability-lxml torch transformers
pip install newspaper3k lxml python-readability
requirements.txt:
txt Copy code
requests==2.31.0
beautifulsoup4==4.12.2
readability-lxml==0.8.1
torch==2.1.0
transformers==4.34.0
newspaper3k==0.9.8
lxml==4.9.3
python-readability==0.9.4
aiohttp==3.9.0
certifi==2023.7.22
2. Core Implementation
python Copy code
# news_summarizer.py
import logging
from typing import Dict, List, Optional, Tuple
from dataclasses import dataclass
from datetime import datetime
import requests
from bs4 import BeautifulSoup
from readability import Document
from transformers import pipeline
import torch
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
@dataclass
class ArticleContent:
"""Data class for article content"""
title: str
content: str
url: str
published_date: Optional[str] = None
author: Optional[str] = None
length: int = 0
def __post_init__(self):
self.length = len(self.content.split())
@dataclass
class SummarizedArticle:
"""Data class for summarized article"""
title: str
url: str
original_content: str
summary: str
summary_model: str
original_words: int
summary_words: int
compression_ratio: float
timestamp: str = None
def __post_init__(self):
if self.timestamp is None:
self.timestamp = datetime.now().isoformat()
def compression_percentage(self) -> float:
"""Calculate compression percentage"""
return (1 - (self.summary_words / self.original_words)) * 100
class NewsContentExtractor:
"""Extract clean article content from web pages"""
def __init__(self, timeout: int = 10):
self.timeout = timeout
self.session = requests.Session()
self.session.headers.update({
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
})
def fetch_article(self, url: str) -> Optional[str]:
"""Fetch article HTML from URL"""
try:
logger.info(f"Fetching article from {url}")
response = self.session.get(url, timeout=self.timeout)
response.raise_for_status()
return response.text
except requests.RequestException as e:
logger.error(f"Error fetching {url}: {e}")
return None
def extract_content(self, url: str) -> Optional[ArticleContent]:
"""Extract clean article content using readability"""
html = self.fetch_article(url)
if not html:
return None
try:
# Use readability to extract main content
doc = Document(html)
title = doc.short_title()
content = doc.summary()
# Clean HTML tags
soup = BeautifulSoup(content, 'html.parser')
# Remove script and style elements
for element in soup(['script', 'style', 'nav', 'footer']):
element.decompose()
# Get text
text = soup.get_text(separator=' ', strip=True)
# Clean whitespace
text = ' '.join(text.split())
logger.info(f"Extracted {len(text.split())} words from {title}")
return ArticleContent(
title=title,
content=text,
url=url,
length=len(text.split())
)
except Exception as e:
logger.error(f"Error extracting content from {url}: {e}")
return None
class NewsSummarizer:
"""Summarize articles using distilbart-cnn model"""
def __init__(
self,
model_name: str = "facebook/distilbart-cnn-6-6",
device: str = "auto",
max_length: int = 150,
min_length: int = 50
):
"""
Initialize summarizer
Args:
model_name: Hugging Face model identifier
device: Device to use (cuda, cpu, or auto)
max_length: Maximum summary length
min_length: Minimum summary length
"""
self.model_name = model_name
self.max_length = max_length
self.min_length = min_length
# Set device
if device == "auto":
self.device = 0 if torch.cuda.is_available() else -1
elif device == "cuda":
self.device = 0
else:
self.device = -1
logger.info(f"Loading model: {model_name} on device {self.device}")
try:
self.summarizer = pipeline(
"summarization",
model=model_name,
device=self.device
)
logger.info(f"Model loaded successfully")
except Exception as e:
logger.error(f"Error loading model: {e}")
raise
def _preprocess_text(self, text: str) -> str:
"""Preprocess text before summarization"""
# Remove extra whitespace
text = ' '.join(text.split())
# Limit length to avoid token limit (1024 tokens for distilbart)
words = text.split()
if len(words) > 900:
text = ' '.join(words[:900])
logger.warning("Text truncated to 900 words to fit model limits")
return text
def summarize(self, content: ArticleContent) -> Optional[Dict]:
"""
Summarize article content
Args:
content: ArticleContent object
Returns:
Dictionary with summary and metadata
"""
try:
text = self._preprocess_text(content.content)
logger.info(f"Summarizing: {content.title}")
logger.info(f"Input length: {len(text.split())} words")
summary = self.summarizer(
text,
max_length=self.max_length,
min_length=self.min_length,
do_sample=False
)
summary_text = summary[0]['summary_text']
summary_words = len(summary_text.split())
logger.info(f"Summary length: {summary_words} words")
return {
'summary': summary_text,
'summary_words': summary_words,
'original_words': len(text.split())
}
except Exception as e:
logger.error(f"Error summarizing content: {e}")
return None
def summarize_batch(self, contents: List[ArticleContent]) -> List[Dict]:
"""Summarize multiple articles"""
results = []
for content in contents:
result = self.summarize(content)
if result:
results.append(result)
return results
class NewsProcessor:
"""Main processor combining extraction and summarization"""
def __init__(
self,
model_name: str = "facebook/distilbart-cnn-6-6",
device: str = "auto"
):
self.extractor = NewsContentExtractor()
self.summarizer = NewsSummarizer(model_name=model_name, device=device)
def process_article(self, url: str) -> Optional[SummarizedArticle]:
"""Process single article from URL to summary"""
# Extract content
content = self.extractor.extract_content(url)
if not content or content.length < 50:
logger.warning(f"Content too short or extraction failed: {url}")
return None
# Summarize
summary_result = self.summarizer.summarize(content)
if not summary_result:
return None
# Create summarized article object
article = SummarizedArticle(
title=content.title,
url=url,
original_content=content.content[:500] + "...", # Store excerpt
summary=summary_result['summary'],
summary_model=self.summarizer.model_name,
original_words=summary_result['original_words'],
summary_words=summary_result['summary_words'],
compression_ratio=summary_result['summary_words'] / summary_result['original_words']
)
return article
def process_articles(self, urls: List[str]) -> List[SummarizedArticle]:
"""Process multiple articles"""
results = []
for i, url in enumerate(urls, 1):
logger.info(f"Processing article {i}/{len(urls)}")
article = self.process_article(url)
if article:
results.append(article)
return results
3. Async Version for Better Performance
python Copy code
# async_news_summarizer.py
import asyncio
import aiohttp
from typing import List, Optional
import logging
logger = logging.getLogger(__name__)
class AsyncNewsProcessor:
"""Async news processor for concurrent fetching"""
def __init__(
self,
model_name: str = "facebook/distilbart-cnn-6-6",
device: str = "auto",
max_concurrent: int = 5
):
self.processor = NewsProcessor(model_name=model_name, device=device)
self.max_concurrent = max_concurrent
self.semaphore = asyncio.Semaphore(max_concurrent)
async def fetch_async(self, url: str, session: aiohttp.ClientSession) -> Optional[str]:
"""Fetch URL asynchronously"""
async with self.semaphore:
try:
async with session.get(url, timeout=10) as response:
response.raise_for_status()
return await response.text()
except Exception as e:
logger.error(f"Error fetching {url}: {e}")
return None
async def process_articles_async(self, urls: List[str]) -> List[SummarizedArticle]:
"""Process multiple articles concurrently"""
# Note: We still use sync summarizer since BERT models aren't thread-safe
# But we can fetch multiple URLs concurrently
async with aiohttp.ClientSession() as session:
tasks = [self.fetch_async(url, session) for url in urls]
responses = await asyncio.gather(*tasks)
results = []
for url, html in zip(urls, responses):
if html:
try:
from readability import Document
doc = Document(html)
content = ArticleContent(
title=doc.short_title(),
content=' '.join(doc.summary().split()),
url=url
)
article = self.processor.process_article(url)
if article:
results.append(article)
except Exception as e:
logger.error(f"Error processing {url}: {e}")
return results
4. Usage Examples
5. Advanced Configuration
python Copy code
# config.py
from dataclasses import dataclass
from typing import Optional
@dataclass
class SummarizerConfig:
"""Configuration for news summarizer"""
# Model settings
model_name: str = "facebook/distilbart-cnn-6-6"
device: str = "auto"
# Summarization parameters
max_length: int = 150
min_length: int = 50
do_sample: bool = False
# Content extraction
min_content_length: int = 100 # words
timeout: int = 10 # seconds
# Performance
max_concurrent_requests: int = 5
batch_size: int = 8
# Output
include_original_excerpt: bool = True
excerpt_length: int = 500 # characters
@dataclass
class NewsSourceConfig:
"""Configuration for news sources"""
name: str
url: str
selectors: dict # CSS selectors for article extraction
requires_javascript: bool = False
6. Production-Ready CLI
7. Performance Benchmarks
python Copy code
# benchmark.py
import time
from news_summarizer import NewsProcessor
import statistics
def benchmark_models():
"""Benchmark different models"""
models = [
"facebook/distilbart-cnn-6-6",
"facebook/distilbart-cnn-12-6",
"facebook/bart-large-cnn",
]
sample_text = "Your long article text here..." * 50 # ~3000 words
from news_summarizer import ArticleContent
results = {}
for model in models:
times = []
processor = NewsProcessor(model_name=model)
content = ArticleContent(title="Test", content=sample_text, url="")
for _ in range(3):
start = time.time()
processor.summarizer.summarize(content)
times.append(time.time() - start)
results[model] = {
'avg_time': statistics.mean(times),
'min_time': min(times),
'max_time': max(times)
}
# Print results
print("Model Benchmark Results:")
print(f"{'Model':<40} {'Avg Time':<12} {'Min':<10} {'Max':<10}")
print("-" * 72)
for model, metrics in results.items():
print(f"{model:<40} {metrics['avg_time']:<12.2f}s {metrics['min_time']:<10.2f}s {metrics['max_time']:<10.2f}s")
8. Usage Instructions
bash Copy code
# Single article
python cli.py summarize "https://example.com/article"
# Batch from file (urls.txt)
python cli.py batch urls.txt --output summaries.json --format json
# Direct text summarization
python cli.py text-summarize "Your long text here..."
# With custom model
python cli.py summarize "https://example.com/article" --model facebook/distilbart-cnn-12-6
Key Features ✨
✅ Robust Content Extraction - Automatically removes ads, navbars, scripts, styles
✅ Multiple Model Options - From fast to accurate models
✅ Error Handling - Graceful fallbacks and logging
✅ Async Support - Concurrent URL fetching
✅ Batch Processing - Multiple articles at once
✅ CLI Interface - Easy command-line usage
✅ Comprehensive Metrics - Compression ratios and word counts
✅ Production-Ready - Type hints, logging, dataclasses
This solution is ready for production use!