### PointTier Initialization Example Source: http://timmahrt.github.io/praatIO/praatio/data_classes/point_tier.html Initializes a PointTier with a name, a list of entries (time, label tuples), and optional min/max times. Entries are homogenized and sorted by time. ```python from praatio.data_classes import point_tier # Example entries: list of (time, label) tuples entries = [(0.5, 'event1'), (1.2, 'event2'), (0.8, 'event3')] # Create a PointTier instance point_tier = point_tier.PointTier('my_point_tier', entries, minT=0.0, maxT=2.0) print(f'Tier Name: {point_tier.name}') print(f'Tier Type: {point_tier.tierType}') print(f'Entries: {point_tier.entries}') print(f'Min Time: {point_tier.minT}') print(f'Max Time: {point_tier.maxT}') ``` -------------------------------- ### Abstract Method: insertSpace Source: http://timmahrt.github.io/praatIO/praatio/data_classes/textgrid_tier.html Defines the signature for inserting space into a tier. Requires start time, duration, and a collision mode. ```python 252 @abstractmethod 253 def insertSpace( 254 self, 255 start: float, 256 duration: float, 257 collisionMode: Literal["stretch", "split", "no_change", "error"], 258 ) -> "TextgridTier": # pragma: no cover 259 pass ``` -------------------------------- ### IntervalTier Initialization Source: http://timmahrt.github.io/praatIO/praatio/data_classes/interval_tier.html Initializes an IntervalTier object. It takes a name, a list of entries (start time, end time, label), and optional minimum and maximum timestamps. ```APIDOC ## IntervalTier(name: str, entries: List[Interval], minT: Optional[float] = None, maxT: Optional[float] = None) ### Description Initializes an IntervalTier object. The entries are expected to be in the format [(startTime1, endTime1, label1), (startTime2, endTime2, label2), ...]. The labels can be any data type but will be interpreted as text by praatio. ### Parameters - **name** (str) - The name of the tier. - **entries** (List[Interval]) - A list of Interval objects or tuples representing the annotations. - **minT** (Optional[float]) - The minimum timestamp for the tier. If not provided, it's calculated from the entries. - **maxT** (Optional[float]) - The maximum timestamp for the tier. If not provided, it's calculated from the entries. ``` -------------------------------- ### Wav.getSamples Source: http://timmahrt.github.io/praatIO/praatio/audio.html Retrieves audio samples as a tuple of integers from a specified time segment. It first gets the frames and then converts them to samples. ```APIDOC ## Wav.getSamples(startTime: float, endTime: float) ### Description Retrieves audio samples as a tuple of integers from a specified time segment. It first gets the frames and then converts them to samples. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### Path Parameters * **startTime** (float) - The start time of the segment. * **endTime** (float) - The end time of the segment. ### Response #### Success Response (200) * **samples** (Tuple[int, ...]) - A tuple of integer audio samples. ``` -------------------------------- ### Get Audio Samples within a Time Range Source: http://timmahrt.github.io/praatIO/praatio/audio.html Retrieves audio samples as a tuple of integers within a given time range. This combines frame retrieval and conversion. ```python audioFrameList = self.getSamples(startTime, endTime) ``` -------------------------------- ### Get Audio Samples by Time Source: http://timmahrt.github.io/praatIO/praatio/audio.html Extracts audio samples as integers within a specified time range. Converts raw audio frames to a tuple of sample values. ```python def getSamples(self, startTime: float, endTime: float) -> Tuple[int, ...]: frames = self.getFrames(startTime, endTime) return convertFromBytes(frames, self.sampleWidth) ``` -------------------------------- ### PointObject Get Points In Interval Method Source: http://timmahrt.github.io/praatIO/praatio/data_classes/data_point.html Retrieves a list of time values from the pointList that fall within the specified start and end times. It can optionally start searching from a given index. ```python def getPointsInInterval( self, start: float, end: float, startIndex: int = 0 ) -> List[float]: returnPointList = [] for entry in self.pointList[startIndex:]: time = entry[0] if time >= start: if time <= end: returnPointList.append(time) else: break return returnPointList ``` -------------------------------- ### Get Timestamps Source: http://timmahrt.github.io/praatIO/praatio/data_classes/interval_tier.html Retrieves all unique timestamps (start and end times of intervals) present in the tier, sorted in ascending order. ```APIDOC ## timestamps() -> List[float] ### Description Returns a sorted list of all unique timestamps (both start and end times) present in the tier's intervals. ### Returns - List[float]: A sorted list of unique timestamps. ``` -------------------------------- ### Initialize AudioGenerator Source: http://timmahrt.github.io/praatIO/praatio/audio.html Sets up an AudioGenerator with specific sample width and frame rate. These parameters are crucial for audio synthesis. ```python self.sampleWidth: int = sampleWidth self.frameRate: int = frameRate ``` -------------------------------- ### Get Unique Timestamps from IntervalTier Source: http://timmahrt.github.io/praatIO/praatio/data_classes/interval_tier.html Retrieves all unique start and end timestamps from the intervals within the tier, sorted in ascending order. ```python @property def timestamps(self) -> List[float]: """All unique timestamps used in this tier""" tmpTimestamps = [ time for start, stop, _ in self.entries for time in [ start, stop, ] ] uniqueTimestamps = list(set(tmpTimestamps)) uniqueTimestamps.sort() return uniqueTimestamps ``` -------------------------------- ### Create AudioGenerator from WAV Parameters Source: http://timmahrt.github.io/praatIO/praatio/audio.html Builds an AudioGenerator instance using the sample width and frame rate extracted from an existing AbstractWav object. Simplifies setup when working with existing audio files. ```python return AudioGenerator(wav.sampleWidth, wav.frameRate) ``` -------------------------------- ### Initialize Wav Object Source: http://timmahrt.github.io/praatIO/praatio/audio.html Initializes a Wav object with audio frames and parameters. This is the constructor for the Wav class. ```python def __init__(self, frames: bytes, params: List): self.frames = frames super(Wav, self).__init__(params) ``` -------------------------------- ### Get Time Interval Source: http://timmahrt.github.io/praatIO/praatio/utilities/utils.html Calculates a time interval of a given duration before or after a start time. Ensures the interval stays within the bounds of 0 and a maximum value. ```python def getInterval( startTime: float, duration: float, max: float, reverse: bool ) -> Tuple[float, float]: if reverse is True: endTime = startTime startTime -= duration else: endTime = startTime + duration # Don't read over the edges if startTime < 0: startTime = 0 elif endTime > max: endTime = max return (startTime, endTime) ``` -------------------------------- ### Wav Class Initialization Source: http://timmahrt.github.io/praatIO/praatio/audio.html Initializes a Wav object with raw audio frames and parameters. The frames are stored as bytes, and parameters are provided as a list. ```APIDOC ## Wav(frames: bytes, params: List) ### Description Initializes a Wav object with raw audio frames and parameters. The frames are stored as bytes, and parameters are provided as a list. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **frames** (bytes) - The raw audio frames. * **params** (List) - A list containing the audio parameters. ``` -------------------------------- ### Get Audio Frames by Time Source: http://timmahrt.github.io/praatIO/praatio/audio.html Retrieves a specific segment of audio frames based on start and end times. Returns the raw frame data as bytes. ```python def getFrames(self, startTime: float, endTime: float) -> bytes: i = self._getIndexAtTime(startTime) j = self._getIndexAtTime(endTime) return self.frames[i:j] ``` -------------------------------- ### Get Audio Frames within a Time Range Source: http://timmahrt.github.io/praatIO/praatio/audio.html Retrieves raw audio frames (bytes) from a specified start time to an end time. Ensure the times are within the audio duration. ```python frames = self.getFrames(startTime, endTime) ``` -------------------------------- ### Create Directory Source: http://timmahrt.github.io/praatIO/praatio/utilities/utils.html Creates a new directory at the specified path. Unlike os.mkdir, it does not raise an exception if the directory already exists. ```python def makeDir(path: str) -> None: """Create a new directory Unlike os.mkdir, it does not throw an exception if the directory already exists """ if not os.path.exists(path): os.mkdir(path) ``` -------------------------------- ### Get Audio Frames by Time Interval Source: http://timmahrt.github.io/praatIO/praatio/audio.html Retrieves audio frames within a specified time interval. If start or end times are not provided, it defaults to the beginning or end of the audio file, respectively. ```python def getFrames(self, startTime: float = None, endTime: float = None) -> bytes: if startTime is None: startTime = 0 if endTime is None: ``` -------------------------------- ### Initialize Textgrid Source: http://timmahrt.github.io/praatIO/praatio/data_classes/textgrid.html Creates an empty Textgrid object. Timestamps can be optionally set during initialization. ```python import io import copy from typing import Optional, Tuple, Sequence from typing_extensions import Literal from collections import OrderedDict from praatio.utilities.constants import ( TextgridFormats, MIN_INTERVAL_LENGTH, CropCollision, ) from praatio.data_classes import textgrid_tier from praatio.data_classes import point_tier from praatio.data_classes import interval_tier from praatio.utilities import constants from praatio.utilities import errors from praatio.utilities import my_math from praatio.utilities import textgrid_io from praatio.utilities import utils class Textgrid: """A container that stores and operates over interval and point tiers Textgrids are used by the Praat software to group tiers. Each tier contains different annotation information for an audio recording. Attributes: tierNames(Tuple[str]): the list of tier names in the textgrid tiers(Tuple[TextgridTier]): the list of ordered tiers minTimestamp(float): the minimum allowable timestamp in the textgrid maxTimestamp(float): the maximum allowable timestamp in the textgrid """ def __init__(self, minTimestamp: float = None, maxTimestamp: float = None): """Constructor for Textgrids Args: minTimestamp: the minimum allowable timestamp in the textgrid maxTimestamp: the maximum allowable timestamp in the textgrid """ self._tierDict: OrderedDict[str, textgrid_tier.TextgridTier] = OrderedDict() # Timestamps are determined by the first tier added self.minTimestamp: float = minTimestamp # type: ignore[assignment] self.maxTimestamp: float = maxTimestamp # type: ignore[assignment] def __len__(self): return len(self._tierDict) def __iter__(self): for entry in self.tiers: yield entry def __eq__(self, other): if not isinstance(other, Textgrid): return False isEqual = True isEqual &= my_math.isclose(self.minTimestamp, other.minTimestamp) isEqual &= my_math.isclose(self.maxTimestamp, other.maxTimestamp) isEqual &= self.tierNames == other.tierNames if isEqual: for tierName in self.tierNames: isEqual &= self.getTier(tierName) == other.getTier(tierName) return isEqual @property def tierNames(self) -> Tuple[str, ...]: return tuple(self._tierDict.keys()) @property def tiers(self) -> Tuple[textgrid_tier.TextgridTier, ...]: return tuple(self._tierDict.values()) def addTier( self, tier: textgrid_tier.TextgridTier, tierIndex: Optional[int] = None, reportingMode: Literal["silence", "warning", "error"] = "warning", ) -> None: """Add a tier to this textgrid. Args: tier: The tier to add to the textgrid tierIndex: Insert the tier into the specified position; if None, the tier will appear after all existing tiers reportingMode: This flag determines the behavior if there is a size difference between the maxTimestamp in the tier and the current textgrid. Returns: None Raises: TierNameExistsError: The textgrid already contains a tier with the same name as the tier being added TextgridStateAutoModified: The minimum or maximum timestamp was changed when not permitted IndexError: TierIndex is too large for the size of the existing tier list """ utils.validateOption( "reportingMode", reportingMode, constants.ErrorReportingMode ) errorReporter = utils.getErrorReporter(reportingMode) if tier.name in self.tierNames: raise errors.TierNameExistsError("Tier name already in tier") if tierIndex is None: self._tierDict[tier.name] = tier else: # Need to recreate the tierDict with the new order newOrderedTierNameList = list(self.tierNames) newOrderedTierNameList.insert(tierIndex, tier.name) newTierDict = OrderedDict() self._tierDict[tier.name] = tier for tmpName in newOrderedTierNameList: newTierDict[tmpName] = self.getTier(tmpName) ``` -------------------------------- ### Get Audio Frames by Time Source: http://timmahrt.github.io/praatIO/praatio/audio.html Retrieves raw audio frames within a specified time range. If start or end times are not provided, it defaults to the beginning or the full duration of the audio file, respectively. ```python def getFrames(self, startTime: float = None, endTime: float = None) -> bytes: if startTime is None: startTime = 0 if endTime is None: endTime = self.duration return readFramesAtTime(self.audiofile, startTime, endTime) ``` -------------------------------- ### Initialize AudioGenerator Source: http://timmahrt.github.io/praatIO/praatio/audio.html Constructor for the AudioGenerator class. Requires sample width and frame rate. ```python def __init__(self, sampleWidth, frameRate): self.sampleWidth: int = sampleWidth self.frameRate: int = frameRate ``` -------------------------------- ### Get Next Value from Data String Source: http://timmahrt.github.io/praatIO/praatio/data_points.html Extracts the next value from a data string starting from a given index. It finds the end of the line to determine the value. This is a utility function used during data parsing. ```python def _getNextValue(data: str, start: int) -> Tuple[str, int]: end = data.index("\n", start) value = data[start + 1 : end] return value, end ``` -------------------------------- ### Initialize PraatExecutionFailed Source: http://timmahrt.github.io/praatIO/praatio/utilities/errors.html Constructor for PraatExecutionFailed, taking a list of strings representing the command to be executed. ```python def __init__(self, cmdList: List[str]): super(PraatExecutionFailed, self).__init__() self.cmdList = cmdList ``` -------------------------------- ### KlattPointTier Initialization Source: http://timmahrt.github.io/praatIO/praatio/data_classes/klattgrid.html The constructor for KlattPointTier processes input entries, ensuring timestamps are floats, and determines the minimum and maximum timestamps for the tier. ```python def __init__( self, name: str, entries: List, minT: Optional[float] = None, maxT: Optional[float] = None, ): entries = [(float(time), label) for time, label in entries] # Determine the min and max timestamps timeList = [time for time, label in entries] if minT is not None: timeList.append(float(minT)) if maxT is not None: timeList.append(float(maxT)) try: setMinT = min(timeList) setMaxT = max(timeList) except ValueError: raise errors.TimelessTextgridTierException() super(KlattPointTier, self).__init__(name, entries, setMinT, setMaxT) ``` -------------------------------- ### findAll Source: http://timmahrt.github.io/praatIO/praatio/utilities/utils.html Finds the starting indices of all occurrences of a substring within a given text. It returns a list of integers representing the starting positions. ```APIDOC ## findAll ### Description Find the starting indices of all instances of `subStr` in `txt`. ### Parameters * `txt` (str) - The text to search within. * `subStr` (str) - The substring to find. ### Returns * `List[int]` - A list of integers, where each integer is the starting index of an occurrence of `subStr` in `txt`. ``` -------------------------------- ### TextgridTier Initialization Source: http://timmahrt.github.io/praatIO/praatio/data_classes/textgrid_tier.html Initializes a TextgridTier with a name, entries, min/max timestamps, and error reporting mode. Entries are sorted upon initialization. ```python def __init__( self, name: str, entries: List, minT: float, maxT: float, errorMode: Literal["silence", "warning", "error"] = "warning", ): "A container that stores and operates over interval and point tiers" utils.validateOption("errorMode", errorMode, constants.ErrorReportingMode) """See PointTier or IntervalTier""" entries.sort() self.name = name self._entries = entries self.minTimestamp = minT self.maxTimestamp = maxT self.errorReporter = utils.getErrorReporter(errorMode) ``` -------------------------------- ### Replace Segment in WAV Source: http://timmahrt.github.io/praatIO/praatio/audio.html Deletes a segment of audio defined by start and end times and inserts new frames at the start time. This effectively replaces a portion of the audio. ```python self.replaceSegment(startTime, endTime, frames) ``` -------------------------------- ### AudioGenerator Constructor Source: http://timmahrt.github.io/praatIO/praatio/audio.html Initializes an AudioGenerator with specified sample width and frame rate. ```APIDOC ## AudioGenerator(sampleWidth, frameRate) ### Description Initializes an AudioGenerator instance. ### Parameters - **sampleWidth** (int) - The number of bytes per sample. - **frameRate** (int) - The number of frames per second. ``` -------------------------------- ### Shrink Tier Entries by Time Offset Source: http://timmahrt.github.io/praatIO/praatio/data_classes/point_tier.html Adjusts the time of entries in a tier when a section is removed. Entries before the start remain unchanged, while entries after the start are shifted back by the removed duration. ```python if doShrink is True: newEntries = [] diff = end - start for point in newTier.entries: if point.time < start: newEntries.append(point) elif point.time > end: newEntries.append(Point(point.time - diff, point.label)) newMax = newTier.maxTimestamp - diff newTier = newTier.new(entries=newEntries, maxTimestamp=newMax) ``` -------------------------------- ### IntervalTier Initialization Source: http://timmahrt.github.io/praatIO/praatio/data_classes/interval_tier.html Initializes an IntervalTier with a name, a list of entries, and optional minimum and maximum times. Entries are homogenized and validated upon initialization. ```python def __init__( self, name: str, entries: List[Interval], minT: Optional[float] = None, maxT: Optional[float] = None, ): """An interval tier is for annotating events that have duration The entries is of the form: [(startTime1, endTime1, label1), (startTime2, endTime2, label2), ] The data stored in the labels can be anything but will be interpreted as text by praatio (the label could be descriptive text e.g. ('erase this region') or numerical data e.g. (average pitch values like '132')) """ entries = _homogenizeEntries(entries) calculatedMinT, calculatedMaxT = _calculateMinAndMaxTime(entries, minT, maxT) super(IntervalTier, self).__init__( name, entries, calculatedMinT, calculatedMaxT ) self._validate() ``` -------------------------------- ### Retrieving Points within a Time Interval Source: http://timmahrt.github.io/praatIO/praatio/data_classes/data_point.html The getPointsInInterval method filters and returns temporal data points that fall within a specified start and end time. It can optionally start searching from a given index. ```python def getPointsInInterval( self, start: float, end: float, startIndex: int = 0, ) -> List[float]: returnPointList = [] for entry in self.pointList[startIndex:]: time = entry[0] if time >= start: if time <= end: returnPointList.append(time) else: break return returnPointList ``` -------------------------------- ### Prepare TextGrid for Saving Source: http://timmahrt.github.io/praatIO/praatio/utilities/textgrid_io.html Prepares a TextGrid dictionary for saving by sorting entries and adjusting timestamps and interval lengths. It ensures the TextGrid conforms to saving requirements. ```python def _prepTgForSaving( tg: Dict, includeBlankSpaces: Optional[bool], minTimestamp: Optional[float], maxTimestamp: Optional[float], minimumIntervalLength: float, ) -> Dict: _sortEntries(tg) if minTimestamp is None: minTimestamp = tg["xmin"] else: tg["xmin"] = minTimestamp if maxTimestamp is None: maxTimestamp = tg["xmax"] ``` -------------------------------- ### Textgrid.insertSpace Source: http://timmahrt.github.io/praatIO/praatio/data_classes/textgrid.html Inserts a blank region of a specified duration into the Textgrid at a given start time. All items occurring after the start time are pushed back by the duration. The behavior for intervals straddling the insertion point is determined by the collisionMode. ```APIDOC ## Textgrid.insertSpace ### Description Inserts a blank region of a specified duration into the Textgrid at a given start time. All items occurring after the start time are pushed back by the duration. The behavior for intervals straddling the insertion point is determined by the collisionMode. ### Method `insertSpace(start: float, duration: float, collisionMode: Literal["stretch", "split", "no_change", "error"] = "error") -> "Textgrid"` ### Parameters - **start** (float) - The time at which to insert the space. - **duration** (float) - The duration of the blank space to insert in seconds. - **collisionMode** (Literal["stretch", "split", "no_change", "error"]) - Determines behavior for intervals straddling the insertion point. Options include 'stretch', 'split', 'no_change', or 'error'. Defaults to 'error'. ### Returns - **Textgrid**: The modified version of the current Textgrid. ``` -------------------------------- ### KlattPointTier Initialization Source: http://timmahrt.github.io/praatIO/praatio/data_classes/klattgrid.html Initializes a KlattPointTier, which is a TextgridTier not contained within another tier. It processes entries to ensure float timestamps and determines min/max timestamps from entries and provided bounds. ```python def __init__( self, name: str, entries: List, minT: Optional[float] = None, maxT: Optional[float] = None, ): entries = [(float(time), label) for time, label in entries] # Determine the min and max timestamps timeList = [time for time, label in entries] if minT is not None: timeList.append(float(minT)) if maxT is not None: timeList.append(float(maxT)) try: setMinT = min(timeList) setMaxT = max(timeList) except ValueError: raise errors.TimelessTextgridTierException() super(KlattPointTier, self).__init__(name, entries, setMinT, setMaxT) ``` -------------------------------- ### Wav.deleteSegment Source: http://timmahrt.github.io/praatIO/praatio/audio.html Deletes a segment of audio from the Wav object between the specified start and end times. ```APIDOC ## Wav.deleteSegment(startTime: float, endTime: float) ### Description Deletes a segment of audio from the Wav object between the specified start and end times. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### Path Parameters * **startTime** (float) - The start time of the segment to delete. * **endTime** (float) - The end time of the segment to delete. ``` -------------------------------- ### Initialize QueryWav for Fast Audio File Info Source: http://timmahrt.github.io/praatIO/praatio/audio.html Initializes a QueryWav object to efficiently access information about a WAV file without loading the entire file into memory. This class is designed for read-only operations and maintains no internal state changes. ```python def __init__(self, fn: str): self.audiofile = wave.open(fn, "r") super(QueryWav, self).__init__(self.audiofile.getparams()) ``` -------------------------------- ### Initialize FindZeroCrossingError Source: http://timmahrt.github.io/praatIO/praatio/utilities/errors.html Constructor for FindZeroCrossingError, taking the start and end times of the search interval. ```python def __init__(self, startTime: float, endTime: float): super(FindZeroCrossingError, self).__init__() self.startTime = startTime self.endTime = endTime ``` -------------------------------- ### makeDir Source: http://timmahrt.github.io/praatIO/praatio/utilities/utils.html Creates a new directory at the specified path. Unlike `os.mkdir`, this function does not raise an exception if the directory already exists. ```APIDOC ## makeDir ### Description Create a new directory at the given path. This function is a convenience wrapper around `os.mkdir` that avoids raising an error if the directory already exists. ### Parameters * `path` (str) - The path of the directory to create. ### Returns * `None` ``` -------------------------------- ### Wav.getFrames Source: http://timmahrt.github.io/praatIO/praatio/audio.html Retrieves a segment of audio frames from the Wav object between the specified start and end times. ```APIDOC ## Wav.getFrames(startTime: float, endTime: float) ### Description Retrieves a segment of audio frames from the Wav object between the specified start and end times. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### Path Parameters * **startTime** (float) - The start time of the segment to retrieve. * **endTime** (float) - The end time of the segment to retrieve. ### Response #### Success Response (200) * **frames** (bytes) - The retrieved audio frames. ``` -------------------------------- ### Get Tier by Name in Textgrid Source: http://timmahrt.github.io/praatIO/praatio/data_classes/textgrid.html Retrieves a specific tier from the Textgrid object using its name. ```python def getTier(self, tierName: str) -> textgrid_tier.TextgridTier: """Get the tier with the specified name""" return self._tierDict[tierName] ``` -------------------------------- ### PointObject Initialization and Basic Usage Source: http://timmahrt.github.io/praatIO/praatio/data_classes/data_point.html Demonstrates the initialization of a PointObject with temporal data and an object class. This class is a base for storing non-annotation data points. ```python class PointObject: def __init__( self, pointList: List[Tuple[float, ...]], # Either (float) or (float, float) objectClass: str, minTime: float = 0, maxTime: float = None, ): self.pointList = [tuple(float(val) for val in row) for row in pointList] self.objectClass = objectClass self.minTime = minTime if minTime > 0 else 0 self.maxTime = maxTime def __eq__(self, other): if not isinstance(other, PointObject): return False isEqual = True isEqual &= self.objectClass == other.objectClass isEqual &= self.minTime == other.minTime isEqual &= self.maxTime == other.maxTime isEqual &= len(self.pointList) == len(other.pointList) if isEqual: for selfEntry, otherEntry in zip(self.pointList, other.pointList): isEqual &= selfEntry == otherEntry return isEqual ``` -------------------------------- ### Get Error Reporter Function Source: http://timmahrt.github.io/praatIO/praatio/utilities/utils.html Selects an appropriate error reporting function based on the specified reporting mode. ```python def getErrorReporter(reportingMode: Literal["silence", "warning", "error"]): modeToFunc = { constants.ErrorReportingMode.SILENCE: reportNoop, constants.ErrorReportingMode.WARNING: reportWarning, constants.ErrorReportingMode.ERROR: reportException, } return modeToFunc[reportingMode] ``` -------------------------------- ### Initialize Textgrid Object Source: http://timmahrt.github.io/praatIO/praatio/data_classes/textgrid.html Constructs a Textgrid object. Optionally sets the minimum and maximum allowable timestamps for the grid. ```python def __init__(self, minTimestamp: float = None, maxTimestamp: float = None): """Constructor for Textgrids Args: minTimestamp: the minimum allowable timestamp in the textgrid maxTimestamp: the maximum allowable timestamp in the textgrid """ self._tierDict: OrderedDict[str, textgrid_tier.TextgridTier] = OrderedDict() # Timestamps are determined by the first tier added self.minTimestamp: float = minTimestamp # type: ignore[assignment] self.maxTimestamp: float = maxTimestamp # type: ignore[assignment] ``` -------------------------------- ### Open and Read WAV File Source: http://timmahrt.github.io/praatIO/praatio/audio.html Opens a WAV file and reads all its audio frames. This is useful for initial loading of audio data. ```python wav = Wav.open(fn) ``` -------------------------------- ### Textgrid.new Source: http://timmahrt.github.io/praatIO/praatio/data_classes/textgrid.html Creates and returns a deep copy of the current Textgrid object. ```APIDOC ## Textgrid.new ### Description Returns a copy of this Textgrid. ### Method `new()` ### Returns - `Textgrid`: A new Textgrid object that is a deep copy of the original. ``` -------------------------------- ### validate Source: http://timmahrt.github.io/praatIO/praatio/data_classes/interval_tier.html Validates the integrity of the interval tier. It checks for invalid intervals where the start time is greater than or equal to the end time. ```APIDOC ## validate ### Description Validates this tier. Checks if interval start times are strictly less than interval end times. ### Method `validate(self, reportingMode: Literal["silence", "warning", "error"] = "warning") -> bool` ### Parameters * `reportingMode` (str, optional): Determines the behavior if validation fails. Options are "silence", "warning", or "error". Defaults to "warning". ### Returns bool: True if the tier is valid; False if not. ``` -------------------------------- ### Wav.getSubwav Source: http://timmahrt.github.io/praatIO/praatio/audio.html Creates and returns a new Wav object representing a sub-segment of the original audio, defined by the start and end times. ```APIDOC ## Wav.getSubwav(startTime: float, endTime: float) ### Description Creates and returns a new Wav object representing a sub-segment of the original audio, defined by the start and end times. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### Path Parameters * **startTime** (float) - The start time of the sub-segment. * **endTime** (float) - The end time of the sub-segment. ### Response #### Success Response (200) * **subwav** (Wav) - A new Wav object representing the specified sub-segment. ``` -------------------------------- ### Wav.open Source: http://timmahrt.github.io/praatIO/praatio/audio.html Class method to open and read a WAV file from a given file path. It reads all audio frames from the file and returns a new Wav object. ```APIDOC ## Wav.open(fn: str) ### Description Class method to open and read a WAV file from a given file path. It reads all audio frames from the file and returns a new Wav object. ### Method classmethod ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) * **Wav** (Wav) - A Wav object representing the opened audio file. ``` -------------------------------- ### Open KlattGrid File Source: http://timmahrt.github.io/praatIO/praatio/klattgrid.html Opens a KlattGrid file, attempting UTF-16 encoding first and falling back to UTF-8 if necessary. Handles different line endings by normalizing them to \n. ```python def openKlattgrid(fnFullPath: str) -> Klattgrid: try: with io.open(fnFullPath, "r", encoding="utf-16") as fd: data = fd.read() except UnicodeError: with io.open(fnFullPath, "r", encoding="utf-8") as fd: data = fd.read() data = data.replace("\r\n", "\n") # Right now, can only open normal klatt grid and not short ones kg = _openNormalKlattgrid(data) return kg ``` -------------------------------- ### Get Tiers Source: http://timmahrt.github.io/praatIO/praatio/data_classes/textgrid.html Returns a tuple of all TextgridTier objects stored in the Textgrid. This property allows access to the actual tier data. ```python @property def tiers(self) -> Tuple[textgrid_tier.TextgridTier, ...]: return tuple(self._tierDict.values()) ``` -------------------------------- ### PointTier Initialization Source: http://timmahrt.github.io/praatIO/praatio/data_classes/point_tier.html Initializes a PointTier object. It takes a name, a list of entries (time-label pairs), and optional min/max timestamps. The entries are homogenized and min/max times are calculated if not provided. ```python def __init__( self, name: str, entries: List[Point], minT: Optional[float] = None, maxT: Optional[float] = None, ): """A point tier is for annotating instaneous events The entries is of the form: [(timeVal1, label1), (timeVal2, label2), ] The data stored in the labels can be anything but will be interpreted as text by praatio (the label could be descriptive text e.g. ('peak point here') or numerical data e.g. (pitch values like '132')) """ entries = _homogenizeEntries(entries) calculatedMinT, calculatedMaxT = _calculateMinAndMaxTime(entries, minT, maxT) super(PointTier, self).__init__(name, entries, calculatedMinT, calculatedMaxT) ``` -------------------------------- ### insertSpace Source: http://timmahrt.github.io/praatIO/praatio/data_classes/textgrid.html Inserts a blank region of a specified duration into the Textgrid starting at a given time. All subsequent items are pushed back by the duration. ```APIDOC ## insertSpace ### Description Inserts a blank region into a textgrid. Every item that occurs after *start* will be pushed back by *duration* seconds. ### Method `insertSpace(self, start: float, duration: float, collisionMode: Literal['stretch', 'split', 'no_change', 'error'] = 'error') -> Textgrid` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **start** (float) - Required - The starting time for inserting space. * **duration** (float) - Required - The duration of the space to insert. * **collisionMode** (Literal['stretch', 'split', 'no_change', 'error']) - Optional - Determines behavior in the event that an interval stradles the starting point. One of ['stretch', 'split', 'no change', None]. * 'stretch' stretches the interval by /duration/ amount * 'split' splits the interval into two--everything to the right of 'start' will be advanced by 'duration' seconds * 'no change' leaves the interval as is with no change * None or any other value throws an AssertionError ### Returns Textgrid: the modified version of the current textgrid ``` -------------------------------- ### TextgridTier Constructor Source: http://timmahrt.github.io/praatIO/praatio/data_classes/textgrid_tier.html Initializes a TextgridTier object. It takes a name, a list of entries, minimum and maximum timestamps, and an error reporting mode. ```APIDOC ## TextgridTier Constructor ### Description Initializes a TextgridTier object. It takes a name, a list of entries, minimum and maximum timestamps, and an error reporting mode. ### Parameters - **name** (str) - The name of the tier. - **entries** (List) - A list of entries (points or intervals) to be stored in the tier. - **minT** (float) - The minimum timestamp for the tier. - **maxT** (float) - The maximum timestamp for the tier. - **errorMode** (Literal["silence", "warning", "error"]) - The mode for reporting errors, defaults to "warning". ### Attributes - **tierType** (str) - The type of the tier (e.g., 'interval', 'point'). - **entryType** (Union[Type[Point], Type[Interval]]) - The type of entries stored in the tier. - **name** (str) - The name of the tier. - **minTimestamp** (float) - The minimum timestamp of the tier. - **maxTimestamp** (float) - The maximum timestamp of the tier. - **errorReporter** - An object responsible for reporting errors. - **entries** (List) - The list of entries in the tier. ``` -------------------------------- ### crop Source: http://timmahrt.github.io/praatIO/praatio/data_classes/point_tier.html Creates a new PointTier containing entries within a specified time interval. Optionally, timestamps can be rebased to start from zero. ```APIDOC ## crop ### Description Creates a new tier containing all entries inside the new interval. ### Method `crop(self, cropStart: float, cropEnd: float, mode: Literal['strict', 'lax', 'truncated'] = 'lax', rebaseToZero: bool = True) -> PointTier` ### Parameters * **cropStart** (float) - The start time of the cropping interval. * **cropEnd** (float) - The end time of the cropping interval. * **mode** (Literal['strict', 'lax', 'truncated'], optional) - This parameter is ignored and kept for compatibility with IntervalTier.crop(). Defaults to 'lax'. * **rebaseToZero** (bool, optional) - If True, all entry timestamps will be subtracted by `cropStart`. Defaults to True. ### Returns * **PointTier** - A new PointTier object containing the cropped entries. ``` -------------------------------- ### Delete Audio Segment Source: http://timmahrt.github.io/praatIO/praatio/audio.html Removes a segment of audio defined by start and end times. The frames within this time range are deleted. ```python def deleteSegment(self, startTime: float, endTime: float) -> None: i = self._getIndexAtTime(startTime) j = self._getIndexAtTime(endTime) self.frames = self.frames[:i] + self.frames[j:] ``` -------------------------------- ### TextgridTier Initialization Source: http://timmahrt.github.io/praatIO/praatio/data_classes/textgrid_tier.html Initializes a TextgridTier object with a name, entries, and timestamp bounds. It sorts the entries and sets up an error reporter based on the provided error mode. ```python class TextgridTier(ABC): tierType: str entryType: Union[Type[constants.Point], Type[constants.Interval]] def __init__( self, name: str, entries: List, minT: float, maxT: float, errorMode: Literal["silence", "warning", "error"] = "warning", ): "A container that stores and operates over interval and point tiers" utils.validateOption("errorMode", errorMode, constants.ErrorReportingMode) """See PointTier or IntervalTier""" entries.sort() self.name = name self._entries = entries self.minTimestamp = minT self.maxTimestamp = maxT self.errorReporter = utils.getErrorReporter(errorMode) ```