repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
tammoippen/iso4217parse
iso4217parse/__init__.py
parse
def parse(v, country_code=None): """Try parse `v` to currencies; filter by country_code If `v` is a number, try `by_code_num()`; otherwise try: 1) if `v` is 3 character uppercase: `by_alpha3()` 2) Exact symbol match: `by_symbol()` 3) Exact country code match: `by_country()` 4) Fuzzy by symbol match heuristic: `by_symbol_match()` Parameters: v: Union[unicode, int] Either a iso4217 numeric code or some string country_code: Optional[unicode] Iso3166 alpha2 country code. Returns: List[Currency]: found Currency objects. """ if isinstance(v, int): res = by_code_num(v) return [] if not res else [res] if not isinstance(v, (str, unicode)): raise ValueError('`v` of incorrect type {}. Only accepts str, bytes, unicode and int.') # check alpha3 if re.match('^[A-Z]{3}$', v): res = by_alpha3(v) if res: return [res] # check by symbol res = by_symbol(v, country_code) if res: return res # check by country code res = by_country(v) if res: return res # more or less fuzzy match by symbol res = by_symbol_match(v, country_code) if res: return res
python
def parse(v, country_code=None): """Try parse `v` to currencies; filter by country_code If `v` is a number, try `by_code_num()`; otherwise try: 1) if `v` is 3 character uppercase: `by_alpha3()` 2) Exact symbol match: `by_symbol()` 3) Exact country code match: `by_country()` 4) Fuzzy by symbol match heuristic: `by_symbol_match()` Parameters: v: Union[unicode, int] Either a iso4217 numeric code or some string country_code: Optional[unicode] Iso3166 alpha2 country code. Returns: List[Currency]: found Currency objects. """ if isinstance(v, int): res = by_code_num(v) return [] if not res else [res] if not isinstance(v, (str, unicode)): raise ValueError('`v` of incorrect type {}. Only accepts str, bytes, unicode and int.') # check alpha3 if re.match('^[A-Z]{3}$', v): res = by_alpha3(v) if res: return [res] # check by symbol res = by_symbol(v, country_code) if res: return res # check by country code res = by_country(v) if res: return res # more or less fuzzy match by symbol res = by_symbol_match(v, country_code) if res: return res
[ "def", "parse", "(", "v", ",", "country_code", "=", "None", ")", ":", "if", "isinstance", "(", "v", ",", "int", ")", ":", "res", "=", "by_code_num", "(", "v", ")", "return", "[", "]", "if", "not", "res", "else", "[", "res", "]", "if", "not", "i...
Try parse `v` to currencies; filter by country_code If `v` is a number, try `by_code_num()`; otherwise try: 1) if `v` is 3 character uppercase: `by_alpha3()` 2) Exact symbol match: `by_symbol()` 3) Exact country code match: `by_country()` 4) Fuzzy by symbol match heuristic: `by_symbol_match()` Parameters: v: Union[unicode, int] Either a iso4217 numeric code or some string country_code: Optional[unicode] Iso3166 alpha2 country code. Returns: List[Currency]: found Currency objects.
[ "Try", "parse", "v", "to", "currencies", ";", "filter", "by", "country_code" ]
dd2971bd66e83424c43d16d6b54b3f6d0c4201cf
https://github.com/tammoippen/iso4217parse/blob/dd2971bd66e83424c43d16d6b54b3f6d0c4201cf/iso4217parse/__init__.py#L233-L275
train
32,600
moremoban/moban
moban/data_loaders/json_loader.py
open_json
def open_json(file_name): """ returns json contents as string """ with open(file_name, "r") as json_data: data = json.load(json_data) return data
python
def open_json(file_name): """ returns json contents as string """ with open(file_name, "r") as json_data: data = json.load(json_data) return data
[ "def", "open_json", "(", "file_name", ")", ":", "with", "open", "(", "file_name", ",", "\"r\"", ")", "as", "json_data", ":", "data", "=", "json", ".", "load", "(", "json_data", ")", "return", "data" ]
returns json contents as string
[ "returns", "json", "contents", "as", "string" ]
5d1674ae461b065a9a54fe89c445cbf6d3cd63c0
https://github.com/moremoban/moban/blob/5d1674ae461b065a9a54fe89c445cbf6d3cd63c0/moban/data_loaders/json_loader.py#L9-L15
train
32,601
moremoban/moban
moban/utils.py
merge
def merge(left, right): """ deep merge dictionary on the left with the one on the right. Fill in left dictionary with right one where the value of the key from the right one in the left one is missing or None. """ if isinstance(left, dict) and isinstance(right, dict): for key, value in right.items(): if key not in left: left[key] = value elif left[key] is None: left[key] = value else: left[key] = merge(left[key], value) return left
python
def merge(left, right): """ deep merge dictionary on the left with the one on the right. Fill in left dictionary with right one where the value of the key from the right one in the left one is missing or None. """ if isinstance(left, dict) and isinstance(right, dict): for key, value in right.items(): if key not in left: left[key] = value elif left[key] is None: left[key] = value else: left[key] = merge(left[key], value) return left
[ "def", "merge", "(", "left", ",", "right", ")", ":", "if", "isinstance", "(", "left", ",", "dict", ")", "and", "isinstance", "(", "right", ",", "dict", ")", ":", "for", "key", ",", "value", "in", "right", ".", "items", "(", ")", ":", "if", "key",...
deep merge dictionary on the left with the one on the right. Fill in left dictionary with right one where the value of the key from the right one in the left one is missing or None.
[ "deep", "merge", "dictionary", "on", "the", "left", "with", "the", "one", "on", "the", "right", "." ]
5d1674ae461b065a9a54fe89c445cbf6d3cd63c0
https://github.com/moremoban/moban/blob/5d1674ae461b065a9a54fe89c445cbf6d3cd63c0/moban/utils.py#L13-L30
train
32,602
smira/txZMQ
txzmq/factory.py
ZmqFactory.shutdown
def shutdown(self): """ Shutdown factory. This is shutting down all created connections and terminating ZeroMQ context. Also cleans up Twisted reactor. """ for connection in self.connections.copy(): connection.shutdown() self.connections = None self.context.term() self.context = None if self.trigger: try: self.reactor.removeSystemEventTrigger(self.trigger) except Exception: pass
python
def shutdown(self): """ Shutdown factory. This is shutting down all created connections and terminating ZeroMQ context. Also cleans up Twisted reactor. """ for connection in self.connections.copy(): connection.shutdown() self.connections = None self.context.term() self.context = None if self.trigger: try: self.reactor.removeSystemEventTrigger(self.trigger) except Exception: pass
[ "def", "shutdown", "(", "self", ")", ":", "for", "connection", "in", "self", ".", "connections", ".", "copy", "(", ")", ":", "connection", ".", "shutdown", "(", ")", "self", ".", "connections", "=", "None", "self", ".", "context", ".", "term", "(", "...
Shutdown factory. This is shutting down all created connections and terminating ZeroMQ context. Also cleans up Twisted reactor.
[ "Shutdown", "factory", "." ]
a2b3caf7884eb68ad952f8db0c07ab5bd88949e7
https://github.com/smira/txZMQ/blob/a2b3caf7884eb68ad952f8db0c07ab5bd88949e7/txzmq/factory.py#L44-L63
train
32,603
smira/txZMQ
txzmq/pubsub.py
ZmqPubConnection.publish
def publish(self, message, tag=b''): """ Publish `message` with specified `tag`. :param message: message data :type message: str :param tag: message tag :type tag: str """ self.send(tag + b'\0' + message)
python
def publish(self, message, tag=b''): """ Publish `message` with specified `tag`. :param message: message data :type message: str :param tag: message tag :type tag: str """ self.send(tag + b'\0' + message)
[ "def", "publish", "(", "self", ",", "message", ",", "tag", "=", "b''", ")", ":", "self", ".", "send", "(", "tag", "+", "b'\\0'", "+", "message", ")" ]
Publish `message` with specified `tag`. :param message: message data :type message: str :param tag: message tag :type tag: str
[ "Publish", "message", "with", "specified", "tag", "." ]
a2b3caf7884eb68ad952f8db0c07ab5bd88949e7
https://github.com/smira/txZMQ/blob/a2b3caf7884eb68ad952f8db0c07ab5bd88949e7/txzmq/pubsub.py#L17-L26
train
32,604
smira/txZMQ
txzmq/req_rep.py
ZmqREQConnection._getNextId
def _getNextId(self): """ Returns an unique id. By default, generates pool of UUID in increments of ``UUID_POOL_GEN_SIZE``. Could be overridden to provide custom ID generation. :return: generated unique "on the wire" message ID :rtype: str """ if not self._uuids: for _ in range(self.UUID_POOL_GEN_SIZE): self._uuids.append(uuid.uuid4().bytes) return self._uuids.pop()
python
def _getNextId(self): """ Returns an unique id. By default, generates pool of UUID in increments of ``UUID_POOL_GEN_SIZE``. Could be overridden to provide custom ID generation. :return: generated unique "on the wire" message ID :rtype: str """ if not self._uuids: for _ in range(self.UUID_POOL_GEN_SIZE): self._uuids.append(uuid.uuid4().bytes) return self._uuids.pop()
[ "def", "_getNextId", "(", "self", ")", ":", "if", "not", "self", ".", "_uuids", ":", "for", "_", "in", "range", "(", "self", ".", "UUID_POOL_GEN_SIZE", ")", ":", "self", ".", "_uuids", ".", "append", "(", "uuid", ".", "uuid4", "(", ")", ".", "bytes...
Returns an unique id. By default, generates pool of UUID in increments of ``UUID_POOL_GEN_SIZE``. Could be overridden to provide custom ID generation. :return: generated unique "on the wire" message ID :rtype: str
[ "Returns", "an", "unique", "id", "." ]
a2b3caf7884eb68ad952f8db0c07ab5bd88949e7
https://github.com/smira/txZMQ/blob/a2b3caf7884eb68ad952f8db0c07ab5bd88949e7/txzmq/req_rep.py#L48-L62
train
32,605
smira/txZMQ
txzmq/req_rep.py
ZmqREQConnection._releaseId
def _releaseId(self, msgId): """ Release message ID to the pool. @param msgId: message ID, no longer on the wire @type msgId: C{str} """ self._uuids.append(msgId) if len(self._uuids) > 2 * self.UUID_POOL_GEN_SIZE: self._uuids[-self.UUID_POOL_GEN_SIZE:] = []
python
def _releaseId(self, msgId): """ Release message ID to the pool. @param msgId: message ID, no longer on the wire @type msgId: C{str} """ self._uuids.append(msgId) if len(self._uuids) > 2 * self.UUID_POOL_GEN_SIZE: self._uuids[-self.UUID_POOL_GEN_SIZE:] = []
[ "def", "_releaseId", "(", "self", ",", "msgId", ")", ":", "self", ".", "_uuids", ".", "append", "(", "msgId", ")", "if", "len", "(", "self", ".", "_uuids", ")", ">", "2", "*", "self", ".", "UUID_POOL_GEN_SIZE", ":", "self", ".", "_uuids", "[", "-",...
Release message ID to the pool. @param msgId: message ID, no longer on the wire @type msgId: C{str}
[ "Release", "message", "ID", "to", "the", "pool", "." ]
a2b3caf7884eb68ad952f8db0c07ab5bd88949e7
https://github.com/smira/txZMQ/blob/a2b3caf7884eb68ad952f8db0c07ab5bd88949e7/txzmq/req_rep.py#L64-L73
train
32,606
smira/txZMQ
txzmq/req_rep.py
ZmqREQConnection._cancel
def _cancel(self, msgId): """ Cancel outstanding REQ, drop reply silently. @param msgId: message ID to cancel @type msgId: C{str} """ _, canceller = self._requests.pop(msgId, (None, None)) if canceller is not None and canceller.active(): canceller.cancel()
python
def _cancel(self, msgId): """ Cancel outstanding REQ, drop reply silently. @param msgId: message ID to cancel @type msgId: C{str} """ _, canceller = self._requests.pop(msgId, (None, None)) if canceller is not None and canceller.active(): canceller.cancel()
[ "def", "_cancel", "(", "self", ",", "msgId", ")", ":", "_", ",", "canceller", "=", "self", ".", "_requests", ".", "pop", "(", "msgId", ",", "(", "None", ",", "None", ")", ")", "if", "canceller", "is", "not", "None", "and", "canceller", ".", "active...
Cancel outstanding REQ, drop reply silently. @param msgId: message ID to cancel @type msgId: C{str}
[ "Cancel", "outstanding", "REQ", "drop", "reply", "silently", "." ]
a2b3caf7884eb68ad952f8db0c07ab5bd88949e7
https://github.com/smira/txZMQ/blob/a2b3caf7884eb68ad952f8db0c07ab5bd88949e7/txzmq/req_rep.py#L75-L85
train
32,607
smira/txZMQ
txzmq/req_rep.py
ZmqREQConnection._timeoutRequest
def _timeoutRequest(self, msgId): """ Cancel timedout request. @param msgId: message ID to cancel @type msgId: C{str} """ d, _ = self._requests.pop(msgId, (None, None)) if not d.called: d.errback(ZmqRequestTimeoutError(msgId))
python
def _timeoutRequest(self, msgId): """ Cancel timedout request. @param msgId: message ID to cancel @type msgId: C{str} """ d, _ = self._requests.pop(msgId, (None, None)) if not d.called: d.errback(ZmqRequestTimeoutError(msgId))
[ "def", "_timeoutRequest", "(", "self", ",", "msgId", ")", ":", "d", ",", "_", "=", "self", ".", "_requests", ".", "pop", "(", "msgId", ",", "(", "None", ",", "None", ")", ")", "if", "not", "d", ".", "called", ":", "d", ".", "errback", "(", "Zmq...
Cancel timedout request. @param msgId: message ID to cancel @type msgId: C{str}
[ "Cancel", "timedout", "request", "." ]
a2b3caf7884eb68ad952f8db0c07ab5bd88949e7
https://github.com/smira/txZMQ/blob/a2b3caf7884eb68ad952f8db0c07ab5bd88949e7/txzmq/req_rep.py#L87-L95
train
32,608
smira/txZMQ
txzmq/req_rep.py
ZmqREQConnection.sendMsg
def sendMsg(self, *messageParts, **kwargs): """ Send request and deliver response back when available. :param messageParts: message data :type messageParts: tuple :param timeout: as keyword argument, timeout on request :type timeout: float :return: Deferred that will fire when response comes back """ messageId = self._getNextId() d = defer.Deferred(canceller=lambda _: self._cancel(messageId)) timeout = kwargs.pop('timeout', None) if timeout is None: timeout = self.defaultRequestTimeout assert len(kwargs) == 0, "Unsupported keyword argument" canceller = None if timeout is not None: canceller = reactor.callLater(timeout, self._timeoutRequest, messageId) self._requests[messageId] = (d, canceller) self.send([messageId, b''] + list(messageParts)) return d
python
def sendMsg(self, *messageParts, **kwargs): """ Send request and deliver response back when available. :param messageParts: message data :type messageParts: tuple :param timeout: as keyword argument, timeout on request :type timeout: float :return: Deferred that will fire when response comes back """ messageId = self._getNextId() d = defer.Deferred(canceller=lambda _: self._cancel(messageId)) timeout = kwargs.pop('timeout', None) if timeout is None: timeout = self.defaultRequestTimeout assert len(kwargs) == 0, "Unsupported keyword argument" canceller = None if timeout is not None: canceller = reactor.callLater(timeout, self._timeoutRequest, messageId) self._requests[messageId] = (d, canceller) self.send([messageId, b''] + list(messageParts)) return d
[ "def", "sendMsg", "(", "self", ",", "*", "messageParts", ",", "*", "*", "kwargs", ")", ":", "messageId", "=", "self", ".", "_getNextId", "(", ")", "d", "=", "defer", ".", "Deferred", "(", "canceller", "=", "lambda", "_", ":", "self", ".", "_cancel", ...
Send request and deliver response back when available. :param messageParts: message data :type messageParts: tuple :param timeout: as keyword argument, timeout on request :type timeout: float :return: Deferred that will fire when response comes back
[ "Send", "request", "and", "deliver", "response", "back", "when", "available", "." ]
a2b3caf7884eb68ad952f8db0c07ab5bd88949e7
https://github.com/smira/txZMQ/blob/a2b3caf7884eb68ad952f8db0c07ab5bd88949e7/txzmq/req_rep.py#L97-L122
train
32,609
smira/txZMQ
txzmq/req_rep.py
ZmqREPConnection.reply
def reply(self, messageId, *messageParts): """ Send reply to request with specified ``messageId``. :param messageId: message uuid :type messageId: str :param messageParts: message data :type messageParts: list """ routingInfo = self._routingInfo.pop(messageId) self.send(routingInfo + [messageId, b''] + list(messageParts))
python
def reply(self, messageId, *messageParts): """ Send reply to request with specified ``messageId``. :param messageId: message uuid :type messageId: str :param messageParts: message data :type messageParts: list """ routingInfo = self._routingInfo.pop(messageId) self.send(routingInfo + [messageId, b''] + list(messageParts))
[ "def", "reply", "(", "self", ",", "messageId", ",", "*", "messageParts", ")", ":", "routingInfo", "=", "self", ".", "_routingInfo", ".", "pop", "(", "messageId", ")", "self", ".", "send", "(", "routingInfo", "+", "[", "messageId", ",", "b''", "]", "+",...
Send reply to request with specified ``messageId``. :param messageId: message uuid :type messageId: str :param messageParts: message data :type messageParts: list
[ "Send", "reply", "to", "request", "with", "specified", "messageId", "." ]
a2b3caf7884eb68ad952f8db0c07ab5bd88949e7
https://github.com/smira/txZMQ/blob/a2b3caf7884eb68ad952f8db0c07ab5bd88949e7/txzmq/req_rep.py#L159-L169
train
32,610
ynop/audiomate
audiomate/corpus/io/base.py
CorpusReader.load
def load(self, path): """ Load and return the corpus from the given path. Args: path (str): Path to the data set to load. Returns: Corpus: The loaded corpus Raises: IOError: When the data set is invalid, for example because required files (annotations, …) are missing. """ # Check for missing files missing_files = self._check_for_missing_files(path) if len(missing_files) > 0: raise IOError('Invalid data set of type {}: files {} not found at {}'.format( self.type(), ' '.join(missing_files), path)) return self._load(path)
python
def load(self, path): """ Load and return the corpus from the given path. Args: path (str): Path to the data set to load. Returns: Corpus: The loaded corpus Raises: IOError: When the data set is invalid, for example because required files (annotations, …) are missing. """ # Check for missing files missing_files = self._check_for_missing_files(path) if len(missing_files) > 0: raise IOError('Invalid data set of type {}: files {} not found at {}'.format( self.type(), ' '.join(missing_files), path)) return self._load(path)
[ "def", "load", "(", "self", ",", "path", ")", ":", "# Check for missing files", "missing_files", "=", "self", ".", "_check_for_missing_files", "(", "path", ")", "if", "len", "(", "missing_files", ")", ">", "0", ":", "raise", "IOError", "(", "'Invalid data set ...
Load and return the corpus from the given path. Args: path (str): Path to the data set to load. Returns: Corpus: The loaded corpus Raises: IOError: When the data set is invalid, for example because required files (annotations, …) are missing.
[ "Load", "and", "return", "the", "corpus", "from", "the", "given", "path", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/io/base.py#L61-L81
train
32,611
ynop/audiomate
audiomate/corpus/io/tuda.py
TudaReader.get_ids_from_folder
def get_ids_from_folder(path, part_name): """ Return all ids from the given folder, which have a corresponding beamformedSignal file. """ valid_ids = set({}) for xml_file in glob.glob(os.path.join(path, '*.xml')): idx = os.path.splitext(os.path.basename(xml_file))[0] if idx not in BAD_FILES[part_name]: valid_ids.add(idx) return valid_ids
python
def get_ids_from_folder(path, part_name): """ Return all ids from the given folder, which have a corresponding beamformedSignal file. """ valid_ids = set({}) for xml_file in glob.glob(os.path.join(path, '*.xml')): idx = os.path.splitext(os.path.basename(xml_file))[0] if idx not in BAD_FILES[part_name]: valid_ids.add(idx) return valid_ids
[ "def", "get_ids_from_folder", "(", "path", ",", "part_name", ")", ":", "valid_ids", "=", "set", "(", "{", "}", ")", "for", "xml_file", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "path", ",", "'*.xml'", ")", ")", ":", "idx"...
Return all ids from the given folder, which have a corresponding beamformedSignal file.
[ "Return", "all", "ids", "from", "the", "given", "folder", "which", "have", "a", "corresponding", "beamformedSignal", "file", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/io/tuda.py#L152-L164
train
32,612
ynop/audiomate
audiomate/corpus/io/tuda.py
TudaReader.load_file
def load_file(folder_path, idx, corpus): """ Load speaker, file, utterance, labels for the file with the given id. """ xml_path = os.path.join(folder_path, '{}.xml'.format(idx)) wav_paths = glob.glob(os.path.join(folder_path, '{}_*.wav'.format(idx))) if len(wav_paths) == 0: return [] xml_file = open(xml_path, 'r', encoding='utf-8') soup = BeautifulSoup(xml_file, 'lxml') transcription = soup.recording.cleaned_sentence.string transcription_raw = soup.recording.sentence.string gender = soup.recording.gender.string is_native = soup.recording.muttersprachler.string age_class = soup.recording.ageclass.string speaker_idx = soup.recording.speaker_id.string if speaker_idx not in corpus.issuers.keys(): start_age_class = int(age_class.split('-')[0]) if start_age_class < 12: age_group = issuers.AgeGroup.CHILD elif start_age_class < 18: age_group = issuers.AgeGroup.YOUTH elif start_age_class < 65: age_group = issuers.AgeGroup.ADULT else: age_group = issuers.AgeGroup.SENIOR native_lang = None if is_native == 'Ja': native_lang = 'deu' issuer = issuers.Speaker(speaker_idx, gender=issuers.Gender(gender), age_group=age_group, native_language=native_lang) corpus.import_issuers(issuer) utt_ids = [] for wav_path in wav_paths: wav_name = os.path.split(wav_path)[1] wav_idx = os.path.splitext(wav_name)[0] corpus.new_file(wav_path, wav_idx) utt = corpus.new_utterance(wav_idx, wav_idx, speaker_idx) utt.set_label_list(annotations.LabelList.create_single( transcription, idx=audiomate.corpus.LL_WORD_TRANSCRIPT )) utt.set_label_list(annotations.LabelList.create_single( transcription_raw, idx=audiomate.corpus.LL_WORD_TRANSCRIPT_RAW )) utt_ids.append(wav_idx) return utt_ids
python
def load_file(folder_path, idx, corpus): """ Load speaker, file, utterance, labels for the file with the given id. """ xml_path = os.path.join(folder_path, '{}.xml'.format(idx)) wav_paths = glob.glob(os.path.join(folder_path, '{}_*.wav'.format(idx))) if len(wav_paths) == 0: return [] xml_file = open(xml_path, 'r', encoding='utf-8') soup = BeautifulSoup(xml_file, 'lxml') transcription = soup.recording.cleaned_sentence.string transcription_raw = soup.recording.sentence.string gender = soup.recording.gender.string is_native = soup.recording.muttersprachler.string age_class = soup.recording.ageclass.string speaker_idx = soup.recording.speaker_id.string if speaker_idx not in corpus.issuers.keys(): start_age_class = int(age_class.split('-')[0]) if start_age_class < 12: age_group = issuers.AgeGroup.CHILD elif start_age_class < 18: age_group = issuers.AgeGroup.YOUTH elif start_age_class < 65: age_group = issuers.AgeGroup.ADULT else: age_group = issuers.AgeGroup.SENIOR native_lang = None if is_native == 'Ja': native_lang = 'deu' issuer = issuers.Speaker(speaker_idx, gender=issuers.Gender(gender), age_group=age_group, native_language=native_lang) corpus.import_issuers(issuer) utt_ids = [] for wav_path in wav_paths: wav_name = os.path.split(wav_path)[1] wav_idx = os.path.splitext(wav_name)[0] corpus.new_file(wav_path, wav_idx) utt = corpus.new_utterance(wav_idx, wav_idx, speaker_idx) utt.set_label_list(annotations.LabelList.create_single( transcription, idx=audiomate.corpus.LL_WORD_TRANSCRIPT )) utt.set_label_list(annotations.LabelList.create_single( transcription_raw, idx=audiomate.corpus.LL_WORD_TRANSCRIPT_RAW )) utt_ids.append(wav_idx) return utt_ids
[ "def", "load_file", "(", "folder_path", ",", "idx", ",", "corpus", ")", ":", "xml_path", "=", "os", ".", "path", ".", "join", "(", "folder_path", ",", "'{}.xml'", ".", "format", "(", "idx", ")", ")", "wav_paths", "=", "glob", ".", "glob", "(", "os", ...
Load speaker, file, utterance, labels for the file with the given id.
[ "Load", "speaker", "file", "utterance", "labels", "for", "the", "file", "with", "the", "given", "id", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/io/tuda.py#L167-L227
train
32,613
ynop/audiomate
audiomate/formats/ctm.py
read_file
def read_file(path): """ Reads a ctm file. Args: path (str): Path to the file Returns: (dict): Dictionary with entries. Example:: >>> read_file('/path/to/file.txt') { 'wave-ab': [ ['1', 0.00, 0.07, 'HI', 1], ['1', 0.09, 0.08, 'AH', 1] ], 'wave-xy': [ ['1', 0.00, 0.07, 'HI', 1], ['1', 0.09, 0.08, 'AH', 1] ] } """ gen = textfile.read_separated_lines_generator(path, max_columns=6, ignore_lines_starting_with=[';;']) utterances = collections.defaultdict(list) for record in gen: values = record[1:len(record)] for i in range(len(values)): if i == 1 or i == 2 or i == 4: values[i] = float(values[i]) utterances[record[0]].append(values) return utterances
python
def read_file(path): """ Reads a ctm file. Args: path (str): Path to the file Returns: (dict): Dictionary with entries. Example:: >>> read_file('/path/to/file.txt') { 'wave-ab': [ ['1', 0.00, 0.07, 'HI', 1], ['1', 0.09, 0.08, 'AH', 1] ], 'wave-xy': [ ['1', 0.00, 0.07, 'HI', 1], ['1', 0.09, 0.08, 'AH', 1] ] } """ gen = textfile.read_separated_lines_generator(path, max_columns=6, ignore_lines_starting_with=[';;']) utterances = collections.defaultdict(list) for record in gen: values = record[1:len(record)] for i in range(len(values)): if i == 1 or i == 2 or i == 4: values[i] = float(values[i]) utterances[record[0]].append(values) return utterances
[ "def", "read_file", "(", "path", ")", ":", "gen", "=", "textfile", ".", "read_separated_lines_generator", "(", "path", ",", "max_columns", "=", "6", ",", "ignore_lines_starting_with", "=", "[", "';;'", "]", ")", "utterances", "=", "collections", ".", "defaultd...
Reads a ctm file. Args: path (str): Path to the file Returns: (dict): Dictionary with entries. Example:: >>> read_file('/path/to/file.txt') { 'wave-ab': [ ['1', 0.00, 0.07, 'HI', 1], ['1', 0.09, 0.08, 'AH', 1] ], 'wave-xy': [ ['1', 0.00, 0.07, 'HI', 1], ['1', 0.09, 0.08, 'AH', 1] ] }
[ "Reads", "a", "ctm", "file", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/formats/ctm.py#L28-L66
train
32,614
ynop/audiomate
audiomate/corpus/subset/utils.py
split_identifiers
def split_identifiers(identifiers=[], proportions={}): """ Split the given identifiers by the given proportions. Args: identifiers (list): List of identifiers (str). proportions (dict): A dictionary containing the proportions with the identifier from the input as key. Returns: dict: Dictionary containing a list of identifiers per part with the same key as the proportions dict. Example:: >>> split_identifiers( >>> identifiers=['a', 'b', 'c', 'd'], >>> proportions={'melvin' : 0.5, 'timmy' : 0.5} >>> ) {'melvin' : ['a', 'c'], 'timmy' : ['b', 'd']} """ abs_proportions = absolute_proportions(proportions, len(identifiers)) parts = {} start_index = 0 for idx, proportion in abs_proportions.items(): parts[idx] = identifiers[start_index:start_index + proportion] start_index += proportion return parts
python
def split_identifiers(identifiers=[], proportions={}): """ Split the given identifiers by the given proportions. Args: identifiers (list): List of identifiers (str). proportions (dict): A dictionary containing the proportions with the identifier from the input as key. Returns: dict: Dictionary containing a list of identifiers per part with the same key as the proportions dict. Example:: >>> split_identifiers( >>> identifiers=['a', 'b', 'c', 'd'], >>> proportions={'melvin' : 0.5, 'timmy' : 0.5} >>> ) {'melvin' : ['a', 'c'], 'timmy' : ['b', 'd']} """ abs_proportions = absolute_proportions(proportions, len(identifiers)) parts = {} start_index = 0 for idx, proportion in abs_proportions.items(): parts[idx] = identifiers[start_index:start_index + proportion] start_index += proportion return parts
[ "def", "split_identifiers", "(", "identifiers", "=", "[", "]", ",", "proportions", "=", "{", "}", ")", ":", "abs_proportions", "=", "absolute_proportions", "(", "proportions", ",", "len", "(", "identifiers", ")", ")", "parts", "=", "{", "}", "start_index", ...
Split the given identifiers by the given proportions. Args: identifiers (list): List of identifiers (str). proportions (dict): A dictionary containing the proportions with the identifier from the input as key. Returns: dict: Dictionary containing a list of identifiers per part with the same key as the proportions dict. Example:: >>> split_identifiers( >>> identifiers=['a', 'b', 'c', 'd'], >>> proportions={'melvin' : 0.5, 'timmy' : 0.5} >>> ) {'melvin' : ['a', 'c'], 'timmy' : ['b', 'd']}
[ "Split", "the", "given", "identifiers", "by", "the", "given", "proportions", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/subset/utils.py#L41-L72
train
32,615
ynop/audiomate
audiomate/corpus/subset/utils.py
select_balanced_subset
def select_balanced_subset(items, select_count, categories, select_count_values=None, seed=None): """ Select items so the summed category weights are balanced. Each item has a dictionary containing the category weights. Items are selected until ``select_count`` is reached. The value that is added to ``select_count`` for an item can be defined in the dictionary ``select_count_values``. If this is not defined it is assumed to be 1, which means `select_count` items are selected. Args: items (dict): Dictionary containing items with category weights. select_count (float): Value to reach for selected items. categories (list): List of all categories. select_count_values (dict): The select_count values to be used. For example an utterance with multiple labels: The category weights (label-lengths) are used for balance, but the utterance-duration is used for reaching the select_count. Returns: list: List of item ids, containing ``number_of_items`` (or ``len(items)`` if smaller). Example: >>> items = { >>> 'utt-1' : {'m': 1, 's': 0, 'n': 0}, >>> 'utt-2' : {'m': 0, 's': 2, 'n': 1}, >>> ... >>> } >>> select_balanced_subset(items, 5) >>> ['utt-1', 'utt-3', 'utt-9', 'utt-33', 'utt-34'] """ rand = random.Random() rand.seed(seed) if select_count_values is None: select_count_values = {item_id: 1 for item_id in items.keys()} if sum(select_count_values.values()) < select_count: return list(items.keys()) available_item_ids = sorted(list(items.keys())) weight_per_category = np.zeros(len(categories)) selected_item_ids = [] available_item_weights = [] current_select_count = 0 rand.shuffle(available_item_ids) # Create dict with weights as vectors for item_id in available_item_ids: weights = items[item_id] all_weights = np.zeros(len(categories)) for category, weight in weights.items(): all_weights[categories.index(category)] = float(weight) available_item_weights.append(all_weights) # Always add best next item while current_select_count < select_count: best_item_index = 0 best_item_id = None best_item_dist = float('inf') current_item_index = 0 while current_item_index < len(available_item_ids) and best_item_dist > 0: item_id = available_item_ids[current_item_index] item_weights = available_item_weights[current_item_index] temp_total_weights = weight_per_category + item_weights dist = temp_total_weights.var() if dist < best_item_dist: best_item_index = current_item_index best_item_dist = dist best_item_id = item_id current_item_index += 1 weight_per_category += available_item_weights[best_item_index] selected_item_ids.append(best_item_id) del available_item_ids[best_item_index] del available_item_weights[best_item_index] current_select_count += select_count_values[best_item_id] return selected_item_ids
python
def select_balanced_subset(items, select_count, categories, select_count_values=None, seed=None): """ Select items so the summed category weights are balanced. Each item has a dictionary containing the category weights. Items are selected until ``select_count`` is reached. The value that is added to ``select_count`` for an item can be defined in the dictionary ``select_count_values``. If this is not defined it is assumed to be 1, which means `select_count` items are selected. Args: items (dict): Dictionary containing items with category weights. select_count (float): Value to reach for selected items. categories (list): List of all categories. select_count_values (dict): The select_count values to be used. For example an utterance with multiple labels: The category weights (label-lengths) are used for balance, but the utterance-duration is used for reaching the select_count. Returns: list: List of item ids, containing ``number_of_items`` (or ``len(items)`` if smaller). Example: >>> items = { >>> 'utt-1' : {'m': 1, 's': 0, 'n': 0}, >>> 'utt-2' : {'m': 0, 's': 2, 'n': 1}, >>> ... >>> } >>> select_balanced_subset(items, 5) >>> ['utt-1', 'utt-3', 'utt-9', 'utt-33', 'utt-34'] """ rand = random.Random() rand.seed(seed) if select_count_values is None: select_count_values = {item_id: 1 for item_id in items.keys()} if sum(select_count_values.values()) < select_count: return list(items.keys()) available_item_ids = sorted(list(items.keys())) weight_per_category = np.zeros(len(categories)) selected_item_ids = [] available_item_weights = [] current_select_count = 0 rand.shuffle(available_item_ids) # Create dict with weights as vectors for item_id in available_item_ids: weights = items[item_id] all_weights = np.zeros(len(categories)) for category, weight in weights.items(): all_weights[categories.index(category)] = float(weight) available_item_weights.append(all_weights) # Always add best next item while current_select_count < select_count: best_item_index = 0 best_item_id = None best_item_dist = float('inf') current_item_index = 0 while current_item_index < len(available_item_ids) and best_item_dist > 0: item_id = available_item_ids[current_item_index] item_weights = available_item_weights[current_item_index] temp_total_weights = weight_per_category + item_weights dist = temp_total_weights.var() if dist < best_item_dist: best_item_index = current_item_index best_item_dist = dist best_item_id = item_id current_item_index += 1 weight_per_category += available_item_weights[best_item_index] selected_item_ids.append(best_item_id) del available_item_ids[best_item_index] del available_item_weights[best_item_index] current_select_count += select_count_values[best_item_id] return selected_item_ids
[ "def", "select_balanced_subset", "(", "items", ",", "select_count", ",", "categories", ",", "select_count_values", "=", "None", ",", "seed", "=", "None", ")", ":", "rand", "=", "random", ".", "Random", "(", ")", "rand", ".", "seed", "(", "seed", ")", "if...
Select items so the summed category weights are balanced. Each item has a dictionary containing the category weights. Items are selected until ``select_count`` is reached. The value that is added to ``select_count`` for an item can be defined in the dictionary ``select_count_values``. If this is not defined it is assumed to be 1, which means `select_count` items are selected. Args: items (dict): Dictionary containing items with category weights. select_count (float): Value to reach for selected items. categories (list): List of all categories. select_count_values (dict): The select_count values to be used. For example an utterance with multiple labels: The category weights (label-lengths) are used for balance, but the utterance-duration is used for reaching the select_count. Returns: list: List of item ids, containing ``number_of_items`` (or ``len(items)`` if smaller). Example: >>> items = { >>> 'utt-1' : {'m': 1, 's': 0, 'n': 0}, >>> 'utt-2' : {'m': 0, 's': 2, 'n': 1}, >>> ... >>> } >>> select_balanced_subset(items, 5) >>> ['utt-1', 'utt-3', 'utt-9', 'utt-33', 'utt-34']
[ "Select", "items", "so", "the", "summed", "category", "weights", "are", "balanced", ".", "Each", "item", "has", "a", "dictionary", "containing", "the", "category", "weights", ".", "Items", "are", "selected", "until", "select_count", "is", "reached", ".", "The"...
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/subset/utils.py#L176-L260
train
32,616
ynop/audiomate
audiomate/utils/misc.py
length_of_overlap
def length_of_overlap(first_start, first_end, second_start, second_end): """ Find the length of the overlapping part of two segments. Args: first_start (float): Start of the first segment. first_end (float): End of the first segment. second_start (float): Start of the second segment. second_end (float): End of the second segment. Return: float: The amount of overlap or 0 if they don't overlap at all. """ if first_end <= second_start or first_start >= second_end: return 0.0 if first_start < second_start: if first_end < second_end: return abs(first_end - second_start) else: return abs(second_end - second_start) if first_start > second_start: if first_end > second_end: return abs(second_end - first_start) else: return abs(first_end - first_start)
python
def length_of_overlap(first_start, first_end, second_start, second_end): """ Find the length of the overlapping part of two segments. Args: first_start (float): Start of the first segment. first_end (float): End of the first segment. second_start (float): Start of the second segment. second_end (float): End of the second segment. Return: float: The amount of overlap or 0 if they don't overlap at all. """ if first_end <= second_start or first_start >= second_end: return 0.0 if first_start < second_start: if first_end < second_end: return abs(first_end - second_start) else: return abs(second_end - second_start) if first_start > second_start: if first_end > second_end: return abs(second_end - first_start) else: return abs(first_end - first_start)
[ "def", "length_of_overlap", "(", "first_start", ",", "first_end", ",", "second_start", ",", "second_end", ")", ":", "if", "first_end", "<=", "second_start", "or", "first_start", ">=", "second_end", ":", "return", "0.0", "if", "first_start", "<", "second_start", ...
Find the length of the overlapping part of two segments. Args: first_start (float): Start of the first segment. first_end (float): End of the first segment. second_start (float): Start of the second segment. second_end (float): End of the second segment. Return: float: The amount of overlap or 0 if they don't overlap at all.
[ "Find", "the", "length", "of", "the", "overlapping", "part", "of", "two", "segments", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/utils/misc.py#L1-L27
train
32,617
ynop/audiomate
audiomate/annotations/relabeling.py
find_missing_projections
def find_missing_projections(label_list, projections): """ Finds all combinations of labels in `label_list` that are not covered by an entry in the dictionary of `projections`. Returns a list containing tuples of uncovered label combinations or en empty list if there are none. All uncovered label combinations are naturally sorted. Each entry in the dictionary of projections represents a single projection that maps a combination of labels (key) to a single new label (value). The combination of labels to be mapped is a tuple of naturally sorted labels that apply to one or more segments simultaneously. By defining a special wildcard projection using `('**',)` is is not required to specify a projection for every single combination of labels. Args: label_list (audiomate.annotations.LabelList): The label list to relabel projections (dict): A dictionary that maps tuples of label combinations to string labels. Returns: List: List of combinations of labels that are not covered by any projection Example: >>> ll = annotations.LabelList(labels=[ ... annotations.Label('b', 3.2, 4.5), ... annotations.Label('a', 4.0, 4.9), ... annotations.Label('c', 4.2, 5.1) ... ]) >>> find_missing_projections(ll, {('b',): 'new_label'}) [('a', 'b'), ('a', 'b', 'c'), ('a', 'c'), ('c',)] """ unmapped_combinations = set() if WILDCARD_COMBINATION in projections: return [] for labeled_segment in label_list.ranges(): combination = tuple(sorted([label.value for label in labeled_segment[2]])) if combination not in projections: unmapped_combinations.add(combination) return sorted(unmapped_combinations)
python
def find_missing_projections(label_list, projections): """ Finds all combinations of labels in `label_list` that are not covered by an entry in the dictionary of `projections`. Returns a list containing tuples of uncovered label combinations or en empty list if there are none. All uncovered label combinations are naturally sorted. Each entry in the dictionary of projections represents a single projection that maps a combination of labels (key) to a single new label (value). The combination of labels to be mapped is a tuple of naturally sorted labels that apply to one or more segments simultaneously. By defining a special wildcard projection using `('**',)` is is not required to specify a projection for every single combination of labels. Args: label_list (audiomate.annotations.LabelList): The label list to relabel projections (dict): A dictionary that maps tuples of label combinations to string labels. Returns: List: List of combinations of labels that are not covered by any projection Example: >>> ll = annotations.LabelList(labels=[ ... annotations.Label('b', 3.2, 4.5), ... annotations.Label('a', 4.0, 4.9), ... annotations.Label('c', 4.2, 5.1) ... ]) >>> find_missing_projections(ll, {('b',): 'new_label'}) [('a', 'b'), ('a', 'b', 'c'), ('a', 'c'), ('c',)] """ unmapped_combinations = set() if WILDCARD_COMBINATION in projections: return [] for labeled_segment in label_list.ranges(): combination = tuple(sorted([label.value for label in labeled_segment[2]])) if combination not in projections: unmapped_combinations.add(combination) return sorted(unmapped_combinations)
[ "def", "find_missing_projections", "(", "label_list", ",", "projections", ")", ":", "unmapped_combinations", "=", "set", "(", ")", "if", "WILDCARD_COMBINATION", "in", "projections", ":", "return", "[", "]", "for", "labeled_segment", "in", "label_list", ".", "range...
Finds all combinations of labels in `label_list` that are not covered by an entry in the dictionary of `projections`. Returns a list containing tuples of uncovered label combinations or en empty list if there are none. All uncovered label combinations are naturally sorted. Each entry in the dictionary of projections represents a single projection that maps a combination of labels (key) to a single new label (value). The combination of labels to be mapped is a tuple of naturally sorted labels that apply to one or more segments simultaneously. By defining a special wildcard projection using `('**',)` is is not required to specify a projection for every single combination of labels. Args: label_list (audiomate.annotations.LabelList): The label list to relabel projections (dict): A dictionary that maps tuples of label combinations to string labels. Returns: List: List of combinations of labels that are not covered by any projection Example: >>> ll = annotations.LabelList(labels=[ ... annotations.Label('b', 3.2, 4.5), ... annotations.Label('a', 4.0, 4.9), ... annotations.Label('c', 4.2, 5.1) ... ]) >>> find_missing_projections(ll, {('b',): 'new_label'}) [('a', 'b'), ('a', 'b', 'c'), ('a', 'c'), ('c',)]
[ "Finds", "all", "combinations", "of", "labels", "in", "label_list", "that", "are", "not", "covered", "by", "an", "entry", "in", "the", "dictionary", "of", "projections", ".", "Returns", "a", "list", "containing", "tuples", "of", "uncovered", "label", "combinat...
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/annotations/relabeling.py#L71-L110
train
32,618
ynop/audiomate
audiomate/annotations/relabeling.py
load_projections
def load_projections(projections_file): """ Loads projections defined in the given `projections_file`. The `projections_file` is expected to be in the following format:: old_label_1 | new_label_1 old_label_1 old_label_2 | new_label_2 old_label_3 | You can define one projection per line. Each projection starts with a list of one or multiple old labels (separated by a single whitespace) that are separated from the new label by a pipe (`|`). In the code above, the segment labeled with `old_label_1` will be labeled with `new_label_1` after applying the projection. Segments that are labeled with `old_label_1` **and** `old_label_2` concurrently are relabeled to `new_label_2`. All segments labeled with `old_label_3` are dropped. Combinations of multiple labels are automatically sorted in natural order. Args: projections_file (str): Path to the file with projections Returns: dict: Dictionary where the keys are tuples of labels to project to the key's value Example: >>> load_projections('/path/to/projections.txt') {('b',): 'foo', ('a', 'b'): 'a_b', ('a',): 'bar'} """ projections = {} for parts in textfile.read_separated_lines_generator(projections_file, '|'): combination = tuple(sorted([label.strip() for label in parts[0].split(' ')])) new_label = parts[1].strip() projections[combination] = new_label return projections
python
def load_projections(projections_file): """ Loads projections defined in the given `projections_file`. The `projections_file` is expected to be in the following format:: old_label_1 | new_label_1 old_label_1 old_label_2 | new_label_2 old_label_3 | You can define one projection per line. Each projection starts with a list of one or multiple old labels (separated by a single whitespace) that are separated from the new label by a pipe (`|`). In the code above, the segment labeled with `old_label_1` will be labeled with `new_label_1` after applying the projection. Segments that are labeled with `old_label_1` **and** `old_label_2` concurrently are relabeled to `new_label_2`. All segments labeled with `old_label_3` are dropped. Combinations of multiple labels are automatically sorted in natural order. Args: projections_file (str): Path to the file with projections Returns: dict: Dictionary where the keys are tuples of labels to project to the key's value Example: >>> load_projections('/path/to/projections.txt') {('b',): 'foo', ('a', 'b'): 'a_b', ('a',): 'bar'} """ projections = {} for parts in textfile.read_separated_lines_generator(projections_file, '|'): combination = tuple(sorted([label.strip() for label in parts[0].split(' ')])) new_label = parts[1].strip() projections[combination] = new_label return projections
[ "def", "load_projections", "(", "projections_file", ")", ":", "projections", "=", "{", "}", "for", "parts", "in", "textfile", ".", "read_separated_lines_generator", "(", "projections_file", ",", "'|'", ")", ":", "combination", "=", "tuple", "(", "sorted", "(", ...
Loads projections defined in the given `projections_file`. The `projections_file` is expected to be in the following format:: old_label_1 | new_label_1 old_label_1 old_label_2 | new_label_2 old_label_3 | You can define one projection per line. Each projection starts with a list of one or multiple old labels (separated by a single whitespace) that are separated from the new label by a pipe (`|`). In the code above, the segment labeled with `old_label_1` will be labeled with `new_label_1` after applying the projection. Segments that are labeled with `old_label_1` **and** `old_label_2` concurrently are relabeled to `new_label_2`. All segments labeled with `old_label_3` are dropped. Combinations of multiple labels are automatically sorted in natural order. Args: projections_file (str): Path to the file with projections Returns: dict: Dictionary where the keys are tuples of labels to project to the key's value Example: >>> load_projections('/path/to/projections.txt') {('b',): 'foo', ('a', 'b'): 'a_b', ('a',): 'bar'}
[ "Loads", "projections", "defined", "in", "the", "given", "projections_file", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/annotations/relabeling.py#L113-L148
train
32,619
ynop/audiomate
audiomate/corpus/subset/selection.py
SubsetGenerator.random_subset_by_duration
def random_subset_by_duration(self, relative_duration, balance_labels=False, label_list_ids=None): """ Create a subview of random utterances with a approximate duration relative to the full corpus. Random utterances are selected so that the sum of all utterance durations equals to the relative duration of the full corpus. Args: relative_duration (float): A value between 0 and 1. (e.g. 0.5 will create a subset with approximately 50% of the full corpus duration) balance_labels (bool): If True, the labels of the selected utterances are balanced as far as possible. So the count/duration of every label within the subset is equal. label_list_ids (list): List of label-list ids. If none is given, all label-lists are considered for balancing. Otherwise only the ones that are in the list are considered. Returns: Subview: The subview representing the subset. """ total_duration = self.corpus.total_duration subset_duration = relative_duration * total_duration utterance_durations = {utt_idx: utt.duration for utt_idx, utt in self.corpus.utterances.items()} if balance_labels: all_label_values = self.corpus.all_label_values(label_list_ids=label_list_ids) label_durations = {} for utt_idx, utt in self.corpus.utterances.items(): label_durations[utt_idx] = utt.label_total_duration(label_list_ids) subset_utterance_ids = utils.select_balanced_subset(label_durations, subset_duration, list(all_label_values), select_count_values=utterance_durations, seed=self.rand.random()) else: dummy_weights = {utt_idx: {'w': 1} for utt_idx in self.corpus.utterances.keys()} subset_utterance_ids = utils.select_balanced_subset(dummy_weights, subset_duration, ['w'], select_count_values=utterance_durations, seed=self.rand.random()) filter = subview.MatchingUtteranceIdxFilter(utterance_idxs=set(subset_utterance_ids)) return subview.Subview(self.corpus, filter_criteria=[filter])
python
def random_subset_by_duration(self, relative_duration, balance_labels=False, label_list_ids=None): """ Create a subview of random utterances with a approximate duration relative to the full corpus. Random utterances are selected so that the sum of all utterance durations equals to the relative duration of the full corpus. Args: relative_duration (float): A value between 0 and 1. (e.g. 0.5 will create a subset with approximately 50% of the full corpus duration) balance_labels (bool): If True, the labels of the selected utterances are balanced as far as possible. So the count/duration of every label within the subset is equal. label_list_ids (list): List of label-list ids. If none is given, all label-lists are considered for balancing. Otherwise only the ones that are in the list are considered. Returns: Subview: The subview representing the subset. """ total_duration = self.corpus.total_duration subset_duration = relative_duration * total_duration utterance_durations = {utt_idx: utt.duration for utt_idx, utt in self.corpus.utterances.items()} if balance_labels: all_label_values = self.corpus.all_label_values(label_list_ids=label_list_ids) label_durations = {} for utt_idx, utt in self.corpus.utterances.items(): label_durations[utt_idx] = utt.label_total_duration(label_list_ids) subset_utterance_ids = utils.select_balanced_subset(label_durations, subset_duration, list(all_label_values), select_count_values=utterance_durations, seed=self.rand.random()) else: dummy_weights = {utt_idx: {'w': 1} for utt_idx in self.corpus.utterances.keys()} subset_utterance_ids = utils.select_balanced_subset(dummy_weights, subset_duration, ['w'], select_count_values=utterance_durations, seed=self.rand.random()) filter = subview.MatchingUtteranceIdxFilter(utterance_idxs=set(subset_utterance_ids)) return subview.Subview(self.corpus, filter_criteria=[filter])
[ "def", "random_subset_by_duration", "(", "self", ",", "relative_duration", ",", "balance_labels", "=", "False", ",", "label_list_ids", "=", "None", ")", ":", "total_duration", "=", "self", ".", "corpus", ".", "total_duration", "subset_duration", "=", "relative_durat...
Create a subview of random utterances with a approximate duration relative to the full corpus. Random utterances are selected so that the sum of all utterance durations equals to the relative duration of the full corpus. Args: relative_duration (float): A value between 0 and 1. (e.g. 0.5 will create a subset with approximately 50% of the full corpus duration) balance_labels (bool): If True, the labels of the selected utterances are balanced as far as possible. So the count/duration of every label within the subset is equal. label_list_ids (list): List of label-list ids. If none is given, all label-lists are considered for balancing. Otherwise only the ones that are in the list are considered. Returns: Subview: The subview representing the subset.
[ "Create", "a", "subview", "of", "random", "utterances", "with", "a", "approximate", "duration", "relative", "to", "the", "full", "corpus", ".", "Random", "utterances", "are", "selected", "so", "that", "the", "sum", "of", "all", "utterance", "durations", "equal...
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/subset/selection.py#L62-L105
train
32,620
ynop/audiomate
audiomate/corpus/subset/selection.py
SubsetGenerator.random_subsets
def random_subsets(self, relative_sizes, by_duration=False, balance_labels=False, label_list_ids=None): """ Create a bunch of subsets with the given sizes relative to the size or duration of the full corpus. Basically the same as calling ``random_subset`` or ``random_subset_by_duration`` multiple times with different values. But this method makes sure that every subset contains only utterances, that are also contained in the next bigger subset. Args: relative_sizes (list): A list of numbers between 0 and 1 indicating the sizes of the desired subsets, relative to the full corpus. by_duration (bool): If True the size measure is the duration of all utterances in a subset/corpus. balance_labels (bool): If True the labels contained in a subset are chosen to be balanced as far as possible. label_list_ids (list): List of label-list ids. If none is given, all label-lists are considered for balancing. Otherwise only the ones that are in the list are considered. Returns: dict : A dictionary containing all subsets with the relative size as key. """ resulting_sets = {} next_bigger_subset = self.corpus for relative_size in reversed(relative_sizes): generator = SubsetGenerator(next_bigger_subset, random_seed=self.random_seed) if by_duration: sv = generator.random_subset_by_duration(relative_size, balance_labels=balance_labels, label_list_ids=label_list_ids) else: sv = generator.random_subset(relative_size, balance_labels=balance_labels, label_list_ids=label_list_ids) resulting_sets[relative_size] = sv return resulting_sets
python
def random_subsets(self, relative_sizes, by_duration=False, balance_labels=False, label_list_ids=None): """ Create a bunch of subsets with the given sizes relative to the size or duration of the full corpus. Basically the same as calling ``random_subset`` or ``random_subset_by_duration`` multiple times with different values. But this method makes sure that every subset contains only utterances, that are also contained in the next bigger subset. Args: relative_sizes (list): A list of numbers between 0 and 1 indicating the sizes of the desired subsets, relative to the full corpus. by_duration (bool): If True the size measure is the duration of all utterances in a subset/corpus. balance_labels (bool): If True the labels contained in a subset are chosen to be balanced as far as possible. label_list_ids (list): List of label-list ids. If none is given, all label-lists are considered for balancing. Otherwise only the ones that are in the list are considered. Returns: dict : A dictionary containing all subsets with the relative size as key. """ resulting_sets = {} next_bigger_subset = self.corpus for relative_size in reversed(relative_sizes): generator = SubsetGenerator(next_bigger_subset, random_seed=self.random_seed) if by_duration: sv = generator.random_subset_by_duration(relative_size, balance_labels=balance_labels, label_list_ids=label_list_ids) else: sv = generator.random_subset(relative_size, balance_labels=balance_labels, label_list_ids=label_list_ids) resulting_sets[relative_size] = sv return resulting_sets
[ "def", "random_subsets", "(", "self", ",", "relative_sizes", ",", "by_duration", "=", "False", ",", "balance_labels", "=", "False", ",", "label_list_ids", "=", "None", ")", ":", "resulting_sets", "=", "{", "}", "next_bigger_subset", "=", "self", ".", "corpus",...
Create a bunch of subsets with the given sizes relative to the size or duration of the full corpus. Basically the same as calling ``random_subset`` or ``random_subset_by_duration`` multiple times with different values. But this method makes sure that every subset contains only utterances, that are also contained in the next bigger subset. Args: relative_sizes (list): A list of numbers between 0 and 1 indicating the sizes of the desired subsets, relative to the full corpus. by_duration (bool): If True the size measure is the duration of all utterances in a subset/corpus. balance_labels (bool): If True the labels contained in a subset are chosen to be balanced as far as possible. label_list_ids (list): List of label-list ids. If none is given, all label-lists are considered for balancing. Otherwise only the ones that are in the list are considered. Returns: dict : A dictionary containing all subsets with the relative size as key.
[ "Create", "a", "bunch", "of", "subsets", "with", "the", "given", "sizes", "relative", "to", "the", "size", "or", "duration", "of", "the", "full", "corpus", ".", "Basically", "the", "same", "as", "calling", "random_subset", "or", "random_subset_by_duration", "m...
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/subset/selection.py#L107-L141
train
32,621
ynop/audiomate
audiomate/utils/text.py
remove_punctuation
def remove_punctuation(text, exceptions=[]): """ Return a string with punctuation removed. Parameters: text (str): The text to remove punctuation from. exceptions (list): List of symbols to keep in the given text. Return: str: The input text without the punctuation. """ all_but = [ r'\w', r'\s' ] all_but.extend(exceptions) pattern = '[^{}]'.format(''.join(all_but)) return re.sub(pattern, '', text)
python
def remove_punctuation(text, exceptions=[]): """ Return a string with punctuation removed. Parameters: text (str): The text to remove punctuation from. exceptions (list): List of symbols to keep in the given text. Return: str: The input text without the punctuation. """ all_but = [ r'\w', r'\s' ] all_but.extend(exceptions) pattern = '[^{}]'.format(''.join(all_but)) return re.sub(pattern, '', text)
[ "def", "remove_punctuation", "(", "text", ",", "exceptions", "=", "[", "]", ")", ":", "all_but", "=", "[", "r'\\w'", ",", "r'\\s'", "]", "all_but", ".", "extend", "(", "exceptions", ")", "pattern", "=", "'[^{}]'", ".", "format", "(", "''", ".", "join",...
Return a string with punctuation removed. Parameters: text (str): The text to remove punctuation from. exceptions (list): List of symbols to keep in the given text. Return: str: The input text without the punctuation.
[ "Return", "a", "string", "with", "punctuation", "removed", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/utils/text.py#L8-L29
train
32,622
ynop/audiomate
audiomate/utils/text.py
starts_with_prefix_in_list
def starts_with_prefix_in_list(text, prefixes): """ Return True if the given string starts with one of the prefixes in the given list, otherwise return False. Arguments: text (str): Text to check for prefixes. prefixes (list): List of prefixes to check for. Returns: bool: True if the given text starts with any of the given prefixes, otherwise False. """ for prefix in prefixes: if text.startswith(prefix): return True return False
python
def starts_with_prefix_in_list(text, prefixes): """ Return True if the given string starts with one of the prefixes in the given list, otherwise return False. Arguments: text (str): Text to check for prefixes. prefixes (list): List of prefixes to check for. Returns: bool: True if the given text starts with any of the given prefixes, otherwise False. """ for prefix in prefixes: if text.startswith(prefix): return True return False
[ "def", "starts_with_prefix_in_list", "(", "text", ",", "prefixes", ")", ":", "for", "prefix", "in", "prefixes", ":", "if", "text", ".", "startswith", "(", "prefix", ")", ":", "return", "True", "return", "False" ]
Return True if the given string starts with one of the prefixes in the given list, otherwise return False. Arguments: text (str): Text to check for prefixes. prefixes (list): List of prefixes to check for. Returns: bool: True if the given text starts with any of the given prefixes, otherwise False.
[ "Return", "True", "if", "the", "given", "string", "starts", "with", "one", "of", "the", "prefixes", "in", "the", "given", "list", "otherwise", "return", "False", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/utils/text.py#L32-L47
train
32,623
ynop/audiomate
audiomate/corpus/io/tatoeba.py
TatoebaDownloader._load_audio_list
def _load_audio_list(self, path): """ Load and filter the audio list. Args: path (str): Path to the audio list file. Returns: dict: Dictionary of filtered sentences (id : username, license, attribution-url) """ result = {} for entry in textfile.read_separated_lines_generator(path, separator='\t', max_columns=4): for i in range(len(entry)): if entry[i] == '\\N': entry[i] = None if len(entry) < 4: entry.extend([None] * (4 - len(entry))) if not self.include_empty_licence and entry[2] is None: continue if self.include_licenses is not None and entry[2] not in self.include_licenses: continue result[entry[0]] = entry[1:] return result
python
def _load_audio_list(self, path): """ Load and filter the audio list. Args: path (str): Path to the audio list file. Returns: dict: Dictionary of filtered sentences (id : username, license, attribution-url) """ result = {} for entry in textfile.read_separated_lines_generator(path, separator='\t', max_columns=4): for i in range(len(entry)): if entry[i] == '\\N': entry[i] = None if len(entry) < 4: entry.extend([None] * (4 - len(entry))) if not self.include_empty_licence and entry[2] is None: continue if self.include_licenses is not None and entry[2] not in self.include_licenses: continue result[entry[0]] = entry[1:] return result
[ "def", "_load_audio_list", "(", "self", ",", "path", ")", ":", "result", "=", "{", "}", "for", "entry", "in", "textfile", ".", "read_separated_lines_generator", "(", "path", ",", "separator", "=", "'\\t'", ",", "max_columns", "=", "4", ")", ":", "for", "...
Load and filter the audio list. Args: path (str): Path to the audio list file. Returns: dict: Dictionary of filtered sentences (id : username, license, attribution-url)
[ "Load", "and", "filter", "the", "audio", "list", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/io/tatoeba.py#L73-L102
train
32,624
ynop/audiomate
audiomate/corpus/io/tatoeba.py
TatoebaDownloader._load_sentence_list
def _load_sentence_list(self, path): """ Load and filter the sentence list. Args: path (str): Path to the sentence list. Returns: dict: Dictionary of sentences (id : language, transcription) """ result = {} for entry in textfile.read_separated_lines_generator(path, separator='\t', max_columns=3): if self.include_languages is None or entry[1] in self.include_languages: result[entry[0]] = entry[1:] return result
python
def _load_sentence_list(self, path): """ Load and filter the sentence list. Args: path (str): Path to the sentence list. Returns: dict: Dictionary of sentences (id : language, transcription) """ result = {} for entry in textfile.read_separated_lines_generator(path, separator='\t', max_columns=3): if self.include_languages is None or entry[1] in self.include_languages: result[entry[0]] = entry[1:] return result
[ "def", "_load_sentence_list", "(", "self", ",", "path", ")", ":", "result", "=", "{", "}", "for", "entry", "in", "textfile", ".", "read_separated_lines_generator", "(", "path", ",", "separator", "=", "'\\t'", ",", "max_columns", "=", "3", ")", ":", "if", ...
Load and filter the sentence list. Args: path (str): Path to the sentence list. Returns: dict: Dictionary of sentences (id : language, transcription)
[ "Load", "and", "filter", "the", "sentence", "list", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/io/tatoeba.py#L104-L121
train
32,625
ynop/audiomate
audiomate/corpus/io/tatoeba.py
TatoebaDownloader._download_audio_files
def _download_audio_files(self, records, target_path): """ Download all audio files based on the given records. """ for record in records: audio_folder = os.path.join(target_path, 'audio', record[2]) audio_file = os.path.join(audio_folder, '{}.mp3'.format(record[0])) os.makedirs(audio_folder, exist_ok=True) download_url = 'https://audio.tatoeba.org/sentences/{}/{}.mp3'.format(record[2], record[0]) download.download_file(download_url, audio_file)
python
def _download_audio_files(self, records, target_path): """ Download all audio files based on the given records. """ for record in records: audio_folder = os.path.join(target_path, 'audio', record[2]) audio_file = os.path.join(audio_folder, '{}.mp3'.format(record[0])) os.makedirs(audio_folder, exist_ok=True) download_url = 'https://audio.tatoeba.org/sentences/{}/{}.mp3'.format(record[2], record[0]) download.download_file(download_url, audio_file)
[ "def", "_download_audio_files", "(", "self", ",", "records", ",", "target_path", ")", ":", "for", "record", "in", "records", ":", "audio_folder", "=", "os", ".", "path", ".", "join", "(", "target_path", ",", "'audio'", ",", "record", "[", "2", "]", ")", ...
Download all audio files based on the given records.
[ "Download", "all", "audio", "files", "based", "on", "the", "given", "records", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/io/tatoeba.py#L123-L134
train
32,626
ynop/audiomate
audiomate/corpus/subset/splitting.py
Splitter.split_by_proportionally_distribute_labels
def split_by_proportionally_distribute_labels(self, proportions={}, use_lengths=True): """ Split the corpus into subsets, so the occurrence of the labels is distributed amongst the subsets according to the given proportions. Args: proportions (dict): A dictionary containing the relative size of the target subsets. The key is an identifier for the subset. use_lengths (bool): If True the lengths of the labels are considered for splitting proportionally, otherwise only the number of occurrences is taken into account. Returns: (dict): A dictionary containing the subsets with the identifier from the input as key. """ identifiers = {} for utterance in self.corpus.utterances.values(): if use_lengths: identifiers[utterance.idx] = {l: int(d * 100) for l, d in utterance.label_total_duration().items()} else: identifiers[utterance.idx] = utterance.label_count() splits = utils.get_identifiers_splitted_by_weights(identifiers, proportions) return self._subviews_from_utterance_splits(splits)
python
def split_by_proportionally_distribute_labels(self, proportions={}, use_lengths=True): """ Split the corpus into subsets, so the occurrence of the labels is distributed amongst the subsets according to the given proportions. Args: proportions (dict): A dictionary containing the relative size of the target subsets. The key is an identifier for the subset. use_lengths (bool): If True the lengths of the labels are considered for splitting proportionally, otherwise only the number of occurrences is taken into account. Returns: (dict): A dictionary containing the subsets with the identifier from the input as key. """ identifiers = {} for utterance in self.corpus.utterances.values(): if use_lengths: identifiers[utterance.idx] = {l: int(d * 100) for l, d in utterance.label_total_duration().items()} else: identifiers[utterance.idx] = utterance.label_count() splits = utils.get_identifiers_splitted_by_weights(identifiers, proportions) return self._subviews_from_utterance_splits(splits)
[ "def", "split_by_proportionally_distribute_labels", "(", "self", ",", "proportions", "=", "{", "}", ",", "use_lengths", "=", "True", ")", ":", "identifiers", "=", "{", "}", "for", "utterance", "in", "self", ".", "corpus", ".", "utterances", ".", "values", "(...
Split the corpus into subsets, so the occurrence of the labels is distributed amongst the subsets according to the given proportions. Args: proportions (dict): A dictionary containing the relative size of the target subsets. The key is an identifier for the subset. use_lengths (bool): If True the lengths of the labels are considered for splitting proportionally, otherwise only the number of occurrences is taken into account. Returns: (dict): A dictionary containing the subsets with the identifier from the input as key.
[ "Split", "the", "corpus", "into", "subsets", "so", "the", "occurrence", "of", "the", "labels", "is", "distributed", "amongst", "the", "subsets", "according", "to", "the", "given", "proportions", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/subset/splitting.py#L153-L178
train
32,627
ynop/audiomate
audiomate/corpus/subset/splitting.py
Splitter._subviews_from_utterance_splits
def _subviews_from_utterance_splits(self, splits): """ Create subviews from a dict containing utterance-ids for each subview. e.g. {'train': ['utt-1', 'utt-2'], 'test': [...], ...} """ subviews = {} for idx, subview_utterances in splits.items(): filter = subview.MatchingUtteranceIdxFilter(utterance_idxs=subview_utterances) split = subview.Subview(self.corpus, filter_criteria=filter) subviews[idx] = split return subviews
python
def _subviews_from_utterance_splits(self, splits): """ Create subviews from a dict containing utterance-ids for each subview. e.g. {'train': ['utt-1', 'utt-2'], 'test': [...], ...} """ subviews = {} for idx, subview_utterances in splits.items(): filter = subview.MatchingUtteranceIdxFilter(utterance_idxs=subview_utterances) split = subview.Subview(self.corpus, filter_criteria=filter) subviews[idx] = split return subviews
[ "def", "_subviews_from_utterance_splits", "(", "self", ",", "splits", ")", ":", "subviews", "=", "{", "}", "for", "idx", ",", "subview_utterances", "in", "splits", ".", "items", "(", ")", ":", "filter", "=", "subview", ".", "MatchingUtteranceIdxFilter", "(", ...
Create subviews from a dict containing utterance-ids for each subview. e.g. {'train': ['utt-1', 'utt-2'], 'test': [...], ...}
[ "Create", "subviews", "from", "a", "dict", "containing", "utterance", "-", "ids", "for", "each", "subview", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/subset/splitting.py#L180-L193
train
32,628
ynop/audiomate
audiomate/tracks/container.py
ContainerTrack.sampling_rate
def sampling_rate(self): """ Return the sampling rate. """ with self.container.open_if_needed(mode='r') as cnt: return cnt.get(self.key)[1]
python
def sampling_rate(self): """ Return the sampling rate. """ with self.container.open_if_needed(mode='r') as cnt: return cnt.get(self.key)[1]
[ "def", "sampling_rate", "(", "self", ")", ":", "with", "self", ".", "container", ".", "open_if_needed", "(", "mode", "=", "'r'", ")", "as", "cnt", ":", "return", "cnt", ".", "get", "(", "self", ".", "key", ")", "[", "1", "]" ]
Return the sampling rate.
[ "Return", "the", "sampling", "rate", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/tracks/container.py#L47-L52
train
32,629
ynop/audiomate
audiomate/tracks/container.py
ContainerTrack.duration
def duration(self): """ Return the duration in seconds. """ with self.container.open_if_needed(mode='r') as cnt: samples, sr = cnt.get(self.key) return samples.shape[0] / sr
python
def duration(self): """ Return the duration in seconds. """ with self.container.open_if_needed(mode='r') as cnt: samples, sr = cnt.get(self.key) return samples.shape[0] / sr
[ "def", "duration", "(", "self", ")", ":", "with", "self", ".", "container", ".", "open_if_needed", "(", "mode", "=", "'r'", ")", "as", "cnt", ":", "samples", ",", "sr", "=", "cnt", ".", "get", "(", "self", ".", "key", ")", "return", "samples", ".",...
Return the duration in seconds.
[ "Return", "the", "duration", "in", "seconds", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/tracks/container.py#L70-L77
train
32,630
ynop/audiomate
audiomate/tracks/container.py
ContainerTrack.read_samples
def read_samples(self, sr=None, offset=0, duration=None): """ Return the samples from the track in the container. Uses librosa for resampling, if needed. Args: sr (int): If ``None``, uses the sampling rate given by the file, otherwise resamples to the given sampling rate. offset (float): The time in seconds, from where to start reading the samples (rel. to the file start). duration (float): The length of the samples to read in seconds. Returns: np.ndarray: A numpy array containing the samples as a floating point (numpy.float32) time series. """ with self.container.open_if_needed(mode='r') as cnt: samples, native_sr = cnt.get(self.key) start_sample_index = int(offset * native_sr) if duration is None: end_sample_index = samples.shape[0] else: end_sample_index = int((offset + duration) * native_sr) samples = samples[start_sample_index:end_sample_index] if sr is not None and sr != native_sr: samples = librosa.core.resample( samples, native_sr, sr, res_type='kaiser_best' ) return samples
python
def read_samples(self, sr=None, offset=0, duration=None): """ Return the samples from the track in the container. Uses librosa for resampling, if needed. Args: sr (int): If ``None``, uses the sampling rate given by the file, otherwise resamples to the given sampling rate. offset (float): The time in seconds, from where to start reading the samples (rel. to the file start). duration (float): The length of the samples to read in seconds. Returns: np.ndarray: A numpy array containing the samples as a floating point (numpy.float32) time series. """ with self.container.open_if_needed(mode='r') as cnt: samples, native_sr = cnt.get(self.key) start_sample_index = int(offset * native_sr) if duration is None: end_sample_index = samples.shape[0] else: end_sample_index = int((offset + duration) * native_sr) samples = samples[start_sample_index:end_sample_index] if sr is not None and sr != native_sr: samples = librosa.core.resample( samples, native_sr, sr, res_type='kaiser_best' ) return samples
[ "def", "read_samples", "(", "self", ",", "sr", "=", "None", ",", "offset", "=", "0", ",", "duration", "=", "None", ")", ":", "with", "self", ".", "container", ".", "open_if_needed", "(", "mode", "=", "'r'", ")", "as", "cnt", ":", "samples", ",", "n...
Return the samples from the track in the container. Uses librosa for resampling, if needed. Args: sr (int): If ``None``, uses the sampling rate given by the file, otherwise resamples to the given sampling rate. offset (float): The time in seconds, from where to start reading the samples (rel. to the file start). duration (float): The length of the samples to read in seconds. Returns: np.ndarray: A numpy array containing the samples as a floating point (numpy.float32) time series.
[ "Return", "the", "samples", "from", "the", "track", "in", "the", "container", ".", "Uses", "librosa", "for", "resampling", "if", "needed", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/tracks/container.py#L79-L115
train
32,631
ynop/audiomate
audiomate/utils/jsonfile.py
write_json_to_file
def write_json_to_file(path, data): """ Writes data as json to file. Parameters: path (str): Path to write to data (dict, list): Data """ with open(path, 'w', encoding='utf-8') as f: json.dump(data, f)
python
def write_json_to_file(path, data): """ Writes data as json to file. Parameters: path (str): Path to write to data (dict, list): Data """ with open(path, 'w', encoding='utf-8') as f: json.dump(data, f)
[ "def", "write_json_to_file", "(", "path", ",", "data", ")", ":", "with", "open", "(", "path", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ":", "json", ".", "dump", "(", "data", ",", "f", ")" ]
Writes data as json to file. Parameters: path (str): Path to write to data (dict, list): Data
[ "Writes", "data", "as", "json", "to", "file", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/utils/jsonfile.py#L8-L17
train
32,632
ynop/audiomate
audiomate/utils/jsonfile.py
read_json_file
def read_json_file(path): """ Reads and return the data from the json file at the given path. Parameters: path (str): Path to read Returns: dict,list: The read json as dict/list. """ with open(path, 'r', encoding='utf-8') as f: data = json.load(f) return data
python
def read_json_file(path): """ Reads and return the data from the json file at the given path. Parameters: path (str): Path to read Returns: dict,list: The read json as dict/list. """ with open(path, 'r', encoding='utf-8') as f: data = json.load(f) return data
[ "def", "read_json_file", "(", "path", ")", ":", "with", "open", "(", "path", ",", "'r'", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ":", "data", "=", "json", ".", "load", "(", "f", ")", "return", "data" ]
Reads and return the data from the json file at the given path. Parameters: path (str): Path to read Returns: dict,list: The read json as dict/list.
[ "Reads", "and", "return", "the", "data", "from", "the", "json", "file", "at", "the", "given", "path", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/utils/jsonfile.py#L20-L34
train
32,633
ynop/audiomate
audiomate/annotations/label_list.py
LabelList.add
def add(self, label): """ Add a label to the end of the list. Args: label (Label): The label to add. """ label.label_list = self self.label_tree.addi(label.start, label.end, label)
python
def add(self, label): """ Add a label to the end of the list. Args: label (Label): The label to add. """ label.label_list = self self.label_tree.addi(label.start, label.end, label)
[ "def", "add", "(", "self", ",", "label", ")", ":", "label", ".", "label_list", "=", "self", "self", ".", "label_tree", ".", "addi", "(", "label", ".", "start", ",", "label", ".", "end", ",", "label", ")" ]
Add a label to the end of the list. Args: label (Label): The label to add.
[ "Add", "a", "label", "to", "the", "end", "of", "the", "list", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/annotations/label_list.py#L90-L98
train
32,634
ynop/audiomate
audiomate/annotations/label_list.py
LabelList.merge_overlaps
def merge_overlaps(self, threshold=0.0): """ Merge overlapping labels with the same value. Two labels are considered overlapping, if ``l2.start - l1.end < threshold``. Args: threshold (float): Maximal distance between two labels to be considered as overlapping. (default: 0.0) Example: >>> ll = LabelList(labels=[ ... Label('a_label', 1.0, 2.0), ... Label('a_label', 1.5, 2.7), ... Label('b_label', 1.0, 2.0), ... ]) >>> ll.merge_overlapping_labels() >>> ll.labels [ Label('a_label', 1.0, 2.7), Label('b_label', 1.0, 2.0), ] """ updated_labels = [] all_intervals = self.label_tree.copy() # recursivly find a group of overlapping labels with the same value def recursive_overlaps(interval): range_start = interval.begin - threshold range_end = interval.end + threshold direct_overlaps = all_intervals.overlap(range_start, range_end) all_overlaps = [interval] all_intervals.discard(interval) for overlap in direct_overlaps: if overlap.data.value == interval.data.value: all_overlaps.extend(recursive_overlaps(overlap)) return all_overlaps # For every remaining interval # - Find overlapping intervals recursively # - Remove them # - Create a concatenated new label while not all_intervals.is_empty(): next_interval = list(all_intervals)[0] overlapping = recursive_overlaps(next_interval) ov_start = float('inf') ov_end = 0.0 ov_value = next_interval.data.value for overlap in overlapping: ov_start = min(ov_start, overlap.begin) ov_end = max(ov_end, overlap.end) all_intervals.discard(overlap) updated_labels.append(Label( ov_value, ov_start, ov_end )) # Replace the old labels with the updated ones self.label_tree.clear() self.update(updated_labels)
python
def merge_overlaps(self, threshold=0.0): """ Merge overlapping labels with the same value. Two labels are considered overlapping, if ``l2.start - l1.end < threshold``. Args: threshold (float): Maximal distance between two labels to be considered as overlapping. (default: 0.0) Example: >>> ll = LabelList(labels=[ ... Label('a_label', 1.0, 2.0), ... Label('a_label', 1.5, 2.7), ... Label('b_label', 1.0, 2.0), ... ]) >>> ll.merge_overlapping_labels() >>> ll.labels [ Label('a_label', 1.0, 2.7), Label('b_label', 1.0, 2.0), ] """ updated_labels = [] all_intervals = self.label_tree.copy() # recursivly find a group of overlapping labels with the same value def recursive_overlaps(interval): range_start = interval.begin - threshold range_end = interval.end + threshold direct_overlaps = all_intervals.overlap(range_start, range_end) all_overlaps = [interval] all_intervals.discard(interval) for overlap in direct_overlaps: if overlap.data.value == interval.data.value: all_overlaps.extend(recursive_overlaps(overlap)) return all_overlaps # For every remaining interval # - Find overlapping intervals recursively # - Remove them # - Create a concatenated new label while not all_intervals.is_empty(): next_interval = list(all_intervals)[0] overlapping = recursive_overlaps(next_interval) ov_start = float('inf') ov_end = 0.0 ov_value = next_interval.data.value for overlap in overlapping: ov_start = min(ov_start, overlap.begin) ov_end = max(ov_end, overlap.end) all_intervals.discard(overlap) updated_labels.append(Label( ov_value, ov_start, ov_end )) # Replace the old labels with the updated ones self.label_tree.clear() self.update(updated_labels)
[ "def", "merge_overlaps", "(", "self", ",", "threshold", "=", "0.0", ")", ":", "updated_labels", "=", "[", "]", "all_intervals", "=", "self", ".", "label_tree", ".", "copy", "(", ")", "# recursivly find a group of overlapping labels with the same value", "def", "recu...
Merge overlapping labels with the same value. Two labels are considered overlapping, if ``l2.start - l1.end < threshold``. Args: threshold (float): Maximal distance between two labels to be considered as overlapping. (default: 0.0) Example: >>> ll = LabelList(labels=[ ... Label('a_label', 1.0, 2.0), ... Label('a_label', 1.5, 2.7), ... Label('b_label', 1.0, 2.0), ... ]) >>> ll.merge_overlapping_labels() >>> ll.labels [ Label('a_label', 1.0, 2.7), Label('b_label', 1.0, 2.0), ]
[ "Merge", "overlapping", "labels", "with", "the", "same", "value", ".", "Two", "labels", "are", "considered", "overlapping", "if", "l2", ".", "start", "-", "l1", ".", "end", "<", "threshold", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/annotations/label_list.py#L141-L209
train
32,635
ynop/audiomate
audiomate/annotations/label_list.py
LabelList.label_total_duration
def label_total_duration(self): """ Return for each distinct label value the total duration of all occurrences. Returns: dict: A dictionary containing for every label-value (key) the total duration in seconds (value). Example: >>> ll = LabelList(labels=[ >>> Label('a', 3, 5), >>> Label('b', 5, 8), >>> Label('a', 8, 10), >>> Label('b', 10, 14), >>> Label('a', 15, 18.5) >>> ]) >>> ll.label_total_duration() {'a': 7.5 'b': 7.0} """ durations = collections.defaultdict(float) for label in self: durations[label.value] += label.duration return durations
python
def label_total_duration(self): """ Return for each distinct label value the total duration of all occurrences. Returns: dict: A dictionary containing for every label-value (key) the total duration in seconds (value). Example: >>> ll = LabelList(labels=[ >>> Label('a', 3, 5), >>> Label('b', 5, 8), >>> Label('a', 8, 10), >>> Label('b', 10, 14), >>> Label('a', 15, 18.5) >>> ]) >>> ll.label_total_duration() {'a': 7.5 'b': 7.0} """ durations = collections.defaultdict(float) for label in self: durations[label.value] += label.duration return durations
[ "def", "label_total_duration", "(", "self", ")", ":", "durations", "=", "collections", ".", "defaultdict", "(", "float", ")", "for", "label", "in", "self", ":", "durations", "[", "label", ".", "value", "]", "+=", "label", ".", "duration", "return", "durati...
Return for each distinct label value the total duration of all occurrences. Returns: dict: A dictionary containing for every label-value (key) the total duration in seconds (value). Example: >>> ll = LabelList(labels=[ >>> Label('a', 3, 5), >>> Label('b', 5, 8), >>> Label('a', 8, 10), >>> Label('b', 10, 14), >>> Label('a', 15, 18.5) >>> ]) >>> ll.label_total_duration() {'a': 7.5 'b': 7.0}
[ "Return", "for", "each", "distinct", "label", "value", "the", "total", "duration", "of", "all", "occurrences", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/annotations/label_list.py#L215-L240
train
32,636
ynop/audiomate
audiomate/annotations/label_list.py
LabelList.label_values
def label_values(self): """ Return a list of all occuring label values. Returns: list: Lexicographically sorted list (str) of label values. Example: >>> ll = LabelList(labels=[ >>> Label('a', 3.2, 4.5), >>> Label('b', 5.1, 8.9), >>> Label('c', 7.2, 10.5), >>> Label('d', 10.5, 14), >>> Label('d', 15, 18) >>> ]) >>> ll.label_values() ['a', 'b', 'c', 'd'] """ all_labels = set([l.value for l in self]) return sorted(all_labels)
python
def label_values(self): """ Return a list of all occuring label values. Returns: list: Lexicographically sorted list (str) of label values. Example: >>> ll = LabelList(labels=[ >>> Label('a', 3.2, 4.5), >>> Label('b', 5.1, 8.9), >>> Label('c', 7.2, 10.5), >>> Label('d', 10.5, 14), >>> Label('d', 15, 18) >>> ]) >>> ll.label_values() ['a', 'b', 'c', 'd'] """ all_labels = set([l.value for l in self]) return sorted(all_labels)
[ "def", "label_values", "(", "self", ")", ":", "all_labels", "=", "set", "(", "[", "l", ".", "value", "for", "l", "in", "self", "]", ")", "return", "sorted", "(", "all_labels", ")" ]
Return a list of all occuring label values. Returns: list: Lexicographically sorted list (str) of label values. Example: >>> ll = LabelList(labels=[ >>> Label('a', 3.2, 4.5), >>> Label('b', 5.1, 8.9), >>> Label('c', 7.2, 10.5), >>> Label('d', 10.5, 14), >>> Label('d', 15, 18) >>> ]) >>> ll.label_values() ['a', 'b', 'c', 'd']
[ "Return", "a", "list", "of", "all", "occuring", "label", "values", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/annotations/label_list.py#L242-L262
train
32,637
ynop/audiomate
audiomate/annotations/label_list.py
LabelList.label_count
def label_count(self): """ Return for each label the number of occurrences within the list. Returns: dict: A dictionary containing for every label-value (key) the number of occurrences (value). Example: >>> ll = LabelList(labels=[ >>> Label('a', 3.2, 4.5), >>> Label('b', 5.1, 8.9), >>> Label('a', 7.2, 10.5), >>> Label('b', 10.5, 14), >>> Label('a', 15, 18) >>> ]) >>> ll.label_count() {'a': 3 'b': 2} """ occurrences = collections.defaultdict(int) for label in self: occurrences[label.value] += 1 return occurrences
python
def label_count(self): """ Return for each label the number of occurrences within the list. Returns: dict: A dictionary containing for every label-value (key) the number of occurrences (value). Example: >>> ll = LabelList(labels=[ >>> Label('a', 3.2, 4.5), >>> Label('b', 5.1, 8.9), >>> Label('a', 7.2, 10.5), >>> Label('b', 10.5, 14), >>> Label('a', 15, 18) >>> ]) >>> ll.label_count() {'a': 3 'b': 2} """ occurrences = collections.defaultdict(int) for label in self: occurrences[label.value] += 1 return occurrences
[ "def", "label_count", "(", "self", ")", ":", "occurrences", "=", "collections", ".", "defaultdict", "(", "int", ")", "for", "label", "in", "self", ":", "occurrences", "[", "label", ".", "value", "]", "+=", "1", "return", "occurrences" ]
Return for each label the number of occurrences within the list. Returns: dict: A dictionary containing for every label-value (key) the number of occurrences (value). Example: >>> ll = LabelList(labels=[ >>> Label('a', 3.2, 4.5), >>> Label('b', 5.1, 8.9), >>> Label('a', 7.2, 10.5), >>> Label('b', 10.5, 14), >>> Label('a', 15, 18) >>> ]) >>> ll.label_count() {'a': 3 'b': 2}
[ "Return", "for", "each", "label", "the", "number", "of", "occurrences", "within", "the", "list", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/annotations/label_list.py#L264-L289
train
32,638
ynop/audiomate
audiomate/annotations/label_list.py
LabelList.all_tokens
def all_tokens(self, delimiter=' '): """ Return a list of all tokens occurring in the label-list. Args: delimiter (str): The delimiter used to split labels into tokens (see :meth:`audiomate.annotations.Label.tokenized`). Returns: :class:`set`: A set of distinct tokens. """ tokens = set() for label in self: tokens = tokens.union(set(label.tokenized(delimiter=delimiter))) return tokens
python
def all_tokens(self, delimiter=' '): """ Return a list of all tokens occurring in the label-list. Args: delimiter (str): The delimiter used to split labels into tokens (see :meth:`audiomate.annotations.Label.tokenized`). Returns: :class:`set`: A set of distinct tokens. """ tokens = set() for label in self: tokens = tokens.union(set(label.tokenized(delimiter=delimiter))) return tokens
[ "def", "all_tokens", "(", "self", ",", "delimiter", "=", "' '", ")", ":", "tokens", "=", "set", "(", ")", "for", "label", "in", "self", ":", "tokens", "=", "tokens", ".", "union", "(", "set", "(", "label", ".", "tokenized", "(", "delimiter", "=", "...
Return a list of all tokens occurring in the label-list. Args: delimiter (str): The delimiter used to split labels into tokens (see :meth:`audiomate.annotations.Label.tokenized`). Returns: :class:`set`: A set of distinct tokens.
[ "Return", "a", "list", "of", "all", "tokens", "occurring", "in", "the", "label", "-", "list", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/annotations/label_list.py#L291-L307
train
32,639
ynop/audiomate
audiomate/annotations/label_list.py
LabelList.join
def join(self, delimiter=' ', overlap_threshold=0.1): """ Return a string with all labels concatenated together. The order of the labels is defined by the start of the label. If the overlapping between two labels is greater than ``overlap_threshold``, an Exception is thrown. Args: delimiter (str): A string to join two consecutive labels. overlap_threshold (float): Maximum overlap between two consecutive labels. Returns: str: A string with all labels concatenated together. Example: >>> ll = LabelList(idx='some', labels=[ >>> Label('a', start=0, end=4), >>> Label('b', start=3.95, end=6.0), >>> Label('c', start=7.0, end=10.2), >>> Label('d', start=10.3, end=14.0) >>> ]) >>> ll.join(' - ') 'a - b - c - d' """ sorted_by_start = sorted(self.labels) concat_values = [] last_label_end = None for label in sorted_by_start: if last_label_end is None or (last_label_end - label.start < overlap_threshold and last_label_end > 0): concat_values.append(label.value) last_label_end = label.end else: raise ValueError('Labels overlap, not able to define the correct order') return delimiter.join(concat_values)
python
def join(self, delimiter=' ', overlap_threshold=0.1): """ Return a string with all labels concatenated together. The order of the labels is defined by the start of the label. If the overlapping between two labels is greater than ``overlap_threshold``, an Exception is thrown. Args: delimiter (str): A string to join two consecutive labels. overlap_threshold (float): Maximum overlap between two consecutive labels. Returns: str: A string with all labels concatenated together. Example: >>> ll = LabelList(idx='some', labels=[ >>> Label('a', start=0, end=4), >>> Label('b', start=3.95, end=6.0), >>> Label('c', start=7.0, end=10.2), >>> Label('d', start=10.3, end=14.0) >>> ]) >>> ll.join(' - ') 'a - b - c - d' """ sorted_by_start = sorted(self.labels) concat_values = [] last_label_end = None for label in sorted_by_start: if last_label_end is None or (last_label_end - label.start < overlap_threshold and last_label_end > 0): concat_values.append(label.value) last_label_end = label.end else: raise ValueError('Labels overlap, not able to define the correct order') return delimiter.join(concat_values)
[ "def", "join", "(", "self", ",", "delimiter", "=", "' '", ",", "overlap_threshold", "=", "0.1", ")", ":", "sorted_by_start", "=", "sorted", "(", "self", ".", "labels", ")", "concat_values", "=", "[", "]", "last_label_end", "=", "None", "for", "label", "i...
Return a string with all labels concatenated together. The order of the labels is defined by the start of the label. If the overlapping between two labels is greater than ``overlap_threshold``, an Exception is thrown. Args: delimiter (str): A string to join two consecutive labels. overlap_threshold (float): Maximum overlap between two consecutive labels. Returns: str: A string with all labels concatenated together. Example: >>> ll = LabelList(idx='some', labels=[ >>> Label('a', start=0, end=4), >>> Label('b', start=3.95, end=6.0), >>> Label('c', start=7.0, end=10.2), >>> Label('d', start=10.3, end=14.0) >>> ]) >>> ll.join(' - ') 'a - b - c - d'
[ "Return", "a", "string", "with", "all", "labels", "concatenated", "together", ".", "The", "order", "of", "the", "labels", "is", "defined", "by", "the", "start", "of", "the", "label", ".", "If", "the", "overlapping", "between", "two", "labels", "is", "great...
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/annotations/label_list.py#L313-L349
train
32,640
ynop/audiomate
audiomate/annotations/label_list.py
LabelList.separated
def separated(self): """ Create a separate Label-List for every distinct label-value. Returns: dict: A dictionary with distinct label-values as keys. Every value is a LabelList containing only labels with the same value. Example: >>> ll = LabelList(idx='some', labels=[ >>> Label('a', start=0, end=4), >>> Label('b', start=3.95, end=6.0), >>> Label('a', start=7.0, end=10.2), >>> Label('b', start=10.3, end=14.0) >>> ]) >>> s = ll.separate() >>> s['a'].labels [Label('a', start=0, end=4), Label('a', start=7.0, end=10.2)] >>> s['b'].labels [Label('b', start=3.95, end=6.0), Label('b', start=10.3, end=14.0)] """ separated_lls = collections.defaultdict(LabelList) for label in self.labels: separated_lls[label.value].add(label) for ll in separated_lls.values(): ll.idx = self.idx return separated_lls
python
def separated(self): """ Create a separate Label-List for every distinct label-value. Returns: dict: A dictionary with distinct label-values as keys. Every value is a LabelList containing only labels with the same value. Example: >>> ll = LabelList(idx='some', labels=[ >>> Label('a', start=0, end=4), >>> Label('b', start=3.95, end=6.0), >>> Label('a', start=7.0, end=10.2), >>> Label('b', start=10.3, end=14.0) >>> ]) >>> s = ll.separate() >>> s['a'].labels [Label('a', start=0, end=4), Label('a', start=7.0, end=10.2)] >>> s['b'].labels [Label('b', start=3.95, end=6.0), Label('b', start=10.3, end=14.0)] """ separated_lls = collections.defaultdict(LabelList) for label in self.labels: separated_lls[label.value].add(label) for ll in separated_lls.values(): ll.idx = self.idx return separated_lls
[ "def", "separated", "(", "self", ")", ":", "separated_lls", "=", "collections", ".", "defaultdict", "(", "LabelList", ")", "for", "label", "in", "self", ".", "labels", ":", "separated_lls", "[", "label", ".", "value", "]", ".", "add", "(", "label", ")", ...
Create a separate Label-List for every distinct label-value. Returns: dict: A dictionary with distinct label-values as keys. Every value is a LabelList containing only labels with the same value. Example: >>> ll = LabelList(idx='some', labels=[ >>> Label('a', start=0, end=4), >>> Label('b', start=3.95, end=6.0), >>> Label('a', start=7.0, end=10.2), >>> Label('b', start=10.3, end=14.0) >>> ]) >>> s = ll.separate() >>> s['a'].labels [Label('a', start=0, end=4), Label('a', start=7.0, end=10.2)] >>> s['b'].labels [Label('b', start=3.95, end=6.0), Label('b', start=10.3, end=14.0)]
[ "Create", "a", "separate", "Label", "-", "List", "for", "every", "distinct", "label", "-", "value", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/annotations/label_list.py#L393-L422
train
32,641
ynop/audiomate
audiomate/annotations/label_list.py
LabelList.labels_in_range
def labels_in_range(self, start, end, fully_included=False): """ Return a list of labels, that are within the given range. Also labels that only overlap are included. Args: start(float): Start-time in seconds. end(float): End-time in seconds. fully_included(bool): If ``True``, only labels fully included in the range are returned. Otherwise also overlapping ones are returned. (default ``False``) Returns: list: List of labels in the range. Example: >>> ll = LabelList(labels=[ >>> Label('a', 3.2, 4.5), >>> Label('b', 5.1, 8.9), >>> Label('c', 7.2, 10.5), >>> Label('d', 10.5, 14) >>>]) >>> ll.labels_in_range(6.2, 10.1) [Label('b', 5.1, 8.9), Label('c', 7.2, 10.5)] """ if fully_included: intervals = self.label_tree.envelop(start, end) else: intervals = self.label_tree.overlap(start, end) return [iv.data for iv in intervals]
python
def labels_in_range(self, start, end, fully_included=False): """ Return a list of labels, that are within the given range. Also labels that only overlap are included. Args: start(float): Start-time in seconds. end(float): End-time in seconds. fully_included(bool): If ``True``, only labels fully included in the range are returned. Otherwise also overlapping ones are returned. (default ``False``) Returns: list: List of labels in the range. Example: >>> ll = LabelList(labels=[ >>> Label('a', 3.2, 4.5), >>> Label('b', 5.1, 8.9), >>> Label('c', 7.2, 10.5), >>> Label('d', 10.5, 14) >>>]) >>> ll.labels_in_range(6.2, 10.1) [Label('b', 5.1, 8.9), Label('c', 7.2, 10.5)] """ if fully_included: intervals = self.label_tree.envelop(start, end) else: intervals = self.label_tree.overlap(start, end) return [iv.data for iv in intervals]
[ "def", "labels_in_range", "(", "self", ",", "start", ",", "end", ",", "fully_included", "=", "False", ")", ":", "if", "fully_included", ":", "intervals", "=", "self", ".", "label_tree", ".", "envelop", "(", "start", ",", "end", ")", "else", ":", "interva...
Return a list of labels, that are within the given range. Also labels that only overlap are included. Args: start(float): Start-time in seconds. end(float): End-time in seconds. fully_included(bool): If ``True``, only labels fully included in the range are returned. Otherwise also overlapping ones are returned. (default ``False``) Returns: list: List of labels in the range. Example: >>> ll = LabelList(labels=[ >>> Label('a', 3.2, 4.5), >>> Label('b', 5.1, 8.9), >>> Label('c', 7.2, 10.5), >>> Label('d', 10.5, 14) >>>]) >>> ll.labels_in_range(6.2, 10.1) [Label('b', 5.1, 8.9), Label('c', 7.2, 10.5)]
[ "Return", "a", "list", "of", "labels", "that", "are", "within", "the", "given", "range", ".", "Also", "labels", "that", "only", "overlap", "are", "included", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/annotations/label_list.py#L424-L456
train
32,642
ynop/audiomate
audiomate/annotations/label_list.py
LabelList.ranges
def ranges(self, yield_ranges_without_labels=False, include_labels=None): """ Generate all ranges of the label-list. A range is defined as a part of the label-list for which the same labels are defined. Args: yield_ranges_without_labels(bool): If True also yields ranges for which no labels are defined. include_labels(list): If not empty, only the label values in the list will be considered. Returns: generator: A generator which yields one range (tuple start/end/list-of-labels) at a time. Example: >>> ll = LabelList(labels=[ >>> Label('a', 3.2, 4.5), >>> Label('b', 5.1, 8.9), >>> Label('c', 7.2, 10.5), >>> Label('d', 10.5, 14) >>>]) >>> ranges = ll.ranges() >>> next(ranges) (3.2, 4.5, [ < audiomate.annotations.Label at 0x1090527c8 > ]) >>> next(ranges) (4.5, 5.1, []) >>> next(ranges) (5.1, 7.2, [ < audiomate.annotations.label.Label at 0x1090484c8 > ]) """ tree_copy = self.label_tree.copy() # Remove labels not included if include_labels is not None: for iv in list(tree_copy): if iv.data.value not in include_labels: tree_copy.remove(iv) def reduce(x, y): x.append(y) return x # Split labels when overlapping and merge equal ranges to a list of labels tree_copy.split_overlaps() tree_copy.merge_equals(data_reducer=reduce, data_initializer=[]) intervals = sorted(tree_copy) last_end = intervals[0].begin # yield range by range for i in range(len(intervals)): iv = intervals[i] # yield an empty range if necessary if yield_ranges_without_labels and iv.begin > last_end: yield (last_end, iv.begin, []) yield (iv.begin, iv.end, iv.data) last_end = iv.end
python
def ranges(self, yield_ranges_without_labels=False, include_labels=None): """ Generate all ranges of the label-list. A range is defined as a part of the label-list for which the same labels are defined. Args: yield_ranges_without_labels(bool): If True also yields ranges for which no labels are defined. include_labels(list): If not empty, only the label values in the list will be considered. Returns: generator: A generator which yields one range (tuple start/end/list-of-labels) at a time. Example: >>> ll = LabelList(labels=[ >>> Label('a', 3.2, 4.5), >>> Label('b', 5.1, 8.9), >>> Label('c', 7.2, 10.5), >>> Label('d', 10.5, 14) >>>]) >>> ranges = ll.ranges() >>> next(ranges) (3.2, 4.5, [ < audiomate.annotations.Label at 0x1090527c8 > ]) >>> next(ranges) (4.5, 5.1, []) >>> next(ranges) (5.1, 7.2, [ < audiomate.annotations.label.Label at 0x1090484c8 > ]) """ tree_copy = self.label_tree.copy() # Remove labels not included if include_labels is not None: for iv in list(tree_copy): if iv.data.value not in include_labels: tree_copy.remove(iv) def reduce(x, y): x.append(y) return x # Split labels when overlapping and merge equal ranges to a list of labels tree_copy.split_overlaps() tree_copy.merge_equals(data_reducer=reduce, data_initializer=[]) intervals = sorted(tree_copy) last_end = intervals[0].begin # yield range by range for i in range(len(intervals)): iv = intervals[i] # yield an empty range if necessary if yield_ranges_without_labels and iv.begin > last_end: yield (last_end, iv.begin, []) yield (iv.begin, iv.end, iv.data) last_end = iv.end
[ "def", "ranges", "(", "self", ",", "yield_ranges_without_labels", "=", "False", ",", "include_labels", "=", "None", ")", ":", "tree_copy", "=", "self", ".", "label_tree", ".", "copy", "(", ")", "# Remove labels not included", "if", "include_labels", "is", "not",...
Generate all ranges of the label-list. A range is defined as a part of the label-list for which the same labels are defined. Args: yield_ranges_without_labels(bool): If True also yields ranges for which no labels are defined. include_labels(list): If not empty, only the label values in the list will be considered. Returns: generator: A generator which yields one range (tuple start/end/list-of-labels) at a time. Example: >>> ll = LabelList(labels=[ >>> Label('a', 3.2, 4.5), >>> Label('b', 5.1, 8.9), >>> Label('c', 7.2, 10.5), >>> Label('d', 10.5, 14) >>>]) >>> ranges = ll.ranges() >>> next(ranges) (3.2, 4.5, [ < audiomate.annotations.Label at 0x1090527c8 > ]) >>> next(ranges) (4.5, 5.1, []) >>> next(ranges) (5.1, 7.2, [ < audiomate.annotations.label.Label at 0x1090484c8 > ])
[ "Generate", "all", "ranges", "of", "the", "label", "-", "list", ".", "A", "range", "is", "defined", "as", "a", "part", "of", "the", "label", "-", "list", "for", "which", "the", "same", "labels", "are", "defined", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/annotations/label_list.py#L458-L518
train
32,643
ynop/audiomate
audiomate/annotations/label_list.py
LabelList.create_single
def create_single(cls, value, idx='default'): """ Create a label-list with a single label containing the given value. """ return LabelList(idx=idx, labels=[ Label(value=value) ])
python
def create_single(cls, value, idx='default'): """ Create a label-list with a single label containing the given value. """ return LabelList(idx=idx, labels=[ Label(value=value) ])
[ "def", "create_single", "(", "cls", ",", "value", ",", "idx", "=", "'default'", ")", ":", "return", "LabelList", "(", "idx", "=", "idx", ",", "labels", "=", "[", "Label", "(", "value", "=", "value", ")", "]", ")" ]
Create a label-list with a single label containing the given value.
[ "Create", "a", "label", "-", "list", "with", "a", "single", "label", "containing", "the", "given", "value", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/annotations/label_list.py#L634-L639
train
32,644
ynop/audiomate
audiomate/corpus/io/mailabs.py
MailabsReader.get_folders
def get_folders(path): """ Return a list of all subfolder-paths in the given path. """ folder_paths = [] for item in os.listdir(path): folder_path = os.path.join(path, item) if os.path.isdir(folder_path): folder_paths.append(folder_path) return folder_paths
python
def get_folders(path): """ Return a list of all subfolder-paths in the given path. """ folder_paths = [] for item in os.listdir(path): folder_path = os.path.join(path, item) if os.path.isdir(folder_path): folder_paths.append(folder_path) return folder_paths
[ "def", "get_folders", "(", "path", ")", ":", "folder_paths", "=", "[", "]", "for", "item", "in", "os", ".", "listdir", "(", "path", ")", ":", "folder_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "item", ")", "if", "os", ".", "pat...
Return a list of all subfolder-paths in the given path.
[ "Return", "a", "list", "of", "all", "subfolder", "-", "paths", "in", "the", "given", "path", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/io/mailabs.py#L82-L94
train
32,645
ynop/audiomate
audiomate/corpus/io/mailabs.py
MailabsReader.load_tag
def load_tag(corpus, path): """ Iterate over all speakers on load them. Collect all utterance-idx and create a subset of them. """ tag_idx = os.path.basename(path) data_path = os.path.join(path, 'by_book') tag_utt_ids = [] for gender_path in MailabsReader.get_folders(data_path): # IN MIX FOLDERS THERE ARE NO SPEAKERS # HANDLE EVERY UTT AS DIFFERENT ISSUER if os.path.basename(gender_path) == 'mix': utt_ids = MailabsReader.load_books_of_speaker(corpus, gender_path, None) tag_utt_ids.extend(utt_ids) else: for speaker_path in MailabsReader.get_folders(gender_path): speaker = MailabsReader.load_speaker(corpus, speaker_path) utt_ids = MailabsReader.load_books_of_speaker(corpus, speaker_path, speaker) tag_utt_ids.extend(utt_ids) filter = subset.MatchingUtteranceIdxFilter( utterance_idxs=set(tag_utt_ids) ) subview = subset.Subview(corpus, filter_criteria=[filter]) corpus.import_subview(tag_idx, subview)
python
def load_tag(corpus, path): """ Iterate over all speakers on load them. Collect all utterance-idx and create a subset of them. """ tag_idx = os.path.basename(path) data_path = os.path.join(path, 'by_book') tag_utt_ids = [] for gender_path in MailabsReader.get_folders(data_path): # IN MIX FOLDERS THERE ARE NO SPEAKERS # HANDLE EVERY UTT AS DIFFERENT ISSUER if os.path.basename(gender_path) == 'mix': utt_ids = MailabsReader.load_books_of_speaker(corpus, gender_path, None) tag_utt_ids.extend(utt_ids) else: for speaker_path in MailabsReader.get_folders(gender_path): speaker = MailabsReader.load_speaker(corpus, speaker_path) utt_ids = MailabsReader.load_books_of_speaker(corpus, speaker_path, speaker) tag_utt_ids.extend(utt_ids) filter = subset.MatchingUtteranceIdxFilter( utterance_idxs=set(tag_utt_ids) ) subview = subset.Subview(corpus, filter_criteria=[filter]) corpus.import_subview(tag_idx, subview)
[ "def", "load_tag", "(", "corpus", ",", "path", ")", ":", "tag_idx", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "data_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'by_book'", ")", "tag_utt_ids", "=", "[", "]", "for"...
Iterate over all speakers on load them. Collect all utterance-idx and create a subset of them.
[ "Iterate", "over", "all", "speakers", "on", "load", "them", ".", "Collect", "all", "utterance", "-", "idx", "and", "create", "a", "subset", "of", "them", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/io/mailabs.py#L97-L129
train
32,646
ynop/audiomate
audiomate/corpus/io/mailabs.py
MailabsReader.load_speaker
def load_speaker(corpus, path): """ Create a speaker instance for the given path. """ base_path, speaker_name = os.path.split(path) base_path, gender_desc = os.path.split(base_path) base_path, __ = os.path.split(base_path) base_path, tag = os.path.split(base_path) gender = issuers.Gender.UNKNOWN if gender_desc == 'male': gender = issuers.Gender.MALE elif gender_desc == 'female': gender = issuers.Gender.FEMALE speaker = issuers.Speaker(speaker_name, gender=gender) corpus.import_issuers(speaker) return speaker
python
def load_speaker(corpus, path): """ Create a speaker instance for the given path. """ base_path, speaker_name = os.path.split(path) base_path, gender_desc = os.path.split(base_path) base_path, __ = os.path.split(base_path) base_path, tag = os.path.split(base_path) gender = issuers.Gender.UNKNOWN if gender_desc == 'male': gender = issuers.Gender.MALE elif gender_desc == 'female': gender = issuers.Gender.FEMALE speaker = issuers.Speaker(speaker_name, gender=gender) corpus.import_issuers(speaker) return speaker
[ "def", "load_speaker", "(", "corpus", ",", "path", ")", ":", "base_path", ",", "speaker_name", "=", "os", ".", "path", ".", "split", "(", "path", ")", "base_path", ",", "gender_desc", "=", "os", ".", "path", ".", "split", "(", "base_path", ")", "base_p...
Create a speaker instance for the given path.
[ "Create", "a", "speaker", "instance", "for", "the", "given", "path", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/io/mailabs.py#L132-L151
train
32,647
ynop/audiomate
audiomate/corpus/io/mailabs.py
MailabsReader.load_books_of_speaker
def load_books_of_speaker(corpus, path, speaker): """ Load all utterances for the speaker at the given path. """ utt_ids = [] for book_path in MailabsReader.get_folders(path): meta_path = os.path.join(book_path, 'metadata.csv') wavs_path = os.path.join(book_path, 'wavs') meta = textfile.read_separated_lines(meta_path, separator='|', max_columns=3) for entry in meta: file_basename = entry[0] transcription_raw = entry[1] transcription_clean = entry[2] if speaker is None: idx = file_basename utt_speaker = issuers.Speaker(idx) speaker_idx = idx corpus.import_issuers(utt_speaker) else: idx = '{}-{}'.format(speaker.idx, file_basename) speaker_idx = speaker.idx wav_name = '{}.wav'.format(file_basename) wav_path = os.path.join(wavs_path, wav_name) if os.path.isfile(wav_path): corpus.new_file(wav_path, idx) ll_raw = annotations.LabelList.create_single( transcription_raw, idx=audiomate.corpus.LL_WORD_TRANSCRIPT_RAW ) ll_clean = annotations.LabelList.create_single( transcription_clean, idx=audiomate.corpus.LL_WORD_TRANSCRIPT ) utterance = corpus.new_utterance(idx, idx, speaker_idx) utterance.set_label_list(ll_raw) utterance.set_label_list(ll_clean) utt_ids.append(utterance.idx) return utt_ids
python
def load_books_of_speaker(corpus, path, speaker): """ Load all utterances for the speaker at the given path. """ utt_ids = [] for book_path in MailabsReader.get_folders(path): meta_path = os.path.join(book_path, 'metadata.csv') wavs_path = os.path.join(book_path, 'wavs') meta = textfile.read_separated_lines(meta_path, separator='|', max_columns=3) for entry in meta: file_basename = entry[0] transcription_raw = entry[1] transcription_clean = entry[2] if speaker is None: idx = file_basename utt_speaker = issuers.Speaker(idx) speaker_idx = idx corpus.import_issuers(utt_speaker) else: idx = '{}-{}'.format(speaker.idx, file_basename) speaker_idx = speaker.idx wav_name = '{}.wav'.format(file_basename) wav_path = os.path.join(wavs_path, wav_name) if os.path.isfile(wav_path): corpus.new_file(wav_path, idx) ll_raw = annotations.LabelList.create_single( transcription_raw, idx=audiomate.corpus.LL_WORD_TRANSCRIPT_RAW ) ll_clean = annotations.LabelList.create_single( transcription_clean, idx=audiomate.corpus.LL_WORD_TRANSCRIPT ) utterance = corpus.new_utterance(idx, idx, speaker_idx) utterance.set_label_list(ll_raw) utterance.set_label_list(ll_clean) utt_ids.append(utterance.idx) return utt_ids
[ "def", "load_books_of_speaker", "(", "corpus", ",", "path", ",", "speaker", ")", ":", "utt_ids", "=", "[", "]", "for", "book_path", "in", "MailabsReader", ".", "get_folders", "(", "path", ")", ":", "meta_path", "=", "os", ".", "path", ".", "join", "(", ...
Load all utterances for the speaker at the given path.
[ "Load", "all", "utterances", "for", "the", "speaker", "at", "the", "given", "path", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/io/mailabs.py#L154-L204
train
32,648
ynop/audiomate
audiomate/containers/container.py
Container.open
def open(self, mode=None): """ Open the container file. Args: mode (str): Either 'r' for read-only, 'w' for truncate and write or 'a' for append. (default: 'a'). If ``None``, uses ``self.mode``. """ if mode is None: mode = self.mode elif mode not in ['r', 'w', 'a']: raise ValueError('Invalid mode! Modes: [\'a\', \'r\', \'w\']') if self._file is None: self._file = h5py.File(self.path, mode=mode)
python
def open(self, mode=None): """ Open the container file. Args: mode (str): Either 'r' for read-only, 'w' for truncate and write or 'a' for append. (default: 'a'). If ``None``, uses ``self.mode``. """ if mode is None: mode = self.mode elif mode not in ['r', 'w', 'a']: raise ValueError('Invalid mode! Modes: [\'a\', \'r\', \'w\']') if self._file is None: self._file = h5py.File(self.path, mode=mode)
[ "def", "open", "(", "self", ",", "mode", "=", "None", ")", ":", "if", "mode", "is", "None", ":", "mode", "=", "self", ".", "mode", "elif", "mode", "not", "in", "[", "'r'", ",", "'w'", ",", "'a'", "]", ":", "raise", "ValueError", "(", "'Invalid mo...
Open the container file. Args: mode (str): Either 'r' for read-only, 'w' for truncate and write or 'a' for append. (default: 'a'). If ``None``, uses ``self.mode``.
[ "Open", "the", "container", "file", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/containers/container.py#L35-L51
train
32,649
ynop/audiomate
audiomate/containers/container.py
Container.open_if_needed
def open_if_needed(self, mode=None): """ Convenience context-manager for the use with ``with``. Opens the container if not already done. Only closes the container if it was opened within this context. Args: mode (str): Either 'r' for read-only, 'w' for truncate and write or 'a' for append. (default: 'a'). If ``None``, uses ``self.mode``. """ was_open = self.is_open() if not was_open: self.open(mode=mode) try: yield self finally: if not was_open: self.close()
python
def open_if_needed(self, mode=None): """ Convenience context-manager for the use with ``with``. Opens the container if not already done. Only closes the container if it was opened within this context. Args: mode (str): Either 'r' for read-only, 'w' for truncate and write or 'a' for append. (default: 'a'). If ``None``, uses ``self.mode``. """ was_open = self.is_open() if not was_open: self.open(mode=mode) try: yield self finally: if not was_open: self.close()
[ "def", "open_if_needed", "(", "self", ",", "mode", "=", "None", ")", ":", "was_open", "=", "self", ".", "is_open", "(", ")", "if", "not", "was_open", ":", "self", ".", "open", "(", "mode", "=", "mode", ")", "try", ":", "yield", "self", "finally", "...
Convenience context-manager for the use with ``with``. Opens the container if not already done. Only closes the container if it was opened within this context. Args: mode (str): Either 'r' for read-only, 'w' for truncate and write or 'a' for append. (default: 'a'). If ``None``, uses ``self.mode``.
[ "Convenience", "context", "-", "manager", "for", "the", "use", "with", "with", ".", "Opens", "the", "container", "if", "not", "already", "done", ".", "Only", "closes", "the", "container", "if", "it", "was", "opened", "within", "this", "context", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/containers/container.py#L68-L88
train
32,650
ynop/audiomate
audiomate/containers/container.py
Container.get
def get(self, key, mem_map=True): """ Read and return the data stored for the given key. Args: key (str): The key to read the data from. mem_map (bool): If ``True`` returns the data as memory-mapped array, otherwise a copy is returned. Note: The container has to be opened in advance. Returns: numpy.ndarray: The stored data. """ self.raise_error_if_not_open() if key in self._file: data = self._file[key] if not mem_map: data = data[()] return data else: return None
python
def get(self, key, mem_map=True): """ Read and return the data stored for the given key. Args: key (str): The key to read the data from. mem_map (bool): If ``True`` returns the data as memory-mapped array, otherwise a copy is returned. Note: The container has to be opened in advance. Returns: numpy.ndarray: The stored data. """ self.raise_error_if_not_open() if key in self._file: data = self._file[key] if not mem_map: data = data[()] return data else: return None
[ "def", "get", "(", "self", ",", "key", ",", "mem_map", "=", "True", ")", ":", "self", ".", "raise_error_if_not_open", "(", ")", "if", "key", "in", "self", ".", "_file", ":", "data", "=", "self", ".", "_file", "[", "key", "]", "if", "not", "mem_map"...
Read and return the data stored for the given key. Args: key (str): The key to read the data from. mem_map (bool): If ``True`` returns the data as memory-mapped array, otherwise a copy is returned. Note: The container has to be opened in advance. Returns: numpy.ndarray: The stored data.
[ "Read", "and", "return", "the", "data", "stored", "for", "the", "given", "key", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/containers/container.py#L111-L136
train
32,651
ynop/audiomate
audiomate/containers/container.py
Container.remove
def remove(self, key): """ Remove the data stored for the given key. Args: key (str): Key of the data to remove. Note: The container has to be opened in advance. """ self.raise_error_if_not_open() if key in self._file: del self._file[key]
python
def remove(self, key): """ Remove the data stored for the given key. Args: key (str): Key of the data to remove. Note: The container has to be opened in advance. """ self.raise_error_if_not_open() if key in self._file: del self._file[key]
[ "def", "remove", "(", "self", ",", "key", ")", ":", "self", ".", "raise_error_if_not_open", "(", ")", "if", "key", "in", "self", ".", "_file", ":", "del", "self", ".", "_file", "[", "key", "]" ]
Remove the data stored for the given key. Args: key (str): Key of the data to remove. Note: The container has to be opened in advance.
[ "Remove", "the", "data", "stored", "for", "the", "given", "key", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/containers/container.py#L196-L209
train
32,652
ynop/audiomate
audiomate/tracks/utterance.py
Utterance.end_abs
def end_abs(self): """ Return the absolute end of the utterance relative to the signal. """ if self.end == float('inf'): return self.track.duration else: return self.end
python
def end_abs(self): """ Return the absolute end of the utterance relative to the signal. """ if self.end == float('inf'): return self.track.duration else: return self.end
[ "def", "end_abs", "(", "self", ")", ":", "if", "self", ".", "end", "==", "float", "(", "'inf'", ")", ":", "return", "self", ".", "track", ".", "duration", "else", ":", "return", "self", ".", "end" ]
Return the absolute end of the utterance relative to the signal.
[ "Return", "the", "absolute", "end", "of", "the", "utterance", "relative", "to", "the", "signal", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/tracks/utterance.py#L68-L75
train
32,653
ynop/audiomate
audiomate/tracks/utterance.py
Utterance.num_samples
def num_samples(self, sr=None): """ Return the number of samples. Args: sr (int): Calculate the number of samples with the given sampling-rate. If None use the native sampling-rate. Returns: int: Number of samples """ native_sr = self.sampling_rate num_samples = units.seconds_to_sample(self.duration, native_sr) if sr is not None: ratio = float(sr) / native_sr num_samples = int(np.ceil(num_samples * ratio)) return num_samples
python
def num_samples(self, sr=None): """ Return the number of samples. Args: sr (int): Calculate the number of samples with the given sampling-rate. If None use the native sampling-rate. Returns: int: Number of samples """ native_sr = self.sampling_rate num_samples = units.seconds_to_sample(self.duration, native_sr) if sr is not None: ratio = float(sr) / native_sr num_samples = int(np.ceil(num_samples * ratio)) return num_samples
[ "def", "num_samples", "(", "self", ",", "sr", "=", "None", ")", ":", "native_sr", "=", "self", ".", "sampling_rate", "num_samples", "=", "units", ".", "seconds_to_sample", "(", "self", ".", "duration", ",", "native_sr", ")", "if", "sr", "is", "not", "Non...
Return the number of samples. Args: sr (int): Calculate the number of samples with the given sampling-rate. If None use the native sampling-rate. Returns: int: Number of samples
[ "Return", "the", "number", "of", "samples", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/tracks/utterance.py#L84-L102
train
32,654
ynop/audiomate
audiomate/tracks/utterance.py
Utterance.read_samples
def read_samples(self, sr=None, offset=0, duration=None): """ Read the samples of the utterance. Args: sr (int): If None uses the sampling rate given by the track, otherwise resamples to the given sampling rate. offset (float): Offset in seconds to read samples from. duration (float): If not ``None`` read only this number of seconds in maximum. Returns: np.ndarray: A numpy array containing the samples as a floating point (numpy.float32) time series. """ read_duration = self.duration if offset > 0 and read_duration is not None: read_duration -= offset if duration is not None: if read_duration is None: read_duration = duration else: read_duration = min(duration, read_duration) return self.track.read_samples( sr=sr, offset=self.start + offset, duration=read_duration )
python
def read_samples(self, sr=None, offset=0, duration=None): """ Read the samples of the utterance. Args: sr (int): If None uses the sampling rate given by the track, otherwise resamples to the given sampling rate. offset (float): Offset in seconds to read samples from. duration (float): If not ``None`` read only this number of seconds in maximum. Returns: np.ndarray: A numpy array containing the samples as a floating point (numpy.float32) time series. """ read_duration = self.duration if offset > 0 and read_duration is not None: read_duration -= offset if duration is not None: if read_duration is None: read_duration = duration else: read_duration = min(duration, read_duration) return self.track.read_samples( sr=sr, offset=self.start + offset, duration=read_duration )
[ "def", "read_samples", "(", "self", ",", "sr", "=", "None", ",", "offset", "=", "0", ",", "duration", "=", "None", ")", ":", "read_duration", "=", "self", ".", "duration", "if", "offset", ">", "0", "and", "read_duration", "is", "not", "None", ":", "r...
Read the samples of the utterance. Args: sr (int): If None uses the sampling rate given by the track, otherwise resamples to the given sampling rate. offset (float): Offset in seconds to read samples from. duration (float): If not ``None`` read only this number of seconds in maximum. Returns: np.ndarray: A numpy array containing the samples as a floating point (numpy.float32) time series.
[ "Read", "the", "samples", "of", "the", "utterance", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/tracks/utterance.py#L108-L139
train
32,655
ynop/audiomate
audiomate/tracks/utterance.py
Utterance.set_label_list
def set_label_list(self, label_lists): """ Set the given label-list for this utterance. If the label-list-idx is not set, ``default`` is used. If there is already a label-list with the given idx, it will be overriden. Args: label_list (LabelList, list): A single or multi. label-lists to add. """ if isinstance(label_lists, annotations.LabelList): label_lists = [label_lists] for label_list in label_lists: if label_list.idx is None: label_list.idx = 'default' label_list.utterance = self self.label_lists[label_list.idx] = label_list
python
def set_label_list(self, label_lists): """ Set the given label-list for this utterance. If the label-list-idx is not set, ``default`` is used. If there is already a label-list with the given idx, it will be overriden. Args: label_list (LabelList, list): A single or multi. label-lists to add. """ if isinstance(label_lists, annotations.LabelList): label_lists = [label_lists] for label_list in label_lists: if label_list.idx is None: label_list.idx = 'default' label_list.utterance = self self.label_lists[label_list.idx] = label_list
[ "def", "set_label_list", "(", "self", ",", "label_lists", ")", ":", "if", "isinstance", "(", "label_lists", ",", "annotations", ".", "LabelList", ")", ":", "label_lists", "=", "[", "label_lists", "]", "for", "label_list", "in", "label_lists", ":", "if", "lab...
Set the given label-list for this utterance. If the label-list-idx is not set, ``default`` is used. If there is already a label-list with the given idx, it will be overriden. Args: label_list (LabelList, list): A single or multi. label-lists to add.
[ "Set", "the", "given", "label", "-", "list", "for", "this", "utterance", ".", "If", "the", "label", "-", "list", "-", "idx", "is", "not", "set", "default", "is", "used", ".", "If", "there", "is", "already", "a", "label", "-", "list", "with", "the", ...
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/tracks/utterance.py#L152-L172
train
32,656
ynop/audiomate
audiomate/tracks/utterance.py
Utterance.all_label_values
def all_label_values(self, label_list_ids=None): """ Return a set of all label-values occurring in this utterance. Args: label_list_ids (list): If not None, only label-values from label-lists with an id contained in this list are considered. Returns: :class:`set`: A set of distinct label-values. """ values = set() for label_list in self.label_lists.values(): if label_list_ids is None or label_list.idx in label_list_ids: values = values.union(label_list.label_values()) return values
python
def all_label_values(self, label_list_ids=None): """ Return a set of all label-values occurring in this utterance. Args: label_list_ids (list): If not None, only label-values from label-lists with an id contained in this list are considered. Returns: :class:`set`: A set of distinct label-values. """ values = set() for label_list in self.label_lists.values(): if label_list_ids is None or label_list.idx in label_list_ids: values = values.union(label_list.label_values()) return values
[ "def", "all_label_values", "(", "self", ",", "label_list_ids", "=", "None", ")", ":", "values", "=", "set", "(", ")", "for", "label_list", "in", "self", ".", "label_lists", ".", "values", "(", ")", ":", "if", "label_list_ids", "is", "None", "or", "label_...
Return a set of all label-values occurring in this utterance. Args: label_list_ids (list): If not None, only label-values from label-lists with an id contained in this list are considered. Returns: :class:`set`: A set of distinct label-values.
[ "Return", "a", "set", "of", "all", "label", "-", "values", "occurring", "in", "this", "utterance", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/tracks/utterance.py#L174-L192
train
32,657
ynop/audiomate
audiomate/tracks/utterance.py
Utterance.label_count
def label_count(self, label_list_ids=None): """ Return a dictionary containing the number of times, every label-value in this utterance is occurring. Args: label_list_ids (list): If not None, only labels from label-lists with an id contained in this list are considered. Returns: dict: A dictionary containing the number of occurrences with the label-value as key. """ count = collections.defaultdict(int) for label_list in self.label_lists.values(): if label_list_ids is None or label_list.idx in label_list_ids: for label_value, label_count in label_list.label_count().items(): count[label_value] += label_count return count
python
def label_count(self, label_list_ids=None): """ Return a dictionary containing the number of times, every label-value in this utterance is occurring. Args: label_list_ids (list): If not None, only labels from label-lists with an id contained in this list are considered. Returns: dict: A dictionary containing the number of occurrences with the label-value as key. """ count = collections.defaultdict(int) for label_list in self.label_lists.values(): if label_list_ids is None or label_list.idx in label_list_ids: for label_value, label_count in label_list.label_count().items(): count[label_value] += label_count return count
[ "def", "label_count", "(", "self", ",", "label_list_ids", "=", "None", ")", ":", "count", "=", "collections", ".", "defaultdict", "(", "int", ")", "for", "label_list", "in", "self", ".", "label_lists", ".", "values", "(", ")", ":", "if", "label_list_ids", ...
Return a dictionary containing the number of times, every label-value in this utterance is occurring. Args: label_list_ids (list): If not None, only labels from label-lists with an id contained in this list are considered. Returns: dict: A dictionary containing the number of occurrences with the label-value as key.
[ "Return", "a", "dictionary", "containing", "the", "number", "of", "times", "every", "label", "-", "value", "in", "this", "utterance", "is", "occurring", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/tracks/utterance.py#L194-L215
train
32,658
ynop/audiomate
audiomate/tracks/utterance.py
Utterance.all_tokens
def all_tokens(self, delimiter=' ', label_list_ids=None): """ Return a list of all tokens occurring in one of the labels in the label-lists. Args: delimiter (str): The delimiter used to split labels into tokens (see :meth:`audiomate.annotations.Label.tokenized`). label_list_ids (list): If not None, only labels from label-lists with an idx contained in this list are considered. Returns: :class:`set`: A set of distinct tokens. """ tokens = set() for label_list in self.label_lists.values(): if label_list_ids is None or label_list.idx in label_list_ids: tokens = tokens.union(label_list.all_tokens(delimiter=delimiter)) return tokens
python
def all_tokens(self, delimiter=' ', label_list_ids=None): """ Return a list of all tokens occurring in one of the labels in the label-lists. Args: delimiter (str): The delimiter used to split labels into tokens (see :meth:`audiomate.annotations.Label.tokenized`). label_list_ids (list): If not None, only labels from label-lists with an idx contained in this list are considered. Returns: :class:`set`: A set of distinct tokens. """ tokens = set() for label_list in self.label_lists.values(): if label_list_ids is None or label_list.idx in label_list_ids: tokens = tokens.union(label_list.all_tokens(delimiter=delimiter)) return tokens
[ "def", "all_tokens", "(", "self", ",", "delimiter", "=", "' '", ",", "label_list_ids", "=", "None", ")", ":", "tokens", "=", "set", "(", ")", "for", "label_list", "in", "self", ".", "label_lists", ".", "values", "(", ")", ":", "if", "label_list_ids", "...
Return a list of all tokens occurring in one of the labels in the label-lists. Args: delimiter (str): The delimiter used to split labels into tokens (see :meth:`audiomate.annotations.Label.tokenized`). label_list_ids (list): If not None, only labels from label-lists with an idx contained in this list are considered. Returns: :class:`set`: A set of distinct tokens.
[ "Return", "a", "list", "of", "all", "tokens", "occurring", "in", "one", "of", "the", "labels", "in", "the", "label", "-", "lists", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/tracks/utterance.py#L217-L237
train
32,659
ynop/audiomate
audiomate/tracks/utterance.py
Utterance.label_total_duration
def label_total_duration(self, label_list_ids=None): """ Return a dictionary containing the number of seconds, every label-value is occurring in this utterance. Args: label_list_ids (list): If not None, only labels from label-lists with an id contained in this list are considered. Returns: dict: A dictionary containing the number of seconds with the label-value as key. """ duration = collections.defaultdict(float) for label_list in self.label_lists.values(): if label_list_ids is None or label_list.idx in label_list_ids: for label_value, label_duration in label_list.label_total_duration().items(): duration[label_value] += label_duration return duration
python
def label_total_duration(self, label_list_ids=None): """ Return a dictionary containing the number of seconds, every label-value is occurring in this utterance. Args: label_list_ids (list): If not None, only labels from label-lists with an id contained in this list are considered. Returns: dict: A dictionary containing the number of seconds with the label-value as key. """ duration = collections.defaultdict(float) for label_list in self.label_lists.values(): if label_list_ids is None or label_list.idx in label_list_ids: for label_value, label_duration in label_list.label_total_duration().items(): duration[label_value] += label_duration return duration
[ "def", "label_total_duration", "(", "self", ",", "label_list_ids", "=", "None", ")", ":", "duration", "=", "collections", ".", "defaultdict", "(", "float", ")", "for", "label_list", "in", "self", ".", "label_lists", ".", "values", "(", ")", ":", "if", "lab...
Return a dictionary containing the number of seconds, every label-value is occurring in this utterance. Args: label_list_ids (list): If not None, only labels from label-lists with an id contained in this list are considered. Returns: dict: A dictionary containing the number of seconds with the label-value as key.
[ "Return", "a", "dictionary", "containing", "the", "number", "of", "seconds", "every", "label", "-", "value", "is", "occurring", "in", "this", "utterance", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/tracks/utterance.py#L239-L260
train
32,660
ynop/audiomate
audiomate/containers/features.py
FeatureContainer.stats
def stats(self): """ Return statistics calculated overall features in the container. Note: The feature container has to be opened in advance. Returns: DataStats: Statistics overall data points of all features. """ self.raise_error_if_not_open() per_key_stats = self.stats_per_key() return stats.DataStats.concatenate(per_key_stats.values())
python
def stats(self): """ Return statistics calculated overall features in the container. Note: The feature container has to be opened in advance. Returns: DataStats: Statistics overall data points of all features. """ self.raise_error_if_not_open() per_key_stats = self.stats_per_key() return stats.DataStats.concatenate(per_key_stats.values())
[ "def", "stats", "(", "self", ")", ":", "self", ".", "raise_error_if_not_open", "(", ")", "per_key_stats", "=", "self", ".", "stats_per_key", "(", ")", "return", "stats", ".", "DataStats", ".", "concatenate", "(", "per_key_stats", ".", "values", "(", ")", "...
Return statistics calculated overall features in the container. Note: The feature container has to be opened in advance. Returns: DataStats: Statistics overall data points of all features.
[ "Return", "statistics", "calculated", "overall", "features", "in", "the", "container", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/containers/features.py#L60-L74
train
32,661
ynop/audiomate
audiomate/containers/features.py
FeatureContainer.stats_per_key
def stats_per_key(self): """ Return statistics calculated for each key in the container. Note: The feature container has to be opened in advance. Returns: dict: A dictionary containing a DataStats object for each key. """ self.raise_error_if_not_open() all_stats = {} for key, data in self._file.items(): data = data[()] all_stats[key] = stats.DataStats(float(np.mean(data)), float(np.var(data)), np.min(data), np.max(data), data.size) return all_stats
python
def stats_per_key(self): """ Return statistics calculated for each key in the container. Note: The feature container has to be opened in advance. Returns: dict: A dictionary containing a DataStats object for each key. """ self.raise_error_if_not_open() all_stats = {} for key, data in self._file.items(): data = data[()] all_stats[key] = stats.DataStats(float(np.mean(data)), float(np.var(data)), np.min(data), np.max(data), data.size) return all_stats
[ "def", "stats_per_key", "(", "self", ")", ":", "self", ".", "raise_error_if_not_open", "(", ")", "all_stats", "=", "{", "}", "for", "key", ",", "data", "in", "self", ".", "_file", ".", "items", "(", ")", ":", "data", "=", "data", "[", "(", ")", "]"...
Return statistics calculated for each key in the container. Note: The feature container has to be opened in advance. Returns: dict: A dictionary containing a DataStats object for each key.
[ "Return", "statistics", "calculated", "for", "each", "key", "in", "the", "container", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/containers/features.py#L76-L98
train
32,662
ynop/audiomate
audiomate/corpus/base.py
CorpusView.all_label_values
def all_label_values(self, label_list_ids=None): """ Return a set of all label-values occurring in this corpus. Args: label_list_ids (list): If not None, only labels from label-lists with an id contained in this list are considered. Returns: :class:`set`: A set of distinct label-values. """ values = set() for utterance in self.utterances.values(): values = values.union(utterance.all_label_values(label_list_ids=label_list_ids)) return values
python
def all_label_values(self, label_list_ids=None): """ Return a set of all label-values occurring in this corpus. Args: label_list_ids (list): If not None, only labels from label-lists with an id contained in this list are considered. Returns: :class:`set`: A set of distinct label-values. """ values = set() for utterance in self.utterances.values(): values = values.union(utterance.all_label_values(label_list_ids=label_list_ids)) return values
[ "def", "all_label_values", "(", "self", ",", "label_list_ids", "=", "None", ")", ":", "values", "=", "set", "(", ")", "for", "utterance", "in", "self", ".", "utterances", ".", "values", "(", ")", ":", "values", "=", "values", ".", "union", "(", "uttera...
Return a set of all label-values occurring in this corpus. Args: label_list_ids (list): If not None, only labels from label-lists with an id contained in this list are considered. Returns: :class:`set`: A set of distinct label-values.
[ "Return", "a", "set", "of", "all", "label", "-", "values", "occurring", "in", "this", "corpus", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/base.py#L133-L149
train
32,663
ynop/audiomate
audiomate/corpus/base.py
CorpusView.label_count
def label_count(self, label_list_ids=None): """ Return a dictionary containing the number of times, every label-value in this corpus is occurring. Args: label_list_ids (list): If not None, only labels from label-lists with an id contained in this list are considered. Returns: dict: A dictionary containing the number of occurrences with the label-value as key. """ count = collections.defaultdict(int) for utterance in self.utterances.values(): for label_value, utt_count in utterance.label_count(label_list_ids=label_list_ids).items(): count[label_value] += utt_count return count
python
def label_count(self, label_list_ids=None): """ Return a dictionary containing the number of times, every label-value in this corpus is occurring. Args: label_list_ids (list): If not None, only labels from label-lists with an id contained in this list are considered. Returns: dict: A dictionary containing the number of occurrences with the label-value as key. """ count = collections.defaultdict(int) for utterance in self.utterances.values(): for label_value, utt_count in utterance.label_count(label_list_ids=label_list_ids).items(): count[label_value] += utt_count return count
[ "def", "label_count", "(", "self", ",", "label_list_ids", "=", "None", ")", ":", "count", "=", "collections", ".", "defaultdict", "(", "int", ")", "for", "utterance", "in", "self", ".", "utterances", ".", "values", "(", ")", ":", "for", "label_value", ",...
Return a dictionary containing the number of times, every label-value in this corpus is occurring. Args: label_list_ids (list): If not None, only labels from label-lists with an id contained in this list are considered. Returns: dict: A dictionary containing the number of occurrences with the label-value as key.
[ "Return", "a", "dictionary", "containing", "the", "number", "of", "times", "every", "label", "-", "value", "in", "this", "corpus", "is", "occurring", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/base.py#L151-L168
train
32,664
ynop/audiomate
audiomate/corpus/base.py
CorpusView.label_durations
def label_durations(self, label_list_ids=None): """ Return a dictionary containing the total duration, every label-value in this corpus is occurring. Args: label_list_ids (list): If not None, only labels from label-lists with an id contained in this list are considered. Returns: dict: A dictionary containing the total duration with the label-value as key. """ duration = collections.defaultdict(int) for utterance in self.utterances.values(): for label_value, utt_count in utterance.label_total_duration(label_list_ids=label_list_ids).items(): duration[label_value] += utt_count return duration
python
def label_durations(self, label_list_ids=None): """ Return a dictionary containing the total duration, every label-value in this corpus is occurring. Args: label_list_ids (list): If not None, only labels from label-lists with an id contained in this list are considered. Returns: dict: A dictionary containing the total duration with the label-value as key. """ duration = collections.defaultdict(int) for utterance in self.utterances.values(): for label_value, utt_count in utterance.label_total_duration(label_list_ids=label_list_ids).items(): duration[label_value] += utt_count return duration
[ "def", "label_durations", "(", "self", ",", "label_list_ids", "=", "None", ")", ":", "duration", "=", "collections", ".", "defaultdict", "(", "int", ")", "for", "utterance", "in", "self", ".", "utterances", ".", "values", "(", ")", ":", "for", "label_value...
Return a dictionary containing the total duration, every label-value in this corpus is occurring. Args: label_list_ids (list): If not None, only labels from label-lists with an id contained in this list are considered. Returns: dict: A dictionary containing the total duration with the label-value as key.
[ "Return", "a", "dictionary", "containing", "the", "total", "duration", "every", "label", "-", "value", "in", "this", "corpus", "is", "occurring", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/base.py#L170-L187
train
32,665
ynop/audiomate
audiomate/corpus/base.py
CorpusView.all_tokens
def all_tokens(self, delimiter=' ', label_list_ids=None): """ Return a list of all tokens occurring in one of the labels in the corpus. Args: delimiter (str): The delimiter used to split labels into tokens (see :meth:`audiomate.annotations.Label.tokenized`). label_list_ids (list): If not None, only labels from label-lists with an idx contained in this list are considered. Returns: :class:`set`: A set of distinct tokens. """ tokens = set() for utterance in self.utterances.values(): tokens = tokens.union(utterance.all_tokens(delimiter=delimiter, label_list_ids=label_list_ids)) return tokens
python
def all_tokens(self, delimiter=' ', label_list_ids=None): """ Return a list of all tokens occurring in one of the labels in the corpus. Args: delimiter (str): The delimiter used to split labels into tokens (see :meth:`audiomate.annotations.Label.tokenized`). label_list_ids (list): If not None, only labels from label-lists with an idx contained in this list are considered. Returns: :class:`set`: A set of distinct tokens. """ tokens = set() for utterance in self.utterances.values(): tokens = tokens.union(utterance.all_tokens(delimiter=delimiter, label_list_ids=label_list_ids)) return tokens
[ "def", "all_tokens", "(", "self", ",", "delimiter", "=", "' '", ",", "label_list_ids", "=", "None", ")", ":", "tokens", "=", "set", "(", ")", "for", "utterance", "in", "self", ".", "utterances", ".", "values", "(", ")", ":", "tokens", "=", "tokens", ...
Return a list of all tokens occurring in one of the labels in the corpus. Args: delimiter (str): The delimiter used to split labels into tokens (see :meth:`audiomate.annotations.Label.tokenized`). label_list_ids (list): If not None, only labels from label-lists with an idx contained in this list are considered. Returns: :class:`set`: A set of distinct tokens.
[ "Return", "a", "list", "of", "all", "tokens", "occurring", "in", "one", "of", "the", "labels", "in", "the", "corpus", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/base.py#L189-L207
train
32,666
ynop/audiomate
audiomate/corpus/base.py
CorpusView.total_duration
def total_duration(self): """ Return the total amount of audio summed over all utterances in the corpus in seconds. """ duration = 0 for utterance in self.utterances.values(): duration += utterance.duration return duration
python
def total_duration(self): """ Return the total amount of audio summed over all utterances in the corpus in seconds. """ duration = 0 for utterance in self.utterances.values(): duration += utterance.duration return duration
[ "def", "total_duration", "(", "self", ")", ":", "duration", "=", "0", "for", "utterance", "in", "self", ".", "utterances", ".", "values", "(", ")", ":", "duration", "+=", "utterance", ".", "duration", "return", "duration" ]
Return the total amount of audio summed over all utterances in the corpus in seconds.
[ "Return", "the", "total", "amount", "of", "audio", "summed", "over", "all", "utterances", "in", "the", "corpus", "in", "seconds", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/base.py#L214-L223
train
32,667
ynop/audiomate
audiomate/corpus/base.py
CorpusView.stats
def stats(self): """ Return statistics calculated overall samples of all utterances in the corpus. Returns: DataStats: A DataStats object containing statistics overall samples in the corpus. """ per_utt_stats = self.stats_per_utterance() return stats.DataStats.concatenate(per_utt_stats.values())
python
def stats(self): """ Return statistics calculated overall samples of all utterances in the corpus. Returns: DataStats: A DataStats object containing statistics overall samples in the corpus. """ per_utt_stats = self.stats_per_utterance() return stats.DataStats.concatenate(per_utt_stats.values())
[ "def", "stats", "(", "self", ")", ":", "per_utt_stats", "=", "self", ".", "stats_per_utterance", "(", ")", "return", "stats", ".", "DataStats", ".", "concatenate", "(", "per_utt_stats", ".", "values", "(", ")", ")" ]
Return statistics calculated overall samples of all utterances in the corpus. Returns: DataStats: A DataStats object containing statistics overall samples in the corpus.
[ "Return", "statistics", "calculated", "overall", "samples", "of", "all", "utterances", "in", "the", "corpus", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/base.py#L225-L234
train
32,668
ynop/audiomate
audiomate/corpus/base.py
CorpusView.stats_per_utterance
def stats_per_utterance(self): """ Return statistics calculated for all samples of each utterance in the corpus. Returns: dict: A dictionary containing a DataStats object for each utt. """ all_stats = {} for utterance in self.utterances.values(): data = utterance.read_samples() all_stats[utterance.idx] = stats.DataStats(float(np.mean(data)), float(np.var(data)), np.min(data), np.max(data), data.size) return all_stats
python
def stats_per_utterance(self): """ Return statistics calculated for all samples of each utterance in the corpus. Returns: dict: A dictionary containing a DataStats object for each utt. """ all_stats = {} for utterance in self.utterances.values(): data = utterance.read_samples() all_stats[utterance.idx] = stats.DataStats(float(np.mean(data)), float(np.var(data)), np.min(data), np.max(data), data.size) return all_stats
[ "def", "stats_per_utterance", "(", "self", ")", ":", "all_stats", "=", "{", "}", "for", "utterance", "in", "self", ".", "utterances", ".", "values", "(", ")", ":", "data", "=", "utterance", ".", "read_samples", "(", ")", "all_stats", "[", "utterance", "....
Return statistics calculated for all samples of each utterance in the corpus. Returns: dict: A dictionary containing a DataStats object for each utt.
[ "Return", "statistics", "calculated", "for", "all", "samples", "of", "each", "utterance", "in", "the", "corpus", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/base.py#L236-L254
train
32,669
ynop/audiomate
audiomate/corpus/base.py
CorpusView.split_utterances_to_max_time
def split_utterances_to_max_time(self, max_time=60.0, overlap=0.0): """ Create a new corpus, where all the utterances are of given maximal duration. Utterance longer than ``max_time`` are split up into multiple utterances. .. warning:: Subviews and FeatureContainers are not added to the newly create corpus. Arguments: max_time (float): Maximal duration for target utterances in seconds. overlap (float): Amount of overlap in seconds. The overlap is measured from the center of the splitting. (The actual overlap of two segments is 2 * overlap) Returns: Corpus: A new corpus instance. """ from audiomate.corpus import Corpus result = Corpus() # Copy Tracks tracks = copy.deepcopy(list(self.tracks.values())) result.import_tracks(tracks) # Copy Issuers issuers = copy.deepcopy(list(self.issuers.values())) result.import_issuers(issuers) for utterance in self.utterances.values(): orig_dur = utterance.duration if orig_dur > max_time: # Compute times where the utterance is split num_sub_utts = math.ceil(orig_dur / max_time) sub_utt_dur = orig_dur / num_sub_utts cutting_points = [] for i in range(1, num_sub_utts): cutting_points.append(i * sub_utt_dur) sub_utts = utterance.split(cutting_points, overlap=overlap) # Set track/issuer from new corpus for sub_utt in sub_utts: sub_utt.track = result.tracks[utterance.track.idx] if utterance.issuer is not None: sub_utt.issuer = result.issuers[utterance.issuer.idx] result.import_utterances(sub_utts) # If utterance <= max_time, just copy else: new_utt = copy.deepcopy(utterance) new_utt.track = result.tracks[new_utt.track.idx] if new_utt.issuer is not None: new_utt.issuer = result.issuers[new_utt.issuer.idx] result.import_utterances(new_utt) return result
python
def split_utterances_to_max_time(self, max_time=60.0, overlap=0.0): """ Create a new corpus, where all the utterances are of given maximal duration. Utterance longer than ``max_time`` are split up into multiple utterances. .. warning:: Subviews and FeatureContainers are not added to the newly create corpus. Arguments: max_time (float): Maximal duration for target utterances in seconds. overlap (float): Amount of overlap in seconds. The overlap is measured from the center of the splitting. (The actual overlap of two segments is 2 * overlap) Returns: Corpus: A new corpus instance. """ from audiomate.corpus import Corpus result = Corpus() # Copy Tracks tracks = copy.deepcopy(list(self.tracks.values())) result.import_tracks(tracks) # Copy Issuers issuers = copy.deepcopy(list(self.issuers.values())) result.import_issuers(issuers) for utterance in self.utterances.values(): orig_dur = utterance.duration if orig_dur > max_time: # Compute times where the utterance is split num_sub_utts = math.ceil(orig_dur / max_time) sub_utt_dur = orig_dur / num_sub_utts cutting_points = [] for i in range(1, num_sub_utts): cutting_points.append(i * sub_utt_dur) sub_utts = utterance.split(cutting_points, overlap=overlap) # Set track/issuer from new corpus for sub_utt in sub_utts: sub_utt.track = result.tracks[utterance.track.idx] if utterance.issuer is not None: sub_utt.issuer = result.issuers[utterance.issuer.idx] result.import_utterances(sub_utts) # If utterance <= max_time, just copy else: new_utt = copy.deepcopy(utterance) new_utt.track = result.tracks[new_utt.track.idx] if new_utt.issuer is not None: new_utt.issuer = result.issuers[new_utt.issuer.idx] result.import_utterances(new_utt) return result
[ "def", "split_utterances_to_max_time", "(", "self", ",", "max_time", "=", "60.0", ",", "overlap", "=", "0.0", ")", ":", "from", "audiomate", ".", "corpus", "import", "Corpus", "result", "=", "Corpus", "(", ")", "# Copy Tracks", "tracks", "=", "copy", ".", ...
Create a new corpus, where all the utterances are of given maximal duration. Utterance longer than ``max_time`` are split up into multiple utterances. .. warning:: Subviews and FeatureContainers are not added to the newly create corpus. Arguments: max_time (float): Maximal duration for target utterances in seconds. overlap (float): Amount of overlap in seconds. The overlap is measured from the center of the splitting. (The actual overlap of two segments is 2 * overlap) Returns: Corpus: A new corpus instance.
[ "Create", "a", "new", "corpus", "where", "all", "the", "utterances", "are", "of", "given", "maximal", "duration", ".", "Utterance", "longer", "than", "max_time", "are", "split", "up", "into", "multiple", "utterances", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/base.py#L260-L323
train
32,670
ynop/audiomate
audiomate/feeding/dataset.py
MultiFrameDataset.get_utt_regions
def get_utt_regions(self): """ Return the regions of all utterances, assuming all utterances are concatenated. It is assumed that the utterances are sorted in ascending order for concatenation. A region is defined by offset (in chunks), length (num-chunks) and a list of references to the utterance datasets in the containers. Returns: list: List of with a tuple for every utterances containing the region info. """ regions = [] current_offset = 0 for utt_idx in sorted(self.utt_ids): offset = current_offset num_frames = [] refs = [] for cnt in self.containers: num_frames.append(cnt.get(utt_idx).shape[0]) refs.append(cnt.get(utt_idx, mem_map=True)) if len(set(num_frames)) != 1: raise ValueError('Utterance {} has not the same number of frames in all containers!'.format(utt_idx)) num_chunks = math.ceil(num_frames[0] / float(self.frames_per_chunk)) region = (offset, num_chunks, refs) regions.append(region) # Sets the offset for the next utterances current_offset += num_chunks return regions
python
def get_utt_regions(self): """ Return the regions of all utterances, assuming all utterances are concatenated. It is assumed that the utterances are sorted in ascending order for concatenation. A region is defined by offset (in chunks), length (num-chunks) and a list of references to the utterance datasets in the containers. Returns: list: List of with a tuple for every utterances containing the region info. """ regions = [] current_offset = 0 for utt_idx in sorted(self.utt_ids): offset = current_offset num_frames = [] refs = [] for cnt in self.containers: num_frames.append(cnt.get(utt_idx).shape[0]) refs.append(cnt.get(utt_idx, mem_map=True)) if len(set(num_frames)) != 1: raise ValueError('Utterance {} has not the same number of frames in all containers!'.format(utt_idx)) num_chunks = math.ceil(num_frames[0] / float(self.frames_per_chunk)) region = (offset, num_chunks, refs) regions.append(region) # Sets the offset for the next utterances current_offset += num_chunks return regions
[ "def", "get_utt_regions", "(", "self", ")", ":", "regions", "=", "[", "]", "current_offset", "=", "0", "for", "utt_idx", "in", "sorted", "(", "self", ".", "utt_ids", ")", ":", "offset", "=", "current_offset", "num_frames", "=", "[", "]", "refs", "=", "...
Return the regions of all utterances, assuming all utterances are concatenated. It is assumed that the utterances are sorted in ascending order for concatenation. A region is defined by offset (in chunks), length (num-chunks) and a list of references to the utterance datasets in the containers. Returns: list: List of with a tuple for every utterances containing the region info.
[ "Return", "the", "regions", "of", "all", "utterances", "assuming", "all", "utterances", "are", "concatenated", ".", "It", "is", "assumed", "that", "the", "utterances", "are", "sorted", "in", "ascending", "order", "for", "concatenation", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/feeding/dataset.py#L343-L379
train
32,671
ynop/audiomate
audiomate/containers/audio.py
AudioContainer.get
def get(self, key, mem_map=True): """ Return the samples for the given key and the sampling-rate. Args: key (str): The key to read the data from. mem_map (bool): If ``True`` returns the data as memory-mapped array, otherwise a copy is returned. Note: The container has to be opened in advance. Returns: tuple: A tuple containing the samples as numpy array with ``np.float32`` [-1.0,1.0] and the sampling-rate. """ self.raise_error_if_not_open() if key in self._file: data = self._file[key] sampling_rate = data.attrs[SAMPLING_RATE_ATTR] if not mem_map: data = data[()] data = np.float32(data) / MAX_INT16_VALUE return data, sampling_rate
python
def get(self, key, mem_map=True): """ Return the samples for the given key and the sampling-rate. Args: key (str): The key to read the data from. mem_map (bool): If ``True`` returns the data as memory-mapped array, otherwise a copy is returned. Note: The container has to be opened in advance. Returns: tuple: A tuple containing the samples as numpy array with ``np.float32`` [-1.0,1.0] and the sampling-rate. """ self.raise_error_if_not_open() if key in self._file: data = self._file[key] sampling_rate = data.attrs[SAMPLING_RATE_ATTR] if not mem_map: data = data[()] data = np.float32(data) / MAX_INT16_VALUE return data, sampling_rate
[ "def", "get", "(", "self", ",", "key", ",", "mem_map", "=", "True", ")", ":", "self", ".", "raise_error_if_not_open", "(", ")", "if", "key", "in", "self", ".", "_file", ":", "data", "=", "self", ".", "_file", "[", "key", "]", "sampling_rate", "=", ...
Return the samples for the given key and the sampling-rate. Args: key (str): The key to read the data from. mem_map (bool): If ``True`` returns the data as memory-mapped array, otherwise a copy is returned. Note: The container has to be opened in advance. Returns: tuple: A tuple containing the samples as numpy array with ``np.float32`` [-1.0,1.0] and the sampling-rate.
[ "Return", "the", "samples", "for", "the", "given", "key", "and", "the", "sampling", "-", "rate", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/containers/audio.py#L19-L46
train
32,672
ynop/audiomate
audiomate/containers/audio.py
AudioContainer.set
def set(self, key, samples, sampling_rate): """ Set the samples and sampling-rate for the given key. Existing data will be overwritten. The samples have to have ``np.float32`` datatype and values in the range of -1.0 and 1.0. Args: key (str): A key to store the data for. samples (numpy.ndarray): 1-D array of audio samples (np.float32). sampling_rate (int): The sampling-rate of the audio samples. Note: The container has to be opened in advance. """ if not np.issubdtype(samples.dtype, np.floating): raise ValueError('Samples are required as np.float32!') if len(samples.shape) > 1: raise ValueError('Only single channel supported!') self.raise_error_if_not_open() if key in self._file: del self._file[key] samples = (samples * MAX_INT16_VALUE).astype(np.int16) dset = self._file.create_dataset(key, data=samples) dset.attrs[SAMPLING_RATE_ATTR] = sampling_rate
python
def set(self, key, samples, sampling_rate): """ Set the samples and sampling-rate for the given key. Existing data will be overwritten. The samples have to have ``np.float32`` datatype and values in the range of -1.0 and 1.0. Args: key (str): A key to store the data for. samples (numpy.ndarray): 1-D array of audio samples (np.float32). sampling_rate (int): The sampling-rate of the audio samples. Note: The container has to be opened in advance. """ if not np.issubdtype(samples.dtype, np.floating): raise ValueError('Samples are required as np.float32!') if len(samples.shape) > 1: raise ValueError('Only single channel supported!') self.raise_error_if_not_open() if key in self._file: del self._file[key] samples = (samples * MAX_INT16_VALUE).astype(np.int16) dset = self._file.create_dataset(key, data=samples) dset.attrs[SAMPLING_RATE_ATTR] = sampling_rate
[ "def", "set", "(", "self", ",", "key", ",", "samples", ",", "sampling_rate", ")", ":", "if", "not", "np", ".", "issubdtype", "(", "samples", ".", "dtype", ",", "np", ".", "floating", ")", ":", "raise", "ValueError", "(", "'Samples are required as np.float3...
Set the samples and sampling-rate for the given key. Existing data will be overwritten. The samples have to have ``np.float32`` datatype and values in the range of -1.0 and 1.0. Args: key (str): A key to store the data for. samples (numpy.ndarray): 1-D array of audio samples (np.float32). sampling_rate (int): The sampling-rate of the audio samples. Note: The container has to be opened in advance.
[ "Set", "the", "samples", "and", "sampling", "-", "rate", "for", "the", "given", "key", ".", "Existing", "data", "will", "be", "overwritten", ".", "The", "samples", "have", "to", "have", "np", ".", "float32", "datatype", "and", "values", "in", "the", "ran...
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/containers/audio.py#L48-L77
train
32,673
ynop/audiomate
audiomate/containers/audio.py
AudioContainer.append
def append(self, key, samples, sampling_rate): """ Append the given samples to the data that already exists in the container for the given key. Args: key (str): A key to store the data for. samples (numpy.ndarray): 1-D array of audio samples (int-16). sampling_rate (int): The sampling-rate of the audio samples. Note: The container has to be opened in advance. For appending to existing data the HDF5-Dataset has to be chunked, so it is not allowed to first add data via ``set``. """ if not np.issubdtype(samples.dtype, np.floating): raise ValueError('Samples are required as np.float32!') if len(samples.shape) > 1: raise ValueError('Only single channel supported!') existing = self.get(key, mem_map=True) samples = (samples * MAX_INT16_VALUE).astype(np.int16) if existing is not None: existing_samples, existing_sr = existing if existing_sr != sampling_rate: raise ValueError('Different sampling-rate than existing data!') num_existing = existing_samples.shape[0] self._file[key].resize(num_existing + samples.shape[0], 0) self._file[key][num_existing:] = samples else: dset = self._file.create_dataset(key, data=samples, chunks=True, maxshape=(None,)) dset.attrs[SAMPLING_RATE_ATTR] = sampling_rate
python
def append(self, key, samples, sampling_rate): """ Append the given samples to the data that already exists in the container for the given key. Args: key (str): A key to store the data for. samples (numpy.ndarray): 1-D array of audio samples (int-16). sampling_rate (int): The sampling-rate of the audio samples. Note: The container has to be opened in advance. For appending to existing data the HDF5-Dataset has to be chunked, so it is not allowed to first add data via ``set``. """ if not np.issubdtype(samples.dtype, np.floating): raise ValueError('Samples are required as np.float32!') if len(samples.shape) > 1: raise ValueError('Only single channel supported!') existing = self.get(key, mem_map=True) samples = (samples * MAX_INT16_VALUE).astype(np.int16) if existing is not None: existing_samples, existing_sr = existing if existing_sr != sampling_rate: raise ValueError('Different sampling-rate than existing data!') num_existing = existing_samples.shape[0] self._file[key].resize(num_existing + samples.shape[0], 0) self._file[key][num_existing:] = samples else: dset = self._file.create_dataset(key, data=samples, chunks=True, maxshape=(None,)) dset.attrs[SAMPLING_RATE_ATTR] = sampling_rate
[ "def", "append", "(", "self", ",", "key", ",", "samples", ",", "sampling_rate", ")", ":", "if", "not", "np", ".", "issubdtype", "(", "samples", ".", "dtype", ",", "np", ".", "floating", ")", ":", "raise", "ValueError", "(", "'Samples are required as np.flo...
Append the given samples to the data that already exists in the container for the given key. Args: key (str): A key to store the data for. samples (numpy.ndarray): 1-D array of audio samples (int-16). sampling_rate (int): The sampling-rate of the audio samples. Note: The container has to be opened in advance. For appending to existing data the HDF5-Dataset has to be chunked, so it is not allowed to first add data via ``set``.
[ "Append", "the", "given", "samples", "to", "the", "data", "that", "already", "exists", "in", "the", "container", "for", "the", "given", "key", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/containers/audio.py#L79-L116
train
32,674
ynop/audiomate
audiomate/corpus/io/voxforge.py
VoxforgeDownloader.available_files
def available_files(url): """ Extract and return urls for all available .tgz files. """ req = requests.get(url) if req.status_code != 200: raise base.FailedDownloadException('Failed to download data (status {}) from {}!'.format(req.status_code, url)) page_content = req.text link_pattern = re.compile(r'<a href="(.*?)">(.*?)</a>') available_files = [] for match in link_pattern.findall(page_content): if match[0].endswith('.tgz'): available_files.append(os.path.join(url, match[0])) return available_files
python
def available_files(url): """ Extract and return urls for all available .tgz files. """ req = requests.get(url) if req.status_code != 200: raise base.FailedDownloadException('Failed to download data (status {}) from {}!'.format(req.status_code, url)) page_content = req.text link_pattern = re.compile(r'<a href="(.*?)">(.*?)</a>') available_files = [] for match in link_pattern.findall(page_content): if match[0].endswith('.tgz'): available_files.append(os.path.join(url, match[0])) return available_files
[ "def", "available_files", "(", "url", ")", ":", "req", "=", "requests", ".", "get", "(", "url", ")", "if", "req", ".", "status_code", "!=", "200", ":", "raise", "base", ".", "FailedDownloadException", "(", "'Failed to download data (status {}) from {}!'", ".", ...
Extract and return urls for all available .tgz files.
[ "Extract", "and", "return", "urls", "for", "all", "available", ".", "tgz", "files", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/io/voxforge.py#L60-L76
train
32,675
ynop/audiomate
audiomate/corpus/io/voxforge.py
VoxforgeDownloader.download_files
def download_files(file_urls, target_path): """ Download all files and store to the given path. """ os.makedirs(target_path, exist_ok=True) downloaded_files = [] for file_url in file_urls: req = requests.get(file_url) if req.status_code != 200: raise base.FailedDownloadException('Failed to download file {} (status {})!'.format(req.status_code, file_url)) file_name = os.path.basename(file_url) target_file_path = os.path.join(target_path, file_name) with open(target_file_path, 'wb') as f: f.write(req.content) downloaded_files.append(target_file_path) return downloaded_files
python
def download_files(file_urls, target_path): """ Download all files and store to the given path. """ os.makedirs(target_path, exist_ok=True) downloaded_files = [] for file_url in file_urls: req = requests.get(file_url) if req.status_code != 200: raise base.FailedDownloadException('Failed to download file {} (status {})!'.format(req.status_code, file_url)) file_name = os.path.basename(file_url) target_file_path = os.path.join(target_path, file_name) with open(target_file_path, 'wb') as f: f.write(req.content) downloaded_files.append(target_file_path) return downloaded_files
[ "def", "download_files", "(", "file_urls", ",", "target_path", ")", ":", "os", ".", "makedirs", "(", "target_path", ",", "exist_ok", "=", "True", ")", "downloaded_files", "=", "[", "]", "for", "file_url", "in", "file_urls", ":", "req", "=", "requests", "."...
Download all files and store to the given path.
[ "Download", "all", "files", "and", "store", "to", "the", "given", "path", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/io/voxforge.py#L79-L99
train
32,676
ynop/audiomate
audiomate/corpus/io/voxforge.py
VoxforgeDownloader.extract_files
def extract_files(file_paths, target_path): """ Unpack all files to the given path. """ os.makedirs(target_path, exist_ok=True) extracted = [] for file_path in file_paths: with tarfile.open(file_path, 'r') as archive: archive.extractall(target_path) file_name = os.path.splitext(os.path.basename(file_path))[0] extracted.append(os.path.join(target_path, file_name)) return extracted
python
def extract_files(file_paths, target_path): """ Unpack all files to the given path. """ os.makedirs(target_path, exist_ok=True) extracted = [] for file_path in file_paths: with tarfile.open(file_path, 'r') as archive: archive.extractall(target_path) file_name = os.path.splitext(os.path.basename(file_path))[0] extracted.append(os.path.join(target_path, file_name)) return extracted
[ "def", "extract_files", "(", "file_paths", ",", "target_path", ")", ":", "os", ".", "makedirs", "(", "target_path", ",", "exist_ok", "=", "True", ")", "extracted", "=", "[", "]", "for", "file_path", "in", "file_paths", ":", "with", "tarfile", ".", "open", ...
Unpack all files to the given path.
[ "Unpack", "all", "files", "to", "the", "given", "path", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/io/voxforge.py#L102-L114
train
32,677
ynop/audiomate
audiomate/utils/naming.py
index_name_if_in_list
def index_name_if_in_list(name, name_list, suffix='', prefix=''): """ Find a unique name by adding an index to the name so it is unique within the given list. Parameters: name (str): Name name_list (iterable): List of names that the new name must differ from. suffix (str): The suffix to append after the index. prefix (str): The prefix to append in front of the index. Returns: str: A unique name within the given list. """ new_name = '{}'.format(name) index = 1 while new_name in name_list: new_name = '{}_{}{}{}'.format(name, prefix, index, suffix) index += 1 return new_name
python
def index_name_if_in_list(name, name_list, suffix='', prefix=''): """ Find a unique name by adding an index to the name so it is unique within the given list. Parameters: name (str): Name name_list (iterable): List of names that the new name must differ from. suffix (str): The suffix to append after the index. prefix (str): The prefix to append in front of the index. Returns: str: A unique name within the given list. """ new_name = '{}'.format(name) index = 1 while new_name in name_list: new_name = '{}_{}{}{}'.format(name, prefix, index, suffix) index += 1 return new_name
[ "def", "index_name_if_in_list", "(", "name", ",", "name_list", ",", "suffix", "=", "''", ",", "prefix", "=", "''", ")", ":", "new_name", "=", "'{}'", ".", "format", "(", "name", ")", "index", "=", "1", "while", "new_name", "in", "name_list", ":", "new_...
Find a unique name by adding an index to the name so it is unique within the given list. Parameters: name (str): Name name_list (iterable): List of names that the new name must differ from. suffix (str): The suffix to append after the index. prefix (str): The prefix to append in front of the index. Returns: str: A unique name within the given list.
[ "Find", "a", "unique", "name", "by", "adding", "an", "index", "to", "the", "name", "so", "it", "is", "unique", "within", "the", "given", "list", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/utils/naming.py#L10-L30
train
32,678
ynop/audiomate
audiomate/utils/naming.py
generate_name
def generate_name(length=15, not_in=None): """ Generates a random string of lowercase letters with the given length. Parameters: length (int): Length of the string to output. not_in (list): Only return a string not in the given iterator. Returns: str: A new name thats not in the given list. """ value = ''.join(random.choice(string.ascii_lowercase) for i in range(length)) while (not_in is not None) and (value in not_in): value = ''.join(random.choice(string.ascii_lowercase) for i in range(length)) return value
python
def generate_name(length=15, not_in=None): """ Generates a random string of lowercase letters with the given length. Parameters: length (int): Length of the string to output. not_in (list): Only return a string not in the given iterator. Returns: str: A new name thats not in the given list. """ value = ''.join(random.choice(string.ascii_lowercase) for i in range(length)) while (not_in is not None) and (value in not_in): value = ''.join(random.choice(string.ascii_lowercase) for i in range(length)) return value
[ "def", "generate_name", "(", "length", "=", "15", ",", "not_in", "=", "None", ")", ":", "value", "=", "''", ".", "join", "(", "random", ".", "choice", "(", "string", ".", "ascii_lowercase", ")", "for", "i", "in", "range", "(", "length", ")", ")", "...
Generates a random string of lowercase letters with the given length. Parameters: length (int): Length of the string to output. not_in (list): Only return a string not in the given iterator. Returns: str: A new name thats not in the given list.
[ "Generates", "a", "random", "string", "of", "lowercase", "letters", "with", "the", "given", "length", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/utils/naming.py#L33-L49
train
32,679
ynop/audiomate
audiomate/corpus/io/__init__.py
create_downloader_of_type
def create_downloader_of_type(type_name): """ Create an instance of the downloader with the given name. Args: type_name: The name of a downloader. Returns: An instance of the downloader with the given type. """ downloaders = available_downloaders() if type_name not in downloaders.keys(): raise UnknownDownloaderException('Unknown downloader: %s' % (type_name,)) return downloaders[type_name]()
python
def create_downloader_of_type(type_name): """ Create an instance of the downloader with the given name. Args: type_name: The name of a downloader. Returns: An instance of the downloader with the given type. """ downloaders = available_downloaders() if type_name not in downloaders.keys(): raise UnknownDownloaderException('Unknown downloader: %s' % (type_name,)) return downloaders[type_name]()
[ "def", "create_downloader_of_type", "(", "type_name", ")", ":", "downloaders", "=", "available_downloaders", "(", ")", "if", "type_name", "not", "in", "downloaders", ".", "keys", "(", ")", ":", "raise", "UnknownDownloaderException", "(", "'Unknown downloader: %s'", ...
Create an instance of the downloader with the given name. Args: type_name: The name of a downloader. Returns: An instance of the downloader with the given type.
[ "Create", "an", "instance", "of", "the", "downloader", "with", "the", "given", "name", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/io/__init__.py#L110-L125
train
32,680
ynop/audiomate
audiomate/corpus/io/__init__.py
create_reader_of_type
def create_reader_of_type(type_name): """ Create an instance of the reader with the given name. Args: type_name: The name of a reader. Returns: An instance of the reader with the given type. """ readers = available_readers() if type_name not in readers.keys(): raise UnknownReaderException('Unknown reader: %s' % (type_name,)) return readers[type_name]()
python
def create_reader_of_type(type_name): """ Create an instance of the reader with the given name. Args: type_name: The name of a reader. Returns: An instance of the reader with the given type. """ readers = available_readers() if type_name not in readers.keys(): raise UnknownReaderException('Unknown reader: %s' % (type_name,)) return readers[type_name]()
[ "def", "create_reader_of_type", "(", "type_name", ")", ":", "readers", "=", "available_readers", "(", ")", "if", "type_name", "not", "in", "readers", ".", "keys", "(", ")", ":", "raise", "UnknownReaderException", "(", "'Unknown reader: %s'", "%", "(", "type_name...
Create an instance of the reader with the given name. Args: type_name: The name of a reader. Returns: An instance of the reader with the given type.
[ "Create", "an", "instance", "of", "the", "reader", "with", "the", "given", "name", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/io/__init__.py#L128-L143
train
32,681
ynop/audiomate
audiomate/corpus/io/__init__.py
create_writer_of_type
def create_writer_of_type(type_name): """ Create an instance of the writer with the given name. Args: type_name: The name of a writer. Returns: An instance of the writer with the given type. """ writers = available_writers() if type_name not in writers.keys(): raise UnknownWriterException('Unknown writer: %s' % (type_name,)) return writers[type_name]()
python
def create_writer_of_type(type_name): """ Create an instance of the writer with the given name. Args: type_name: The name of a writer. Returns: An instance of the writer with the given type. """ writers = available_writers() if type_name not in writers.keys(): raise UnknownWriterException('Unknown writer: %s' % (type_name,)) return writers[type_name]()
[ "def", "create_writer_of_type", "(", "type_name", ")", ":", "writers", "=", "available_writers", "(", ")", "if", "type_name", "not", "in", "writers", ".", "keys", "(", ")", ":", "raise", "UnknownWriterException", "(", "'Unknown writer: %s'", "%", "(", "type_name...
Create an instance of the writer with the given name. Args: type_name: The name of a writer. Returns: An instance of the writer with the given type.
[ "Create", "an", "instance", "of", "the", "writer", "with", "the", "given", "name", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/io/__init__.py#L146-L161
train
32,682
ynop/audiomate
audiomate/corpus/subset/subview.py
Subview.serialize
def serialize(self): """ Return a string representing the subview with all of its filter criteria. Returns: str: String with subview definition. """ lines = [] for criterion in self.filter_criteria: lines.append(criterion.name()) lines.append(criterion.serialize()) return '\n'.join(lines)
python
def serialize(self): """ Return a string representing the subview with all of its filter criteria. Returns: str: String with subview definition. """ lines = [] for criterion in self.filter_criteria: lines.append(criterion.name()) lines.append(criterion.serialize()) return '\n'.join(lines)
[ "def", "serialize", "(", "self", ")", ":", "lines", "=", "[", "]", "for", "criterion", "in", "self", ".", "filter_criteria", ":", "lines", ".", "append", "(", "criterion", ".", "name", "(", ")", ")", "lines", ".", "append", "(", "criterion", ".", "se...
Return a string representing the subview with all of its filter criteria. Returns: str: String with subview definition.
[ "Return", "a", "string", "representing", "the", "subview", "with", "all", "of", "its", "filter", "criteria", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/subset/subview.py#L233-L246
train
32,683
ynop/audiomate
audiomate/processing/pipeline/spectral.py
stft_from_frames
def stft_from_frames(frames, window='hann', dtype=np.complex64): """ Variation of the librosa.core.stft function, that computes the short-time-fourier-transfrom from frames instead from the signal. See http://librosa.github.io/librosa/_modules/librosa/core/spectrum.html#stft """ win_length = frames.shape[0] n_fft = win_length fft_window = filters.get_window(window, win_length, fftbins=True) # Reshape so that the window can be broadcast fft_window = fft_window.reshape((-1, 1)) # Pre-allocate the STFT matrix stft_matrix = np.empty((int(1 + n_fft // 2), frames.shape[1]), dtype=dtype, order='F') # how many columns can we fit within MAX_MEM_BLOCK? n_columns = int(util.MAX_MEM_BLOCK / (stft_matrix.shape[0] * stft_matrix.itemsize)) for bl_s in range(0, stft_matrix.shape[1], n_columns): bl_t = min(bl_s + n_columns, stft_matrix.shape[1]) # RFFT and Conjugate here to match phase from DPWE code stft_matrix[:, bl_s:bl_t] = fft.fft(fft_window * frames[:, bl_s:bl_t], axis=0)[:stft_matrix.shape[0]].conj() return stft_matrix
python
def stft_from_frames(frames, window='hann', dtype=np.complex64): """ Variation of the librosa.core.stft function, that computes the short-time-fourier-transfrom from frames instead from the signal. See http://librosa.github.io/librosa/_modules/librosa/core/spectrum.html#stft """ win_length = frames.shape[0] n_fft = win_length fft_window = filters.get_window(window, win_length, fftbins=True) # Reshape so that the window can be broadcast fft_window = fft_window.reshape((-1, 1)) # Pre-allocate the STFT matrix stft_matrix = np.empty((int(1 + n_fft // 2), frames.shape[1]), dtype=dtype, order='F') # how many columns can we fit within MAX_MEM_BLOCK? n_columns = int(util.MAX_MEM_BLOCK / (stft_matrix.shape[0] * stft_matrix.itemsize)) for bl_s in range(0, stft_matrix.shape[1], n_columns): bl_t = min(bl_s + n_columns, stft_matrix.shape[1]) # RFFT and Conjugate here to match phase from DPWE code stft_matrix[:, bl_s:bl_t] = fft.fft(fft_window * frames[:, bl_s:bl_t], axis=0)[:stft_matrix.shape[0]].conj() return stft_matrix
[ "def", "stft_from_frames", "(", "frames", ",", "window", "=", "'hann'", ",", "dtype", "=", "np", ".", "complex64", ")", ":", "win_length", "=", "frames", ".", "shape", "[", "0", "]", "n_fft", "=", "win_length", "fft_window", "=", "filters", ".", "get_win...
Variation of the librosa.core.stft function, that computes the short-time-fourier-transfrom from frames instead from the signal. See http://librosa.github.io/librosa/_modules/librosa/core/spectrum.html#stft
[ "Variation", "of", "the", "librosa", ".", "core", ".", "stft", "function", "that", "computes", "the", "short", "-", "time", "-", "fourier", "-", "transfrom", "from", "frames", "instead", "from", "the", "signal", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/processing/pipeline/spectral.py#L10-L43
train
32,684
ynop/audiomate
audiomate/corpus/validation/combine.py
CombinedValidator.validate
def validate(self, corpus): """ Perform validation on the given corpus. Args: corpus (Corpus): The corpus to test/validate. """ passed = True results = {} for validator in self.validators: sub_result = validator.validate(corpus) results[validator.name()] = sub_result if not sub_result.passed: passed = False return CombinedValidationResult(passed, results)
python
def validate(self, corpus): """ Perform validation on the given corpus. Args: corpus (Corpus): The corpus to test/validate. """ passed = True results = {} for validator in self.validators: sub_result = validator.validate(corpus) results[validator.name()] = sub_result if not sub_result.passed: passed = False return CombinedValidationResult(passed, results)
[ "def", "validate", "(", "self", ",", "corpus", ")", ":", "passed", "=", "True", "results", "=", "{", "}", "for", "validator", "in", "self", ".", "validators", ":", "sub_result", "=", "validator", ".", "validate", "(", "corpus", ")", "results", "[", "va...
Perform validation on the given corpus. Args: corpus (Corpus): The corpus to test/validate.
[ "Perform", "validation", "on", "the", "given", "corpus", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/validation/combine.py#L48-L66
train
32,685
ynop/audiomate
audiomate/corpus/io/kaldi.py
KaldiWriter.feature_scp_generator
def feature_scp_generator(path): """ Return a generator over all feature matrices defined in a scp. """ scp_entries = textfile.read_key_value_lines(path, separator=' ') for utterance_id, rx_specifier in scp_entries.items(): yield utterance_id, KaldiWriter.read_float_matrix(rx_specifier)
python
def feature_scp_generator(path): """ Return a generator over all feature matrices defined in a scp. """ scp_entries = textfile.read_key_value_lines(path, separator=' ') for utterance_id, rx_specifier in scp_entries.items(): yield utterance_id, KaldiWriter.read_float_matrix(rx_specifier)
[ "def", "feature_scp_generator", "(", "path", ")", ":", "scp_entries", "=", "textfile", ".", "read_key_value_lines", "(", "path", ",", "separator", "=", "' '", ")", "for", "utterance_id", ",", "rx_specifier", "in", "scp_entries", ".", "items", "(", ")", ":", ...
Return a generator over all feature matrices defined in a scp.
[ "Return", "a", "generator", "over", "all", "feature", "matrices", "defined", "in", "a", "scp", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/io/kaldi.py#L261-L267
train
32,686
ynop/audiomate
audiomate/corpus/io/kaldi.py
KaldiWriter.read_float_matrix
def read_float_matrix(rx_specifier): """ Return float matrix as np array for the given rx specifier. """ path, offset = rx_specifier.strip().split(':', maxsplit=1) offset = int(offset) sample_format = 4 with open(path, 'rb') as f: # move to offset f.seek(offset) # assert binary ark binary = f.read(2) assert (binary == b'\x00B') # assert type float 32 format = f.read(3) assert (format == b'FM ') # get number of mfcc features f.read(1) num_frames = struct.unpack('<i', f.read(4))[0] # get size of mfcc features f.read(1) feature_size = struct.unpack('<i', f.read(4))[0] # read feature data data = f.read(num_frames * feature_size * sample_format) feature_vector = np.frombuffer(data, dtype='float32') feature_matrix = np.reshape(feature_vector, (num_frames, feature_size)) return feature_matrix
python
def read_float_matrix(rx_specifier): """ Return float matrix as np array for the given rx specifier. """ path, offset = rx_specifier.strip().split(':', maxsplit=1) offset = int(offset) sample_format = 4 with open(path, 'rb') as f: # move to offset f.seek(offset) # assert binary ark binary = f.read(2) assert (binary == b'\x00B') # assert type float 32 format = f.read(3) assert (format == b'FM ') # get number of mfcc features f.read(1) num_frames = struct.unpack('<i', f.read(4))[0] # get size of mfcc features f.read(1) feature_size = struct.unpack('<i', f.read(4))[0] # read feature data data = f.read(num_frames * feature_size * sample_format) feature_vector = np.frombuffer(data, dtype='float32') feature_matrix = np.reshape(feature_vector, (num_frames, feature_size)) return feature_matrix
[ "def", "read_float_matrix", "(", "rx_specifier", ")", ":", "path", ",", "offset", "=", "rx_specifier", ".", "strip", "(", ")", ".", "split", "(", "':'", ",", "maxsplit", "=", "1", ")", "offset", "=", "int", "(", "offset", ")", "sample_format", "=", "4"...
Return float matrix as np array for the given rx specifier.
[ "Return", "float", "matrix", "as", "np", "array", "for", "the", "given", "rx", "specifier", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/io/kaldi.py#L270-L303
train
32,687
ynop/audiomate
audiomate/feeding/partitioning.py
PartitioningContainerLoader.reload
def reload(self): """ Create a new partition scheme. A scheme defines which utterances are in which partition. The scheme only changes after every call if ``self.shuffle == True``. Returns: list: List of PartitionInfo objects, defining the new partitions (same as ``self.partitions``) """ # Create the order in which utterances will be loaded utt_ids = sorted(self.utt_ids) if self.shuffle: self.rand.shuffle(utt_ids) partitions = [] current_partition = PartitionInfo() for utt_id in utt_ids: utt_size = self.utt_sizes[utt_id] utt_lengths = self.utt_lengths[utt_id] # We add utterance to the partition as long the partition-size is not exceeded # Otherwise we start with new partition. if current_partition.size + utt_size > self.partition_size: partitions.append(current_partition) current_partition = PartitionInfo() current_partition.utt_ids.append(utt_id) current_partition.utt_lengths.append(utt_lengths) current_partition.size += utt_size if current_partition.size > 0: partitions.append(current_partition) self.partitions = partitions return self.partitions
python
def reload(self): """ Create a new partition scheme. A scheme defines which utterances are in which partition. The scheme only changes after every call if ``self.shuffle == True``. Returns: list: List of PartitionInfo objects, defining the new partitions (same as ``self.partitions``) """ # Create the order in which utterances will be loaded utt_ids = sorted(self.utt_ids) if self.shuffle: self.rand.shuffle(utt_ids) partitions = [] current_partition = PartitionInfo() for utt_id in utt_ids: utt_size = self.utt_sizes[utt_id] utt_lengths = self.utt_lengths[utt_id] # We add utterance to the partition as long the partition-size is not exceeded # Otherwise we start with new partition. if current_partition.size + utt_size > self.partition_size: partitions.append(current_partition) current_partition = PartitionInfo() current_partition.utt_ids.append(utt_id) current_partition.utt_lengths.append(utt_lengths) current_partition.size += utt_size if current_partition.size > 0: partitions.append(current_partition) self.partitions = partitions return self.partitions
[ "def", "reload", "(", "self", ")", ":", "# Create the order in which utterances will be loaded", "utt_ids", "=", "sorted", "(", "self", ".", "utt_ids", ")", "if", "self", ".", "shuffle", ":", "self", ".", "rand", ".", "shuffle", "(", "utt_ids", ")", "partition...
Create a new partition scheme. A scheme defines which utterances are in which partition. The scheme only changes after every call if ``self.shuffle == True``. Returns: list: List of PartitionInfo objects, defining the new partitions (same as ``self.partitions``)
[ "Create", "a", "new", "partition", "scheme", ".", "A", "scheme", "defines", "which", "utterances", "are", "in", "which", "partition", ".", "The", "scheme", "only", "changes", "after", "every", "call", "if", "self", ".", "shuffle", "==", "True", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/feeding/partitioning.py#L91-L128
train
32,688
ynop/audiomate
audiomate/feeding/partitioning.py
PartitioningContainerLoader.load_partition_data
def load_partition_data(self, index): """ Load and return the partition with the given index. Args: index (int): The index of partition, that refers to the index in ``self.partitions``. Returns: PartitionData: A PartitionData object containing the data for the partition with the given index. """ info = self.partitions[index] data = PartitionData(info) for utt_id in info.utt_ids: utt_data = [c._file[utt_id][:] for c in self.containers] data.utt_data.append(utt_data) return data
python
def load_partition_data(self, index): """ Load and return the partition with the given index. Args: index (int): The index of partition, that refers to the index in ``self.partitions``. Returns: PartitionData: A PartitionData object containing the data for the partition with the given index. """ info = self.partitions[index] data = PartitionData(info) for utt_id in info.utt_ids: utt_data = [c._file[utt_id][:] for c in self.containers] data.utt_data.append(utt_data) return data
[ "def", "load_partition_data", "(", "self", ",", "index", ")", ":", "info", "=", "self", ".", "partitions", "[", "index", "]", "data", "=", "PartitionData", "(", "info", ")", "for", "utt_id", "in", "info", ".", "utt_ids", ":", "utt_data", "=", "[", "c",...
Load and return the partition with the given index. Args: index (int): The index of partition, that refers to the index in ``self.partitions``. Returns: PartitionData: A PartitionData object containing the data for the partition with the given index.
[ "Load", "and", "return", "the", "partition", "with", "the", "given", "index", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/feeding/partitioning.py#L130-L148
train
32,689
ynop/audiomate
audiomate/feeding/partitioning.py
PartitioningContainerLoader._raise_error_if_container_is_missing_an_utterance
def _raise_error_if_container_is_missing_an_utterance(self): """ Check if there is a dataset for every utterance in every container, otherwise raise an error. """ expected_keys = frozenset(self.utt_ids) for cnt in self.containers: keys = set(cnt.keys()) if not keys.issuperset(expected_keys): raise ValueError('Container is missing data for some utterances!')
python
def _raise_error_if_container_is_missing_an_utterance(self): """ Check if there is a dataset for every utterance in every container, otherwise raise an error. """ expected_keys = frozenset(self.utt_ids) for cnt in self.containers: keys = set(cnt.keys()) if not keys.issuperset(expected_keys): raise ValueError('Container is missing data for some utterances!')
[ "def", "_raise_error_if_container_is_missing_an_utterance", "(", "self", ")", ":", "expected_keys", "=", "frozenset", "(", "self", ".", "utt_ids", ")", "for", "cnt", "in", "self", ".", "containers", ":", "keys", "=", "set", "(", "cnt", ".", "keys", "(", ")",...
Check if there is a dataset for every utterance in every container, otherwise raise an error.
[ "Check", "if", "there", "is", "a", "dataset", "for", "every", "utterance", "in", "every", "container", "otherwise", "raise", "an", "error", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/feeding/partitioning.py#L150-L158
train
32,690
ynop/audiomate
audiomate/feeding/partitioning.py
PartitioningContainerLoader._scan
def _scan(self): """ For every utterance, calculate the size it will need in memory. """ utt_sizes = {} for dset_name in self.utt_ids: per_container = [] for cnt in self.containers: dset = cnt._file[dset_name] dtype_size = dset.dtype.itemsize record_size = dtype_size * dset.size per_container.append(record_size) utt_size = sum(per_container) if utt_size > self.partition_size: raise ValueError('Records in "{0}" are larger than the partition size'.format(dset_name)) utt_sizes[dset_name] = utt_size return utt_sizes
python
def _scan(self): """ For every utterance, calculate the size it will need in memory. """ utt_sizes = {} for dset_name in self.utt_ids: per_container = [] for cnt in self.containers: dset = cnt._file[dset_name] dtype_size = dset.dtype.itemsize record_size = dtype_size * dset.size per_container.append(record_size) utt_size = sum(per_container) if utt_size > self.partition_size: raise ValueError('Records in "{0}" are larger than the partition size'.format(dset_name)) utt_sizes[dset_name] = utt_size return utt_sizes
[ "def", "_scan", "(", "self", ")", ":", "utt_sizes", "=", "{", "}", "for", "dset_name", "in", "self", ".", "utt_ids", ":", "per_container", "=", "[", "]", "for", "cnt", "in", "self", ".", "containers", ":", "dset", "=", "cnt", ".", "_file", "[", "ds...
For every utterance, calculate the size it will need in memory.
[ "For", "every", "utterance", "calculate", "the", "size", "it", "will", "need", "in", "memory", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/feeding/partitioning.py#L160-L181
train
32,691
ynop/audiomate
audiomate/feeding/partitioning.py
PartitioningContainerLoader._get_all_lengths
def _get_all_lengths(self): """ For every utterance, get the length of the data in every container. Return a list of tuples. """ utt_lengths = {} for utt_idx in self.utt_ids: per_container = [c._file[utt_idx].shape[0] for c in self.containers] utt_lengths[utt_idx] = tuple(per_container) return utt_lengths
python
def _get_all_lengths(self): """ For every utterance, get the length of the data in every container. Return a list of tuples. """ utt_lengths = {} for utt_idx in self.utt_ids: per_container = [c._file[utt_idx].shape[0] for c in self.containers] utt_lengths[utt_idx] = tuple(per_container) return utt_lengths
[ "def", "_get_all_lengths", "(", "self", ")", ":", "utt_lengths", "=", "{", "}", "for", "utt_idx", "in", "self", ".", "utt_ids", ":", "per_container", "=", "[", "c", ".", "_file", "[", "utt_idx", "]", ".", "shape", "[", "0", "]", "for", "c", "in", "...
For every utterance, get the length of the data in every container. Return a list of tuples.
[ "For", "every", "utterance", "get", "the", "length", "of", "the", "data", "in", "every", "container", ".", "Return", "a", "list", "of", "tuples", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/feeding/partitioning.py#L183-L191
train
32,692
ynop/audiomate
audiomate/processing/pipeline/base.py
Buffer.update
def update(self, data, offset, is_last, buffer_index=0): """ Update the buffer at the given index. Args: data (np.ndarray): The frames. offset (int): The index of the first frame in `data` within the sequence. is_last (bool): Whether this is the last block of frames in the sequence. buffer_index (int): The index of the buffer to update (< self.num_buffers). """ if buffer_index >= self.num_buffers: raise ValueError('Expected buffer index < {} but got index {}.'.format(self.num_buffers, buffer_index)) if self.buffers[buffer_index] is not None and self.buffers[buffer_index].shape[0] > 0: expected_next_frame = self.current_frame + self.buffers[buffer_index].shape[0] if expected_next_frame != offset: raise ValueError( 'There are missing frames. Last frame in buffer is {}. The passed frames start at {}.'.format( expected_next_frame, offset)) self.buffers[buffer_index] = np.vstack([self.buffers[buffer_index], data]) else: self.buffers[buffer_index] = data self.buffers_full[buffer_index] = is_last
python
def update(self, data, offset, is_last, buffer_index=0): """ Update the buffer at the given index. Args: data (np.ndarray): The frames. offset (int): The index of the first frame in `data` within the sequence. is_last (bool): Whether this is the last block of frames in the sequence. buffer_index (int): The index of the buffer to update (< self.num_buffers). """ if buffer_index >= self.num_buffers: raise ValueError('Expected buffer index < {} but got index {}.'.format(self.num_buffers, buffer_index)) if self.buffers[buffer_index] is not None and self.buffers[buffer_index].shape[0] > 0: expected_next_frame = self.current_frame + self.buffers[buffer_index].shape[0] if expected_next_frame != offset: raise ValueError( 'There are missing frames. Last frame in buffer is {}. The passed frames start at {}.'.format( expected_next_frame, offset)) self.buffers[buffer_index] = np.vstack([self.buffers[buffer_index], data]) else: self.buffers[buffer_index] = data self.buffers_full[buffer_index] = is_last
[ "def", "update", "(", "self", ",", "data", ",", "offset", ",", "is_last", ",", "buffer_index", "=", "0", ")", ":", "if", "buffer_index", ">=", "self", ".", "num_buffers", ":", "raise", "ValueError", "(", "'Expected buffer index < {} but got index {}.'", ".", "...
Update the buffer at the given index. Args: data (np.ndarray): The frames. offset (int): The index of the first frame in `data` within the sequence. is_last (bool): Whether this is the last block of frames in the sequence. buffer_index (int): The index of the buffer to update (< self.num_buffers).
[ "Update", "the", "buffer", "at", "the", "given", "index", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/processing/pipeline/base.py#L113-L137
train
32,693
ynop/audiomate
audiomate/processing/pipeline/base.py
Buffer.get
def get(self): """ Get a new chunk if available. Returns: Chunk or list: If enough frames are available a chunk is returned. Otherwise None. If ``self.num_buffer >= 1`` a list instead of single chunk is returned. """ chunk_size = self._smallest_buffer() all_full = self._all_full() if all_full: right_context = 0 num_frames = chunk_size - self.current_left_context else: right_context = self.right_context num_frames = self.min_frames chunk_size_needed = num_frames + self.current_left_context + right_context if chunk_size >= chunk_size_needed: data = [] keep_frames = self.left_context + self.right_context keep_from = max(0, chunk_size - keep_frames) for index in range(self.num_buffers): data.append(self.buffers[index][:chunk_size]) self.buffers[index] = self.buffers[index][keep_from:] if self.num_buffers == 1: data = data[0] chunk = Chunk(data, self.current_frame, all_full, self.current_left_context, right_context) self.current_left_context = min(self.left_context, chunk_size) self.current_frame = max(self.current_frame + chunk_size - keep_frames, 0) return chunk
python
def get(self): """ Get a new chunk if available. Returns: Chunk or list: If enough frames are available a chunk is returned. Otherwise None. If ``self.num_buffer >= 1`` a list instead of single chunk is returned. """ chunk_size = self._smallest_buffer() all_full = self._all_full() if all_full: right_context = 0 num_frames = chunk_size - self.current_left_context else: right_context = self.right_context num_frames = self.min_frames chunk_size_needed = num_frames + self.current_left_context + right_context if chunk_size >= chunk_size_needed: data = [] keep_frames = self.left_context + self.right_context keep_from = max(0, chunk_size - keep_frames) for index in range(self.num_buffers): data.append(self.buffers[index][:chunk_size]) self.buffers[index] = self.buffers[index][keep_from:] if self.num_buffers == 1: data = data[0] chunk = Chunk(data, self.current_frame, all_full, self.current_left_context, right_context) self.current_left_context = min(self.left_context, chunk_size) self.current_frame = max(self.current_frame + chunk_size - keep_frames, 0) return chunk
[ "def", "get", "(", "self", ")", ":", "chunk_size", "=", "self", ".", "_smallest_buffer", "(", ")", "all_full", "=", "self", ".", "_all_full", "(", ")", "if", "all_full", ":", "right_context", "=", "0", "num_frames", "=", "chunk_size", "-", "self", ".", ...
Get a new chunk if available. Returns: Chunk or list: If enough frames are available a chunk is returned. Otherwise None. If ``self.num_buffer >= 1`` a list instead of single chunk is returned.
[ "Get", "a", "new", "chunk", "if", "available", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/processing/pipeline/base.py#L139-L180
train
32,694
ynop/audiomate
audiomate/processing/pipeline/base.py
Buffer._smallest_buffer
def _smallest_buffer(self): """ Get the size of the smallest buffer. """ smallest = np.inf for buffer in self.buffers: if buffer is None: return 0 elif buffer.shape[0] < smallest: smallest = buffer.shape[0] return smallest
python
def _smallest_buffer(self): """ Get the size of the smallest buffer. """ smallest = np.inf for buffer in self.buffers: if buffer is None: return 0 elif buffer.shape[0] < smallest: smallest = buffer.shape[0] return smallest
[ "def", "_smallest_buffer", "(", "self", ")", ":", "smallest", "=", "np", ".", "inf", "for", "buffer", "in", "self", ".", "buffers", ":", "if", "buffer", "is", "None", ":", "return", "0", "elif", "buffer", ".", "shape", "[", "0", "]", "<", "smallest",...
Get the size of the smallest buffer.
[ "Get", "the", "size", "of", "the", "smallest", "buffer", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/processing/pipeline/base.py#L182-L195
train
32,695
ynop/audiomate
audiomate/processing/pipeline/base.py
Step.process_frames
def process_frames(self, data, sampling_rate, offset=0, last=False, utterance=None, corpus=None): """ Execute the processing of this step and all dependent parent steps. """ if offset == 0: self.steps_sorted = list(nx.algorithms.dag.topological_sort(self.graph)) self._create_buffers() self._define_output_buffers() # Update buffers with input data self._update_buffers(None, data, offset, last) # Go through the ordered (by dependencies) steps for step in self.steps_sorted: chunk = self.buffers[step].get() if chunk is not None: res = step.compute(chunk, sampling_rate, utterance=utterance, corpus=corpus) # If step is self, we know its the last step so return the data if step == self: return res # Otherwise update buffers of child steps else: self._update_buffers(step, res, chunk.offset + chunk.left_context, chunk.is_last)
python
def process_frames(self, data, sampling_rate, offset=0, last=False, utterance=None, corpus=None): """ Execute the processing of this step and all dependent parent steps. """ if offset == 0: self.steps_sorted = list(nx.algorithms.dag.topological_sort(self.graph)) self._create_buffers() self._define_output_buffers() # Update buffers with input data self._update_buffers(None, data, offset, last) # Go through the ordered (by dependencies) steps for step in self.steps_sorted: chunk = self.buffers[step].get() if chunk is not None: res = step.compute(chunk, sampling_rate, utterance=utterance, corpus=corpus) # If step is self, we know its the last step so return the data if step == self: return res # Otherwise update buffers of child steps else: self._update_buffers(step, res, chunk.offset + chunk.left_context, chunk.is_last)
[ "def", "process_frames", "(", "self", ",", "data", ",", "sampling_rate", ",", "offset", "=", "0", ",", "last", "=", "False", ",", "utterance", "=", "None", ",", "corpus", "=", "None", ")", ":", "if", "offset", "==", "0", ":", "self", ".", "steps_sort...
Execute the processing of this step and all dependent parent steps.
[ "Execute", "the", "processing", "of", "this", "step", "and", "all", "dependent", "parent", "steps", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/processing/pipeline/base.py#L237-L264
train
32,696
ynop/audiomate
audiomate/processing/pipeline/base.py
Step._update_buffers
def _update_buffers(self, from_step, data, offset, is_last): """ Update the buffers of all steps that need data from ``from_step``. If ``from_step`` is None it means the data is the input data. """ for to_step, buffer in self.target_buffers[from_step]: parent_index = 0 # if there multiple inputs we have to get the correct index, to keep the ordering if isinstance(to_step, Reduction): parent_index = to_step.parents.index(from_step) buffer.update(data, offset, is_last, buffer_index=parent_index)
python
def _update_buffers(self, from_step, data, offset, is_last): """ Update the buffers of all steps that need data from ``from_step``. If ``from_step`` is None it means the data is the input data. """ for to_step, buffer in self.target_buffers[from_step]: parent_index = 0 # if there multiple inputs we have to get the correct index, to keep the ordering if isinstance(to_step, Reduction): parent_index = to_step.parents.index(from_step) buffer.update(data, offset, is_last, buffer_index=parent_index)
[ "def", "_update_buffers", "(", "self", ",", "from_step", ",", "data", ",", "offset", ",", "is_last", ")", ":", "for", "to_step", ",", "buffer", "in", "self", ".", "target_buffers", "[", "from_step", "]", ":", "parent_index", "=", "0", "# if there multiple in...
Update the buffers of all steps that need data from ``from_step``. If ``from_step`` is None it means the data is the input data.
[ "Update", "the", "buffers", "of", "all", "steps", "that", "need", "data", "from", "from_step", ".", "If", "from_step", "is", "None", "it", "means", "the", "data", "is", "the", "input", "data", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/processing/pipeline/base.py#L327-L340
train
32,697
ynop/audiomate
audiomate/processing/pipeline/base.py
Step._define_output_buffers
def _define_output_buffers(self): """ Prepare a dictionary so we know what buffers have to be update with the the output of every step. """ # First define buffers that need input data self.target_buffers = { None: [(step, self.buffers[step]) for step in self._get_input_steps()] } # Go through all steps and append the buffers of their child nodes for step in self.steps_sorted: if step != self: child_steps = [edge[1] for edge in self.graph.out_edges(step)] self.target_buffers[step] = [(child_step, self.buffers[child_step]) for child_step in child_steps]
python
def _define_output_buffers(self): """ Prepare a dictionary so we know what buffers have to be update with the the output of every step. """ # First define buffers that need input data self.target_buffers = { None: [(step, self.buffers[step]) for step in self._get_input_steps()] } # Go through all steps and append the buffers of their child nodes for step in self.steps_sorted: if step != self: child_steps = [edge[1] for edge in self.graph.out_edges(step)] self.target_buffers[step] = [(child_step, self.buffers[child_step]) for child_step in child_steps]
[ "def", "_define_output_buffers", "(", "self", ")", ":", "# First define buffers that need input data", "self", ".", "target_buffers", "=", "{", "None", ":", "[", "(", "step", ",", "self", ".", "buffers", "[", "step", "]", ")", "for", "step", "in", "self", "....
Prepare a dictionary so we know what buffers have to be update with the the output of every step.
[ "Prepare", "a", "dictionary", "so", "we", "know", "what", "buffers", "have", "to", "be", "update", "with", "the", "the", "output", "of", "every", "step", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/processing/pipeline/base.py#L342-L356
train
32,698
ynop/audiomate
audiomate/processing/pipeline/base.py
Step._get_input_steps
def _get_input_steps(self): """ Search and return all steps that have no parents. These are the steps that are get the input data. """ input_steps = [] for step in self.steps_sorted: parent_steps = self._parent_steps(step) if len(parent_steps) == 0: input_steps.append(step) return input_steps
python
def _get_input_steps(self): """ Search and return all steps that have no parents. These are the steps that are get the input data. """ input_steps = [] for step in self.steps_sorted: parent_steps = self._parent_steps(step) if len(parent_steps) == 0: input_steps.append(step) return input_steps
[ "def", "_get_input_steps", "(", "self", ")", ":", "input_steps", "=", "[", "]", "for", "step", "in", "self", ".", "steps_sorted", ":", "parent_steps", "=", "self", ".", "_parent_steps", "(", "step", ")", "if", "len", "(", "parent_steps", ")", "==", "0", ...
Search and return all steps that have no parents. These are the steps that are get the input data.
[ "Search", "and", "return", "all", "steps", "that", "have", "no", "parents", ".", "These", "are", "the", "steps", "that", "are", "get", "the", "input", "data", "." ]
61727920b23a708293c3d526fa3000d4de9c6c21
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/processing/pipeline/base.py#L358-L370
train
32,699