Package: praat-textgrids
praat-textgrids -- Praat TextGrid manipulation in PythonDescriptiontextgridsis a module for handling Praat TextGrid files in any format (short text, long text, or binary). The module implements five classes, from largest to smallest:TextGrid-- adictwith tier names as keys andTiers as valuesTier-- alistof eitherIntervalorPointobjectsInterval-- anobjectrepresenting Praat intervalsPoint-- anamedtuplerepresenting Praat pointsTranscript-- astrwith special methods for transcription handlingAll Praat text objects are represented asTranscriptobjects.The module also exports the following variables:diacritics-- adictof all diacritics with their Unicode counterpartsinline_diacritics-- adictof inline (symbol-like) diacriticsindex_diacritics-- adictof over/understrike diacriticssymbols-- adictof special Praat symbols with their Unicode counterpartsvowels-- alistof all vowels in either Praat or Unicode notationAnd the following constants (although they arenotactually constants in Python, they SHOULDN’T be changed):BINARY-- symbolic name for the binary file formatTEXT_LONG-- symbolic name for the long text file formatTEXT_SHORT-- symbolic name for the short text file formatversion-- module version as stringVersionThis file documentspraat-textgridsversion 1.4.0.CopyrightCopyright © 2019–22 Legisign.org, Tommi Nieminensoftware@legisign.orgThis program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.You should have received a copy of the GNU General Public License along with this program.  If not, seehttps://www.gnu.org/licenses/.Module contents0. Module propertiesBesidestextgrids.version, which contains the module version number as string, the module exports the following properties:0.1. symbolssymbolsis adictthat contains all the Praat special notation symbols (as keys) and their Unicode counterparts (as values).0.2. vowelsvowelsis alistof all vowel symbols in either Praat notation (e.g.,"\as") or in Unicode. It is used byIntervalmethodscontainsvowel()andstartswithvowel(), so changing it, for example, adding new symbols to it or removing symbols used for other purposes in a specific case, will change how those methods function.0.3. diacritics, inline_diacritics, and index_diacriticsdiacriticsis adictof all diacritics in Praat notation (as keys) and their Unicode counterparts (as values).inline_diacriticsandindex_diacriticsare subsets ofdiacritics. The former are semantically diacritics but appear as inline symbols, the latter are the "true" diacritics (i.e., under- or overstrikes) that need special handling when transcoding.0.4. TEXT_LONG, TEXT_SHORT, BINARYSymbolic constants specifying different file formats inTextGrid.format()andTextGrid.write()methods. Internally they are just small integers (0, 1, and 2, respectively). The default format isTEXT_LONG.1. TextGridTextGridis ancollections.OrderedDictwhose keys are tier names (strings) and values areTierobjects. The constructor takes an optional filename argument for easy loading and parsing textgrid files.1.1. PropertiesAll the properties ofdictplus:filenameholds the textgrid filename, if any.read()andwrite()methods both set or update it.1.2. MethodsAll the methods ofdictplus:parse()-- parse string into a TextGridread()-- read (and parse) a TextGrid filetier_from_csv()-- read a textgrid tier from a CSV filetier_to_csv()-- write a textgrid tier into a CSV filewrite()-- write a TextGrid fileparse()takes an obligatory string (orbytes) argument which contains textgrid data in any of Praat’s three formats (long text, short text, or binary).read()andwrite()both take an obligatory filename argument.write()can take an optional argument specifying the file format; this can be one ofBINARY(=int2),TEXT_LONG(=int0, the default), orTEXT_SHORT(=int1).tier_from_csv()andtier_to_csv()both take two obligatory arguments, the tier name and the filename, in that order.2. TierTieris a list of eitherIntervalorPointobjects.NOTE:Tieronly allows addingIntervalorPointobjects. Adding anything else or mixingIntervals andPoints will trigger an exception.2.2. PropertiesAll the properties oflistplus:is_point_tier--boolTruefor point tier,Falsefor interval tier.tier_type--str, either"IntervalTier"or"PointTier"tier_typeexists principally for the convenience of the formatting functions.2.3. MethodsAll the methods oflistplus:merge()-- merge intervalsNOTErenamed from 1.3!to_csv()-- convert tier data into a CSV-like listmerge()merges given intervals into one. It takes two arguments,first=andlast=, both of which are integer indexes with the usual Python semantics: 0 stands for the first element, -1 for the last element, these being also the defaults. The function raises aTypeErrorif used with a point tier, andValueErrorif the parameters do not specify a valid slice.NB!This is a function and returns the result instead of modifying theTierin place.to_csv()returns a CSV-like list. It’s mainly intended to be used from theTextGridlevel methodtier_to_csv()but can be called directly if writing to a file is not desired.3. IntervalIntervalis anobjectclass representing one Interval on an IntervalTier.3.1. Propertiesdur-- interval duration (float)mid-- interval midpoint (float)text-- text label (Transcript)xmax-- interval end time (float)xmin-- interval start time (float)3.3. Methodscontainsvowel()-- does the interval contain a vowel?endswithvowel()-- does the interval end with a vowel?startswithvowel()-- does the interval start with a vowel?timegrid()-- create a time gridcontainsvowel(),endswithvowel(), andstartswithvowel()areboolfunctions (or predicates, in Lisp-parlance). They check for possible vowels in thetextproperty in both Praat notation and Unicode, but can of course make an error if symbols are used in an unexpected way. They don’t take arguments. (Internally,endswithvowel()first transcodes the text to IPA removing all diacritics to simplify the test.)timegrid()returns a list of timepoints (infloat) evenly distributed fromxmintoxmax. It takes an optional integer argument specifying the number of timepoints desired; the default is 3. It raises aValueErrorif the argument is not an integer or is less than 1.4. PointPointis anamedtuplerepresenting one Point on a PointTier.4.1. Propertiestext-- text label (Transcript)xpos-- temporal position (float)5. TranscriptTranscriptis astr-derived class with one special method:transcode().5.1. PropertiesAll the properties ofstr.5.2. MethodsAll the methods ofstrplus:transcode()-- convert Praat notation to Unicode or vice versa.Without arguments,transcode()assumes its input to be in Praat notation and converts it to Unicode; no check is made as to whether the input really is in Praat notation but nothingshouldhappen if it isn’t. User should take care and handle any exceptions.Optionalto_unicode=Falseargument inverts the direction of the transcoding from Unicode to Praat. Again, it is not checked whether input is in Unicode.With optionalretain_diacritics=Trueargument the transcoding does not remove over- and understrike diacritics from the result.ExamplesSnippet 1: list syllable durationsimport sys
import textgrids

for arg in sys.argv[1:]:
    # Try to open the file as textgrid
    try:
        grid = textgrids.TextGrid(arg)
    # Discard and try the next one
    except:
        continue

    # Assume "syllables" is the name of the tier
    # containing syllable information
    for syll in grid['syllables']:
        # Convert Praat to Unicode in the label
        label = syll.text.transcode()
        # Print label and syllable duration, CSV-like
        print('"{}";{}'.format(label, syll.dur))Snippet 2: convert any textgrid to binary formatimport sys
import os.path
import textgrids

for arg in sys.argv[1:]:
    name, ext = os.path.splitext(arg)
    try:
        grid = textgrids.TextGrid(arg)
    except (textgrids.ParseError, textgrids.BinaryError):
        print('Not a recognized file format!', file=sys.stderr)
        continue

    # Write a new file
    grid.write(name + '.bin', fmt=textgrids.BINARY)