| Crates.io | markdown-harvest |
| lib.rs | markdown-harvest |
| version | 0.1.5 |
| created_at | 2025-08-10 20:04:13.480691+00 |
| updated_at | 2025-09-12 19:19:12.373072+00 |
| description | 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. |
| homepage | |
| repository | https://github.com/franciscotbjr/markdown-harvest |
| max_upload_size | |
| id | 1789255 |
| size | 215,814 |
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.
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.
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
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
<body> elementsMarkdownSplitter with semantic boundaries and configurable overlapHttpConfig::builder()use markdown_harvest::{MarkdownHarvester, HttpConfig};
fn main() {
let text = "Check this out: https://example.com/article";
let config = HttpConfig::default(); // Use default HTTP configuration
let results = MarkdownHarvester::get_hyperlinks_content(text.to_string(), config);
for (url, content) in results {
println!("URL: {}\nContent: {}", url, content);
}
}
Add this to your Cargo.toml:
[dependencies]
markdown-harvest = "0.1.5"
# For RAG systems with semantic chunking and overlap support
markdown-harvest = { version = "0.1.5", features = ["chunks"] }
use markdown_harvest::{MarkdownHarvester, HttpConfig};
fn main() {
let text = "Check out this article: https://example.com/article.html and this one too: https://news.site.com/story";
// Use default configuration
let config = HttpConfig::default();
let results = MarkdownHarvester::get_hyperlinks_content(text.to_string(), config);
for (url, content) in results {
println!("URL: {}", url);
println!("Markdown Content:\n{}", content);
println!("---");
}
}
use markdown_harvest::{MarkdownHarvester, HttpConfig};
use std::sync::{Arc, Mutex};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let text = "Check out: https://example.com and https://httpbin.org/json";
let config = HttpConfig::builder().timeout(30000).build();
// Collect results in a thread-safe vector
let results = Arc::new(Mutex::new(Vec::new()));
let results_clone = results.clone();
let callback = move |url: Option<String>, content: Option<String>| {
let results = results_clone.clone();
async move {
if let (Some(url), Some(content)) = (url, content) {
let mut results = results.lock().unwrap();
results.push((url, content));
println!("โ
Processed URL with {} characters", content.len());
}
}
};
MarkdownHarvester::get_hyperlinks_content_async(text.to_string(), config, callback).await?;
let final_results = results.lock().unwrap();
println!("๐ Total URLs processed: {}", final_results.len());
Ok(())
}
use markdown_harvest::{MarkdownHarvester, HttpConfig};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let text = "Visit https://example.com for more info";
let config = HttpConfig::default();
// Process and display results immediately as they arrive
let callback = |url: Option<String>, content: Option<String>| async move {
match (url, content) {
(Some(url), Some(content)) => {
println!("๐ Processed: {}", url);
println!("๐ Content length: {} characters", content.len());
// Save to database, send to API, etc.
}
(None, None) => {
println!("โน๏ธ No URLs found in the provided text");
}
_ => unreachable!(),
}
};
MarkdownHarvester::get_hyperlinks_content_async(text.to_string(), config, callback).await?;
Ok(())
}
The crate provides an interactive CLI mode for testing:
cargo run
Then enter text containing URLs when prompted.
use markdown_harvest::{MarkdownHarvester, HttpConfig};
fn main() {
let text = "Articles: https://site1.com and https://site2.com";
// Custom HTTP configuration with Builder pattern
let config = HttpConfig::builder()
.timeout(10000) // 10 second timeout
.max_redirect(5) // Allow up to 5 redirects
.cookie_store(true) // Enable cookie storage for sessions
.build();
let results = MarkdownHarvester::get_hyperlinks_content(text.to_string(), config);
for (url, content) in results {
println!("Processed: {}", url);
println!("Content length: {} chars", content.len());
}
}
use markdown_harvest::{MarkdownHarvester, HttpConfig};
// Quick timeout for fast responses only
let fast_config = HttpConfig::builder()
.timeout(3000) // 3 seconds
.build();
// Conservative configuration for slow sites
let patient_config = HttpConfig::builder()
.timeout(30000) // 30 seconds
.max_redirect(10) // More redirects allowed
.cookie_store(true) // 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 = MarkdownHarvester::get_hyperlinks_content(urgent_text.to_string(), fast_config);
let research_results = MarkdownHarvester::get_hyperlinks_content(deep_text.to_string(), patient_config);
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.
use markdown_harvest::{MarkdownHarvester, HttpConfig};
#[cfg(feature = "chunks")]
fn main() {
let text = "Research these articles: https://example.com/article1 and https://example.com/article2";
let config = HttpConfig::default();
let chunk_size = 1000; // 1000 characters per chunk
let results = MarkdownHarvester::get_hyperlinks_content_as_chunks(
text.to_string(),
config,
chunk_size,
Some(100) // 100 characters overlap for better context preservation
);
for (url, chunks) in results {
println!("๐ URL: {}", url);
println!("๐ฆ Generated {} semantic chunks:", chunks.len());
for (i, chunk) in chunks.iter().enumerate() {
println!(" Chunk {}: {} chars", i + 1, chunk.len());
println!(" Content: {}\n---", chunk.chars().take(100).collect::<String>());
}
}
}
use markdown_harvest::{MarkdownHarvester, HttpConfig};
use std::sync::{Arc, Mutex};
#[cfg(feature = "chunks")]
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let text = "Process these for RAG: https://docs.example.com https://blog.example.com";
let config = HttpConfig::builder()
.timeout(15000)
.build();
let chunk_size = 800; // Optimal for embedding models
// Real-time chunk processing for RAG pipeline
let callback = |url: Option<String>, chunks: Option<Vec<String>>| async move {
match (url, chunks) {
(Some(url), Some(chunks)) => {
println!("๐ Processing {} chunks from: {}", chunks.len(), url);
for (i, chunk) in chunks.iter().enumerate() {
println!(" ๐ฆ Chunk {}: {} chars", i + 1, chunk.len());
// RAG Pipeline Integration:
// 1. Generate embeddings for this semantic chunk
// 2. Store in vector database with metadata
// 3. Index for semantic search
// 4. Preserve document context and structure
}
}
(None, None) => {
println!("โน๏ธ No URLs found in text");
}
_ => unreachable!(),
}
};
MarkdownHarvester::get_hyperlinks_content_as_chunks_async(
text.to_string(),
config,
chunk_size,
Some(80), // 80 characters overlap - optimal for embedding models
callback
).await?;
Ok(())
}
The MarkdownSplitter uses intelligent semantic levels for optimal RAG performance:
Chunk Size Recommendations for RAG:
The chunk_overlap parameter enables context preservation between adjacent chunks:
use markdown_harvest::{MarkdownHarvester, HttpConfig};
#[cfg(feature = "chunks")]
fn main() {
let text = "Process: https://example.com/documentation";
let config = HttpConfig::default();
// Without overlap - standard chunking
let standard_chunks = MarkdownHarvester::get_hyperlinks_content_as_chunks(
text.clone(),
config.clone(),
1000,
None // No overlap
);
// Result: [Chunk1][Chunk2][Chunk3]
// With overlap - better context preservation
let overlap_chunks = MarkdownHarvester::get_hyperlinks_content_as_chunks(
text,
config,
1000,
Some(200) // 200 characters overlap
);
// Result: [Chunk1][Chunk1+2][Chunk2+3][Chunk3] (200 char overlap)
println!("Standard chunks: {}", standard_chunks.len());
println!("Overlap chunks: {}", overlap_chunks.len());
}
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:
// Main function to extract content from URLs in text (blocking)
MarkdownHarvester::get_hyperlinks_content(text: String, http_config: HttpConfig) -> Vec<(String, String)>
// Async function for high-performance concurrent processing
MarkdownHarvester::get_hyperlinks_content_async<F, Fut>(
text: String,
http_config: HttpConfig,
callback: F
) -> Result<(), Box<dyn std::error::Error>>
where
F: Fn(Option<String>, Option<String>) -> Fut + Clone,
Fut: Future<Output = ()>
// Synchronous chunking for RAG systems with optional overlap
MarkdownHarvester::get_hyperlinks_content_as_chunks(
text: String,
http_config: HttpConfig,
chunk_size: usize,
chunk_overlap: Option<usize> // โ NEW: Overlap between chunks (must be < chunk_size)
) -> Vec<(String, Vec<String>)>
// Asynchronous chunking with real-time callback processing and optional overlap
MarkdownHarvester::get_hyperlinks_content_as_chunks_async<F, Fut>(
text: String,
http_config: HttpConfig,
chunk_size: usize,
chunk_overlap: Option<usize>, // โ NEW: Overlap between chunks (must be < chunk_size)
callback: F
) -> Result<(), Box<dyn std::error::Error>>
where
F: Fn(Option<String>, Option<Vec<String>>) -> Fut + Clone,
Fut: Future<Output = ()>
Overlap Parameter Details:
chunk_overlap: Option<usize> - Optional overlap between adjacent chunksNone - No overlap (standard chunking behavior)Some(n) - n characters overlap between chunks// HTTP configuration with Builder pattern
HttpConfig::default() -> HttpConfig
HttpConfig::builder() -> HttpConfigBuilder
HttpConfigBuilder::new() -> HttpConfigBuilder
HttpConfigBuilder::timeout(ms: u64) -> HttpConfigBuilder
HttpConfigBuilder::max_redirect(count: usize) -> HttpConfigBuilder
HttpConfigBuilder::cookie_store(enabled: bool) -> HttpConfigBuilder
HttpConfigBuilder::build() -> HttpConfig
// User agent utilities
UserAgent::random() -> UserAgent
UserAgent::to_string(&self) -> String
| 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 |
| 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 |
The crate includes user agents for:
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)This crate was specifically designed to serve as a content extraction component in Retrieval-Augmented Generation (RAG) workflows where:
The extracted content can then be fed into language models, search systems, or other AI components for further processing.
The crate performs intelligent HTML to Markdown conversion that preserves essential formatting while removing clutter:
<h1> โ # Header, <h2> โ ## Header<strong> โ **bold**, <em> โ *italic*<ul><li> โ - item, <ol><li> โ 1. item<blockquote> โ > quote text<i>Bertholletia excelsa</i> โ *Bertholletia excelsa*[text](url) โ text (keeps text, removes URL)<img> tags completely removed<iframe>, <video>, <audio> elements stripped<nav>, <header>, <footer>, <aside> sectionsgraph 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[โ๏ธ Content Extraction]
F --> G[๐งน Clean & Filter]
G --> H[๐ Markdown Conversion]
H --> I[๐ง Final Cleanup]
I --> J[โ
Output]
<body> element[text](url) links to plain text, removes standalone URLsThe crate handles various error conditions gracefully:
โ ๏ธ Breaking Change: v0.1.3 introduces a breaking change in the API.
use markdown_harvest::MarkdownHarvester;
let text = "Check https://example.com";
let results = MarkdownHarvester::get_hyperlinks_content(text.to_string());
use markdown_harvest::{MarkdownHarvester, HttpConfig};
let text = "Check https://example.com";
let config = HttpConfig::default(); // Add this line
let results = MarkdownHarvester::get_hyperlinks_content(text.to_string(), config); // Add config parameter
HttpConfig: Add HttpConfig to your use statementHttpConfig::default() for same behavior as beforeget_hyperlinks_content()The change enables powerful new features like custom timeouts, redirect control, and cookie management while maintaining the same core functionality.
Contributions are welcome! Here's how to get started:
git checkout -b feature/amazing-feature)git commit -m 'Add amazing feature')git push origin feature/amazing-feature)# Clone the repository
git clone https://github.com/franciscotbjr/markdown-harvest
cd markdown-harvest
# Run tests
cargo test
# Run the interactive CLI
cargo run
# Format code
cargo fmt
# Check for issues
cargo clippy
Licensed under the MIT License. See LICENSE for details.
chunk_overlap parameter to both sync and async chunking functionsChunkConfig.with_overlap() functionalitychunks feature for RAG systems using MarkdownSplitterget_hyperlinks_content_as_chunks) and async (get_hyperlinks_content_as_chunks_async) implementationstext-splitter v0.28 with Markdown support as optional featuremain.rs with interactive examples showing both sync and async processing modesget_hyperlinks_content() now requires HttpConfig parameterBuilt with โค๏ธ for RAG systems and AI workflows
โญ Star this repo if it helps your project!