praatio 6.2.2

repository·main·Indexed 43 days ago

https://github.com/timmahrt/praatio

A Python library for working with Praat TextGrids, KlattGrids, time-aligned audio transcripts, and audio files. It provides utilities for manipulating speech transcripts, shifting timestamps, querying intervals, and splitting audio. The library includes modules for audio manipulation (Wav, QueryWav), pitch and intensity extraction, and the ability to run Praat scripts directly from Python.

Tokens
12.8K
Snippets
47
Records
59
Agent score
56%

What's inside praatio

  1. TextGrid output formats and schemas

    main

    PraatIO supports four output types:

    1. Short TextGrid: Concise format, natively supported by Praat.
    2. Long TextGrid: Human-readable format, natively supported by Praat.
    3. JSON: A minimal, developer-friendly format. Note: This format does not support different min/max timestamps for the TextGrid vs its tiers.
    4. Textgrid-like JSON: A developer-friendly format that includes xmin, xmax, and tier-specific xmin/xmax. Use this if your TextGrid has specific timestamp bounds that differ from the global bounds.
    // Schema for Textgrid-like JSON (supports specific min/max per tier)
    {
        "xmin": 0.0,
        "xmax": 1.8,
        "tiers": [
            {
                "class": "IntervalTier",
                "name": "phone",
                "xmin": 0.0,
                "xmax": 1.8,
                "entries": [[0.0, 0.3, ""], [0.3, 0.38, "m"]]
            }
        ]
    }
  2. Migrate from Praatio 4 to 5: Installation and Dependency Management

    main

    Version 5 introduced breaking changes, including the renaming of the tgio module to textgrid. If you encounter errors regarding tgio imports, you are likely running version 5 code on a version 4 installation or vice versa.

    To downgrade to version 4:

    pip uninstall praatio
    pip install "praatio<5"

    To specify version constraints in dependency files:

    In setup.py:

    install_requires=["praatio ~= 4.1"]

    In pyproject.toml (for version 6+):

    dependencies = [
        "praatio ~= 6.2",
    ]
  3. Migrate from Praatio 5 to 6: JSON output formats

    main

    In version 6, Praatio introduced two distinct JSON output schemas: 'JSON' and 'Textgrid JSON'.

    • Reading: textgrid.openTextgrid() is updated to automatically handle either JSON variant.
    • Writing: To maintain the legacy behavior from version 5.0, you must explicitly specify the format when saving. Use format=textgrid_json in the textgrid.Textgrid.save() method.
    # To maintain version 5.0 behavior in version 6
    textgrid.Textgrid.save(fn='output.json', format='textgrid_json')
  4. Overview of praatio modules

    main

    praatio is a Python library designed for working with Praat files (like .TextGrid) and audio data. It provides high-level abstractions for speech transcription data and utilities for audio manipulation and Praat script execution.

    Key modules include:

    • textgrid: Contains Textgrid, IntervalTier, and PointTier classes for representing and reading/writing .TextGrid files.
    • audio: Used for reading, writing, and performing simple manipulations on .wav files.
    • pitch_and_intensity: Uses Praat to extract pitch and intensity values from audio files.
    • praat_scripts: Enables running various Praat scripts directly from within Python.
    • praatio_scripts: High-level functions that combine various parts of the library, often working with both TextGrids and audio files.
    • data_points and klattgrid: Handle other specific Praat data file formats.
    • data_classes and utilities: Provide supporting data structures and helper functions.
  5. Understand Klattgrid data structures

    main

    Klattgrid files contain three types of data tiers, which are represented by different classes in praatio:

    1. Null Tiers: Contain no data points; they act as headers for sets of regular tiers. Represented by KlattPointTier.
    2. Regular Tiers: Standard tiers containing data points. Represented by KlattPointTier.
    3. Embedded Tiers: Complex tiers containing tiers of tiers (up to 3 layers). These are structured as:
      • KlattContainerTier: The top-level container.
      • KlattIntermediateTier: A middle layer.
      • KlattSubPointTier: The bottom layer that actually contains the data points.

    Common container tier names include oral_formants, nasal_formants, nasal_antiformants, tracheal_formants, tracheal_antiformants, delta_formants, and frication_formants.

  6. Represent Textgrid data using Textgrid, IntervalTier, and PointTier

    main

    The praatio.textgrid module provides the core data structures for representing Praat annotation data:

    • Textgrid: A container for multiple annotation tiers. It manages the overall time range (minTimestamp and maxTimestamp) and holds an ordered collection of tiers.
    • IntervalTier: A tier containing interval-based data (segments with start/end times and labels).
    • PointTier: A tier containing point-based data (single timestamps with labels).

    All tiers within a Textgrid must have unique names. You can save a Textgrid object to a file using the Textgrid.save() method.

  7. Create bare TextGrid files

    main

    You can programmatically create new, empty TextGrid files using the textgrid.Textgrid class. A TextGrid is a container for tiers. You can then add IntervalTier (for durations like words) or PointTier (for instantaneous events like pitch peaks) to it.

    Note: Textgrid objects do not take arguments in their constructor; they derive attributes from the tiers they contain. IntervalTier and PointTier take the following arguments:

    • name: The tier name.
    • entries: A list of intervals or points.
    • minT: Starting time.
    • maxT: Ending time.

    To ensure the TextGrid matches the length of an audio file, you can use praatio.audio.getDuration() to find the duration and use it as the maxT for your tiers.

    from praatio import textgrid
    from praatio import audio
    
    # Create an empty TextGrid
    tg = textgrid.Textgrid()
    
    # Create tiers with specific durations
    # Using 0 to 1.0 as an example
    wordTier = textgrid.IntervalTier('words', [], 0, 1.0)
    maxF0Tier = textgrid.PointTier('maxF0', [], 0, 1.0)
    
    tg.addTier(wordTier)
    tg.addTier(maxF0Tier)
    
    # Save the TextGrid
    tg.save("empty_textgrid.TextGrid", format="short_textgrid", includeBlankSpaces=True)
  8. Query TextGrid tiers and intervals

    main

    You can access tiers via tg.tierDict and perform queries on their entries. Use .entries to get all intervals or .find(label) to find the indices of all occurrences of a specific label.

    tg = textgrid.openTextgrid("path_to_textgrid", False)
    # Get all intervals in a specific tier
    entries = tg.tierDict["speaker_1_tier"].entries 
    # Get the indices of all occurrences of 'a' in a tier
    entries = tg.tierDict["phone_tier"].find("a")
  9. Adjust TextGrid timestamps

    main

    If your audio file has been modified (e.g., audio was added to the beginning), you can shift all intervals in a TextGrid by a specific offset using editTimestamps(offset).

    tg = textgrid.openTextgrid("path_to_textgrid", False)
    # Add five seconds to every interval
    moddedTG = tg.editTimestamps(5)
    # Save the modified TextGrid
    moddedTG.save('output_path_to_textgrid', 'long_textgrid', True)
  10. Modify KlattGrid subtiers

    main

    You can use the modifySubtiers method on a KlattGrid tier to apply a function to all values within a subtier (e.g., scaling formants).

    import klattgrid
    kg = klattgrid.openKlattGrid("path_to_klattgrid")
    # Define a scaling function
    incrTwenty = lambda x: x * 1.2
    # Apply to the 'formants' subtier of 'oral_formants'
    kg.tierDict["oral_formants"].modifySubtiers("formants", incrTwenty)
    kg.save("output_path.KlattGrid")