dom-to-semantic-markdown
repository·main·Indexed 21 days ago
https://github.com/romansky/dom-to-semantic-markdownA library and CLI tool (d2m) that converts HTML DOM into semantic Markdown optimized for LLM processing. It focuses on structure preservation, token efficiency, and metadata extraction. Key features include main content detection, table column tracking, and support for dynamic content via Playwright. Version 1.5.0.
What's inside dom-to-semantic-markdown
- DOM to Semantic Markdown is a library designed to convert HTML DOM into a semantic Markdown format specifically optimized for Large Language Models (LLMs). It focuses on preserving the semantic meaning of web content while reducing token consumption, making it more efficient for LLMs to process information compared to raw HTML.
Key Features of DOM to Semantic Markdown
mainThe library provides several features to improve the quality of Markdown generated from HTML for LLM consumption:
- Semantic Structure Preservation: Maintains the meaning of structural elements like
<header>,<footer>,<nav>, etc. - Metadata Extraction: Automatically captures
title,description,keywords, Open Graph tags, Twitter Card tags, and JSON-LD data. - Token Efficiency: Reduces token usage via URL refication and concise content representation.
- Main Content Detection: Automatically identifies and extracts the primary content area of a webpage.
- Table Column Tracking: Injects unique identifiers into table columns to help LLMs correctly correlate data across rows.
- Semantic Structure Preservation: Maintains the meaning of structural elements like
Install dom-to-semantic-markdown
mainYou can install the library via npm to use it in your projects.
npm install dom-to-semantic-markdownHow to use semantic Markdown with LLMs
mainThe output is optimized for Large Language Models (LLMs). For best results:
- Extract the Markdown content using the library.
- Provide a brief instruction or context.
- Wrap the extracted Markdown in triple backticks (```).
- Follow the Markdown with your question or prompt.
Example Prompt Structure:
The following is a semantic Markdown representation of a webpage. Please analyze its content: ```markdown {paste your extracted markdown here} ``` {your question, e.g., "What are the main points discussed in this article?"}Install the DOM to Markdown CLI
mainYou can use the
d2mCLI tool either without a permanent installation usingnpx, or by installing it globally on your system.Using
npx(No installation required)Run the tool directly using the latest version:
npx d2m@latest -i <input_file> -o <output_file>Global Installation
To install the tool globally so you can use the
d2mcommand anywhere, follow these steps:- Clone the repository and navigate to the CLI example directory:
git clone https://github.com/romansky/dom-to-semantic-markdown.git cd examples/cli - Install dependencies:
npm install - Build the project:
npm run build - Link the package globally:
npm link
npx d2m@latest -i tryme.html -o output.md- Clone the repository and navigate to the CLI example directory:
Configure ConversionOptions
mainThe
ConversionOptionsobject allows you to customize the conversion process:Key Type Description websiteDomainstringThe domain of the website being converted. extractMainContentbooleanWhether to extract only the main content of the page. refifyUrlsbooleanWhether to convert URLs to reference-style links. debugbooleanEnable debug logging. overrideDOMParserDOMParserCustom DOMParser for Node.js environments. enableTableColumnTrackingbooleanAdds unique identifiers to table columns. overrideElementProcessing(element: Element, options: ConversionOptions, indentLevel: number) => SemanticMarkdownAST[] | undefinedCustom processing for HTML elements. processUnhandledElement(element: Element, options: ConversionOptions, indentLevel: number) => SemanticMarkdownAST[] | undefinedHandler for unknown HTML elements. overrideNodeRenderer(node: SemanticMarkdownAST, options: ConversionOptions, indentLevel: number) => string | undefinedCustom renderer for AST nodes. renderCustomNode(node: CustomNode, options: ConversionOptions, indentLevel: number) => string | undefinedRenderer for custom AST nodes. includeMetaData'basic' | 'extended'Controls whether to include metadata extracted from the HTML head. 'basic'includes title, description, and keywords.'extended'includes basic tags plus Open Graph, Twitter Card, and JSON-LD.Understand the SemanticMarkdownAST structure
mainThe output of the conversion is a
SemanticMarkdownAST, which is a union type of various node objects. Each node represents a semantic part of the document. Common nodes include:TextNode: Plain text (type: 'text').HeadingNode: Headings with levels 1-6 (type: 'heading').LinkNode: Hyperlinks (type: 'link') containinghrefandcontent.ImageNode: Images (type: 'image') withsrcand optionalalttext.ListNode&ListItemNode: Ordered or unordered lists.TableNode,TableRowNode, &TableCellNode: Structured table data.CodeNode: Code blocks or inline code (type: 'code') with an optionallanguage.SemanticHtmlNode: Semantic HTML wrappers likearticle,section,nav,header,footer, etc.MetaDataNode: Extracted metadata (type: 'meta') containingstandard,openGraph,twitter, orjsonLddata.
Extend conversion logic with `overrideElementProcessing`
mainYou can intercept the conversion of specific elements by providing an
overrideElementProcessingfunction in theConversionOptions. This is useful for handling custom web components or specific HTML tags that require unique Markdown representations.If the callback returns an array of
SemanticMarkdownASTnodes, those nodes are inserted into the result instead of the default conversion.const options = { overrideElementProcessing: (element, options, indentLevel) => { if (element.tagName.toLowerCase() === 'custom-widget') { return [{ type: 'text', content: 'Custom Widget Content' }]; } return undefined; // Fallback to default processing } }; const ast = htmlToMarkdownAST(element, options);Track table columns in Markdown output
mainWhen converting a webpage that contains tables, you can use the
-tand-eflags to add unique identifiers to table columns (e.g.,<!-- col-0 -->). This helps Large Language Models (LLMs) better understand and parse the table structure.npx d2m@latest -u https://softwareyoga.com/latency-numbers-everyone-should-know/ -t -eConvert HTML to Markdown in the Browser
mainIn a browser environment, you can pass a DOM node (like
document.body) directly toconvertHtmlToMarkdown.import {convertHtmlToMarkdown} from 'dom-to-semantic-markdown'; const markdown = convertHtmlToMarkdown(document.body); console.log(markdown);Extract basic metadata to Markdown frontmatter
mainUse the
-m basicflag to extract basic metadata such astitle,description, andkeywordsfrom the source URL and include them in the Markdown output's YAML frontmatter.npx d2m@latest -u https://xkcd.com -m basicConvert HTML to Markdown via CLI examples
mainCommon CLI usage patterns:
# Convert input.html to output.md d2m -i input.html -o output.md # Fetch and convert a webpage to Markdown d2m -u https://example.com -o output.md # Extract main content from input.html d2m -i input.html -e # Enable table column tracking d2m -i input.html -t # Include basic metadata d2m -i input.html -m basic # Include extended metadata d2m -i input.html -m extendedd2m -i input.html -o output.md d2m -u https://example.com -o output.md d2m -i input.html -e d2m -i input.html -t d2m -i input.html -m basic d2m -i input.html -m extended