Metadata-Version: 2.2
Name: betterhtmlchunking
Version: 0.9.1
Summary: A Python library for intelligent HTML segmentation and ROI extraction. It builds a DOM tree from raw HTML and extracts content-rich regions for efficient web scraping and analysis.
Author-email: "Carlos A. Planchón" <carlosandresplanchonprestes@gmail.com>
License: MIT License
Project-URL: repository, https://github.com/carlosplanchon/betterhtmlchunking.git
Keywords: html,chunking,scraping,dom,roi,content extraction,web-scraping
Classifier: Intended Audience :: Developers
Classifier: Topic :: Software Development :: Libraries
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3.13
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: attrs
Requires-Dist: attrs-strict
Requires-Dist: beautifulsoup4
Requires-Dist: lxml
Requires-Dist: treelib
Requires-Dist: parsel_text

```markdown
# betterhtmlchunking

A Python library for intelligently chunking HTML documents into structured, size-limited segments based on DOM tree analysis.

## Overview

This library processes HTML content to split it into semantically coherent chunks while respecting specified size constraints. It analyzes the DOM structure to identify optimal split points, preserving contextual information and document hierarchy.

## Key Features

- Custom DOM tree representation. 
- Configurable chunk size limits (counting by text or HTML length).
- Intelligent region-of-interest detection.
- Dual output formats: HTML and plain text chunks.  
- Preservation of structure relationships.
- Customizable tag filtering.

## Installation

```bash
pip install betterhtmlchunking
```

### Dependencies
- Python 3.12+
- attrs
- treelib
- beautifulsoup4
- parsel-text
- lxml
- attrs-strict

## Usage

### Basic Example

```python
from betterhtmlchunking import DomRepresentation

html_content = """
<html>
  <body>
    <div id="content">
      <h1>Document Title</h1>
      <p>First paragraph...</p>
      <p>Second paragraph...</p>
    </div>
  </body>
</html>
"""

# Create document representation with 500 character chunks
doc = DomRepresentation(
    MAX_NODE_REPR_LENGTH=500,
    website_code=html_content,
    repr_length_compared_by="html_length"
)

# Access HTML chunks
html_chunks = doc.render_system.html_render_roi
for chunk_id, chunk in html_chunks.items():
    print(f"Chunk {chunk_id}:\n{chunk}\n{'='*50}")

# Access text chunks
text_chunks = doc.render_system.text_render_roi
for chunk_id, chunk in text_chunks.items():
    print(f"Chunk {chunk_id}:\n{chunk}\n{'='*50}")
```

## Configuration

### Key Parameters
- `MAX_NODE_REPR_LENGTH`: Maximum allowed length for each chunk (in characters)
- `repr_length_compared_by`: Length calculation method:
  - `html_length`: HTML source length
  - `text_length`: Rendered text length
- `website_code`: Input HTML content

### Advanced Features
```python
# Access the DOM tree structure
tree = doc.tree_representation.tree

# Get node metadata
for node in tree.all_nodes():
    print(f"XPath: {node.identifier}")
    print(f"Text length: {node.data.text_length}")
    print(f"HTML length: {node.data.html_length}")

# Custom tag filtering (before processing)
from betterhtmlchunking.tree_representation import DOMTreeRepresentation
from betterhtmlchunking.utils import remove_unwanted_tags

# Example usage of remove_unwanted_tags:
tree_rep = DOMTreeRepresentation(website_code=html_content)
filtered_rep = remove_unwanted_tags(tree_rep)
```

## How It Works

1. **DOM Parsing**  
   - Builds a tree representation of the HTML document.
   - Calculates metadata (text length, HTML length) for each node.

2. **Region Detection**  
   - Uses **Breadth First Search (BFS)** to traverse the DOM tree in a level-order fashion, ensuring that each node is processed systematically.
   - Combines nodes until the specified size limit is reached.
   - Preserves parent-child relationships to maintain contextual integrity.

3. **Chunk Generation**  
   - Creates HTML chunks with original markup.
   - Generates parallel text-only chunks.
   - Maintains chunk order based on document structure.

## Comparison to popular Chunking Techniques

The actual practice (Feb. 2025) is to use **plain-text** or **token-based** chunking strategies, primarily aimed at keeping prompts within certain token limits for large language models. This approach is ideal for quick semantic retrieval or QA tasks on *unstructured* text.

By contrast, **betterhtmlchunking** preserves the **HTML DOM structure**, calculating chunk boundaries based on each node’s text or HTML length. This approach is especially useful when you want to:
- Retain or leverage the **hierarchical relationships** in the HTML (e.g., headings, nested divs)  
- Filter out undesired tags or sections (like `<script>` or `<style>`)  
- Pinpoint exactly where each chunk originated in the document (via positional XPaths)

You can even combine the two techniques if you need both **structured extraction** (via betterhtmlchunking) and **LLM-friendly text chunking** (via LangChain) for advanced tasks such as summarization, semantic search, or large-scale QA pipelines.

## License

MIT License

## Contributing
Feel free to open issues or submit pull requests if you have suggestions or improvements.
