markdown-harvest 0.1.2

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


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

## โœจ Features


- **๐Ÿ” URL Detection**: Automatically identifies HTTP/HTTPS URLs in text using regex patterns
- **๐ŸŽฏ Smart Content Extraction**: Extracts only relevant content from HTML `<body>` elements
- **๐Ÿ“„ 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
- **๐Ÿค– Multi-Platform User Agents**: Rotates between different browser user agents to avoid detection
- **โšก Async/Blocking Support**: Choose between async and blocking HTTP requests
- **๐Ÿ›ก๏ธ Error Handling**: Graceful handling of network errors and invalid URLs
- **๐Ÿ“ Clean Text Output**: Normalizes whitespace and removes common non-content patterns

## ๐Ÿš€ Quick Start


```rust
use markdown_harvest::MarkdownHarvester;

fn main() {
    let text = "Check this out: https://example.com/article";
    let results = MarkdownHarvester::get_hyperlinks_content(text.to_string());
    
    for (url, content) in results {
        println!("URL: {}\nContent: {}", url, content);
    }
}
```

## ๐Ÿ“ฆ Installation


Add this to your `Cargo.toml`:

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

## ๐Ÿ“š Usage Examples


### ๐Ÿ“ Basic Usage


```rust
use markdown_harvest::MarkdownHarvester;

fn main() {
    let text = "Check out this article: https://example.com/article.html and this one too: https://news.site.com/story";
    
    let results = MarkdownHarvester::get_hyperlinks_content(text.to_string());
    
    for (url, content) in results {
        println!("URL: {}", url);
        println!("Markdown Content:\n{}", content);
        println!("---");
    }
}
```

### ๐Ÿ’ป Interactive CLI Mode


The crate provides an interactive CLI mode for testing:

```bash
cargo run
```

Then enter text containing URLs when prompted.

### ๐Ÿ”ง Library Integration

er
```rust
use markdown_harvest::{MarkdownHarvester, UserAgent};

// Use different user agents
let user_agent = UserAgent::random_windows();
println!("Using: {}", user_agent.to_string());

// Process multiple URLs from text
let input = "Articles: https://site1.com and https://site2.com";
let results = MarkdownHarvest::get_hyperlinks_content(input.to_string());
```

## ๐Ÿ“– API Documentation


### Core Functions


```rust
// Main function to extract content from URLs in text
MarkdownHarvester::get_hyperlinks_content(text: String) -> Vec<(String, String)>

// User agent utilities
UserAgent::random_windows() -> String
UserAgent::random_macos() -> String  
UserAgent::random_linux() -> String
UserAgent::random_android() -> String
UserAgent::random_ios() -> String
```

### 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 blocking 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 support

## ๐Ÿค– 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[โœ‚๏ธ Content Extraction]
    F --> G[๐Ÿงน Clean & Filter]
    G --> H[๐Ÿ“ Markdown Conversion]
    H --> I[๐Ÿ”ง Final Cleanup]
    I --> J[โœ… Output]
```

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. **โœ‚๏ธ Body Extraction**: Extracts only content from HTML `<body>` element
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 (articles, main content, headings, paragraphs)
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

## ๐Ÿค 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.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>