{"id":31063458,"url":"https://github.com/carlosplanchon/betterhtmlchunking","last_synced_at":"2025-09-15T13:04:30.569Z","repository":{"id":277500221,"uuid":"932589297","full_name":"carlosplanchon/betterhtmlchunking","owner":"carlosplanchon","description":"BetterHTMLChunking is a Python library for intelligent HTML segmentation. It builds a DOM tree from raw HTML and extracts content-rich regions of interest, making content analysis effortless. Great for LLM based processing.","archived":false,"fork":false,"pushed_at":"2025-09-07T02:38:59.000Z","size":43,"stargazers_count":42,"open_issues_count":4,"forks_count":3,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-09-07T04:17:17.531Z","etag":null,"topics":["ai","chunking","html","llm","splitting"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/carlosplanchon.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-02-14T06:49:14.000Z","updated_at":"2025-09-07T02:37:24.000Z","dependencies_parsed_at":"2025-03-29T00:22:54.595Z","dependency_job_id":"00eff7fa-b491-41a6-8969-8069f3bac4eb","html_url":"https://github.com/carlosplanchon/betterhtmlchunking","commit_stats":null,"previous_names":["carlosplanchon/betterhtmlchunking"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/carlosplanchon/betterhtmlchunking","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/carlosplanchon%2Fbetterhtmlchunking","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/carlosplanchon%2Fbetterhtmlchunking/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/carlosplanchon%2Fbetterhtmlchunking/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/carlosplanchon%2Fbetterhtmlchunking/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/carlosplanchon","download_url":"https://codeload.github.com/carlosplanchon/betterhtmlchunking/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/carlosplanchon%2Fbetterhtmlchunking/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":274071905,"owners_count":25217644,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-07T02:00:09.463Z","response_time":67,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai","chunking","html","llm","splitting"],"created_at":"2025-09-15T13:04:27.287Z","updated_at":"2025-09-15T13:04:30.557Z","avatar_url":"https://github.com/carlosplanchon.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# betterhtmlchunking\n\nA Python library for intelligently chunking HTML documents into structured, size-limited segments based on DOM tree analysis.\n\n## Our Discord Server:\n[https://discord.gg/2uVF5FZg](https://discord.gg/EgXeu9qnrR)\n\n## Overview\n\nThis 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.\n\n### DeepWiki Docs: [https://deepwiki.com/carlosplanchon/betterhtmlchunking](https://deepwiki.com/carlosplanchon/betterhtmlchunking)\n\n## Key Features\n\n- Custom DOM tree representation. \n- Configurable chunk size limits (counting by text or HTML length).\n- Intelligent region-of-interest detection.\n- Dual output formats: HTML and plain text chunks.  \n- Preservation of structure relationships.\n- Customizable tag filtering.\n\n## Installation\n\n```bash\npip install betterhtmlchunking\n```\n\n### Dependencies\n- Python 3.12+\n- attrs\n- treelib\n- beautifulsoup4\n- parsel-text\n- lxml\n- attrs-strict\n\n## Usage\n\n### Basic Example\n\n```python\nfrom betterhtmlchunking import DomRepresentation\nfrom betterhtmlchunking.main import ReprLengthComparisionBy\nfrom betterhtmlchunking.main import tag_list_to_filter_out\n\nhtml_content = \"\"\"\n\u003chtml\u003e\n  \u003cbody\u003e\n    \u003cdiv id=\"content\"\u003e\n      \u003ch1\u003eDocument Title\u003c/h1\u003e\n      \u003cp\u003eFirst paragraph...\u003c/p\u003e\n      \u003cp\u003eSecond paragraph...\u003c/p\u003e\n    \u003c/div\u003e\n  \u003c/body\u003e\n\u003c/html\u003e\n\"\"\"\n\n# Create document representation with 20 character chunks.\ndom_repr = DomRepresentation(\n    MAX_NODE_REPR_LENGTH=20,\n    website_code=html_content,\n    repr_length_compared_by=ReprLengthComparisionBy.HTML_LENGTH\n    # tag_list_to_filter_out=[\"/head\", \"/header\", \"...\"]  # By default tag_list_to_filter_out is used.\n)\ndom_repr.start()\n\n# Render HTML:\nfor idx in dom_repr.tree_regions_system.sorted_roi_by_pos_xpath:\n    print(\"*\" * 50)\n    print(f\"IDX: {idx}\")\n    roi_html_render: str =\\\n        dom_repr.render_system.get_roi_html_render_with_pos_xpath(\n            roi_idx=idx\n        )\n    print(roi_html_render)\n\n\n# Render text:\nfor idx in dom_repr.tree_regions_system.sorted_roi_by_pos_xpath:\n    print(\"*\" * 50)\n    print(f\"IDX: {idx}\")\n    roi_text_render: str =\\\n        dom_repr.render_system.get_roi_text_render_with_pos_xpath(\n            roi_idx=idx\n        )\n    print(roi_text_render)\n\n```\n\nRender output (HTML):\n```\n**************************************************\nIDX: 0\n\u003ch1\u003e\n Document Title\n\u003c/h1\u003e\n\n**************************************************\nIDX: 1\n\u003cp\u003e\n First paragraph...\n\u003c/p\u003e\n\n**************************************************\nIDX: 2\n\u003cp\u003e\n Second paragraph...\n\u003c/p\u003e\n```\n\nRender output (text):\n```\n**************************************************\nIDX: 0\nDocument Title\n\n**************************************************\nIDX: 1\nFirst paragraph...\n\n**************************************************\nIDX: 2\nSecond paragraph...\n```\n\n\n## Configuration\n\n### Key Parameters\n- `MAX_NODE_REPR_LENGTH`: Maximum allowed length for each chunk (in characters)\n- `repr_length_compared_by`: Length calculation method:\n  - ReprLengthComparisionBy.HTML_LENGTH: HTML source length\n  - ReprLengthComparisionBy.TEXT_LENGTH: Rendered text length\n- `website_code`: Input HTML content\n\n### Advanced Features\n```python\n# Access the DOM tree structure\ntree = dom_repr.tree_representation.tree\n\n# Get node metadata:\nfor node in tree.all_nodes():\n    if node.data is not None:\n        print(f\"XPath: {node.identifier}\")\n        print(f\"Text length: {node.data.text_length}\")\n        print(f\"HTML length: {node.data.html_length}\")\n\n```\n\n## How It Works\n\n1. **DOM Parsing**  \n   - Builds a tree representation of the HTML document.\n   - Calculates metadata (text length, HTML length) for each node.\n\n2. **Region Detection**  \n   - Uses **Breadth First Search (BFS)** to traverse the DOM tree in a level-order fashion, ensuring that each node is processed systematically.\n   - Combines nodes until the specified size limit is reached.\n   - Preserves parent-child relationships to maintain contextual integrity.\n\n3. **Chunk Generation**  \n   - Creates HTML chunks with original markup.\n   - Generates parallel text-only chunks.\n   - Maintains chunk order based on document structure.\n\n## Comparison to popular Chunking Techniques\n\nThe 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.\n\nBy 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:\n- Retain or leverage the **hierarchical relationships** in the HTML (e.g., headings, nested divs)  \n- Filter out undesired tags or sections (like `\u003cscript\u003e` or `\u003cstyle\u003e`)  \n- Pinpoint exactly where each chunk originated in the document (via positional XPaths)\n\nYou 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.\n\n## CLI\n\nThe package ships with a small command line interface built with [Typer](https://typer.tiangolo.com/). You can pipe HTML to the tool and obtain a specific chunk as HTML:\n\n```bash\ncat input.html | betterhtmlchunking --max-length 32768 --chunk-index 0 \u003e chunk.html\n```\n\nBy default the command reads from `stdin`, processes chunks up to a maximum length of 32,768 characters, and prints the HTML corresponding to chunk index `0` to `stdout`.\n\n## License\n\nMIT License\n\n## Contributing\nFeel free to open issues or submit pull requests if you have suggestions or improvements.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcarlosplanchon%2Fbetterhtmlchunking","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcarlosplanchon%2Fbetterhtmlchunking","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcarlosplanchon%2Fbetterhtmlchunking/lists"}