jiwer

repository·master·Indexed 19 days ago

https://github.com/jitsi/jiwer

A Python tool for evaluating speech-to-text (ASR) systems using similarity measures such as Word Error Rate (WER) and Character Error Rate (CER). It provides a CLI for computing error rates from text files and a Python API featuring functions like process_words, process_characters, and visualization tools for alignment and error frequencies.

Tokens
7.5K
Snippets
24
Records
31
Agent score
74%

What's inside jiwer

  1. Use global alignment with the JiWER CLI

    master

    By default, JiWER expects the reference and hypothesis files to have an equal number of lines. If your files have a different number of lines, use the -g or --global flag. This flag applies a global minimal alignment between the reference and hypothesis sentences before computing the WER.

    # Use global alignment for files with unequal line counts
    jiwer -r references.txt -h hypotheses.txt --global
  2. Use the JiWER CLI to compute WER and CER

    master

    The JiWER CLI is a Python tool used to compute the Word Error Rate (WER) or Character Error Rate (CER) of Automatic Speech Recognition (ASR) systems.

    Input Format Requirements:

    • Reference and hypothesis sentences must be stored in text files where each sentence is delimited by a new-line character.
    • The reference and hypothesis files must contain an equal number of lines.
    • Note: The CLI does not support custom pre-processing. You must manually pre-process your text files before running the command.

    Basic Usage: To compute WER, provide paths to your reference and hypothesis files using the -r and -h flags.

    To compute CER instead of WER, add the -c or --cer flag.

    # Compute Word Error Rate (WER)
    jiwer -r references.txt -h hypotheses.txt
    
    # Compute Character Error Rate (CER)
    jiwer -r references.txt -h hypotheses.txt --cer
  3. How text transformation pipelines work in JiWER

    master

    JiWER uses a pipeline pattern to transform input strings (sentences) into a specific format required for calculating Word Error Rate (WER) or Character Error Rate (CER).

    To use transformations, you chain them using Compose.

    Crucial Requirement: Every pipeline must end with a specific 'reduction' transform depending on your goal:

    1. For WER: The pipeline must end with ReduceToListOfListOfWords. This converts sentences into a list of lists, where each inner list contains individual words.
    2. For CER: The pipeline must end with ReduceToListOfListOfChars. This converts sentences into a list of lists, where each inner list contains individual characters.

    If you do not end with one of these, the output will not be in the format expected by the error rate calculation functions.

    import jiwer
    
    # Example pipeline for WER
    pipeline = jiwer.Compose([
        jiwer.ToLowerCase(),
        jiwer.RemovePunctuation(),
        jiwer.RemoveMultipleSpaces(),
        jiwer.ReduceToListOfListOfWords()
    ])
    
    result = pipeline(["Hello, World!"])
    # Result: [['hello', 'world']]
  4. Select the appropriate CER transformation for sentence mismatches

    master

    When calculating Character Error Rate (CER), if your reference and hypothesis inputs contain a different number of sentences, use the contiguous variant to ensure the text is treated as a single unit.

    • Use cer_default for standard character-level processing.
    • Use cer_contiguous when the number of reference and hypothesis sentences differ.
  5. Select the appropriate WER transformation for sentence mismatches

    master

    When calculating Word Error Rate (WER), if your reference and hypothesis inputs contain a different number of sentences, the default transformations may fail or produce incorrect results. In these cases, you should use the contiguous variants of the transformations, which include a ReduceToSingleSentence step to flatten the input.

    • Use wer_contiguous for standard word-level processing with mismatched sentence counts.
    • Use wer_standardize_contiguous if you require text standardization (lowercase, contraction expansion, etc.) alongside sentence flattening.
  6. JiWER CLI command options reference

    master

    The following options are available for the jiwer command line interface:

    OptionLong FlagDescription
    -r, --reference PATH--reference PATH[Required] Path to new-line delimited text file of reference sentences.
    -h, --hypothesis PATH--hypothesis PATH[Required] Path to new-line delimited text file of hypothesis sentences.
    -c, --cer--cerCompute CER instead of WER.
    -a, --align--alignPrint alignment of each sentence.
    -g, --global--globalApply a global minimal alignment between reference and hypothesis sentences before computing the WER. This allows files with unequal line counts.
    --help--helpShow this message and exit.
    Usage: jiwer [OPTIONS]
    
      JiWER is a python tool for computing the word-error-rate of ASR systems. To
      use this CLI, store the reference and hypothesis sentences in a text file,
      where each sentence is delimited by a new-line character. The text files are
      expected to have an equal number of lines, unless the `-g` flag is used. The
      `-g` flag joins computation of the WER by doing a global minimal alignment.
    
    Options:
      -r, --reference PATH   Path to new-line delimited text file of reference
                             sentences.  [required]
      -h, --hypothesis PATH  Path to new-line delimited text file of hypothesis
                             sentences.  [required]
      -c, --cer              Compute CER instead of WER.
      -a, --align            Print alignment of each sentence.
      -g, --global           Apply a global minimal alignment between reference
                             and hypothesis sentences before computing the WER.
      --help                 Show this message and exit.
  7. Visualize alignment and errors with `visualize_alignment`

    master

    Use visualize_alignment to create a human-readable string showing the alignment between reference and hypothesis pairs. It highlights substitutions (S), deletions (D), and insertions (I).

    Arguments:

    • output: The processed output from jiwer.process_words or jiwer.process_characters.
    • show_measures (bool, default True): If True, includes summary statistics like WER, MER, WIL, and WIP in the output.
    • skip_correct (bool, default True): If True, excludes sentences where the reference and hypothesis match perfectly.
    • line_width (int, optional): If set, attempts to wrap long sentences into multiple lines to prevent horizontal scrolling.
    import jiwer
    
    out = jiwer.process_words(
        ["short one here", "quite a bit of longer sentence"],
        ["shoe order one", "quite bit of an even longest sentence here"],
    )
    
    print(jiwer.visualize_alignment(out))
  8. Visualize error frequencies with `visualize_error_counts`

    master

    Use visualize_error_counts to generate a summary report of the most frequent errors in your dataset. This is useful for identifying systematic errors in a speech-to-text model.

    Arguments:

    • output: The processed output from jiwer.process_words or jiwer.process_characters.
    • show_substitutions (bool, default True): Whether to include the substitution report.
    • show_insertions (bool, default True): Whether to include the insertion report.
    • show_deletions (bool, default True): Whether to include the deletion report.
    • top_k (int, optional): If provided, only shows the k most frequent errors for each category.
    import jiwer
    
    out = jiwer.process_words(
        ["short one here", "quite a bit of longer sentence"],
        ["shoe order one", "quite bit of an even longest sentence here"],
    )
    print(jiwer.visualize_error_counts(out))
  9. Use default transformations for WER and CER

    master

    JiWER provides pre-composed transformation pipelines via jiwer.transformations to prepare input text for Word Error Rate (WER) or Character Error Rate (CER) calculations. These pipelines handle whitespace removal, normalization, and data structure conversion (e.g., converting strings to lists of words or characters).

    Word Error Rate (WER) Transformations

    • wer_default: The standard pipeline for process_words. It removes leading/trailing whitespace, removes multiple spaces between words, and converts strings into a list of lists of words.
    • wer_contiguous: Use this instead of wer_default if the number of reference and hypothesis sentences differ. It adds a ReduceToSingleSentence step.
    • wer_standardize: A heavy normalization pipeline. It converts text to lowercase, expands common English contractions, removes Kaldi non-words, and cleans whitespace before applying the default WER steps.
    • wer_standardize_contiguous: The standardized pipeline that also includes ReduceToSingleSentence for cases where sentence counts differ.

    Character Error Rate (CER) Transformations

    • cer_default: The standard pipeline for process_characters. It strips whitespace and converts strings into a list of lists of characters.
    • cer_contiguous: Use this instead of cer_default if the number of reference and hypothesis sentences differ. It adds a ReduceToSingleSentence step.
    from jiwer.transformations import wer_default, cer_default
    
    # Example usage with JiWER processing functions
    # (Assuming process_words and process_characters are available in the API)
    result = process_words(reference, hypothesis, transform=wer_default)
    cer_result = process_characters(reference, hypothesis, transform=cer_default)
  10. Compute character-level error metrics with `process_characters`

    master

    Use process_characters to calculate character-level Levenshtein distance and alignment. This is useful for measuring Character Error Rate (CER).

    Note: By default, this method includes spaces ( ) as characters in the computation. To exclude spaces, you must provide custom reference_transform and hypothesis_transform functions.

    Arguments:

    • reference: A single string or a list of strings.
    • hypothesis: A single string or a list of strings.
    • reference_transform: (Optional) Defaults to cer_default.
    • hypothesis_transform: (Optional) Defaults to cer_default.

    Returns: A CharacterOutput object containing:

    • cer: Character Error Rate
    • hits, substitutions, insertions, deletions: Counts of correct characters and error types
    • alignments: A list of AlignmentChunk objects.
    from jiwer import process_characters
    
    reference = "hello"
    hypothesis = "hallo"
    
    output = process_characters(reference, hypothesis)
    print(f"CER: {output.cer}")
  11. Collect error counts with `collect_error_counts`

    master

    Use collect_error_counts to extract raw frequency data of errors from a processed output object. It returns a three-tuple of dictionaries representing the counts for each error type.

    Returns:

    • substitutions: A dictionary where keys are (from_token, to_token) tuples and values are the frequency of that specific substitution.
    • insertions: A dictionary where keys are the inserted tokens and values are their frequencies.
    • deletions: A dictionary where keys are the deleted tokens and values are their frequencies.

    Note: For WordOutput, tokens are joined by spaces; for CharacterOutput, they are joined by empty strings.

    from jiwer import process_words, collect_error_counts
    
    out = process_words(["hello world"], ["hello there world"])
    substitutions, insertions, deletions = collect_error_counts(out)
  12. Use `mer`, `wip`, or `wil` for word-level metrics

    master

    JiWER provides convenience functions for Match Error Rate (mer), Word Information Preserved (wip), and Word Information Lost (wil). These all operate on a word-level basis using process_words internally.

    Signatures:

    • mer(reference, hypothesis, reference_transform=wer_default, hypothesis_transform=wer_default) -> float
    • wip(reference, hypothesis, reference_transform=wer_default, hypothesis_transform=wer_default) -> float
    • wil(reference, hypothesis, reference_transform=wer_default, hypothesis_transform=wer_default) -> float

    Arguments:

    • reference: The reference sentence(s) (str or List[str]).
    • hypothesis: The hypothesis sentence(s) (str or List[str]).
    • reference_transform: Transformation applied to reference. Defaults to wer_default.
    • hypothesis_transform: Transformation applied to hypothesis. Defaults to wer_default.