markdown-harvest 0.1.6

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.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
# ๐Ÿ“ Markdown Harvest

<div align="center">
  <img src="assets/logo.svg" alt="Markdown Harvest Logo" width="1200" height="300">
  
  [![Crates.io](https://img.shields.io/crates/v/markdown-harvest)](https://crates.io/crates/markdown-harvest)
  [![Documentation](https://docs.rs/markdown-harvest/badge.svg)](https://docs.rs/markdown-harvest)
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
  [![Rust](https://img.shields.io/badge/rust-2024-orange.svg)](https://www.rust-lang.org/)
</div>

<br>

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]#overview
- [Features]#features
- [Quick Start]#quick-start
- [Installation]#installation
- [Usage Examples]#usage-examples
- [API Documentation]#api-documentation
- [Content Processing Pipeline]#content-processing-pipeline
- [Supported Platforms]#supported-platforms
- [Contributing]#contributing
- [License]#license
- [Changelog]#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
```mermaid
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)
```mermaid
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]https://github.com/franciscotbjr/markdown-harvest/issues/40)
  - **Backward compatible**: Graceful fallback to `<body>` for legacy sites
- **๐Ÿ“„ 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 `MarkdownSplitter` with 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

```rust
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);
    }
}
```

## ๐Ÿ“ฆ Installation

Add this to your `Cargo.toml`:

```toml
[dependencies]
markdown-harvest = "0.1.5"

# For RAG systems with semantic chunking and overlap support
markdown-harvest = { version = "0.1.5", features = ["chunks"] }
```

## ๐Ÿ“š Usage Examples

### ๐Ÿ“ Synchronous Processing (Traditional)

```rust
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!("---");
    }
}
```

### โšก Asynchronous Processing (High Performance)

```rust
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(())
}
```

### ๐Ÿ”„ Real-time Processing with Immediate Output

```rust
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(())
}
```

### ๐Ÿ’ป Interactive CLI Mode

The crate provides an interactive CLI mode for testing:

```bash
cargo run
```

Then enter text containing URLs when prompted.

### ๐Ÿ”ง Advanced HTTP Configuration

```rust
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());
    }
}
```

### ๐ŸŽฏ Different Configuration Examples

```rust
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);
```

### ๐Ÿ“ฆ 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

```rust
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>());
        }
    }
}
```

#### โšก Asynchronous Chunking

```rust
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(())
}
```

#### ๐Ÿง  Semantic Chunking Benefits

The `MarkdownSplitter` uses intelligent semantic levels for optimal RAG performance:

1. **๐Ÿ“Š Heading Preservation**: Keeps headers with their content sections
2. **๐Ÿ“ Paragraph Integrity**: Maintains paragraph boundaries and flow
3. **๐Ÿ“‹ List Coherence**: Preserves list items and hierarchical structure  
4. **๐Ÿ’ป Code Block Unity**: Keeps code blocks intact as single units
5. **๐Ÿ”— Link Context**: Maintains inline formatting and link relationships
6. **โš–๏ธ 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:

```rust
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:**
- ๐Ÿ”— **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
```rust
// Main function to extract content from URLs in text (blocking)
MarkdownHarvester::get_hyperlinks_content(text: String, http_config: HttpConfig) -> Vec<(String, String)>
```

#### Asynchronous Processing
```rust
// 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 = ()>
```

#### Semantic Chunking Functions (chunks feature)
```rust
// 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 chunks
- `None` - 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
```rust
// 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
```

#### Utility Functions
```rust
// User agent utilities
UserAgent::random() -> UserAgent
UserAgent::to_string(&self) -> String
```

### 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 support
- **`scraper`** - HTML parsing and CSS selector engine  
- **`html2md`** - Intelligent HTML to Markdown conversion
- **`regex`** - URL detection and content filtering
- **`rand`** - Random user agent selection
- **`tokio`** - Async runtime for high-performance concurrent processing
- **`futures`** - Async utilities and combinators
- **`text-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:

1. **๐Ÿ‘ฅ Users submit messages** containing URLs alongside other text
2. **๐Ÿง  AI systems need structured content** from those URLs for analysis  
3. **๐Ÿ“ Clean, readable Markdown is required** preserving essential content and structure while removing HTML markup, scripts, ads, and links
4. **๐Ÿ”„ Multiple URLs need processing** in batch operations
5. **๐Ÿ›ก๏ธ 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

```mermaid
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
```

1. **๐Ÿ” Input**: Raw text from user containing URLs
2. **๐ŸŽฏ Detection**: Regex-based URL extraction with punctuation cleanup
3. **๐ŸŒ Fetching**: HTTP requests with randomized user agents
4. **๐Ÿ“„ HTML Parsing**: Document parsing with scraper crate
5. **๐ŸŽฏ 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
6. **๐Ÿšซ Media Removal**: Strips images, iframes, videos, and other non-textual elements
7. **๐Ÿงน Structure Cleaning**: Removes scripts, styles, navigation, headers, footers, and ads
8. **๐ŸŽฏ Content Selection**: Focuses on relevant elements preserving semantic structure
9. **๐Ÿ“ Markdown Conversion**: Transforms cleaned HTML to structured Markdown using html2md
10. **๐Ÿ”— Link Processing**: Converts `[text](url)` links to plain text, removes standalone URLs
11. **โœจ Format Preservation**: Maintains headers, bold, italic, lists, and blockquotes
12. **๐Ÿ”ง Final Cleanup**: Removes metadata, navigation text, and excessive whitespace
13. **โœ… 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)
```rust
use markdown_harvest::MarkdownHarvester;

let text = "Check https://example.com";
let results = MarkdownHarvester::get_hyperlinks_content(text.to_string());
```

### After (v0.1.3)
```rust
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
```

### Quick Migration Tips
1. **Import `HttpConfig`**: Add `HttpConfig` to your use statement
2. **Create config**: Use `HttpConfig::default()` for same behavior as before
3. **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:

1. **๐Ÿด Fork** the repository
2. **๐Ÿ”ง Create** a feature branch (`git checkout -b feature/amazing-feature`)
3. **๐Ÿ’พ Commit** your changes (`git commit -m 'Add amazing feature'`)
4. **๐Ÿ“ค Push** to the branch (`git push origin feature/amazing-feature`)
5. **๐Ÿ”€ Open** a Pull Request

### Development Setup

```bash
# 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
```

## ๐Ÿ“„ License

Licensed under the **MIT License**. See [LICENSE](LICENSE) for details.

## ๐Ÿ“‹ Changelog

### v0.1.5 ๐Ÿ”„ NEW: Chunk Overlap Support
- ๐Ÿ”„ **Chunk Overlap Parameter**: Added optional `chunk_overlap` parameter 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 `chunks` feature for RAG systems using `MarkdownSplitter`
- ๐Ÿ”ง **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-splitter` v0.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.rs` with 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 requires `HttpConfig` parameter
- โšก **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

---

<div align="center">
  <p><strong>Built with โค๏ธ for RAG systems and AI workflows</strong></p>
  <p>โญ Star this repo if it helps your project!</p>
</div>