### Preview Project Documentation Source: https://github.com/timmahrt/praatio/blob/main/DEVELOP.md Starts a live preview server for the project documentation using pdoc. The documentation is generated from the package as installed on the system. ```bash pdoc praatio -d google ``` -------------------------------- ### Install PraatIO from source Source: https://github.com/timmahrt/praatio/blob/main/README.md Manually install the praatio library after downloading the source code. Navigate to the root directory of the source code in your command-line shell. ```bash python -m pip install . ``` -------------------------------- ### Install PraatIO using pip Source: https://github.com/timmahrt/praatio/blob/main/README.md Install or upgrade the praatio library from the Python Package Index (PyPI) using pip. ```bash python -m pip install praatio --upgrade ``` -------------------------------- ### Install PraatIO from source with full path Source: https://github.com/timmahrt/praatio/blob/main/README.md Manually install the praatio library from source when the python executable is not in your system's PATH. Provide the full path to the python executable. ```bash C:\Python37\python.exe -m pip install . ``` -------------------------------- ### Getting samples from QueryWav Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/audio.html Retrieves audio samples as a tuple of integers within a specified time range. It first gets the frames and then converts them. ```python frames = self.getFrames(startTime, endTime) audioFrameList = convertFromBytes(frames, self.sampleWidth) return audioFrameList ``` -------------------------------- ### Pitch Extraction Setup Source: https://github.com/timmahrt/praatio/blob/main/tutorials/tutorial1_intro_to_praatio.ipynb Initializes necessary modules and defines paths for pitch extraction. Requires Praat executable and audio/textgrid files. ```python import os from os.path import join from praatio import textgrid from praatio import pitch_and_intensity # For pitch extraction, we need the location of praat on your computer #praatEXE = r"C:\\Praat.exe" praatEXE = "/Applications/Praat.app/Contents/MacOS/Praat" # The 'os.getcwd()' is kindof a hack. With jypter __file__ is undefined and # os.getcwd() seems to default to the praatio installation files. rootPath = join(os.getcwd(), '..', 'examples', 'files') pitchPath = join(rootPath, "pitch_extraction", "pitch") fnList = [('mary.wav', 'mary.TextGrid'), ('bobby.wav', 'bobby_words.TextGrid')] ``` -------------------------------- ### Install PraatIO using pip Source: https://github.com/timmahrt/praatio/blob/main/tutorials/tutorial1_intro_to_praatio.ipynb Install the PraatIO library and its dependencies using pip. This command upgrades the package if it is already installed. ```python %pip install praatio --upgrade ``` -------------------------------- ### Initial Search Setup Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/utilities/my_math.html Initializes the search functionality if a search term is present in the URL, or sets up an event listener to initialize on the first focus. ```javascript if (getSearchTerm()) { initialize(); searchBox.value = getSearchTerm(); onInput(); } else { searchBox.addEventListener("focus", initialize, {once: true}); } ``` -------------------------------- ### Build and Release Package Source: https://github.com/timmahrt/praatio/blob/main/DEVELOP.md Builds the project distribution files and uploads them to PyPI using build and twine. Ensure 'build' and 'twine' are installed and up-to-date. ```bash pip install --upgrade build python -m build pip install --upgrade twine twine upload dist/* ``` -------------------------------- ### Install Praatio 4.x Source: https://github.com/timmahrt/praatio/blob/main/UPGRADING.md If you have installed version 5 but your code was written for praatio 4.x or earlier, uninstall version 5 and install version 4.x. This is the immediate solution to resolve import errors. ```bash pip uninstall praatio pip install "praatio<5" ``` -------------------------------- ### Get Audio Samples Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/audio.html Extracts audio samples as a tuple of integers within a specified time range. It first gets the raw frames and then converts them. ```python def getSamples(self, startTime: float, endTime: float) -> Tuple[int, ...]: frames = self.getFrames(startTime, endTime) return convertFromBytes(frames, self.sampleWidth) ``` -------------------------------- ### Save TextGrid to File Source: https://github.com/timmahrt/praatio/blob/main/tutorials/tutorial1_intro_to_praatio.ipynb Saves a TextGrid object to a file. This example demonstrates saving with short_textgrid format and including blank spaces. ```python outputFN = join('..', 'examples', 'files', 'damon_set_test_output.TextGrid') setTG = textgrid.Textgrid() for tier in [syllableTier, errorTier, diffTier, interTier, unionTier]: setTG.addTier(tier) setTG.save(outputFN, format="short_textgrid", includeBlankSpaces=True) ``` -------------------------------- ### Get Time Interval Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/utilities/utils.html Calculates a time interval either before or after a given start time, ensuring the interval stays within the bounds of 0 and a specified maximum time. Use 'reverse=True' to get an interval preceding the start time. ```python def getInterval( startTime: float, duration: float, max: float, reverse: bool) -> Tuple[float, float]: """returns an interval before or after some start time The returned timestamps will be between 0 and max Args: startTime: the time to get the interval from duration: duration of the interval max: the maximum allowed time reverse: is the interval before or after the targetTime? Returns: the start and end time of an interval """ 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) ``` -------------------------------- ### Get Time Interval Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/utilities/utils.html Calculates a time interval (start and end) before or after a given start time, constrained by a maximum time. Ensures the interval stays within the bounds of 0 and max. ```Python def getInterval( startTime: float, duration: float, max: float, reverse: bool ) -> Tuple[float, float]: """returns an interval before or after some start time The returned timestamps will be between 0 and max Args: startTime: the time to get the interval from duration: duration of the interval max: the maximum allowed time reverse: is the interval before or after the targetTime? Returns: the start and end time of an interval """ 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) ``` -------------------------------- ### Get Points in Time Interval Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/data_classes/data_point.html Retrieves a list of time values from the point list that fall within a specified start and end time. 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 ``` -------------------------------- ### Initializing QueryWav Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/audio.html Opens a WAV file for querying without loading its entire content. It stores the file descriptor and audio parameters. ```python self.audiofile = wave.open(fn, "r") super(QueryWav, self).__init__(self.audiofile.getparams()) ``` -------------------------------- ### Getting frame index at time Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/audio.html Calculates the byte index within the frames data corresponding to a given start time. ```python return round(startTime * self.frameRate * self.sampleWidth) ``` -------------------------------- ### Get Unique Timestamps from IntervalTier Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/data_classes/interval_tier.html Retrieves a sorted list of all unique start and end timestamps present in the IntervalTier's entries. ```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 ``` -------------------------------- ### Generate Project Documentation Source: https://github.com/timmahrt/praatio/blob/main/DEVELOP.md Generates project documentation using pdoc with Google-style docstrings and outputs it to the 'docs' directory. Ensure the package is installed locally if generating from an edited version. ```bash pdoc praatio -d google -o docs ``` -------------------------------- ### Initialize QueryWav with File Path Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/audio.html Opens a WAV file for reading and initializes the QueryWav object with its parameters. This is used for fast, read-only access to audio file information. ```python def __init__(self, fn: str): self.audiofile = wave.open(fn, "r") super(QueryWav, self).__init__(self.audiofile.getparams()) ``` -------------------------------- ### Iterate Through Tier Entries Source: https://github.com/timmahrt/praatio/blob/main/tutorials/tutorial1_intro_to_praatio.ipynb A common idiom to process intervals within a tier. This example prints the start time, end time, and label for each interval. ```python # Print out each interval on a separate line from os.path import join from praatio import textgrid inputFN = join('..', 'examples', 'files', 'mary.TextGrid') tg = textgrid.openTextgrid(inputFN, includeEmptyIntervals=False) tier = tg.getTier('word') for start, stop, label in tier.entries: print("From:%f, To:%f, %s" % (start, stop, label)) ``` -------------------------------- ### Get Points in Interval Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/data_classes/data_point.html Retrieves a list of timestamps from the PointObject that fall within a specified time interval [start, end]. The search can optionally begin from a startIndex. ```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 ``` -------------------------------- ### AudioGenerator.__init__ Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/audio.html Initializes an AudioGenerator instance with sample width and frame rate. ```APIDOC ## AudioGenerator.__init__ ### Description Initializes an AudioGenerator instance with sample width and frame rate. ### Parameters #### Path Parameters - **sampleWidth** (int) - Required - The sample width of the audio. - **frameRate** (int) - Required - The frame rate of the audio. ``` -------------------------------- ### Get Values Within Time Interval Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/utilities/utils.html Filters a list of data tuples (sorted by time) to include only those whose timestamps fall within a specified start and end time. Assumes data is time-ordered. ```python def getValuesInInterval(dataTupleList: List, start: float, end: float) -> List: """Gets the values that exist within an interval The function assumes that the data is formated as [(t1, v1a, v1b, ...), (t2, v2a, v2b, ...)] """ intervalDataList = [] for dataTuple in dataTupleList: time = dataTuple[0] if start <= time and end >= time: intervalDataList.append(dataTuple) return intervalDataList ``` -------------------------------- ### Get Section Header Information Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/klattgrid.html Extracts a section of data based on start and end indices from a list of indices. It then splits the section data into a tuple containing the header, time information, and the rest of the data. ```python def _getSectionHeader(data, indexList, i): sectionStart = indexList[i] sectionEnd = indexList[i + 1] sectionData = data[sectionStart:sectionEnd].strip() sectionTuple = sectionData.split("\n", 4) return sectionTuple ``` -------------------------------- ### Get Values in Intervals Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/data_classes/interval_tier.html Retrieves data values from a list of time-stamped tuples that fall within each labeled interval of the tier. The input data should be a list of tuples, where each tuple starts with a timestamp followed by associated values. ```python def getValuesInIntervals(self, dataTupleList: List) -> List[Tuple[Interval, List]]: """Returns data from dataTupleList contained in labeled intervals Each labeled interval will get its own list of data values. dataTupleList should be of the form: [(time1, value1a, value1b,...), (time2, value2a, value2b...), ...] """ returnList = [] for interval in self.entries: intervalDataList = utils.getValuesInInterval( dataTupleList, interval.start, interval.end ) returnList.append((interval, intervalDataList)) return returnList ``` -------------------------------- ### AbstractWav Initialization Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/audio.html Initializes an AbstractWav object with audio parameters. Ensures the audio has a single channel. ```python def __init__(self, params: List): self.params = params self.nchannels: int = params[0] self.sampleWidth: int = params[1] self.frameRate: int = params[2] self.nframes: int = params[3] self.comptype = params[4] self.compname = params[5] if self.nchannels != 1: raise ( errors.ArgumentError( "Only audio with a single channel can be loaded. " f"Your file was #{self.nchannels}." ) ) ``` -------------------------------- ### Get Intervals Within a Target Interval Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/utilities/utils.html This Python function retrieves intervals that fall within a specified target interval (defined by start and end times). It supports different modes ('strict', 'lax', 'truncated') to control how partial overlaps are handled. Intervals outside the target range are ignored. ```python def getIntervalsInInterval( start: float, end: float, intervals: List[Interval], mode: Literal["strict", "lax", "truncated"], ) -> List[Interval]: """Gets all intervals that exist between /start/ and /end/" Args: start: the target interval start time end: the target interval stop time intervals: the list of intervals to check mode: Determines judgement criteria - 'strict', only intervals wholly contained by the target interval will be kept - 'lax', partially contained intervals will be kept - 'truncated', partially contained intervals will be truncated to fit within the crop region. Returns: The list of intervals that overlap with the target interval """ # TODO: move to Interval class? validateOption("mode", mode, constants.CropCollision) containedIntervals = [] for interval in intervals: matchedEntry = None # Don't need to investigate if the current interval is # before start or after end if interval.end <= start or interval.start >= end: continue # Determine if the current interval is wholly contained # within the superEntry if interval.start >= start and interval.end <= end: matchedEntry = interval # If the current interval is only partially contained within the # target interval AND inclusion is 'lax', include it anyways elif mode == constants.CropCollision.LAX and ( interval.start >= start or interval.end <= end ): matchedEntry = interval # The current interval stradles the end of the target interval elif interval.start >= start and interval.end > end: if mode == constants.CropCollision.TRUNCATED: matchedEntry = Interval(interval.start, end, interval.label) # The current interval stradles the start of the target interval elif interval.start < start and interval.end <= end: if mode == constants.CropCollision.TRUNCATED: matchedEntry = Interval(start, interval.end, interval.label) # The current interval contains the target interval completely elif interval.start <= start and interval.end >= end: if mode == constants.CropCollision.LAX: matchedEntry = interval elif mode == constants.CropCollision.TRUNCATED: matchedEntry = Interval(start, end, interval.label) if matchedEntry is not None: containedIntervals.append(matchedEntry) return containedIntervals ``` -------------------------------- ### Create a basic empty TextGrid Source: https://github.com/timmahrt/praatio/blob/main/tutorials/tutorial1_intro_to_praatio.ipynb Demonstrates creating a TextGrid object with an empty IntervalTier for words and an empty PointTier for maxF0. The TextGrid is then saved in a short_textgrid format. ```python from praatio import textgrid tg = textgrid.Textgrid() wordTier = textgrid.IntervalTier('words', [], 0, 1.0) maxF0Tier = textgrid.PointTier('maxF0', [], 0, 1.0) tg.addTier(wordTier) tg.addTier(maxF0Tier) tg.save("empty_textgrid.TextGrid", format="short_textgrid", includeBlankSpaces=True) ``` -------------------------------- ### Initialize AbstractWav Class Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/audio.html Initializes the AbstractWav class with audio parameters. It enforces that the audio must have a single channel. ```python class AbstractWav(ABC): def __init__(self, params: List): self.params = params self.nchannels: int = params[0] self.sampleWidth: int = params[1] self.frameRate: int = params[2] self.nframes: int = params[3] self.comptype = params[4] self.compname = params[5] if self.nchannels != 1: raise ( errors.ArgumentError( "Only audio with a single channel can be loaded. " "Your file was #{self.nchannels}." ) ) ``` -------------------------------- ### Initialize Wav Object Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/audio.html Constructs a Wav object with the provided audio frames and parameters. It inherits from AbstractWav and initializes its internal state. ```python def __init__(self, frames: bytes, params: List): self.frames = frames super(Wav, self).__init__(params) ``` -------------------------------- ### KlattPointTier.__init__ Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/data_classes/klattgrid.html Initializes a new KlattPointTier object. This constructor is used to create instances of the tier. ```APIDOC ## KlattPointTier.__init__ ### Description Initializes a new KlattPointTier object. ### Method (Not specified in source, likely a method call) ### Endpoint (Not applicable for SDK method) ### Parameters (Parameters not explicitly detailed in the source) ### Request Example (Not applicable for SDK method) ### Response (Response details not explicitly detailed in the source) ``` -------------------------------- ### Specify Praatio 4.1 Dependency in setup.py Source: https://github.com/timmahrt/praatio/blob/main/UPGRADING.md If Praatio is a project dependency in setup.py, update the install_requires argument to specify a version compatible with praatio 4.x. ```python install_requires=["praatio ~= 4.1"], ``` -------------------------------- ### Initialize Search Functionality Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/utilities/timit.html Asynchronously loads the search index script and sets up the initial state for the search functionality. It handles potential errors during script loading and calls onInput to display initial results if a search term is present. ```javascript async function initialize() { try { search = await new Promise((resolve, reject) => { const script = document.createElement("script"); script.type = "text/javascript"; script.async = true; script.onload = () => resolve(window.pdocSearch); script.onerror = (e) => reject(e); script.src = "../../search.js"; document.getElementsByTagName("head")\[0\].appendChild(script); }); } catch (e) { console.error("Cannot fetch pdoc search index"); searchErr = "Cannot fetch search index."; } onInput(); document.querySelector("nav.pdoc").addEventListener("click", e => { if (e.target.hash) { searchBox.value = ""; searchBox.dispatchEvent(new Event("input")); } }); } ``` -------------------------------- ### Get Text Representation of Tiers Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/data_classes/klattgrid.html Iterates through all tier names in the container and concatenates their text representations. Use this to get a combined string output of all tiers. ```python def getAsText(self): outputTxt = "" for name in self.tierNameList: outputTxt += self.tierDict[name].getAsText() return outputTxt ``` -------------------------------- ### Get Values in Intervals Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/data_classes/interval_tier.html Retrieves data from a list of time-value tuples that fall within the labeled intervals of the tier. Each interval gets its own list of associated data. ```python def getValuesInIntervals(self, dataTupleList: List) -> List[Tuple[Interval, List]]: """Returns data from dataTupleList contained in labeled intervals Each labeled interval will get its own list of data values. dataTupleList should be of the form: [(time1, value1a, value1b,...), (time2, value2a, value2b...), ...] """ returnList = [] for interval in self.entries: intervalDataList = utils.getValuesInInterval( dataTupleList, interval.start, interval.end ) returnList.append((interval, intervalDataList)) return returnList ``` -------------------------------- ### Search Initialization and Loading Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/textgrid.html Initializes the search functionality by loading the search index script and handling potential errors. Also sets up navigation click listeners. ```javascript let search, searchErr; async function initialize() { try { search = await new Promise((resolve, reject) => { const script = document.createElement("script"); script.type = "text/javascript"; script.async = true; script.onload = () => resolve(window.pdocSearch); script.onerror = (e) => reject(e); script.src = "../search.js"; document.getElementsByTagName("head")\[0\]appendChild(script); }); } catch (e) { console.error("Cannot fetch pdoc search index"); searchErr = "Cannot fetch search index."; } onInput(); document.querySelector("nav.pdoc").addEventListener("click", e => { if (e.target.hash) { searchBox.value = ""; searchBox.dispatchEvent(new Event("input")); } }); } ``` -------------------------------- ### Wav Class Initialization Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/audio.html Initializes a Wav object with audio frames and parameters. The frames are stored as bytes, and the parameters are passed to the superclass constructor. ```APIDOC ## Wav(frames: bytes, params: List) ### Description Initializes a Wav object with audio frames and parameters. The frames are stored as bytes, and the parameters are passed to the superclass constructor. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **frames** (bytes) - The audio frames of the WAV file. * **params** (List) - A list containing the parameters of the WAV file (e.g., number of channels, sample width, frame rate). ``` -------------------------------- ### Retrieving Points in Interval Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/data_classes/data_point.html Returns a list of temporal values (first element of each point tuple) that fall within the specified start and end times. It efficiently iterates through the point list, starting from an optional startIndex. ```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 ``` -------------------------------- ### Initialize Audio Generator Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/audio.html Constructor for the AudioGenerator class. It requires the sample width and frame rate for audio generation. ```python def __init__(self, sampleWidth, frameRate): self.sampleWidth: int = sampleWidth self.frameRate: int = frameRate ``` -------------------------------- ### KlattPointTier Initialization and Timestamp Calculation Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/data_classes/klattgrid.html Initializes a KlattPointTier by processing entries and determining minimum and maximum timestamps. Raises an error if no valid timestamps are found. ```python def __init__(self, name, entries, minT=None, maxT=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) ``` -------------------------------- ### Get Audio Samples by Time Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/audio.html Retrieves audio samples (as integers) from a specified time range. This method first gets the raw frames using getFrames and then converts them into a list of sample integers based on the audio's sample width. ```python def getSamples(self, startTime: float, endTime: float) -> Tuple[int, ...]: frames = self.getFrames(startTime, endTime) audioFrameList = convertFromBytes(frames, self.sampleWidth) return audioFrameList ``` -------------------------------- ### Wav.duration Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/audio.html Gets the total duration of the audio in seconds. ```APIDOC ## duration(self) -> float ### Description Gets the total duration of the audio in seconds. ### Response #### Success Response (200) * **duration** (float) - The duration of the audio in seconds. ``` -------------------------------- ### Search Index Initialization Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/data_classes/textgrid_tier.html Asynchronously loads the search index script ('search.js') and handles potential errors during loading. It also initializes the search functionality and sets up event listeners. ```javascript let search, searchErr; async function initialize() { try { search = await new Promise((resolve, reject) => { const script = document.createElement("script"); script.type = "text/javascript"; script.async = true; script.onload = () => resolve(window.pdocSearch); script.onerror = (e) => reject(e); script.src = "../../search.js"; document.getElementsByTagName("head")[0].appendChild(script); }); } catch (e) { console.error("Cannot fetch pdoc search index"); searchErr = "Cannot fetch search index."; } onInput(); document.querySelector("nav.pdoc").addEventListener("click", e => { if (e.target.hash) { searchBox.value = ""; searchBox.dispatchEvent(new Event("input")); } }); } ``` -------------------------------- ### Create Directory Safely Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/utilities/utils.html Creates a new directory. Unlike os.mkdir, it does not throw an exception if the directory already exists. ```python def makeDir(path: str) -> None: if not os.path.exists(path): os.mkdir(path) ``` -------------------------------- ### Custom Interval NamedTuple with Equality Overloading Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/utilities/constants.html Defines a custom namedtuple 'Interval' with 'start', 'end', and 'label' fields. Includes overloaded equality (__eq__) and inequality (__ne__) methods to compare intervals based on floating-point proximity for start and end times, and exact match for labels. ```python class Interval(namedtuple("Interval", ["start", "end", "label"])): def __eq__(self, other): if not isinstance(other, Interval): return False return ( math.isclose(self.start, other.start) and math.isclose(self.end, other.end) and self.label == other.label ) def __ne__(self, other): return not self == other ``` -------------------------------- ### getErrorReporter Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/utilities/utils.html Gets an appropriate error reporting function based on the specified reporting mode. ```APIDOC ## getErrorReporter(reportingMode: Literal['silence', 'warning', 'error']) ### Description Returns an error reporting function based on the `reportingMode`. Available modes are 'silence' (noop reporter), 'warning' (prints warnings), and 'error' (raises exceptions). ### Method N/A (Python function) ### Parameters - **reportingMode** (Literal['silence', 'warning', 'error']) - The desired reporting mode. ### Response #### Success Response - **errorReporter** (function) - A function that handles error reporting according to the specified mode. ``` -------------------------------- ### KlattPointTier Initialization Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/data_classes/klattgrid.html Initializes a KlattPointTier with a name, a list of entries (time, label pairs), and optional minimum and maximum timestamps. It processes entries to ensure timestamps are floats and determines the overall min/max timestamps for the tier. ```python class KlattPointTier(textgrid_tier.TextgridTier): """ A Klatt tier not contained within another tier """ 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.insert Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/audio.html Inserts new audio frames into the Wav object at a specified start time. ```APIDOC ## insert(self, startTime: float, frames: bytes) -> None ### Description Inserts new audio frames into the Wav object at a specified start time. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **startTime** (float) - The time at which to insert the new frames in seconds. * **frames** (bytes) - The audio frames to insert. ``` -------------------------------- ### KlattPointTier Initialization Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/data_classes/klattgrid.html Initializes a KlattPointTier with a name, a list of entries (time, label pairs), and optional minimum and maximum timestamps. It processes entries to ensure timestamps are floats and determines the overall min/max 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] 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) ``` -------------------------------- ### Create Output Directory Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/praatio_scripts.html Ensures the output directory exists before proceeding. Creates the directory if it does not already exist. ```Python if not os.path.exists(outputPath): os.mkdir(outputPath) ``` -------------------------------- ### Wav.deleteSegment Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/audio.html Deletes a segment of audio from the Wav object specified by start and end times. ```APIDOC ## deleteSegment(self, startTime: float, endTime: float) -> None ### Description Deletes a segment of audio from the Wav object specified by start and end times. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **startTime** (float) - The start time of the segment to delete in seconds. * **endTime** (float) - The end time of the segment to delete in seconds. ``` -------------------------------- ### TextgridTier Length and Iteration Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/data_classes/textgrid_tier.html Provides methods to get the number of entries in the tier and to iterate over the entries. ```python def __len__(self): return len(self._entries) ``` ```python def __iter__(self): for entry in self.entries: yield entry ``` -------------------------------- ### Initialize Search Index and Event Listeners Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/utilities/textgrid_io.html Asynchronously loads the search index script and sets up event listeners for navigation clicks and search input. Initializes the search display if a search term is present on page load. ```javascript let search, searchErr; async function initialize() { try { search = await new Promise((resolve, reject) => { const script = document.createElement("script"); script.type = "text/javascript"; script.async = true; script.onload = () => resolve(window.pdocSearch); script.onerror = (e) => reject(e); script.src = "../../search.js"; document.getElementsByTagName("head")\[0\].appendChild(script); }); } catch (e) { console.error("Cannot fetch pdoc search index"); searchErr = "Cannot fetch search index."; } onInput(); document.querySelector("nav.pdoc").addEventListener("click", e => { if (e.target.hash) { searchBox.value = ""; searchBox.dispatchEvent(new Event("input")); } }); } ``` -------------------------------- ### TextgridTier Length and Iteration Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/data_classes/textgrid_tier.html Provides methods to get the number of entries in the tier and to iterate over its entries. ```python def __len__(self): return len(self._entries) ``` ```python def __iter__(self): for entry in self.entries: yield entry ``` -------------------------------- ### Initialize Search Functionality Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/data_classes/klattgrid.html Asynchronously loads the search script and initializes the search functionality. Handles potential errors during script loading and sets up event listeners for search input and navigation. ```javascript async function initialize() { try { search = await new Promise((resolve, reject) => { const script = document.createElement("script"); script.type = "text/javascript"; script.async = true; script.onload = () => resolve(window.pdocSearch); script.onerror = (e) => reject(e); script.src = "../../search.js"; document.getElementsByTagName("head")[0].appendChild(script); }); } catch (e) { console.error("Cannot fetch pdoc search index"); searchErr = "Cannot fetch search index."; } onInput(); document.querySelector("nav.pdoc").addEventListener("click", e => { if (e.target.hash) { searchBox.value = ""; searchBox.dispatchEvent(new Event("input")); } }); } ``` -------------------------------- ### Find All Substring Occurrences Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/utilities/utils.html Finds the starting indices of all instances of a substring within a larger string. ```python def findAll(txt: str, subStr: str) -> List[int]: indexList = [] index = 0 while True: try: index = txt.index(subStr, index) except ValueError: break indexList.append(int(index)) index += 1 return indexList ``` -------------------------------- ### IntervalTier Initialization Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/data_classes/interval_tier.html Initializes an IntervalTier with a name, a list of intervals, and optional min/max times. It homogenizes and validates the entries. ```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() ``` -------------------------------- ### Wav.getFrames Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/audio.html Retrieves a segment of audio frames from the Wav object within the specified start and end times. ```APIDOC ## Wav.getFrames ### Description Retrieves a segment of audio frames from the Wav object within the specified start and end times. ### Method GET ### Endpoint `/wav/getFrames` (conceptual, as this is a method call) ### Parameters #### Query Parameters - **startTime** (float) - Required - The start time in seconds of the segment to retrieve. - **endTime** (float) - Required - The end time in seconds of the segment to retrieve. ### Response #### Success Response - **frames** (bytes) - The retrieved audio frames. ``` -------------------------------- ### Initialize Search Functionality Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/utilities/constants.html Asynchronously loads the search script and initializes search functionality. Handles potential errors during script loading. ```JavaScript let search, searchErr; async function initialize() { try { search = await new Promise((resolve, reject) => { const script = document.createElement("script"); script.type = "text/javascript"; script.async = true; script.onload = () => resolve(window.pdocSearch); script.onerror = (e) => reject(e); script.src = "../../search.js"; document.getElementsByTagName("head")\[0\]appendChild(script); }); } catch (e) { console.error("Cannot fetch pdoc search index"); searchErr = "Cannot fetch search index."; } onInput(); document.querySelector("nav.pdoc").addEventListener("click", e => { if (e.target.hash) { searchBox.value = ""; searchBox.dispatchEvent(new Event("input")); } }); } if (getSearchTerm()) { initialize(); searchBox.value = getSearchTerm(); onInput(); } else { searchBox.addEventListener("focus", initialize, {once: true}); } ``` -------------------------------- ### Wav.deleteSegment Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/audio.html Deletes a segment of audio frames from the Wav object within the specified start and end times. ```APIDOC ## Wav.deleteSegment ### Description Deletes a segment of audio frames from the Wav object within the specified start and end times. ### Method DELETE (implied by removal of data) ### Endpoint `/wav/deleteSegment` (conceptual, as this is a method call) ### Parameters #### Query Parameters - **startTime** (float) - Required - The start time in seconds of the segment to delete. - **endTime** (float) - Required - The end time in seconds of the segment to delete. ``` -------------------------------- ### Wav.getFrames Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/audio.html Retrieves a segment of audio frames from the Wav object based on the specified start and end times. ```APIDOC ## getFrames(self, startTime: float, endTime: float) -> bytes ### Description Retrieves a segment of audio frames from the Wav object based on the specified start and end times. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **startTime** (float) - The start time of the segment in seconds. * **endTime** (float) - The end time of the segment in seconds. ### Response #### Success Response (200) * **frames** (bytes) - The audio frames within the specified time range. ``` -------------------------------- ### JavaScript Search Initialization and Input Handling Source: https://github.com/timmahrt/praatio/blob/main/docs/praatio/data_classes/textgrid.html Initializes the search functionality by loading the search index and sets up event listeners for search input and window popstate events. Handles displaying search results or loading/error messages. ```javascript function escapeHTML(html) { return document.createElement('div').appendChild(document.createTextNode(html)).parentNode.innerHTML; } const originalContent = document.querySelector("main.pdoc"); let currentContent = originalContent; function setContent(innerHTML) { let elem; if (innerHTML) { elem = document.createElement("main"); elem.classList.add("pdoc"); elem.innerHTML = innerHTML; } else { elem = originalContent; } if (currentContent !== elem) { currentContent.replaceWith(elem); currentContent = elem; } } function getSearchTerm() { return (new URL(window.location)).searchParams.get("search"); } const searchBox = document.querySelector(".pdoc input[type=search]"); searchBox.addEventListener("input", function () { let url = new URL(window.location); if (searchBox.value.trim()) { url.hash = ""; url.searchParams.set("search", searchBox.value); } else { url.searchParams.delete("search"); } history.replaceState("", "", url.toString()); onInput(); }); window.addEventListener("popstate", onInput); let search, searchErr; async function initialize() { try { search = await new Promise((resolve, reject) => { const script = document.createElement("script"); script.type = "text/javascript"; script.async = true; script.onload = () => resolve(window.pdocSearch); script.onerror = (e) => reject(e); script.src = "../../search.js"; document.getElementsByTagName("head")[0].appendChild(script); }); } catch (e) { console.error("Cannot fetch pdoc search index"); searchErr = "Cannot fetch search index."; } onInput(); document.querySelector("nav.pdoc").addEventListener("click", e => { if (e.target.hash) { searchBox.value = ""; searchBox.dispatchEvent(new Event("input")); } }); } function onInput() { setContent((() => { const term = getSearchTerm(); if (!term) { return null } if (searchErr) { return `