praatio/audio.py
class AudioDeletion:
class AbstractWav(ABC):
class WavQueryObj(AbstractWav):
class WavObj(AbstractWav):
    SHRINK: Final = "shrink"
    SILENCE: Final = "silence"
    SINE_WAVE: Final = "sine wave"
_KEEP: Final = "keep"
_DELETE: Final = "delete"
ZERO_CROSSING_TIMESTEP: Final = 0.002
def samplesAsNums(waveData, sampleWidth: int) -> Tuple[int, ...]:
def numsAsSamples(sampleWidth: int, numList: List[int]) -> bytes:
def getDuration(wavFN: str) -> float:
def getMaxAmplitude(sampleWidth: int) -> int:
def generateSineWave(
    duration: float, freq: int, samplingFreq: int, amplitude: float
) -> List[int]:
def generateSilence(duration: float, samplingFreq: int) -> Tuple[int, ...]:
def extractSubwav(fn: str, outputFN: str, startT: float, endT: float) -> None:
    def __init__(self, params):
    def findNearestZeroCrossing(
        self, targetTime: float, timeStep: float = ZERO_CROSSING_TIMESTEP
    ) -> float:
    def findNextZeroCrossing(
        self,
        targetTime: float,
        timeStep: float = ZERO_CROSSING_TIMESTEP,
        reverse: bool = False,
    ) -> float:
    def getDuration(self) -> float:
    def getSamples(self, startTime: float, endTime: float) -> Tuple[int, ...]:
    def __init__(self, fn: str):
    def concatenate(
        self, targetFrames: List[int], outputFN: str, prepend: bool = False
    ) -> None:
    def getDuration(self) -> float:
    def getFrames(self, startTime: float = None, endTime: float = None):
    def getSamples(self, startTime: float, endTime: float) -> Tuple[int, ...]:
    def deleteWavSections(
        self,
        outputFN: str,
        keepList: List[Tuple[float, float, str]] = None,
        deleteList: List[Tuple[float, float, str]] = None,
        operation: Literal["shrink", "silence", "sine wave"] = AudioDeletion.SHRINK,
        sineWaveAmplitude: float = None,
    ):
    def outputModifiedWav(self, audioFrames: bytes, outputFN: str):
    def __init__(self, audioSamples: Tuple[int, ...], params: dict):
    def getIndexAtTime(self, startTime: float):
    def insertSilence(self, startTime: float, silenceDuration: float):
    def insert(self, startTime: float, audioSamples: Tuple[int, ...]):
    def deleteSegment(self, startTime: float, endTime: float):
    def getDuration(self):
    def getSamples(self, startTime: float, endTime: float) -> Tuple[int, ...]:
    def getSubsegment(self, startTime: float, endTime: float) -> "WavObj":
    def new(self):
    def save(self, outputFN: str):
def openAudioFile(
    fn: str,
    keepList: List[Tuple[float, float, str]] = None,
    deleteList: List[Tuple[float, float, str]] = None,
    doShrink: bool = True,
) -> WavObj:
praatio/utilities/constants.py
INTERVAL_TIER: Final = "IntervalTier"
POINT_TIER: Final = "TextTier"
MIN_INTERVAL_LENGTH: Final = 0.00000001  # Arbitrary threshold
    LONG_TEXTGRID: Final = "long_textgrid"
    SHORT_TEXTGRID: Final = "short_textgrid"
    JSON: Final = "json"
    POINT: Final = "PointProcess"
    PITCH: Final = "PitchTier"
    DURATION: Final = "DurationTier"
    STRICT: Final = "strict"
    LAX: Final = "lax"
    TRUNCATED: Final = "truncated"
    SILENCE: Final = "silence"
    WARNING: Final = "warning"
    ERROR: Final = "error"
    REPLACE: Final = "replace"
    MERGE: Final = "merge"
    ERROR: Final = "error"
    STRETCH: Final = "stretch"
    SPLIT: Final = "split"
    NO_CHANGE: Final = "no_change"
    ERROR: Final = "error"
    TRUNCATE: Final = "truncate"
    CATEGORICAL: Final = "categorical"
    ERROR: Final = "error"
    ERROR: Final = "error"
    RENAME: Final = "rename"
