TextDescriptives

repository·main·Indexed 18 days ago

https://github.com/hlasse/textdescriptives

A Python library for calculating linguistic and text quality metrics using spaCy v3 pipeline components and extensions. It provides tools for descriptive statistics, readability, dependency distance, POS proportions, information theory (entropy and perplexity), and document coherence. Metrics can be accessed via spaCy Doc, Span, and Token attributes or extracted into pandas DataFrames using extract_df.

Tokens
19.8K
Snippets
62
Records
77
Agent score
62%

What's inside textdescriptives

  1. Overview of TextDescriptives features and functionality

    main

    TextDescriptives is a Python package built on top of spaCy designed to extract a wide variety of document-level linguistic metrics. It provides modular spaCy pipeline components that can be added to existing workflows to calculate:

    • Descriptive Statistics: Token counts (total, unique), character counts, and statistical measures (mean, median, std dev) for token length, sentence length, and syllables per token.
    • Readability: Standard indices including Gunning-Fog, SMOG, Flesch reading ease, Flesch-Kincaid grade, Automated Readability Index, Coleman-Liau, Lix, and Rix.
    • Dependency Distance: Mean and standard deviation of the distance between a word and its head, and proportions of adjacent dependency relations.
    • POS Proportions: Proportions of all part-of-speech tags in the document.
    • Coherence: First- and second-order coherence based on word embedding similarity between sentences.
    • Information Theory: Shannon entropy and perplexity.
    • Quality: Metrics for filtering low-quality text, including stop word counts, symbol-to-word ratios, ellipsis/bullet point proportions, and repetitious text detection (duplicate lines, paragraphs, or n-grams).
  2. Overview of TextDescriptives

    main

    TextDescriptives is a Python library designed to calculate a wide variety of statistics from text using spaCy v3 pipeline components and extensions. It supports several categories of metrics, including:

    • Descriptive statistics
    • Readability metrics
    • Dependency distance metrics
    • POS (Part-of-Speech) proportions
    • Information theory metrics
    • Coherence metrics
    • Quality metrics

    The library integrates directly with spaCy, allowing users to leverage spaCy's NLP pipeline to extract these features.

  3. How to extract metrics using TextDescriptives

    main

    TextDescriptives integrates with spaCy by providing pipeline components. Once the desired components are added to your spaCy pipeline, you can extract all metrics into a single data structure using either a DataFrame or a dictionary.

    To use the package, you typically:

    1. Load a spaCy model.
    2. Add the textdescriptives components to the pipeline.
    3. Process text with the model.
    4. Call textdescriptives.extract_df(doc) for a pandas DataFrame or textdescriptives.extract_dict(doc) for a dictionary.
  4. Install TextDescriptives

    main

    To install the package along with its tutorial dependencies, use pip with the [tutorials] extra. For standard usage, a simple pip install textdescriptives is sufficient.

    !pip install "textdescriptives[tutorials]"
  5. Quick Start with extract_metrics()

    main

    Use td.extract_metrics() to quickly extract text metrics into a Pandas DataFrame.

    • If lang is provided, TextDescriptives will automatically download the appropriate spaCy model.
    • If spacy_model is provided, it will use that specific model.
    • If metrics is set to None, all available metrics will be extracted.
    • To see a list of valid metric names, use td.get_valid_metrics().
    import textdescriptives as td
    
    text = "The world is changed. I feel it in the water. I feel it in the earth. I smell it in the air. Much that once was is lost, for none now live who remember it."
    
    # Option 1: Auto-download model and extract all metrics
    df = td.extract_metrics(text=text, lang="en", metrics=None)
    
    # Option 2: Specify a specific spaCy model and subset of metrics
    df = td.extract_metrics(text=text, spacy_model="en_core_web_lg", metrics=["readability", "coherence"])
  6. Use the Information Theory component to calculate text complexity

    main

    The information_theory component calculates Shannon entropy, perplexity, and length-normalized perplexity. These metrics are used to describe text complexity: higher entropy indicates more complex text, while perplexity measures how well a model predicts the sample.

    Metrics available via spaCy extensions:

    • {doc/span}._.entropy: Shannon entropy using token.prob as the probability of each token.
    • {doc/span}._.perplexity: Perplexity defined as $e^{-H(X)}$.
    • {doc/span}._.per_word_perplexity: Perplexity divided by the number of words (length-normalized).

    Important Requirement: This component requires a lexeme prop table from spaCy. If the table is not available for your chosen language, a warning will be raised and values will be set to np.nan.

    import spacy
    from textdescriptives as td
    
    # Load a spaCy model and add the information_theory pipe
    nlp = spacy.load("en_core_web_lg")
    nlp.add_pipe("textdescriptives/information_theory")
    
    doc = nlp("This is a simple text")
    
    # Access individual metrics
    perplexity = doc._.perplexity
    entropy = doc._.entropy
    
    # Extract all information theory metrics into a pandas DataFrame
    df = td.extract_df(doc)
  7. Explore TextDescriptives tutorials

    main

    The package provides several Jupyter notebooks that serve as tutorials for different use cases. You can download and run these locally to learn the library's capabilities. The recommended learning path is:

    1. Introductory Tutorial: A baseline guide to getting started with the library.
    2. Filter Corpus Using Quality: Demonstrates how to use extracted text metrics to filter a collection of documents based on quality scores.
    3. Scikit-learn Integration: Shows how to integrate TextDescriptives metrics into machine learning workflows using sklearn.
    tutorials/introductory_tutorial.ipynb
    tutorials/filter_corpus_using_quality.ipynb
    tutorials/sklearn_integration.ipynb
  8. Render the TextDescriptives paper to an arXiv-style PDF

    main

    The project includes a Quarto file (paper_quarto.qmd) designed to be rendered into an arXiv-style preprint PDF. To do this, you must first install the quarto-arxiv extension and then run the Quarto render command.

    # install the quarto-arxiv template (https://github.com/mikemahoney218/quarto-arxiv)
    quarto install extension mikemahoney218/quarto-arxiv
    
    # render to pdf
    quarto render paper_quarto.qmd
  9. Configure quality metric thresholds

    main

    You can customize the quality requirements by passing a QualityThresholds object to the component. Thresholds are typically defined as tuples representing a range (min, max). Use None for no bound.

    Common threshold configuration keys include:

    • n_stop_words: (min, max)
    • alpha_ratio: (min, max)
    • mean_word_length: (min, max)
    • doc_length: (min, max)
    • symbol_to_word_ratio: A dictionary mapping symbols to ranges, e.g., {"#": (None, 0.1)}
    • proportion_ellipsis: (min, max)
    • proportion_bullet_points: (min, max)
    • contains: A dictionary mapping strings to a boolean (e.g., {"lorem ipsum": False} to fail if present)
    • duplicate_line_chr_fraction: (min, max)
    • duplicate_paragraph_chr_fraction: (min, max)
    • duplicate_ngram_chr_fraction: A dictionary mapping n-gram sizes (as strings) to ranges, e.g., {"5": (None, 0.15)}
    • top_ngram_chr_fraction: A dictionary mapping n-gram sizes to ranges
    • oov_ratio: (min, max)
    import spacy
    import textdescriptives as td
    from textdescriptives.components.quality import QualityThresholds
    
    nlp = spacy.load("en_core_web_sm")
    
    # Define custom thresholds
    thresholds = QualityThresholds(
        n_stop_words=(2, None),
        alpha_ratio=(0.7, None),
        mean_word_length=(3, 10),
        doc_length=(10, 100000),
        symbol_to_word_ratio={"#": (None, 0.1)},
        proportion_ellipsis=(None, 0.3),
        proportion_bullet_points=(None, 0.8),
        contains={"lorem ipsum": False},
        duplicate_line_chr_fraction=(None, 0.2),
        duplicate_paragraph_chr_fraction=(None, 0.2),
        duplicate_ngram_chr_fraction={
            "5": (None, 0.15),
            "6": (None, 0.14),
            "7": (None, 0.13),
            "8": (None, 0.12),
            "9": (None, 0.11),
            "10": (None, 0.1),
        },
        top_ngram_chr_fraction={"2": (None, 0.2), "3": (None, 0.18), "4": (None, 0.16)},
        oov_ratio=(None, 0.2)
    )
    
    # Add pipe and apply thresholds
    quality_pipe = nlp.add_pipe("textdescriptives.quality")
    quality_pipe.set_quality_thresholds(thresholds)
    
    doc = nlp("The world is changed. I feel it in the water.")
    print(doc._.passed_quality_check)
  10. Add the descriptive_stats component to a spaCy pipeline

    main

    To extract descriptive statistics from text using spaCy, add the textdescriptives/descriptive_stats component to your nlp pipeline. This component calculates various metrics such as token counts, sentence length, syllable counts, and token length. Ensure you have a spaCy model loaded (e.g., en_core_web_sm) before adding the pipe.

    import spacy
    import textdescriptives as td
    
    nlp = spacy.load("en_core_web_sm")
    nlp.add_pipe("textdescriptives/descriptive_stats")
    doc = nlp("Your text here.")
  11. Install the scikit-learn integration

    main

    To use the TextDescriptivesFeaturizer within a scikit-learn pipeline, you must have scikit-learn installed. You can install it directly or use the textdescriptives extra:

    pip install textdescriptives[sklearn]
    pip install textdescriptives[sklearn]
  12. Use the readability component with spaCy

    main

    To calculate readability metrics, add the textdescriptives/readability pipe to your spaCy pipeline. Once processed, the metrics are available via the ._.readability attribute on the Doc object. You can also use td.extract_df(doc) to convert the results into a pandas DataFrame.

    Note on Language Support: The readability component uses the Pyphen hyphenation module. If the language of your text is not supported by Pyphen, a warning will be raised and metrics requiring hyphenation (like Gunning-Fog, SMOG, Flesch, and Flesch-Kincaid) will be set to np.nan.

    import spacy
    import textdescriptives as td
    
    nlp = spacy.load("en_core_web_sm")
    nlp.add_pipe("textdescriptives/readability") 
    doc = nlp("The world is changed. I feel it in the water. I feel it in the earth. I smell it in the air. Much that once was is lost, for none now live who remember it.")
    
    # Access metrics as a dictionary
    print(doc._.readability)
    
    # Extract metrics to a pandas DataFrame
    df = td.extract_df(doc)
    print(df)