๐ Markdown Harvest
A Rust crate designed to extract, clean, and convert web content from URLs found in text messages into clean Markdown format. Originally created as an auxiliary component for Retrieval-Augmented Generation (RAG) solutions to process URLs submitted by users.
๐ Table of Contents
- Overview
- Features
- Quick Start
- Installation
- Usage Examples
- API Documentation
- Content Processing Pipeline
- Supported Platforms
- Contributing
- License
- Changelog
Overview
Markdown Harvest was initially developed as part of a Retrieval-Augmented Generation (RAG) system where users submit text containing URLs, and the system needs to extract meaningful content from those URLs for further analysis or processing. This crate handles the extraction, cleaning, and structuring of web content automatically.
๐ฏ Why Markdown Harvest?
- ๐ Built for AI/RAG Systems: Specifically designed for content preprocessing in AI workflows
- ๐งน Smart Content Extraction: Removes ads, navigation, and irrelevant elements automatically
- ๐ Markdown Output: Clean, structured Markdown perfect for LLM processing
- ๐ Batch Processing: Handle multiple URLs efficiently in a single operation
- ๐ก๏ธ Robust Error Handling: Gracefully handles network issues and invalid URLs
Use Case Process Flow
๐ Standard Content Processing
graph LR
A[User Input] --> B{Identifies URLs}
B -->|Yes| C[Retrieves HTTP Content]
C --> D[Processes & Extracts Data]
D --> E[Augments Context]
E --> F[Generates Response with Model]
B -->|No| F
F -->|Contextualized response| A
๐ฆ Chunks Feature Process Flow (RAG Systems)
graph TD
A[User Input with URLs] --> B[Extract URLs]
B --> C[HTTP Content Retrieval]
C --> D[HTML to Markdown Conversion]
D --> E[Semantic Chunking]
E --> F{Overlap Configuration}
F -->|With Overlap| G[Generate Overlapping Chunks]
F -->|No Overlap| H[Generate Standard Chunks]
G --> I[Chunk Processing Pipeline]
H --> I
I --> J[Generate Embeddings]
J --> K[Store in Vector Database]
K --> L[Index for Semantic Search]
L --> M[RAG Context Enhancement]
M --> N[Enhanced AI Response]
style E fill:#e1f5fe
style G fill:#f3e5f5
style H fill:#f3e5f5
style I fill:#e8f5e8
style M fill:#fff3e0
โจ Features
- ๐ URL Detection: Automatically identifies HTTP/HTTPS URLs in text using regex patterns
- ๐ฏ Smart Content Extraction: Priority-based semantic HTML5 extraction with intelligent fallback
- Semantic-first approach: Prioritizes
<article>,<main>, and[role='main']tags - 120x improvement: Better extraction quality for modern HTML5 sites (Issue #40)
- Backward compatible: Graceful fallback to
<body>for legacy sites
- Semantic-first approach: Prioritizes
- ๐ HTML to Markdown Conversion: Converts HTML content to clean, readable Markdown while preserving structure and removing unwanted elements
- ๐งน Content Cleaning: Removes JavaScript, CSS, advertisements, and navigation elements
- ๐ฆ Semantic Chunking: Optional chunks feature for RAG systems using
MarkdownSplitterwith semantic boundaries and configurable overlap - ๐ค Multi-Platform User Agents: Rotates between different browser user agents to avoid detection
- โก Configurable HTTP Options: Customizable timeout, redirect limits, and cookie management
- ๐๏ธ Builder Pattern API: Fluent and intuitive configuration with
HttpConfig::builder() - ๐ก๏ธ Error Handling: Graceful handling of network errors and invalid URLs
- ๐ Clean Text Output: Normalizes whitespace and removes common non-content patterns
- โก Asynchronous Processing: High-performance async/await support for concurrent URL processing
- ๐ Callback Architecture: Flexible callback system for real-time result streaming
- ๐งช Comprehensive Testing: 55+ unit tests with 100% API coverage including async functionality, chunks, and overlap
๐ Quick Start
use ;
๐ฆ Installation
Add this to your Cargo.toml:
[]
= "0.1.5"
# For RAG systems with semantic chunking and overlap support
= { = "0.1.5", = ["chunks"] }
๐ Usage Examples
๐ Synchronous Processing (Traditional)
use ;
โก Asynchronous Processing (High Performance)
use ;
use ;
async
๐ Real-time Processing with Immediate Output
use ;
async
๐ป Interactive CLI Mode
The crate provides an interactive CLI mode for testing:
Then enter text containing URLs when prompted.
๐ง Advanced HTTP Configuration
use ;
๐ฏ Different Configuration Examples
use ;
// Quick timeout for fast responses only
let fast_config = builder
.timeout // 3 seconds
.build;
// Conservative configuration for slow sites
let patient_config = builder
.timeout // 30 seconds
.max_redirect // More redirects allowed
.cookie_store // Handle authentication
.build;
// Use different configs for different scenarios
let urgent_text = "Breaking news: https://news-site.com/urgent";
let deep_text = "Research: https://academic-site.edu/paper";
let urgent_results = get_hyperlinks_content;
let research_results = get_hyperlinks_content;
๐ฆ Semantic Chunking for RAG Systems (chunks feature)
Feature gate: chunks - Enable with markdown-harvest = { version = "0.1.5", features = ["chunks"] }
The chunks feature provides semantic text splitting optimized for RAG (Retrieval-Augmented Generation) systems using MarkdownSplitter with intelligent boundary detection.
๐ Synchronous Chunking
use ;
โก Asynchronous Chunking
use ;
use ;
async
๐ง Semantic Chunking Benefits
The MarkdownSplitter uses intelligent semantic levels for optimal RAG performance:
- ๐ Heading Preservation: Keeps headers with their content sections
- ๐ Paragraph Integrity: Maintains paragraph boundaries and flow
- ๐ List Coherence: Preserves list items and hierarchical structure
- ๐ป Code Block Unity: Keeps code blocks intact as single units
- ๐ Link Context: Maintains inline formatting and link relationships
- โ๏ธ Semantic Balance: Optimizes chunk size vs. content coherence
Chunk Size Recommendations for RAG:
- Small Models: 400-800 characters
- Medium Models: 800-1500 characters
- Large Models: 1500-2500 characters
๐ Chunk Overlap Examples
The chunk_overlap parameter enables context preservation between adjacent chunks:
use ;
Overlap Size Recommendations:
| Use Case | Chunk Size | Recommended Overlap | Overlap % |
|---|---|---|---|
| Small Embeddings | 400-800 | 100-200 chars | 25-50% |
| Medium Embeddings | 800-1500 | 150-300 chars | 15-20% |
| Large Embeddings | 1500-2500 | 200-400 chars | 10-15% |
| Code Documentation | 1000-2000 | 200-500 chars | 20-25% |
| Academic Papers | 1500-3000 | 300-600 chars | 20-25% |
Benefits of Overlap:
- ๐ Context Continuity: Important information doesn't get "cut" between chunks
- ๐ Improved Retrieval: Higher probability of finding relevant information
- ๐ง Better Embeddings: More coherent semantic representations
- โก Flexible Tuning: Adjust overlap based on content type and model requirements
๐ API Documentation
Core Functions
Synchronous Processing
// Main function to extract content from URLs in text (blocking)
get_hyperlinks_content
Asynchronous Processing
// Async function for high-performance concurrent processing
get_hyperlinks_content_async where
F: Fn + Clone,
Fut:
Semantic Chunking Functions (chunks feature)
// Synchronous chunking for RAG systems with optional overlap
get_hyperlinks_content_as_chunks // Asynchronous chunking with real-time callback processing and optional overlap
get_hyperlinks_content_as_chunks_async where
F: Fn + Clone,
Fut:
Overlap Parameter Details:
chunk_overlap: Option<usize>- Optional overlap between adjacent chunksNone- No overlap (standard chunking behavior)Some(n)- n characters overlap between chunks- Constraint: overlap must be less than chunk_size
- Validation: Invalid values return empty results with stderr warning
HTTP Configuration
// HTTP configuration with Builder pattern
default
Utility Functions
// User agent utilities
random
When to Use Async vs Sync
| Feature | Synchronous | Asynchronous |
|---|---|---|
| Processing | Sequential - one URL at a time | Parallel - all URLs concurrently |
| Results | Returns after ALL URLs complete | Streams results as EACH URL completes |
| Use Case | Need all results before proceeding | Real-time processing as URLs finish |
| Performance | Slower for multiple URLs | Faster for multiple URLs |
| Complexity | Simple function call | Requires tokio runtime + callbacks |
| Memory Usage | Collects all results in Vec | Streams results via callbacks |
| Error Handling | Direct Result handling | Callback-based error handling |
| Integration | Easy to integrate | Better for async/await codebases |
๐ง HTTP Configuration Options
| Option | Type | Default | Description |
|---|---|---|---|
timeout |
Option<u64> |
None |
Request timeout in milliseconds |
max_redirect |
Option<usize> |
None |
Maximum number of redirects to follow |
cookie_store |
bool |
false |
Enable cookie storage for session management |
Supported Platforms & User Agents
The crate includes user agents for:
- Windows: Chrome, Firefox, Edge
- macOS: Chrome, Safari, Firefox
- Linux: Chrome, Firefox
- Android: Chrome, Firefox
- iOS: Safari, Chrome
๐๏ธ Dependencies
reqwest- HTTP client with both blocking and async supportscraper- HTML parsing and CSS selector enginehtml2md- Intelligent HTML to Markdown conversionregex- URL detection and content filteringrand- Random user agent selectiontokio- Async runtime for high-performance concurrent processingfutures- Async utilities and combinatorstext-splitter- Semantic Markdown chunking for RAG systems (optional, chunks feature)
๐ค AI Integration Context
This crate was specifically designed to serve as a content extraction component in Retrieval-Augmented Generation (RAG) workflows where:
- ๐ฅ Users submit messages containing URLs alongside other text
- ๐ง AI systems need structured content from those URLs for analysis
- ๐ Clean, readable Markdown is required preserving essential content and structure while removing HTML markup, scripts, ads, and links
- ๐ Multiple URLs need processing in batch operations
- ๐ก๏ธ Reliability is crucial with proper error handling and fallbacks
The extracted content can then be fed into language models, search systems, or other AI components for further processing.
๐ฏ Perfect for RAG Systems
- Vector Database Integration: Clean Markdown is ideal for embedding generation
- Token Optimization: Removes unnecessary content to reduce token usage
- Batch Processing: Handle multiple URLs from user queries efficiently
- Content Quality: Preserves semantic structure while removing noise
โ๏ธ Markdown Transformation Details
The crate performs intelligent HTML to Markdown conversion that preserves essential formatting while removing clutter:
โ Preserved Elements
- Headers:
<h1>โ# Header,<h2>โ## Header - Emphasis:
<strong>โ**bold**,<em>โ*italic* - Lists:
<ul><li>โ- item,<ol><li>โ1. item - Blockquotes:
<blockquote>โ> quote text - Scientific names:
<i>Bertholletia excelsa</i>โ*Bertholletia excelsa*
โ Removed Elements
- Links:
[text](url)โtext(keeps text, removes URL) - Images:
<img>tags completely removed - Media:
<iframe>,<video>,<audio>elements stripped - Navigation:
<nav>,<header>,<footer>,<aside>sections - Metadata: Author bylines, publication dates, tag lists
- Advertisements: Elements with ad-related classes or IDs
๐งน Text Cleanup
- Normalizes excessive whitespace and line breaks
- Removes photo captions and image attribution text
- Filters out navigation phrases ("click here", "read more")
- Eliminates code blocks and technical markup
- Preserves paragraph structure and readability
๐ Content Processing Pipeline
graph TD
A[๐ Input Text] --> B{URL Detection}
B -->|URLs Found| C[๐ HTTP Request]
B -->|No URLs| D[โก Return Empty]
C --> E[๐ HTML Parsing]
E --> F{๐ฏ Smart Content Extraction}
F -->|Priority 1| G1[๐ท๏ธ Semantic HTML5 Tags]
F -->|Priority 2| G2[๐ Content Selectors]
F -->|Priority 3| G3[๐ฆ Body Fallback]
G1 -->|article, main, role=main| H[โ
Content Found]
G2 -->|.content, .article, .post| H
G3 -->|body element| H
H --> I[๐งน Clean & Filter]
I --> J[๐ Markdown Conversion]
J --> K[๐ง Final Cleanup]
K --> L[โ
Output]
style G1 fill:#e1f5fe
style G2 fill:#f3e5f5
style G3 fill:#fff3e0
style F fill:#c8e6c9
- ๐ Input: Raw text from user containing URLs
- ๐ฏ Detection: Regex-based URL extraction with punctuation cleanup
- ๐ Fetching: HTTP requests with randomized user agents
- ๐ HTML Parsing: Document parsing with scraper crate
- ๐ฏ Smart Content Extraction: Priority-based semantic extraction strategy
- Priority 1: Semantic HTML5 tags (
<article>,<main>,[role='main']) - Priority 2: Content-specific selectors (
.content,.article,.post,.entry) - Priority 3: Fallback to
<body>element for legacy sites
- Priority 1: Semantic HTML5 tags (
- ๐ซ Media Removal: Strips images, iframes, videos, and other non-textual elements
- ๐งน Structure Cleaning: Removes scripts, styles, navigation, headers, footers, and ads
- ๐ฏ Content Selection: Focuses on relevant elements preserving semantic structure
- ๐ Markdown Conversion: Transforms cleaned HTML to structured Markdown using html2md
- ๐ Link Processing: Converts
[text](url)links to plain text, removes standalone URLs - โจ Format Preservation: Maintains headers, bold, italic, lists, and blockquotes
- ๐ง Final Cleanup: Removes metadata, navigation text, and excessive whitespace
- โ Output: Clean, readable Markdown content paired with source URLs
โ ๏ธ Error Handling
The crate handles various error conditions gracefully:
- ๐ Network timeouts and connection errors
- ๐ Invalid or malformed URLs
- ๐ Empty or missing content
- ๐ซ Server errors (404, 500, etc.)
- ๐ก๏ธ Blocked requests or rate limiting
๐ Migration from v0.1.2
โ ๏ธ Breaking Change: v0.1.3 introduces a breaking change in the API.
Before (v0.1.2)
use MarkdownHarvester;
let text = "Check https://example.com";
let results = get_hyperlinks_content;
After (v0.1.3)
use ;
let text = "Check https://example.com";
let config = default; // Add this line
let results = get_hyperlinks_content; // Add config parameter
Quick Migration Tips
- Import
HttpConfig: AddHttpConfigto your use statement - Create config: Use
HttpConfig::default()for same behavior as before - Pass config: Add the config as the second parameter to
get_hyperlinks_content()
The change enables powerful new features like custom timeouts, redirect control, and cookie management while maintaining the same core functionality.
๐ค Contributing
Contributions are welcome! Here's how to get started:
- ๐ด Fork the repository
- ๐ง Create a feature branch (
git checkout -b feature/amazing-feature) - ๐พ Commit your changes (
git commit -m 'Add amazing feature') - ๐ค Push to the branch (
git push origin feature/amazing-feature) - ๐ Open a Pull Request
Development Setup
# Clone the repository
# Run tests
# Run the interactive CLI
# Format code
# Check for issues
๐ License
Licensed under the MIT License. See LICENSE for details.
๐ Changelog
v0.1.5 ๐ NEW: Chunk Overlap Support
- ๐ Chunk Overlap Parameter: Added optional
chunk_overlapparameter to both sync and async chunking functions - ๐ง Context Preservation: Configurable overlap between adjacent chunks for better context continuity in RAG systems
- โ๏ธ Smart Validation: Automatic validation ensuring overlap < chunk_size with graceful error handling
- ๐ Flexible Configuration: Support for overlap sizes from 0% to 99% of chunk size
- ๐งช Enhanced Testing: 6 new unit tests for overlap functionality (49โ55 total tests)
- ๐ Comprehensive Documentation: Complete examples with overlap recommendations for different embedding models
- ๐ง ChunkConfig Integration: Native use of text-splitter's
ChunkConfig.with_overlap()functionality - โ Backward Compatible: No breaking changes - overlap parameter is optional (None = no overlap)
v0.1.5 ๐ฆ NEW: Semantic Chunking for RAG Systems
- ๐ฆ Semantic Chunking Feature: New optional
chunksfeature for RAG systems usingMarkdownSplitter - ๐ง Smart Boundary Detection: Intelligent semantic splitting preserving document structure
- โก Dual Processing Modes: Both sync (
get_hyperlinks_content_as_chunks) and async (get_hyperlinks_content_as_chunks_async) implementations - ๐ง RAG Optimized: Semantic levels preserve headings, paragraphs, code blocks, and lists as coherent units
- ๐ Flexible Chunk Sizes: Configurable chunk sizes with recommendations for different embedding models
- ๐งช Enhanced Testing: 8 new chunk-specific unit tests (41โ49 total tests)
- ๐ Comprehensive Documentation: Complete examples and integration guides for RAG workflows
- ๐๏ธ Optional Dependency:
text-splitterv0.28 with Markdown support as optional feature - โ Backward Compatible: No breaking changes - chunks feature is completely optional
v0.1.4 ๐ NEW: Async Processing
- โก Asynchronous Processing Support: Complete async/await implementation for high-performance concurrent URL processing
- ๐ Performance Improvements: Faster processing when handling multiple URLs simultaneously through parallel processing
- ๐ Enhanced Examples: Updated
main.rswith interactive examples showing both sync and async processing modes - ๐งช Async Test Suite: 8 new async unit tests covering all async methods (27โ36 total tests)
- ๐ Callback Architecture: Flexible callback system supporting custom processing pipelines
- ๐ Comprehensive Documentation: Complete documentation with 3 detailed async examples
- โ Backward Compatible: No breaking changes - all existing sync code continues to work
v0.1.3 โ ๏ธ BREAKING CHANGES
- ๐๏ธ HTTP Configuration with Builder Pattern: Complete HTTP configuration system
- ๐ฅ API Change:
get_hyperlinks_content()now requiresHttpConfigparameter - โก New Features: Configurable timeout, redirects, and cookie management
- ๐งช Testing: 17 new unit tests (10โ27 total) with 100% API coverage
- ๐ Enhanced Documentation: Updated examples and migration guide
v0.1.2
- ๐ง Component Architecture: Separated responsibilities with HttpClient and ContentProcessor
- ๐ฏ Facade Pattern: MarkdownHarvester as clean interface
- ๐งช Unit Tests: Comprehensive testing for all components
v0.1.0
- โจ Initial release
- ๐ URL detection and content extraction
- ๐ค Multi-platform user agent support
- ๐งน Content cleaning and normalization
- ๐ป Interactive CLI mode