class Interval(namedtuple("Interval", ["start", "end", "label"])):
class Point(namedtuple("Point", ["time", "label"])):
class TextgridFormats:
class DataPointTypes:
class CropCollision:
class ErrorReportingMode:
class IntervalCollision:
class WhitespaceCollision:
class EraseCollision:
class DuplicateNames:
    def __eq__(self, other):
    def __ne__(self, other):
    def __eq__(self, other):
    def __ne__(self, other):
praatio/utilities/utils.py
def reportNoop(_exception: Type[BaseException], _text: str) -> None:
def reportException(exception: Type[BaseException], text: str) -> NoReturn:
def reportWarning(_exception: Type[BaseException], text: str) -> None:
def getErrorReporter(reportingMode: Literal["silence", "warning", "error"]):
def checkIsUndershoot(time: float, referenceTime: float, errorReporter) -> bool:
def checkIsOvershoot(time: float, referenceTime: float, errorReporter) -> bool:
def validateOption(variableName, value, optionClass):
def intervalOverlapCheck(
    interval: Interval,
    cmprInterval: Interval,
    percentThreshold: float = 0,
    timeThreshold: float = 0,
    boundaryInclusive: bool = False,
) -> bool:
def getIntervalsInInterval(
    start: float,
    end: float,
    intervals: List[Interval],
    mode: Literal["strict", "lax", "truncated"],
) -> List[Interval]:
def escapeQuotes(text: str) -> str:
def strToIntOrFloat(inputStr: str) -> float:
def getValueAtTime(
    timestamp: float,
    sortedDataTupleList: List[Tuple[Any, ...]],
    fuzzyMatching: bool = False,
    startI: int = 0,
) -> Tuple[Tuple[Any, ...], int]:
def getValuesInInterval(dataTupleList: List, start: float, end: float) -> List:
def sign(x: float) -> int:
def invertIntervalList(
    inputList: List[Tuple[float, float]], minValue: float = None, maxValue: float = None
) -> List[Tuple[float, float]]:
def makeDir(path: str) -> None:
def findAll(txt: str, subStr: str) -> List[int]:
def runPraatScript(
    praatEXE: str, scriptFN: str, argList: List[Any], cwd: str = None
) -> None:
def safeZip(listOfLists: List[list], enforceLength: bool) -> Iterator[Any]:
def getWavDuration(wavFN: str) -> float:
praatio/utilities/errors.py
class PraatioException(Exception):
class SafeZipException(PraatioException):
class FileNotFound(PraatioException):
class ParsingError(PraatioException):
class ArgumentError(PraatioException):
class UnexpectedError(PraatioException):
class WrongOption(PraatioException):
class TextgridException(PraatioException):
class DuplicateTierName(TextgridException):
class OutOfBounds(TextgridException):
class CollisionError(TextgridException):
class TimelessTextgridTierException(TextgridException):
class TextgridStateAutoModified(TextgridException):
class TextgridStateError(TextgridException):
class TierNameExistsError(TextgridException):
class IncompatibleTierError(TextgridException):
class PraatExecutionFailed(PraatioException):
class EndOfAudioData(PraatioException):
class FindZeroCrossingError(PraatioException):
class NormalizationException(PraatioException):
    def __init__(self, fullPath: str):
    def __str__(self):
    def __init__(self, argumentName: str, givenValue: str, availableOptions: List[str]):
    def __str__(self):
    def __str__(self):
    def __init__(self, tier):
    def __str__(self):
    def __init__(self, cmdList: List[str]):
    def __str__(self):
    def __init__(self, startTime: float, endTime: float):
    def __str__(self):
    def __str__(self):
