Inscriptis HTML to Text Converter

repository·master·Indexed 43 days ago

https://github.com/weblyzard/inscriptis

A high-performance Python library, CLI, and Web service for converting HTML to layout-aware text. Designed for data science and NLP tasks, it preserves spatial structures like nested tables and lists by interpreting HTML semantics and a subset of CSS. Version 2.7.4 supports annotated text conversion to XML, JSONL, and annotated HTML, allowing users to map HTML tags to semantic labels for knowledge extraction.

Tokens
10.9K
Snippets
32
Records
42
Agent score
56%

What's inside Inscriptis

  1. What is inscriptis and when to use it

    master

    inscriptis is a Python-based HTML to text conversion library, command line client, and Web service.

    It is specifically designed for high-performance, layout-aware text extraction. Unlike simpler tools (like Beautiful Soup's get_text()), inscriptis preserves the spatial arrangement of text elements by interpreting HTML semantics and a subset of CSS. This makes it suitable for:

    • Knowledge extraction and data science tasks.
    • Computing word embeddings and language models.
    • Sentiment analysis.
    • Tasks requiring accurate representation of nested tables, itemizations, and enumerations.

    Additionally, it supports annotation rules, allowing users to map HTML structural/semantic information to the extracted text. It can export to multiple formats including XML, annotated HTML, and JSONL (compatible with doccano).

  2. What is Inscriptis and when should I use it?

    master

    Inscriptis is a Python-based library, command line client, and Web service designed for converting HTML to plain text. It is specifically optimized for knowledge extraction tasks where preserving the spatial arrangement and layout of text is critical.

    Use Inscriptis when:

    • You need layout-aware conversion that preserves the spatial alignment of text elements (e.g., correctly rendering nested tables or text alignment determined by CSS like display, white-space, margin-top, or vertical-align).
    • You want to avoid the artifacts (like concatenated words) often produced by scraping libraries like Beautiful Soup or lxml when encountering complex structures like lists and tables.
    • You need to preserve semantic information from the original HTML (such as headings, emphasized text, or table structures) by using annotation rules to map HTML tags/attributes to the extracted text.
    • You are preparing data for downstream NLP tasks like entity recognition, sentiment analysis, or text summarization that benefit from knowing the original document's structure.
  3. Understand inscriptis HTML rendering behavior

    master

    inscriptis is designed primarily for natural language processing (NLP) tasks. Consequently, its rendering engine follows a specific philosophy regarding whitespace and line breaks:

    • Minimal Line Breaks: Unlike web browsers (e.g., Firefox) or text-based browsers (e.g., Lynx), inscriptis does not insert arbitrary line breaks.
    • Explicit Breaks Only: Line breaks are only inserted when they are explicitly requested in the HTML source code using tags such as <p> or <br>.
    • NLP Optimization: This approach preserves the flow of text, making the output more suitable for downstream NLP pipelines compared to tools that wrap text aggressively.
  4. Annotated text conversion in Inscriptis

    master

    Beyond simple text extraction, Inscriptis supports annotated text conversion. This allows you to map structural and semantic information from HTML tags and attributes onto the resulting plain text.

    Key benefits of annotations:

    • Enhanced NLP: Provides downstream components (like summarizers or sentiment analyzers) with cues such as bold/italic text or heading levels.
    • Manual Annotation Support: Assists in creating gold standards for qualitative analysis by exporting to formats compatible with annotation tools.
    • Content Extraction: Enables tasks that rely on the document's structural hierarchy.

    Supported Export Formats:

    • XML
    • Annotated HTML (can be triggered via the --postprocessor html CLI option)
    • JSONL (compatible with the doccano annotation tool)

    Developers can extend these capabilities by implementing custom annotation post-processors.

  5. Understand the HTML to text test case format

    master

    Inscriptis uses a specific file structure for its HTML-to-text conversion test cases located in the tests/html directory. A complete test case consists of:

    1. test-name.html: The source HTML file.
    2. test-name.txt: The reference text output expected from the conversion.
    3. test-name.json (Optional, since v2.0): A JSON dictionary used for testing annotated text conversion. It contains:
      • annotation_rules: A dictionary defining the rules for extracting metadata (e.g., mapping HTML tags to semantic labels).
      • result: A list of extracted metadata surface forms.

    This structure allows for both standard text comparison and validation of metadata extraction accuracy.

    {
    	"annotation_rules": {
    	    "h1": ["heading"],
    	    "b": ["emphasis"]
    	 },
    	 "result": [
    		["heading", "The first"],
    		["heading", "The second"],
    		["heading", "Subheading"]
    	 ]
    }
  6. Run the HTML to text conversion benchmarking script

    master

    The project includes a benchmarking script to compare different HTML-to-text conversion algorithms (e.g., Lynx, Justext, HTML2Text, BeautifulSoup, and Inscriptis) against a list of URLs.

    Setup

    1. Prepare URLs: Create a file named url_list.txt in the benchmarking directory. Add the target URLs, one per line, ensuring they include the protocol (e.g., http:// or https://).
    2. Configure Algorithms: Open run_benchmarking.py and modify the pipeline() function to enable or disable specific algorithms by setting their boolean flags to True or False:
      • run_lynx
      • run_justext
      • run_html2text
      • run_beautifulsoup
      • run_inscriptis

    Execution

    Run the script from within the benchmarking folder:

    python run_benchmarking.py

    Results

    Results are saved in a timestamped folder within benchmarking/benchmarking_results:

    • Text Outputs: The converted text for manual comparison.
    • speed_comparisons.txt: A file containing the measured processing speed of every algorithm per URL.
    # Inside run_benchmarking.py
    def pipeline():
        run_lynx = True
        run_justext = True
        run_html2text = True
        run_beautifulsoup = True
        run_inscriptis = True
  7. Fine-tune HTML rendering with ParserConfig

    master

    Use the ParserConfig class to modify how HTML tags are interpreted and how elements like anchors, captions, and images are rendered.

    Use strict CSS profiles

    To achieve Firefox-like whitespace handling (where <div> and <span> do not automatically add extra whitespace), use the strict profile from inscriptis.css_profiles.CSS_PROFILES.

    You can enable the display of inline links and anchor URLs by setting display_links=True and display_anchors=True in ParserConfig.

    Hide elements (e.g., forms)

    You can prevent specific elements from appearing in the output by overriding the CSS profile and setting the element's display property to Display.none using inscriptis.html_properties.Display.

    from lxml.html import fromstring
    from inscriptis import Inscriptis
    from inscriptis.css_profiles import CSS_PROFILES
    from inscriptis.model.config import ParserConfig
    
    # Example: Using strict CSS and enabling link/anchor display
    css = CSS_PROFILES['strict']
    config = ParserConfig(css=css, display_links=True, display_anchors=True)
    
    html_tree = fromstring(html_content)
    parser = Inscriptis(html_tree, config)
    text = parser.get_text()
  8. Use the inscript CLI for HTML to text conversion

    master

    The inscript command line client converts HTML files or URLs into plain text. You can provide input via a file path, a URL, or stdin.

    # Convert a URL and output to screen
    inscript https://www.fhgr.ch
    
    # Convert a file and save to a specific output file
    inscript fhgr.html -o fhgr.txt
    
    # Use strict indentation (minimizes extra spaces) and save output
    inscript --indentation strict fhgr.html -o fhgr-layout-optimized.txt
    
    # Convert HTML provided via stdin
    echo "<body><p>Make it so!</p></body>" | inscript -o output.txt
  9. Compare inscriptis rendering with Firefox and Lynx

    master

    When evaluating the output of inscriptis, it is helpful to compare it against standard rendering engines to understand its specific characteristics:

    1. Firefox (Browser): Provides a visual, graphical representation. inscriptis aims to capture the semantic structure (like tables) without the visual styling.
    2. Lynx (Text Browser): Often uses aggressive line wrapping and may include link annotations (e.g., [166]). inscriptis tends to produce cleaner text for NLP by avoiding the heavy wrapping seen in Lynx.
    3. inscriptis: Focuses on structural fidelity (tables, nested tables) and explicit line breaks, producing a format optimized for machine reading.
  10. How TableCell works and its lifecycle

    master

    A TableCell represents a single cell in a table and manages its own content, dimensions, and alignment. It operates in two distinct phases:

    1. Construction Phase: The cell's content blocks are mutable. You can set the content using the blocks property (a list of strings).
    2. Normalization Phase: Calling normalize_blocks() converts multi-line blocks into individual lines and freezes the content. Once normalized, the _content_blocks become an immutable tuple, and attempting to modify blocks will raise a FrozenError.

    Dimensions vs. Content:

    • Content Dimensions: The actual width (longest line) and height (number of lines) of the text inside.
    • Requested Dimensions: You can set a minimum width and height. The cell's actual dimensions will be the maximum of its content dimensions and its requested dimensions. This allows for padding and alignment (horizontal and vertical) within the cell.
    from inscriptis.model.table import TableCell
    from inscriptis.html_properties import HorizontalAlignment, VerticalAlignment
    
    # 1. Initialize with alignment
    cell = TableCell(align=HorizontalAlignment.CENTER, valign=VerticalAlignment.MIDDLE)
    
    # 2. Set content (mutable phase)
    cell.blocks = ["Line 1", "Line 2\nLine 3"]
    
    # 3. Normalize (freezes content)
    cell.normalize_blocks()
    
    # 4. Set requested dimensions (padding/alignment will apply)
    cell.width = 20
    cell.height = 5
  11. Use postprocessors with the inscript CLI

    master

    The --postprocessor flag allows you to specify a component to process the annotated text. The CLI looks for a class named <Name>Extractor within the inscriptis.annotation.output.<name> module.

    Commonly used postprocessor names include:

    • html
    • surface
    • xml

    If the selected postprocessor has a verbatim attribute set to False, the output will be serialized as a JSON string.

    # Example of using an XML postprocessor
    inscript https://example.com -p xml