praatio/klattgrid.py
def openKlattgrid(fnFullPath: str) -> Klattgrid:
def wavToKlattgrid(
    praatEXE: str,
    inputFullPath: str,
    outputFullPath: str,
    timeStep: float = 0.005,
    numFormants: int = 5,
    maxFormantFreq: float = 5500.0,
    windowLength: float = 0.025,
    preEmphasis: float = 50.0,
    pitchFloor: float = 60.0,
    pitchCeiling: float = 600.0,
    minPitch: float = 50.0,
    subtractMean: bool = True,
    scriptFN: Optional[str] = None,
) -> None:
def resynthesize(
    praatEXE: str,
    wavFN: str,
    klattFN: str,
    outputWavFN: str,
    doCascade: bool = True,
    scriptFN: Optional[str] = None,
) -> None:
def _openNormalKlattgrid(data: str) -> Klattgrid:
def _proccessContainerTierInput(sectionData: str, name: str):
def _findIndicies(data, keyword):
def _getSectionHeader(data, indexList, i):
def _buildEntryList(sectionTuple):
def _processSectionData(sectionData: str) -> List[Tuple[float, float]]:
praatio/data_points.py
def open1DPointObject(fn: str) -> PointObject1D:
def open2DPointObject(fn: str) -> PointObject2D:
def _parseNormalHeader(fn: str) -> Tuple[str, str, float, float]:
def _getNextValue(data: str, start: int) -> Tuple[str, int]:
def _parseShortHeader(fn: str) -> Tuple[str, str, float, float]:
praatio/utilities/textgrid_io.py
def reSearch(pattern, string, flags=None) -> Match[str]:
def _removeBlanks(tier: Dict) -> None:
    def hasContent(entry):
def _removeUltrashortIntervals(
    tier: Dict, minLength: float, minTimestamp: float
) -> None:
def _fillInBlanks(
    tier: Dict,
    blankLabel: str = "",
    minTime: Optional[float] = None,
    maxTime: Optional[float] = None,
) -> None:
def parseTextgridStr(data: str, includeEmptyIntervals: bool = False) -> Dict:
def getTextgridAsStr(
    tg: Dict,
    format: Literal["short_textgrid", "long_textgrid", "json"],
    includeBlankSpaces: bool,
    minTimestamp: Optional[float] = None,
    maxTimestamp: Optional[float] = None,
    minimumIntervalLength: float = MIN_INTERVAL_LENGTH,
) -> str:
def _sortEntries(tg: Dict) -> None:
def _prepTgForSaving(
    tg: Dict,
    includeBlankSpaces: Optional[bool],
    minTimestamp: Optional[float],
    maxTimestamp: Optional[float],
    minimumIntervalLength: float,
) -> Dict:
def _tgToShortTextForm(
    tg: Dict,
) -> str:
def _tgToLongTextForm(tg: Dict) -> str:
def _tgToJson(tgAsDict: Dict) -> str:
def _parseNormalTextgrid(data: str) -> Dict:
def _parseShortTextgrid(data: str) -> Dict:
def _fetchRow(
    dataStr: str, index: int, searchStr: Optional[str] = None
) -> Tuple[str, int]:
def _fetchTextRow(
    dataStr: str, index: int, searchStr: Optional[str] = None
) -> Tuple[str, int]:
praatio/data_classes/textgrid.py
class Textgrid:
    def __init__(self, minTimestamp: float = None, maxTimestamp: float = None):
    def __eq__(self, other):
    def addTier(
        self,
        tier: textgrid_tier.TextgridTier,
        tierIndex: Optional[int] = None,
        reportingMode: Literal["silence", "warning", "error"] = "warning",
    ) -> None:
    def appendTextgrid(self, tg: "Textgrid", onlyMatchingNames: bool) -> "Textgrid":
    def crop(
        self,
        cropStart: float,
        cropEnd: float,
        mode: Literal["strict", "lax", "truncated"],
        rebaseToZero: bool,
    ) -> "Textgrid":
    def eraseRegion(self, start: float, end: float, doShrink: bool) -> "Textgrid":
    def editTimestamps(
        self,
        offset: float,
        reportingMode: Literal["silence", "warning", "error"] = "warning",
    ) -> "Textgrid":
    def insertSpace(
        self,
        start: float,
        duration: float,
        collisionMode: Literal["stretch", "split", "no_change", "error"] = "error",
    ) -> "Textgrid":
    def mergeTiers(
        self, tierList: Optional[List[str]] = None, preserveOtherTiers: bool = True
    ) -> "Textgrid":
    def new(self) -> "Textgrid":
    def save(
        self,
        fn: str,
        format: Literal["short_textgrid", "long_textgrid", "json"],
        includeBlankSpaces: bool,
        minTimestamp: Optional[float] = None,
        maxTimestamp: Optional[float] = None,
        minimumIntervalLength: float = MIN_INTERVAL_LENGTH,
        reportingMode: Literal["silence", "warning", "error"] = "warning",
    ) -> None:
    def renameTier(self, oldName: str, newName: str) -> None:
    def removeTier(self, name: str) -> textgrid_tier.TextgridTier:
    def replaceTier(
        self,
        name: str,
        newTier: textgrid_tier.TextgridTier,
        reportingMode: Literal["silence", "warning", "error"] = "warning",
    ) -> None:
    def validate(
        self, reportingMode: Literal["silence", "warning", "error"] = "warning"
    ) -> bool:
def _tgToDictionary(tg: Textgrid) -> dict:
praatio/textgrid.py
def openTextgrid(
    fnFullPath: str,
    includeEmptyIntervals: bool,
    reportingMode: Literal["silence", "warning", "error"] = "warning",
    duplicateNamesMode: Literal["error", "rename"] = "error",
) -> Textgrid:
def _dictionaryToTg(
    tgAsDict: dict, reportingMode: Literal["silence", "warning", "error"]
) -> Textgrid:
tests/testing_utils.py
def areTheSameFiles(fn1, fn2, fileHandler, *args):
    """
    Tests that files contain the same data

    If fileHandler is a textgrid file reader like
    textgrid.openTextgrid then we can compare
    a shortTextgrid and a longTextgrid.

    If fileHandler is readFile or io.open, etc then the raw
    text will be compared.
    """
    data1 = fileHandler(fn1, *args)
    data2 = fileHandler(fn2, *args)

    return data1 == data2


Question: import unittest
import os
import io
from os.path import join
from praatio import textgrid
from praatio import data_points
from praatio import klattgrid
from praatio.data_classes import textgrid as tg_helper
from praatio import audio
from praatio.utilities import constants
from praatio.utilities import utils
from praatio.utilities import textgrid_io
from praatio.utilities import errors
from tests.testing_utils import areTheSameFiles
"""
Created on Jan 27, 2016

@author: tmahrt

Tests that praat files can be read in and then written out, and that the two
resulting files are the same.

This does not test that the file reader is correct.  If the file
reader is bad (e.g. truncates floating points to 1 decimal place), the
resulting data structures will look the same for both the source and
generated files.
"""





def readFile(fn):
    with io.open(fn, "r") as fd:
        return fd.read()


def run_save(
    tg,
    includeBlankSpaces=True,
    minimumIntervalLength=None,
    minTimestamp=None,
    maxTimestamp=None,
):
    """
    Mock write function and return the first tier's entry list

    tg.save() mutates the textgrid's data, so the entry list
    before and after saving can be different
    """

    textgridStr = textgrid_io.getTextgridAsStr(
        tg_helper._tgToDictionary(tg),
        constants.TextgridFormats.SHORT_TEXTGRID,
        includeBlankSpaces,
        minTimestamp,
        maxTimestamp,
        minimumIntervalLength,
    )
    tgAsDict = textgrid_io.parseTextgridStr(textgridStr, includeBlankSpaces)

Answer:     savedTg = textgrid._dictionaryToTg(tgAsDict, constants.ErrorReportingMode.ERROR)