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 list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
persephone-tools/persephone | persephone/corpus.py | Corpus.initialize_labels | def initialize_labels(self, labels: Set[str]) -> Tuple[dict, dict]:
"""Create mappings from label to index and index to label"""
logger.debug("Creating mappings for labels")
label_to_index = {label: index for index, label in enumerate(
["pad"] + sorted(list(labe... | python | def initialize_labels(self, labels: Set[str]) -> Tuple[dict, dict]:
"""Create mappings from label to index and index to label"""
logger.debug("Creating mappings for labels")
label_to_index = {label: index for index, label in enumerate(
["pad"] + sorted(list(labe... | [
"def",
"initialize_labels",
"(",
"self",
",",
"labels",
":",
"Set",
"[",
"str",
"]",
")",
"->",
"Tuple",
"[",
"dict",
",",
"dict",
"]",
":",
"logger",
".",
"debug",
"(",
"\"Creating mappings for labels\"",
")",
"label_to_index",
"=",
"{",
"label",
":",
"... | Create mappings from label to index and index to label | [
"Create",
"mappings",
"from",
"label",
"to",
"index",
"and",
"index",
"to",
"label"
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/corpus.py#L357-L366 | train |
persephone-tools/persephone | persephone/corpus.py | Corpus.prepare_feats | def prepare_feats(self) -> None:
""" Prepares input features"""
logger.debug("Preparing input features")
self.feat_dir.mkdir(parents=True, exist_ok=True)
should_extract_feats = False
for path in self.wav_dir.iterdir():
if not path.suffix == ".wav":
l... | python | def prepare_feats(self) -> None:
""" Prepares input features"""
logger.debug("Preparing input features")
self.feat_dir.mkdir(parents=True, exist_ok=True)
should_extract_feats = False
for path in self.wav_dir.iterdir():
if not path.suffix == ".wav":
l... | [
"def",
"prepare_feats",
"(",
"self",
")",
"->",
"None",
":",
"logger",
".",
"debug",
"(",
"\"Preparing input features\"",
")",
"self",
".",
"feat_dir",
".",
"mkdir",
"(",
"parents",
"=",
"True",
",",
"exist_ok",
"=",
"True",
")",
"should_extract_feats",
"=",... | Prepares input features | [
"Prepares",
"input",
"features"
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/corpus.py#L368-L392 | train |
persephone-tools/persephone | persephone/corpus.py | Corpus.make_data_splits | def make_data_splits(self, max_samples: int) -> None:
""" Splits the utterances into training, validation and test sets."""
train_f_exists = self.train_prefix_fn.is_file()
valid_f_exists = self.valid_prefix_fn.is_file()
test_f_exists = self.test_prefix_fn.is_file()
if train_f_e... | python | def make_data_splits(self, max_samples: int) -> None:
""" Splits the utterances into training, validation and test sets."""
train_f_exists = self.train_prefix_fn.is_file()
valid_f_exists = self.valid_prefix_fn.is_file()
test_f_exists = self.test_prefix_fn.is_file()
if train_f_e... | [
"def",
"make_data_splits",
"(",
"self",
",",
"max_samples",
":",
"int",
")",
"->",
"None",
":",
"train_f_exists",
"=",
"self",
".",
"train_prefix_fn",
".",
"is_file",
"(",
")",
"valid_f_exists",
"=",
"self",
".",
"valid_prefix_fn",
".",
"is_file",
"(",
")",
... | Splits the utterances into training, validation and test sets. | [
"Splits",
"the",
"utterances",
"into",
"training",
"validation",
"and",
"test",
"sets",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/corpus.py#L394-L438 | train |
persephone-tools/persephone | persephone/corpus.py | Corpus.divide_prefixes | def divide_prefixes(prefixes: List[str], seed:int=0) -> Tuple[List[str], List[str], List[str]]:
"""Divide data into training, validation and test subsets"""
if len(prefixes) < 3:
raise PersephoneException(
"{} cannot be split into 3 groups as it only has {} items".format(pref... | python | def divide_prefixes(prefixes: List[str], seed:int=0) -> Tuple[List[str], List[str], List[str]]:
"""Divide data into training, validation and test subsets"""
if len(prefixes) < 3:
raise PersephoneException(
"{} cannot be split into 3 groups as it only has {} items".format(pref... | [
"def",
"divide_prefixes",
"(",
"prefixes",
":",
"List",
"[",
"str",
"]",
",",
"seed",
":",
"int",
"=",
"0",
")",
"->",
"Tuple",
"[",
"List",
"[",
"str",
"]",
",",
"List",
"[",
"str",
"]",
",",
"List",
"[",
"str",
"]",
"]",
":",
"if",
"len",
"... | Divide data into training, validation and test subsets | [
"Divide",
"data",
"into",
"training",
"validation",
"and",
"test",
"subsets"
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/corpus.py#L464-L495 | train |
persephone-tools/persephone | persephone/corpus.py | Corpus.indices_to_labels | def indices_to_labels(self, indices: Sequence[int]) -> List[str]:
""" Converts a sequence of indices into their corresponding labels."""
return [(self.INDEX_TO_LABEL[index]) for index in indices] | python | def indices_to_labels(self, indices: Sequence[int]) -> List[str]:
""" Converts a sequence of indices into their corresponding labels."""
return [(self.INDEX_TO_LABEL[index]) for index in indices] | [
"def",
"indices_to_labels",
"(",
"self",
",",
"indices",
":",
"Sequence",
"[",
"int",
"]",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"[",
"(",
"self",
".",
"INDEX_TO_LABEL",
"[",
"index",
"]",
")",
"for",
"index",
"in",
"indices",
"]"
] | Converts a sequence of indices into their corresponding labels. | [
"Converts",
"a",
"sequence",
"of",
"indices",
"into",
"their",
"corresponding",
"labels",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/corpus.py#L497-L500 | train |
persephone-tools/persephone | persephone/corpus.py | Corpus.labels_to_indices | def labels_to_indices(self, labels: Sequence[str]) -> List[int]:
""" Converts a sequence of labels into their corresponding indices."""
return [self.LABEL_TO_INDEX[label] for label in labels] | python | def labels_to_indices(self, labels: Sequence[str]) -> List[int]:
""" Converts a sequence of labels into their corresponding indices."""
return [self.LABEL_TO_INDEX[label] for label in labels] | [
"def",
"labels_to_indices",
"(",
"self",
",",
"labels",
":",
"Sequence",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"int",
"]",
":",
"return",
"[",
"self",
".",
"LABEL_TO_INDEX",
"[",
"label",
"]",
"for",
"label",
"in",
"labels",
"]"
] | Converts a sequence of labels into their corresponding indices. | [
"Converts",
"a",
"sequence",
"of",
"labels",
"into",
"their",
"corresponding",
"indices",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/corpus.py#L502-L505 | train |
persephone-tools/persephone | persephone/corpus.py | Corpus.num_feats | def num_feats(self):
""" The number of features per time step in the corpus. """
if not self._num_feats:
filename = self.get_train_fns()[0][0]
feats = np.load(filename)
# pylint: disable=maybe-no-member
if len(feats.shape) == 3:
# Then ther... | python | def num_feats(self):
""" The number of features per time step in the corpus. """
if not self._num_feats:
filename = self.get_train_fns()[0][0]
feats = np.load(filename)
# pylint: disable=maybe-no-member
if len(feats.shape) == 3:
# Then ther... | [
"def",
"num_feats",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_num_feats",
":",
"filename",
"=",
"self",
".",
"get_train_fns",
"(",
")",
"[",
"0",
"]",
"[",
"0",
"]",
"feats",
"=",
"np",
".",
"load",
"(",
"filename",
")",
"# pylint: disable=m... | The number of features per time step in the corpus. | [
"The",
"number",
"of",
"features",
"per",
"time",
"step",
"in",
"the",
"corpus",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/corpus.py#L508-L523 | train |
persephone-tools/persephone | persephone/corpus.py | Corpus.prefixes_to_fns | def prefixes_to_fns(self, prefixes: List[str]) -> Tuple[List[str], List[str]]:
""" Fetches the file paths to the features files and labels files
corresponding to the provided list of features"""
# TODO Return pathlib.Paths
feat_fns = [str(self.feat_dir / ("%s.%s.npy" % (prefix, self.feat... | python | def prefixes_to_fns(self, prefixes: List[str]) -> Tuple[List[str], List[str]]:
""" Fetches the file paths to the features files and labels files
corresponding to the provided list of features"""
# TODO Return pathlib.Paths
feat_fns = [str(self.feat_dir / ("%s.%s.npy" % (prefix, self.feat... | [
"def",
"prefixes_to_fns",
"(",
"self",
",",
"prefixes",
":",
"List",
"[",
"str",
"]",
")",
"->",
"Tuple",
"[",
"List",
"[",
"str",
"]",
",",
"List",
"[",
"str",
"]",
"]",
":",
"# TODO Return pathlib.Paths",
"feat_fns",
"=",
"[",
"str",
"(",
"self",
"... | Fetches the file paths to the features files and labels files
corresponding to the provided list of features | [
"Fetches",
"the",
"file",
"paths",
"to",
"the",
"features",
"files",
"and",
"labels",
"files",
"corresponding",
"to",
"the",
"provided",
"list",
"of",
"features"
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/corpus.py#L525-L533 | train |
persephone-tools/persephone | persephone/corpus.py | Corpus.get_train_fns | def get_train_fns(self) -> Tuple[List[str], List[str]]:
""" Fetches the training set of the corpus.
Outputs a Tuple of size 2, where the first element is a list of paths
to input features files, one per utterance. The second element is a list
of paths to the transcriptions.
"""
... | python | def get_train_fns(self) -> Tuple[List[str], List[str]]:
""" Fetches the training set of the corpus.
Outputs a Tuple of size 2, where the first element is a list of paths
to input features files, one per utterance. The second element is a list
of paths to the transcriptions.
"""
... | [
"def",
"get_train_fns",
"(",
"self",
")",
"->",
"Tuple",
"[",
"List",
"[",
"str",
"]",
",",
"List",
"[",
"str",
"]",
"]",
":",
"return",
"self",
".",
"prefixes_to_fns",
"(",
"self",
".",
"train_prefixes",
")"
] | Fetches the training set of the corpus.
Outputs a Tuple of size 2, where the first element is a list of paths
to input features files, one per utterance. The second element is a list
of paths to the transcriptions. | [
"Fetches",
"the",
"training",
"set",
"of",
"the",
"corpus",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/corpus.py#L535-L542 | train |
persephone-tools/persephone | persephone/corpus.py | Corpus.get_valid_fns | def get_valid_fns(self) -> Tuple[List[str], List[str]]:
""" Fetches the validation set of the corpus."""
return self.prefixes_to_fns(self.valid_prefixes) | python | def get_valid_fns(self) -> Tuple[List[str], List[str]]:
""" Fetches the validation set of the corpus."""
return self.prefixes_to_fns(self.valid_prefixes) | [
"def",
"get_valid_fns",
"(",
"self",
")",
"->",
"Tuple",
"[",
"List",
"[",
"str",
"]",
",",
"List",
"[",
"str",
"]",
"]",
":",
"return",
"self",
".",
"prefixes_to_fns",
"(",
"self",
".",
"valid_prefixes",
")"
] | Fetches the validation set of the corpus. | [
"Fetches",
"the",
"validation",
"set",
"of",
"the",
"corpus",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/corpus.py#L544-L546 | train |
persephone-tools/persephone | persephone/corpus.py | Corpus.review | def review(self) -> None:
""" Used to play the WAV files and compare with the transcription. """
for prefix in self.determine_prefixes():
print("Utterance: {}".format(prefix))
wav_fn = self.feat_dir / "{}.wav".format(prefix)
label_fn = self.label_dir / "{}.{}".format... | python | def review(self) -> None:
""" Used to play the WAV files and compare with the transcription. """
for prefix in self.determine_prefixes():
print("Utterance: {}".format(prefix))
wav_fn = self.feat_dir / "{}.wav".format(prefix)
label_fn = self.label_dir / "{}.{}".format... | [
"def",
"review",
"(",
"self",
")",
"->",
"None",
":",
"for",
"prefix",
"in",
"self",
".",
"determine_prefixes",
"(",
")",
":",
"print",
"(",
"\"Utterance: {}\"",
".",
"format",
"(",
"prefix",
")",
")",
"wav_fn",
"=",
"self",
".",
"feat_dir",
"/",
"\"{}... | Used to play the WAV files and compare with the transcription. | [
"Used",
"to",
"play",
"the",
"WAV",
"files",
"and",
"compare",
"with",
"the",
"transcription",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/corpus.py#L589-L599 | train |
persephone-tools/persephone | persephone/corpus.py | Corpus.pickle | def pickle(self) -> None:
""" Pickles the Corpus object in a file in tgt_dir. """
pickle_path = self.tgt_dir / "corpus.p"
logger.debug("pickling %r object and saving it to path %s", self, pickle_path)
with pickle_path.open("wb") as f:
pickle.dump(self, f) | python | def pickle(self) -> None:
""" Pickles the Corpus object in a file in tgt_dir. """
pickle_path = self.tgt_dir / "corpus.p"
logger.debug("pickling %r object and saving it to path %s", self, pickle_path)
with pickle_path.open("wb") as f:
pickle.dump(self, f) | [
"def",
"pickle",
"(",
"self",
")",
"->",
"None",
":",
"pickle_path",
"=",
"self",
".",
"tgt_dir",
"/",
"\"corpus.p\"",
"logger",
".",
"debug",
"(",
"\"pickling %r object and saving it to path %s\"",
",",
"self",
",",
"pickle_path",
")",
"with",
"pickle_path",
".... | Pickles the Corpus object in a file in tgt_dir. | [
"Pickles",
"the",
"Corpus",
"object",
"in",
"a",
"file",
"in",
"tgt_dir",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/corpus.py#L601-L607 | train |
persephone-tools/persephone | persephone/utils.py | zero_pad | def zero_pad(matrix, to_length):
""" Zero pads along the 0th dimension to make sure the utterance array
x is of length to_length."""
assert matrix.shape[0] <= to_length
if not matrix.shape[0] <= to_length:
logger.error("zero_pad cannot be performed on matrix with shape {}"
... | python | def zero_pad(matrix, to_length):
""" Zero pads along the 0th dimension to make sure the utterance array
x is of length to_length."""
assert matrix.shape[0] <= to_length
if not matrix.shape[0] <= to_length:
logger.error("zero_pad cannot be performed on matrix with shape {}"
... | [
"def",
"zero_pad",
"(",
"matrix",
",",
"to_length",
")",
":",
"assert",
"matrix",
".",
"shape",
"[",
"0",
"]",
"<=",
"to_length",
"if",
"not",
"matrix",
".",
"shape",
"[",
"0",
"]",
"<=",
"to_length",
":",
"logger",
".",
"error",
"(",
"\"zero_pad canno... | Zero pads along the 0th dimension to make sure the utterance array
x is of length to_length. | [
"Zero",
"pads",
"along",
"the",
"0th",
"dimension",
"to",
"make",
"sure",
"the",
"utterance",
"array",
"x",
"is",
"of",
"length",
"to_length",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/utils.py#L58-L69 | train |
persephone-tools/persephone | persephone/utils.py | load_batch_x | def load_batch_x(path_batch,
flatten = False,
time_major = False):
""" Loads a batch of input features given a list of paths to numpy
arrays in that batch."""
utterances = [np.load(str(path)) for path in path_batch]
utter_lens = [utterance.shape[0] for utterance in utt... | python | def load_batch_x(path_batch,
flatten = False,
time_major = False):
""" Loads a batch of input features given a list of paths to numpy
arrays in that batch."""
utterances = [np.load(str(path)) for path in path_batch]
utter_lens = [utterance.shape[0] for utterance in utt... | [
"def",
"load_batch_x",
"(",
"path_batch",
",",
"flatten",
"=",
"False",
",",
"time_major",
"=",
"False",
")",
":",
"utterances",
"=",
"[",
"np",
".",
"load",
"(",
"str",
"(",
"path",
")",
")",
"for",
"path",
"in",
"path_batch",
"]",
"utter_lens",
"=",
... | Loads a batch of input features given a list of paths to numpy
arrays in that batch. | [
"Loads",
"a",
"batch",
"of",
"input",
"features",
"given",
"a",
"list",
"of",
"paths",
"to",
"numpy",
"arrays",
"in",
"that",
"batch",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/utils.py#L88-L104 | train |
persephone-tools/persephone | persephone/utils.py | batch_per | def batch_per(hyps: Sequence[Sequence[T]],
refs: Sequence[Sequence[T]]) -> float:
""" Calculates the phoneme error rate of a batch."""
macro_per = 0.0
for i in range(len(hyps)):
ref = [phn_i for phn_i in refs[i] if phn_i != 0]
hyp = [phn_i for phn_i in hyps[i] if phn_i != 0]
... | python | def batch_per(hyps: Sequence[Sequence[T]],
refs: Sequence[Sequence[T]]) -> float:
""" Calculates the phoneme error rate of a batch."""
macro_per = 0.0
for i in range(len(hyps)):
ref = [phn_i for phn_i in refs[i] if phn_i != 0]
hyp = [phn_i for phn_i in hyps[i] if phn_i != 0]
... | [
"def",
"batch_per",
"(",
"hyps",
":",
"Sequence",
"[",
"Sequence",
"[",
"T",
"]",
"]",
",",
"refs",
":",
"Sequence",
"[",
"Sequence",
"[",
"T",
"]",
"]",
")",
"->",
"float",
":",
"macro_per",
"=",
"0.0",
"for",
"i",
"in",
"range",
"(",
"len",
"("... | Calculates the phoneme error rate of a batch. | [
"Calculates",
"the",
"phoneme",
"error",
"rate",
"of",
"a",
"batch",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/utils.py#L106-L115 | train |
persephone-tools/persephone | persephone/utils.py | filter_by_size | def filter_by_size(feat_dir: Path, prefixes: List[str], feat_type: str,
max_samples: int) -> List[str]:
""" Sorts the files by their length and returns those with less
than or equal to max_samples length. Returns the filename prefixes of
those files. The main job of the method is to filte... | python | def filter_by_size(feat_dir: Path, prefixes: List[str], feat_type: str,
max_samples: int) -> List[str]:
""" Sorts the files by their length and returns those with less
than or equal to max_samples length. Returns the filename prefixes of
those files. The main job of the method is to filte... | [
"def",
"filter_by_size",
"(",
"feat_dir",
":",
"Path",
",",
"prefixes",
":",
"List",
"[",
"str",
"]",
",",
"feat_type",
":",
"str",
",",
"max_samples",
":",
"int",
")",
"->",
"List",
"[",
"str",
"]",
":",
"# TODO Tell the user what utterances we are removing."... | Sorts the files by their length and returns those with less
than or equal to max_samples length. Returns the filename prefixes of
those files. The main job of the method is to filter, but the sorting
may give better efficiency when doing dynamic batching unless it gets
shuffled downstream. | [
"Sorts",
"the",
"files",
"by",
"their",
"length",
"and",
"returns",
"those",
"with",
"less",
"than",
"or",
"equal",
"to",
"max_samples",
"length",
".",
"Returns",
"the",
"filename",
"prefixes",
"of",
"those",
"files",
".",
"The",
"main",
"job",
"of",
"the"... | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/utils.py#L141-L154 | train |
persephone-tools/persephone | persephone/utils.py | wav_length | def wav_length(fn: str) -> float:
""" Returns the length of the WAV file in seconds."""
args = [config.SOX_PATH, fn, "-n", "stat"]
p = subprocess.Popen(
args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
length_line = str(p.communicate()[1]).split("\\n")[1].split()
print(length_line)
assert le... | python | def wav_length(fn: str) -> float:
""" Returns the length of the WAV file in seconds."""
args = [config.SOX_PATH, fn, "-n", "stat"]
p = subprocess.Popen(
args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
length_line = str(p.communicate()[1]).split("\\n")[1].split()
print(length_line)
assert le... | [
"def",
"wav_length",
"(",
"fn",
":",
"str",
")",
"->",
"float",
":",
"args",
"=",
"[",
"config",
".",
"SOX_PATH",
",",
"fn",
",",
"\"-n\"",
",",
"\"stat\"",
"]",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"args",
",",
"stdin",
"=",
"PIPE",
",",
"... | Returns the length of the WAV file in seconds. | [
"Returns",
"the",
"length",
"of",
"the",
"WAV",
"file",
"in",
"seconds",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/utils.py#L170-L179 | train |
persephone-tools/persephone | persephone/datasets/bkw.py | pull_en_words | def pull_en_words() -> None:
""" Fetches a repository containing English words. """
ENGLISH_WORDS_URL = "https://github.com/dwyl/english-words.git"
en_words_path = Path(config.EN_WORDS_PATH)
if not en_words_path.is_file():
subprocess.run(["git", "clone",
ENGLISH_WORDS_UR... | python | def pull_en_words() -> None:
""" Fetches a repository containing English words. """
ENGLISH_WORDS_URL = "https://github.com/dwyl/english-words.git"
en_words_path = Path(config.EN_WORDS_PATH)
if not en_words_path.is_file():
subprocess.run(["git", "clone",
ENGLISH_WORDS_UR... | [
"def",
"pull_en_words",
"(",
")",
"->",
"None",
":",
"ENGLISH_WORDS_URL",
"=",
"\"https://github.com/dwyl/english-words.git\"",
"en_words_path",
"=",
"Path",
"(",
"config",
".",
"EN_WORDS_PATH",
")",
"if",
"not",
"en_words_path",
".",
"is_file",
"(",
")",
":",
"su... | Fetches a repository containing English words. | [
"Fetches",
"a",
"repository",
"containing",
"English",
"words",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/datasets/bkw.py#L27-L34 | train |
persephone-tools/persephone | persephone/datasets/bkw.py | get_en_words | def get_en_words() -> Set[str]:
"""
Returns a list of English words which can be used to filter out
code-switched sentences.
"""
pull_en_words()
with open(config.EN_WORDS_PATH) as words_f:
raw_words = words_f.readlines()
en_words = set([word.strip().lower() for word in raw_words])
... | python | def get_en_words() -> Set[str]:
"""
Returns a list of English words which can be used to filter out
code-switched sentences.
"""
pull_en_words()
with open(config.EN_WORDS_PATH) as words_f:
raw_words = words_f.readlines()
en_words = set([word.strip().lower() for word in raw_words])
... | [
"def",
"get_en_words",
"(",
")",
"->",
"Set",
"[",
"str",
"]",
":",
"pull_en_words",
"(",
")",
"with",
"open",
"(",
"config",
".",
"EN_WORDS_PATH",
")",
"as",
"words_f",
":",
"raw_words",
"=",
"words_f",
".",
"readlines",
"(",
")",
"en_words",
"=",
"se... | Returns a list of English words which can be used to filter out
code-switched sentences. | [
"Returns",
"a",
"list",
"of",
"English",
"words",
"which",
"can",
"be",
"used",
"to",
"filter",
"out",
"code",
"-",
"switched",
"sentences",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/datasets/bkw.py#L36-L69 | train |
persephone-tools/persephone | persephone/datasets/bkw.py | explore_elan_files | def explore_elan_files(elan_paths):
"""
A function to explore the tiers of ELAN files.
"""
for elan_path in elan_paths:
print(elan_path)
eafob = Eaf(elan_path)
tier_names = eafob.get_tier_names()
for tier in tier_names:
print("\t", tier)
try:
... | python | def explore_elan_files(elan_paths):
"""
A function to explore the tiers of ELAN files.
"""
for elan_path in elan_paths:
print(elan_path)
eafob = Eaf(elan_path)
tier_names = eafob.get_tier_names()
for tier in tier_names:
print("\t", tier)
try:
... | [
"def",
"explore_elan_files",
"(",
"elan_paths",
")",
":",
"for",
"elan_path",
"in",
"elan_paths",
":",
"print",
"(",
"elan_path",
")",
"eafob",
"=",
"Eaf",
"(",
"elan_path",
")",
"tier_names",
"=",
"eafob",
".",
"get_tier_names",
"(",
")",
"for",
"tier",
"... | A function to explore the tiers of ELAN files. | [
"A",
"function",
"to",
"explore",
"the",
"tiers",
"of",
"ELAN",
"files",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/datasets/bkw.py#L73-L90 | train |
persephone-tools/persephone | persephone/preprocess/elan.py | sort_annotations | def sort_annotations(annotations: List[Tuple[int, int, str]]
) -> List[Tuple[int, int, str]]:
""" Sorts the annotations by their start_time. """
return sorted(annotations, key=lambda x: x[0]) | python | def sort_annotations(annotations: List[Tuple[int, int, str]]
) -> List[Tuple[int, int, str]]:
""" Sorts the annotations by their start_time. """
return sorted(annotations, key=lambda x: x[0]) | [
"def",
"sort_annotations",
"(",
"annotations",
":",
"List",
"[",
"Tuple",
"[",
"int",
",",
"int",
",",
"str",
"]",
"]",
")",
"->",
"List",
"[",
"Tuple",
"[",
"int",
",",
"int",
",",
"str",
"]",
"]",
":",
"return",
"sorted",
"(",
"annotations",
",",... | Sorts the annotations by their start_time. | [
"Sorts",
"the",
"annotations",
"by",
"their",
"start_time",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/preprocess/elan.py#L62-L65 | train |
persephone-tools/persephone | persephone/preprocess/elan.py | utterances_from_tier | def utterances_from_tier(eafob: Eaf, tier_name: str) -> List[Utterance]:
""" Returns utterances found in the given Eaf object in the given tier."""
try:
speaker = eafob.tiers[tier_name][2]["PARTICIPANT"]
except KeyError:
speaker = None # We don't know the name of the speaker.
tier_utte... | python | def utterances_from_tier(eafob: Eaf, tier_name: str) -> List[Utterance]:
""" Returns utterances found in the given Eaf object in the given tier."""
try:
speaker = eafob.tiers[tier_name][2]["PARTICIPANT"]
except KeyError:
speaker = None # We don't know the name of the speaker.
tier_utte... | [
"def",
"utterances_from_tier",
"(",
"eafob",
":",
"Eaf",
",",
"tier_name",
":",
"str",
")",
"->",
"List",
"[",
"Utterance",
"]",
":",
"try",
":",
"speaker",
"=",
"eafob",
".",
"tiers",
"[",
"tier_name",
"]",
"[",
"2",
"]",
"[",
"\"PARTICIPANT\"",
"]",
... | Returns utterances found in the given Eaf object in the given tier. | [
"Returns",
"utterances",
"found",
"in",
"the",
"given",
"Eaf",
"object",
"in",
"the",
"given",
"tier",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/preprocess/elan.py#L68-L91 | train |
persephone-tools/persephone | persephone/preprocess/elan.py | utterances_from_eaf | def utterances_from_eaf(eaf_path: Path, tier_prefixes: Tuple[str, ...]) -> List[Utterance]:
"""
Extracts utterances in tiers that start with tier_prefixes found in the ELAN .eaf XML file
at eaf_path.
For example, if xv@Mark is a tier in the eaf file, and
tier_prefixes = ["xv"], then utterances from... | python | def utterances_from_eaf(eaf_path: Path, tier_prefixes: Tuple[str, ...]) -> List[Utterance]:
"""
Extracts utterances in tiers that start with tier_prefixes found in the ELAN .eaf XML file
at eaf_path.
For example, if xv@Mark is a tier in the eaf file, and
tier_prefixes = ["xv"], then utterances from... | [
"def",
"utterances_from_eaf",
"(",
"eaf_path",
":",
"Path",
",",
"tier_prefixes",
":",
"Tuple",
"[",
"str",
",",
"...",
"]",
")",
"->",
"List",
"[",
"Utterance",
"]",
":",
"if",
"not",
"eaf_path",
".",
"is_file",
"(",
")",
":",
"raise",
"FileNotFoundErro... | Extracts utterances in tiers that start with tier_prefixes found in the ELAN .eaf XML file
at eaf_path.
For example, if xv@Mark is a tier in the eaf file, and
tier_prefixes = ["xv"], then utterances from that tier will be gathered. | [
"Extracts",
"utterances",
"in",
"tiers",
"that",
"start",
"with",
"tier_prefixes",
"found",
"in",
"the",
"ELAN",
".",
"eaf",
"XML",
"file",
"at",
"eaf_path",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/preprocess/elan.py#L94-L113 | train |
persephone-tools/persephone | persephone/preprocess/elan.py | utterances_from_dir | def utterances_from_dir(eaf_dir: Path,
tier_prefixes: Tuple[str, ...]) -> List[Utterance]:
""" Returns the utterances found in ELAN files in a directory.
Recursively explores the directory, gathering ELAN files and extracting
utterances from them for tiers that start with the specif... | python | def utterances_from_dir(eaf_dir: Path,
tier_prefixes: Tuple[str, ...]) -> List[Utterance]:
""" Returns the utterances found in ELAN files in a directory.
Recursively explores the directory, gathering ELAN files and extracting
utterances from them for tiers that start with the specif... | [
"def",
"utterances_from_dir",
"(",
"eaf_dir",
":",
"Path",
",",
"tier_prefixes",
":",
"Tuple",
"[",
"str",
",",
"...",
"]",
")",
"->",
"List",
"[",
"Utterance",
"]",
":",
"logger",
".",
"info",
"(",
"\"EAF from directory: {}, searching with tier_prefixes {}\"",
... | Returns the utterances found in ELAN files in a directory.
Recursively explores the directory, gathering ELAN files and extracting
utterances from them for tiers that start with the specified prefixes.
Args:
eaf_dir: A path to the directory to be searched
tier_prefixes: Stings matching the... | [
"Returns",
"the",
"utterances",
"found",
"in",
"ELAN",
"files",
"in",
"a",
"directory",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/preprocess/elan.py#L116-L142 | train |
persephone-tools/persephone | persephone/corpus_reader.py | CorpusReader.load_batch | def load_batch(self, fn_batch):
""" Loads a batch with the given prefixes. The prefixes is the full path to the
training example minus the extension.
"""
# TODO Assumes targets are available, which is how its distinct from
# utils.load_batch_x(). These functions need to change n... | python | def load_batch(self, fn_batch):
""" Loads a batch with the given prefixes. The prefixes is the full path to the
training example minus the extension.
"""
# TODO Assumes targets are available, which is how its distinct from
# utils.load_batch_x(). These functions need to change n... | [
"def",
"load_batch",
"(",
"self",
",",
"fn_batch",
")",
":",
"# TODO Assumes targets are available, which is how its distinct from",
"# utils.load_batch_x(). These functions need to change names to be",
"# clearer.",
"inverse",
"=",
"list",
"(",
"zip",
"(",
"*",
"fn_batch",
")"... | Loads a batch with the given prefixes. The prefixes is the full path to the
training example minus the extension. | [
"Loads",
"a",
"batch",
"with",
"the",
"given",
"prefixes",
".",
"The",
"prefixes",
"is",
"the",
"full",
"path",
"to",
"the",
"training",
"example",
"minus",
"the",
"extension",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/corpus_reader.py#L95-L117 | train |
persephone-tools/persephone | persephone/corpus_reader.py | CorpusReader.train_batch_gen | def train_batch_gen(self) -> Iterator:
""" Returns a generator that outputs batches in the training data."""
if len(self.train_fns) == 0:
raise PersephoneException("""No training data available; cannot
generate training batches.""")
# Create b... | python | def train_batch_gen(self) -> Iterator:
""" Returns a generator that outputs batches in the training data."""
if len(self.train_fns) == 0:
raise PersephoneException("""No training data available; cannot
generate training batches.""")
# Create b... | [
"def",
"train_batch_gen",
"(",
"self",
")",
"->",
"Iterator",
":",
"if",
"len",
"(",
"self",
".",
"train_fns",
")",
"==",
"0",
":",
"raise",
"PersephoneException",
"(",
"\"\"\"No training data available; cannot\n generate training batch... | Returns a generator that outputs batches in the training data. | [
"Returns",
"a",
"generator",
"that",
"outputs",
"batches",
"in",
"the",
"training",
"data",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/corpus_reader.py#L125-L144 | train |
persephone-tools/persephone | persephone/corpus_reader.py | CorpusReader.valid_batch | def valid_batch(self):
""" Returns a single batch with all the validation cases."""
valid_fns = list(zip(*self.corpus.get_valid_fns()))
return self.load_batch(valid_fns) | python | def valid_batch(self):
""" Returns a single batch with all the validation cases."""
valid_fns = list(zip(*self.corpus.get_valid_fns()))
return self.load_batch(valid_fns) | [
"def",
"valid_batch",
"(",
"self",
")",
":",
"valid_fns",
"=",
"list",
"(",
"zip",
"(",
"*",
"self",
".",
"corpus",
".",
"get_valid_fns",
"(",
")",
")",
")",
"return",
"self",
".",
"load_batch",
"(",
"valid_fns",
")"
] | Returns a single batch with all the validation cases. | [
"Returns",
"a",
"single",
"batch",
"with",
"all",
"the",
"validation",
"cases",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/corpus_reader.py#L146-L150 | train |
persephone-tools/persephone | persephone/corpus_reader.py | CorpusReader.untranscribed_batch_gen | def untranscribed_batch_gen(self):
""" A batch generator for all the untranscribed data. """
feat_fns = self.corpus.get_untranscribed_fns()
fn_batches = self.make_batches(feat_fns)
for fn_batch in fn_batches:
batch_inputs, batch_inputs_lens = utils.load_batch_x(fn_batch,
... | python | def untranscribed_batch_gen(self):
""" A batch generator for all the untranscribed data. """
feat_fns = self.corpus.get_untranscribed_fns()
fn_batches = self.make_batches(feat_fns)
for fn_batch in fn_batches:
batch_inputs, batch_inputs_lens = utils.load_batch_x(fn_batch,
... | [
"def",
"untranscribed_batch_gen",
"(",
"self",
")",
":",
"feat_fns",
"=",
"self",
".",
"corpus",
".",
"get_untranscribed_fns",
"(",
")",
"fn_batches",
"=",
"self",
".",
"make_batches",
"(",
"feat_fns",
")",
"for",
"fn_batch",
"in",
"fn_batches",
":",
"batch_in... | A batch generator for all the untranscribed data. | [
"A",
"batch",
"generator",
"for",
"all",
"the",
"untranscribed",
"data",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/corpus_reader.py#L158-L167 | train |
persephone-tools/persephone | persephone/corpus_reader.py | CorpusReader.human_readable_hyp_ref | def human_readable_hyp_ref(self, dense_decoded, dense_y):
""" Returns a human readable version of the hypothesis for manual
inspection, along with the reference.
"""
hyps = []
refs = []
for i in range(len(dense_decoded)):
ref = [phn_i for phn_i in dense_y[i] ... | python | def human_readable_hyp_ref(self, dense_decoded, dense_y):
""" Returns a human readable version of the hypothesis for manual
inspection, along with the reference.
"""
hyps = []
refs = []
for i in range(len(dense_decoded)):
ref = [phn_i for phn_i in dense_y[i] ... | [
"def",
"human_readable_hyp_ref",
"(",
"self",
",",
"dense_decoded",
",",
"dense_y",
")",
":",
"hyps",
"=",
"[",
"]",
"refs",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"dense_decoded",
")",
")",
":",
"ref",
"=",
"[",
"phn_i",
"for",
... | Returns a human readable version of the hypothesis for manual
inspection, along with the reference. | [
"Returns",
"a",
"human",
"readable",
"version",
"of",
"the",
"hypothesis",
"for",
"manual",
"inspection",
"along",
"with",
"the",
"reference",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/corpus_reader.py#L169-L184 | train |
persephone-tools/persephone | persephone/corpus_reader.py | CorpusReader.human_readable | def human_readable(self, dense_repr: Sequence[Sequence[int]]) -> List[List[str]]:
""" Returns a human readable version of a dense representation of
either or reference to facilitate simple manual inspection.
"""
transcripts = []
for dense_r in dense_repr:
non_empty_p... | python | def human_readable(self, dense_repr: Sequence[Sequence[int]]) -> List[List[str]]:
""" Returns a human readable version of a dense representation of
either or reference to facilitate simple manual inspection.
"""
transcripts = []
for dense_r in dense_repr:
non_empty_p... | [
"def",
"human_readable",
"(",
"self",
",",
"dense_repr",
":",
"Sequence",
"[",
"Sequence",
"[",
"int",
"]",
"]",
")",
"->",
"List",
"[",
"List",
"[",
"str",
"]",
"]",
":",
"transcripts",
"=",
"[",
"]",
"for",
"dense_r",
"in",
"dense_repr",
":",
"non_... | Returns a human readable version of a dense representation of
either or reference to facilitate simple manual inspection. | [
"Returns",
"a",
"human",
"readable",
"version",
"of",
"a",
"dense",
"representation",
"of",
"either",
"or",
"reference",
"to",
"facilitate",
"simple",
"manual",
"inspection",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/corpus_reader.py#L186-L197 | train |
persephone-tools/persephone | persephone/corpus_reader.py | CorpusReader.calc_time | def calc_time(self) -> None:
"""
Prints statistics about the the total duration of recordings in the
corpus.
"""
def get_number_of_frames(feat_fns):
""" fns: A list of numpy files which contain a number of feature
frames. """
total = 0
... | python | def calc_time(self) -> None:
"""
Prints statistics about the the total duration of recordings in the
corpus.
"""
def get_number_of_frames(feat_fns):
""" fns: A list of numpy files which contain a number of feature
frames. """
total = 0
... | [
"def",
"calc_time",
"(",
"self",
")",
"->",
"None",
":",
"def",
"get_number_of_frames",
"(",
"feat_fns",
")",
":",
"\"\"\" fns: A list of numpy files which contain a number of feature\n frames. \"\"\"",
"total",
"=",
"0",
"for",
"feat_fn",
"in",
"feat_fns",
":"... | Prints statistics about the the total duration of recordings in the
corpus. | [
"Prints",
"statistics",
"about",
"the",
"the",
"total",
"duration",
"of",
"recordings",
"in",
"the",
"corpus",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/corpus_reader.py#L205-L241 | train |
persephone-tools/persephone | persephone/rnn_ctc.py | lstm_cell | def lstm_cell(hidden_size):
""" Wrapper function to create an LSTM cell. """
return tf.contrib.rnn.LSTMCell(
hidden_size, use_peepholes=True, state_is_tuple=True) | python | def lstm_cell(hidden_size):
""" Wrapper function to create an LSTM cell. """
return tf.contrib.rnn.LSTMCell(
hidden_size, use_peepholes=True, state_is_tuple=True) | [
"def",
"lstm_cell",
"(",
"hidden_size",
")",
":",
"return",
"tf",
".",
"contrib",
".",
"rnn",
".",
"LSTMCell",
"(",
"hidden_size",
",",
"use_peepholes",
"=",
"True",
",",
"state_is_tuple",
"=",
"True",
")"
] | Wrapper function to create an LSTM cell. | [
"Wrapper",
"function",
"to",
"create",
"an",
"LSTM",
"cell",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/rnn_ctc.py#L12-L16 | train |
persephone-tools/persephone | persephone/rnn_ctc.py | Model.write_desc | def write_desc(self) -> None:
""" Writes a description of the model to the exp_dir. """
path = os.path.join(self.exp_dir, "model_description.txt")
with open(path, "w") as desc_f:
for key, val in self.__dict__.items():
print("%s=%s" % (key, val), file=desc_f)
... | python | def write_desc(self) -> None:
""" Writes a description of the model to the exp_dir. """
path = os.path.join(self.exp_dir, "model_description.txt")
with open(path, "w") as desc_f:
for key, val in self.__dict__.items():
print("%s=%s" % (key, val), file=desc_f)
... | [
"def",
"write_desc",
"(",
"self",
")",
"->",
"None",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"exp_dir",
",",
"\"model_description.txt\"",
")",
"with",
"open",
"(",
"path",
",",
"\"w\"",
")",
"as",
"desc_f",
":",
"for",
"ke... | Writes a description of the model to the exp_dir. | [
"Writes",
"a",
"description",
"of",
"the",
"model",
"to",
"the",
"exp_dir",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/rnn_ctc.py#L21-L58 | train |
persephone-tools/persephone | persephone/preprocess/feat_extract.py | empty_wav | def empty_wav(wav_path: Union[Path, str]) -> bool:
"""Check if a wav contains data"""
with wave.open(str(wav_path), 'rb') as wav_f:
return wav_f.getnframes() == 0 | python | def empty_wav(wav_path: Union[Path, str]) -> bool:
"""Check if a wav contains data"""
with wave.open(str(wav_path), 'rb') as wav_f:
return wav_f.getnframes() == 0 | [
"def",
"empty_wav",
"(",
"wav_path",
":",
"Union",
"[",
"Path",
",",
"str",
"]",
")",
"->",
"bool",
":",
"with",
"wave",
".",
"open",
"(",
"str",
"(",
"wav_path",
")",
",",
"'rb'",
")",
"as",
"wav_f",
":",
"return",
"wav_f",
".",
"getnframes",
"(",... | Check if a wav contains data | [
"Check",
"if",
"a",
"wav",
"contains",
"data"
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/preprocess/feat_extract.py#L19-L22 | train |
persephone-tools/persephone | persephone/preprocess/feat_extract.py | extract_energy | def extract_energy(rate, sig):
""" Extracts the energy of frames. """
mfcc = python_speech_features.mfcc(sig, rate, appendEnergy=True)
energy_row_vec = mfcc[:, 0]
energy_col_vec = energy_row_vec[:, np.newaxis]
return energy_col_vec | python | def extract_energy(rate, sig):
""" Extracts the energy of frames. """
mfcc = python_speech_features.mfcc(sig, rate, appendEnergy=True)
energy_row_vec = mfcc[:, 0]
energy_col_vec = energy_row_vec[:, np.newaxis]
return energy_col_vec | [
"def",
"extract_energy",
"(",
"rate",
",",
"sig",
")",
":",
"mfcc",
"=",
"python_speech_features",
".",
"mfcc",
"(",
"sig",
",",
"rate",
",",
"appendEnergy",
"=",
"True",
")",
"energy_row_vec",
"=",
"mfcc",
"[",
":",
",",
"0",
"]",
"energy_col_vec",
"=",... | Extracts the energy of frames. | [
"Extracts",
"the",
"energy",
"of",
"frames",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/preprocess/feat_extract.py#L25-L31 | train |
persephone-tools/persephone | persephone/preprocess/feat_extract.py | fbank | def fbank(wav_path, flat=True):
""" Currently grabs log Mel filterbank, deltas and double deltas."""
(rate, sig) = wav.read(wav_path)
if len(sig) == 0:
logger.warning("Empty wav: {}".format(wav_path))
fbank_feat = python_speech_features.logfbank(sig, rate, nfilt=40)
energy = extract_energy(... | python | def fbank(wav_path, flat=True):
""" Currently grabs log Mel filterbank, deltas and double deltas."""
(rate, sig) = wav.read(wav_path)
if len(sig) == 0:
logger.warning("Empty wav: {}".format(wav_path))
fbank_feat = python_speech_features.logfbank(sig, rate, nfilt=40)
energy = extract_energy(... | [
"def",
"fbank",
"(",
"wav_path",
",",
"flat",
"=",
"True",
")",
":",
"(",
"rate",
",",
"sig",
")",
"=",
"wav",
".",
"read",
"(",
"wav_path",
")",
"if",
"len",
"(",
"sig",
")",
"==",
"0",
":",
"logger",
".",
"warning",
"(",
"\"Empty wav: {}\"",
".... | Currently grabs log Mel filterbank, deltas and double deltas. | [
"Currently",
"grabs",
"log",
"Mel",
"filterbank",
"deltas",
"and",
"double",
"deltas",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/preprocess/feat_extract.py#L33-L56 | train |
persephone-tools/persephone | persephone/preprocess/feat_extract.py | mfcc | def mfcc(wav_path):
""" Grabs MFCC features with energy and derivates. """
(rate, sig) = wav.read(wav_path)
feat = python_speech_features.mfcc(sig, rate, appendEnergy=True)
delta_feat = python_speech_features.delta(feat, 2)
all_feats = [feat, delta_feat]
all_feats = np.array(all_feats)
# Ma... | python | def mfcc(wav_path):
""" Grabs MFCC features with energy and derivates. """
(rate, sig) = wav.read(wav_path)
feat = python_speech_features.mfcc(sig, rate, appendEnergy=True)
delta_feat = python_speech_features.delta(feat, 2)
all_feats = [feat, delta_feat]
all_feats = np.array(all_feats)
# Ma... | [
"def",
"mfcc",
"(",
"wav_path",
")",
":",
"(",
"rate",
",",
"sig",
")",
"=",
"wav",
".",
"read",
"(",
"wav_path",
")",
"feat",
"=",
"python_speech_features",
".",
"mfcc",
"(",
"sig",
",",
"rate",
",",
"appendEnergy",
"=",
"True",
")",
"delta_feat",
"... | Grabs MFCC features with energy and derivates. | [
"Grabs",
"MFCC",
"features",
"with",
"energy",
"and",
"derivates",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/preprocess/feat_extract.py#L58-L71 | train |
persephone-tools/persephone | persephone/preprocess/feat_extract.py | from_dir | def from_dir(dirpath: Path, feat_type: str) -> None:
""" Performs feature extraction from the WAV files in a directory.
Args:
dirpath: A `Path` to the directory where the WAV files reside.
feat_type: The type of features that are being used.
"""
logger.info("Extracting features from di... | python | def from_dir(dirpath: Path, feat_type: str) -> None:
""" Performs feature extraction from the WAV files in a directory.
Args:
dirpath: A `Path` to the directory where the WAV files reside.
feat_type: The type of features that are being used.
"""
logger.info("Extracting features from di... | [
"def",
"from_dir",
"(",
"dirpath",
":",
"Path",
",",
"feat_type",
":",
"str",
")",
"->",
"None",
":",
"logger",
".",
"info",
"(",
"\"Extracting features from directory {}\"",
".",
"format",
"(",
"dirpath",
")",
")",
"dirname",
"=",
"str",
"(",
"dirpath",
"... | Performs feature extraction from the WAV files in a directory.
Args:
dirpath: A `Path` to the directory where the WAV files reside.
feat_type: The type of features that are being used. | [
"Performs",
"feature",
"extraction",
"from",
"the",
"WAV",
"files",
"in",
"a",
"directory",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/preprocess/feat_extract.py#L117-L173 | train |
persephone-tools/persephone | persephone/preprocess/feat_extract.py | convert_wav | def convert_wav(org_wav_fn: Path, tgt_wav_fn: Path) -> None:
""" Converts the wav into a 16bit mono 16000Hz wav.
Args:
org_wav_fn: A `Path` to the original wave file
tgt_wav_fn: The `Path` to output the processed wave file
"""
if not org_wav_fn.exists():
raise FileNo... | python | def convert_wav(org_wav_fn: Path, tgt_wav_fn: Path) -> None:
""" Converts the wav into a 16bit mono 16000Hz wav.
Args:
org_wav_fn: A `Path` to the original wave file
tgt_wav_fn: The `Path` to output the processed wave file
"""
if not org_wav_fn.exists():
raise FileNo... | [
"def",
"convert_wav",
"(",
"org_wav_fn",
":",
"Path",
",",
"tgt_wav_fn",
":",
"Path",
")",
"->",
"None",
":",
"if",
"not",
"org_wav_fn",
".",
"exists",
"(",
")",
":",
"raise",
"FileNotFoundError",
"args",
"=",
"[",
"config",
".",
"FFMPEG_PATH",
",",
"\"-... | Converts the wav into a 16bit mono 16000Hz wav.
Args:
org_wav_fn: A `Path` to the original wave file
tgt_wav_fn: The `Path` to output the processed wave file | [
"Converts",
"the",
"wav",
"into",
"a",
"16bit",
"mono",
"16000Hz",
"wav",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/preprocess/feat_extract.py#L175-L186 | train |
persephone-tools/persephone | persephone/preprocess/feat_extract.py | kaldi_pitch | def kaldi_pitch(wav_dir: str, feat_dir: str) -> None:
""" Extract Kaldi pitch features. Assumes 16k mono wav files."""
logger.debug("Make wav.scp and pitch.scp files")
# Make wav.scp and pitch.scp files
prefixes = []
for fn in os.listdir(wav_dir):
prefix, ext = os.path.splitext(fn)
... | python | def kaldi_pitch(wav_dir: str, feat_dir: str) -> None:
""" Extract Kaldi pitch features. Assumes 16k mono wav files."""
logger.debug("Make wav.scp and pitch.scp files")
# Make wav.scp and pitch.scp files
prefixes = []
for fn in os.listdir(wav_dir):
prefix, ext = os.path.splitext(fn)
... | [
"def",
"kaldi_pitch",
"(",
"wav_dir",
":",
"str",
",",
"feat_dir",
":",
"str",
")",
"->",
"None",
":",
"logger",
".",
"debug",
"(",
"\"Make wav.scp and pitch.scp files\"",
")",
"# Make wav.scp and pitch.scp files",
"prefixes",
"=",
"[",
"]",
"for",
"fn",
"in",
... | Extract Kaldi pitch features. Assumes 16k mono wav files. | [
"Extract",
"Kaldi",
"pitch",
"features",
".",
"Assumes",
"16k",
"mono",
"wav",
"files",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/preprocess/feat_extract.py#L188-L230 | train |
persephone-tools/persephone | persephone/experiment.py | get_exp_dir_num | def get_exp_dir_num(parent_dir: str) -> int:
""" Gets the number of the current experiment directory."""
return max([int(fn.split(".")[0])
for fn in os.listdir(parent_dir) if fn.split(".")[0].isdigit()]
+ [-1]) | python | def get_exp_dir_num(parent_dir: str) -> int:
""" Gets the number of the current experiment directory."""
return max([int(fn.split(".")[0])
for fn in os.listdir(parent_dir) if fn.split(".")[0].isdigit()]
+ [-1]) | [
"def",
"get_exp_dir_num",
"(",
"parent_dir",
":",
"str",
")",
"->",
"int",
":",
"return",
"max",
"(",
"[",
"int",
"(",
"fn",
".",
"split",
"(",
"\".\"",
")",
"[",
"0",
"]",
")",
"for",
"fn",
"in",
"os",
".",
"listdir",
"(",
"parent_dir",
")",
"if... | Gets the number of the current experiment directory. | [
"Gets",
"the",
"number",
"of",
"the",
"current",
"experiment",
"directory",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/experiment.py#L18-L22 | train |
persephone-tools/persephone | persephone/experiment.py | transcribe | def transcribe(model_path, corpus):
""" Applies a trained model to untranscribed data in a Corpus. """
exp_dir = prep_exp_dir()
model = get_simple_model(exp_dir, corpus)
model.transcribe(model_path) | python | def transcribe(model_path, corpus):
""" Applies a trained model to untranscribed data in a Corpus. """
exp_dir = prep_exp_dir()
model = get_simple_model(exp_dir, corpus)
model.transcribe(model_path) | [
"def",
"transcribe",
"(",
"model_path",
",",
"corpus",
")",
":",
"exp_dir",
"=",
"prep_exp_dir",
"(",
")",
"model",
"=",
"get_simple_model",
"(",
"exp_dir",
",",
"corpus",
")",
"model",
".",
"transcribe",
"(",
"model_path",
")"
] | Applies a trained model to untranscribed data in a Corpus. | [
"Applies",
"a",
"trained",
"model",
"to",
"untranscribed",
"data",
"in",
"a",
"Corpus",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/experiment.py#L106-L111 | train |
persephone-tools/persephone | persephone/preprocess/wav.py | trim_wav_ms | def trim_wav_ms(in_path: Path, out_path: Path,
start_time: int, end_time: int) -> None:
""" Extracts part of a WAV File.
First attempts to call sox. If sox is unavailable, it backs off to
pydub+ffmpeg.
Args:
in_path: A path to the source file to extract a portion of
out... | python | def trim_wav_ms(in_path: Path, out_path: Path,
start_time: int, end_time: int) -> None:
""" Extracts part of a WAV File.
First attempts to call sox. If sox is unavailable, it backs off to
pydub+ffmpeg.
Args:
in_path: A path to the source file to extract a portion of
out... | [
"def",
"trim_wav_ms",
"(",
"in_path",
":",
"Path",
",",
"out_path",
":",
"Path",
",",
"start_time",
":",
"int",
",",
"end_time",
":",
"int",
")",
"->",
"None",
":",
"try",
":",
"trim_wav_sox",
"(",
"in_path",
",",
"out_path",
",",
"start_time",
",",
"e... | Extracts part of a WAV File.
First attempts to call sox. If sox is unavailable, it backs off to
pydub+ffmpeg.
Args:
in_path: A path to the source file to extract a portion of
out_path: A path describing the to-be-created WAV file.
start_time: The point in the source WAV file at whi... | [
"Extracts",
"part",
"of",
"a",
"WAV",
"File",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/preprocess/wav.py#L18-L43 | train |
persephone-tools/persephone | persephone/preprocess/wav.py | trim_wav_pydub | def trim_wav_pydub(in_path: Path, out_path: Path,
start_time: int, end_time: int) -> None:
""" Crops the wav file. """
logger.info(
"Using pydub/ffmpeg to create {} from {}".format(out_path, in_path) +
" using a start_time of {} and an end_time of {}".format(start_time,
... | python | def trim_wav_pydub(in_path: Path, out_path: Path,
start_time: int, end_time: int) -> None:
""" Crops the wav file. """
logger.info(
"Using pydub/ffmpeg to create {} from {}".format(out_path, in_path) +
" using a start_time of {} and an end_time of {}".format(start_time,
... | [
"def",
"trim_wav_pydub",
"(",
"in_path",
":",
"Path",
",",
"out_path",
":",
"Path",
",",
"start_time",
":",
"int",
",",
"end_time",
":",
"int",
")",
"->",
"None",
":",
"logger",
".",
"info",
"(",
"\"Using pydub/ffmpeg to create {} from {}\"",
".",
"format",
... | Crops the wav file. | [
"Crops",
"the",
"wav",
"file",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/preprocess/wav.py#L45-L70 | train |
persephone-tools/persephone | persephone/preprocess/wav.py | trim_wav_sox | def trim_wav_sox(in_path: Path, out_path: Path,
start_time: int, end_time: int) -> None:
""" Crops the wav file at in_fn so that the audio between start_time and
end_time is output to out_fn. Measured in milliseconds.
"""
if out_path.is_file():
logger.info("Output path %s alrea... | python | def trim_wav_sox(in_path: Path, out_path: Path,
start_time: int, end_time: int) -> None:
""" Crops the wav file at in_fn so that the audio between start_time and
end_time is output to out_fn. Measured in milliseconds.
"""
if out_path.is_file():
logger.info("Output path %s alrea... | [
"def",
"trim_wav_sox",
"(",
"in_path",
":",
"Path",
",",
"out_path",
":",
"Path",
",",
"start_time",
":",
"int",
",",
"end_time",
":",
"int",
")",
"->",
"None",
":",
"if",
"out_path",
".",
"is_file",
"(",
")",
":",
"logger",
".",
"info",
"(",
"\"Outp... | Crops the wav file at in_fn so that the audio between start_time and
end_time is output to out_fn. Measured in milliseconds. | [
"Crops",
"the",
"wav",
"file",
"at",
"in_fn",
"so",
"that",
"the",
"audio",
"between",
"start_time",
"and",
"end_time",
"is",
"output",
"to",
"out_fn",
".",
"Measured",
"in",
"milliseconds",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/preprocess/wav.py#L72-L88 | train |
persephone-tools/persephone | persephone/preprocess/wav.py | extract_wavs | def extract_wavs(utterances: List[Utterance], tgt_dir: Path,
lazy: bool) -> None:
""" Extracts WAVs from the media files associated with a list of Utterance
objects and stores it in a target directory.
Args:
utterances: A list of Utterance objects, which include information
... | python | def extract_wavs(utterances: List[Utterance], tgt_dir: Path,
lazy: bool) -> None:
""" Extracts WAVs from the media files associated with a list of Utterance
objects and stores it in a target directory.
Args:
utterances: A list of Utterance objects, which include information
... | [
"def",
"extract_wavs",
"(",
"utterances",
":",
"List",
"[",
"Utterance",
"]",
",",
"tgt_dir",
":",
"Path",
",",
"lazy",
":",
"bool",
")",
"->",
"None",
":",
"tgt_dir",
".",
"mkdir",
"(",
"parents",
"=",
"True",
",",
"exist_ok",
"=",
"True",
")",
"for... | Extracts WAVs from the media files associated with a list of Utterance
objects and stores it in a target directory.
Args:
utterances: A list of Utterance objects, which include information
about the source media file, and the offset of the utterance in the
media_file.
tg... | [
"Extracts",
"WAVs",
"from",
"the",
"media",
"files",
"associated",
"with",
"a",
"list",
"of",
"Utterance",
"objects",
"and",
"stores",
"it",
"in",
"a",
"target",
"directory",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/preprocess/wav.py#L90-L114 | train |
persephone-tools/persephone | persephone/results.py | filter_labels | def filter_labels(sent: Sequence[str], labels: Set[str] = None) -> List[str]:
""" Returns only the tokens present in the sentence that are in labels."""
if labels:
return [tok for tok in sent if tok in labels]
return list(sent) | python | def filter_labels(sent: Sequence[str], labels: Set[str] = None) -> List[str]:
""" Returns only the tokens present in the sentence that are in labels."""
if labels:
return [tok for tok in sent if tok in labels]
return list(sent) | [
"def",
"filter_labels",
"(",
"sent",
":",
"Sequence",
"[",
"str",
"]",
",",
"labels",
":",
"Set",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"List",
"[",
"str",
"]",
":",
"if",
"labels",
":",
"return",
"[",
"tok",
"for",
"tok",
"in",
"sent",
"if",
... | Returns only the tokens present in the sentence that are in labels. | [
"Returns",
"only",
"the",
"tokens",
"present",
"in",
"the",
"sentence",
"that",
"are",
"in",
"labels",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/results.py#L11-L16 | train |
persephone-tools/persephone | persephone/results.py | filtered_error_rate | def filtered_error_rate(hyps_path: Union[str, Path], refs_path: Union[str, Path], labels: Set[str]) -> float:
""" Returns the error rate of hypotheses in hyps_path against references in refs_path after filtering only for labels in labels.
"""
if isinstance(hyps_path, Path):
hyps_path = str(hyps_path... | python | def filtered_error_rate(hyps_path: Union[str, Path], refs_path: Union[str, Path], labels: Set[str]) -> float:
""" Returns the error rate of hypotheses in hyps_path against references in refs_path after filtering only for labels in labels.
"""
if isinstance(hyps_path, Path):
hyps_path = str(hyps_path... | [
"def",
"filtered_error_rate",
"(",
"hyps_path",
":",
"Union",
"[",
"str",
",",
"Path",
"]",
",",
"refs_path",
":",
"Union",
"[",
"str",
",",
"Path",
"]",
",",
"labels",
":",
"Set",
"[",
"str",
"]",
")",
"->",
"float",
":",
"if",
"isinstance",
"(",
... | Returns the error rate of hypotheses in hyps_path against references in refs_path after filtering only for labels in labels. | [
"Returns",
"the",
"error",
"rate",
"of",
"hypotheses",
"in",
"hyps_path",
"against",
"references",
"in",
"refs_path",
"after",
"filtering",
"only",
"for",
"labels",
"in",
"labels",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/results.py#L18-L42 | train |
persephone-tools/persephone | persephone/results.py | fmt_latex_output | def fmt_latex_output(hyps: Sequence[Sequence[str]],
refs: Sequence[Sequence[str]],
prefixes: Sequence[str],
out_fn: Path,
) -> None:
""" Output the hypotheses and references to a LaTeX source file for
pretty printing.
"""
... | python | def fmt_latex_output(hyps: Sequence[Sequence[str]],
refs: Sequence[Sequence[str]],
prefixes: Sequence[str],
out_fn: Path,
) -> None:
""" Output the hypotheses and references to a LaTeX source file for
pretty printing.
"""
... | [
"def",
"fmt_latex_output",
"(",
"hyps",
":",
"Sequence",
"[",
"Sequence",
"[",
"str",
"]",
"]",
",",
"refs",
":",
"Sequence",
"[",
"Sequence",
"[",
"str",
"]",
"]",
",",
"prefixes",
":",
"Sequence",
"[",
"str",
"]",
",",
"out_fn",
":",
"Path",
",",
... | Output the hypotheses and references to a LaTeX source file for
pretty printing. | [
"Output",
"the",
"hypotheses",
"and",
"references",
"to",
"a",
"LaTeX",
"source",
"file",
"for",
"pretty",
"printing",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/results.py#L57-L96 | train |
persephone-tools/persephone | persephone/results.py | fmt_confusion_matrix | def fmt_confusion_matrix(hyps: Sequence[Sequence[str]],
refs: Sequence[Sequence[str]],
label_set: Set[str] = None,
max_width: int = 25) -> str:
""" Formats a confusion matrix over substitutions, ignoring insertions
and deletions. """
... | python | def fmt_confusion_matrix(hyps: Sequence[Sequence[str]],
refs: Sequence[Sequence[str]],
label_set: Set[str] = None,
max_width: int = 25) -> str:
""" Formats a confusion matrix over substitutions, ignoring insertions
and deletions. """
... | [
"def",
"fmt_confusion_matrix",
"(",
"hyps",
":",
"Sequence",
"[",
"Sequence",
"[",
"str",
"]",
"]",
",",
"refs",
":",
"Sequence",
"[",
"Sequence",
"[",
"str",
"]",
"]",
",",
"label_set",
":",
"Set",
"[",
"str",
"]",
"=",
"None",
",",
"max_width",
":"... | Formats a confusion matrix over substitutions, ignoring insertions
and deletions. | [
"Formats",
"a",
"confusion",
"matrix",
"over",
"substitutions",
"ignoring",
"insertions",
"and",
"deletions",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/results.py#L132-L167 | train |
persephone-tools/persephone | persephone/results.py | fmt_latex_untranscribed | def fmt_latex_untranscribed(hyps: Sequence[Sequence[str]],
prefixes: Sequence[str],
out_fn: Path) -> None:
""" Formats automatic hypotheses that have not previously been
transcribed in LaTeX. """
hyps_prefixes = list(zip(hyps, prefixes))
def utter... | python | def fmt_latex_untranscribed(hyps: Sequence[Sequence[str]],
prefixes: Sequence[str],
out_fn: Path) -> None:
""" Formats automatic hypotheses that have not previously been
transcribed in LaTeX. """
hyps_prefixes = list(zip(hyps, prefixes))
def utter... | [
"def",
"fmt_latex_untranscribed",
"(",
"hyps",
":",
"Sequence",
"[",
"Sequence",
"[",
"str",
"]",
"]",
",",
"prefixes",
":",
"Sequence",
"[",
"str",
"]",
",",
"out_fn",
":",
"Path",
")",
"->",
"None",
":",
"hyps_prefixes",
"=",
"list",
"(",
"zip",
"(",... | Formats automatic hypotheses that have not previously been
transcribed in LaTeX. | [
"Formats",
"automatic",
"hypotheses",
"that",
"have",
"not",
"previously",
"been",
"transcribed",
"in",
"LaTeX",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/results.py#L169-L192 | train |
persephone-tools/persephone | persephone/preprocess/labels.py | segment_into_chars | def segment_into_chars(utterance: str) -> str:
""" Segments an utterance into space delimited characters. """
if not isinstance(utterance, str):
raise TypeError("Input type must be a string. Got {}.".format(type(utterance)))
utterance.strip()
utterance = utterance.replace(" ", "")
return "... | python | def segment_into_chars(utterance: str) -> str:
""" Segments an utterance into space delimited characters. """
if not isinstance(utterance, str):
raise TypeError("Input type must be a string. Got {}.".format(type(utterance)))
utterance.strip()
utterance = utterance.replace(" ", "")
return "... | [
"def",
"segment_into_chars",
"(",
"utterance",
":",
"str",
")",
"->",
"str",
":",
"if",
"not",
"isinstance",
"(",
"utterance",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"Input type must be a string. Got {}.\"",
".",
"format",
"(",
"type",
"(",
"uttera... | Segments an utterance into space delimited characters. | [
"Segments",
"an",
"utterance",
"into",
"space",
"delimited",
"characters",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/preprocess/labels.py#L28-L36 | train |
persephone-tools/persephone | persephone/preprocess/labels.py | make_indices_to_labels | def make_indices_to_labels(labels: Set[str]) -> Dict[int, str]:
""" Creates a mapping from indices to labels. """
return {index: label for index, label in
enumerate(["pad"] + sorted(list(labels)))} | python | def make_indices_to_labels(labels: Set[str]) -> Dict[int, str]:
""" Creates a mapping from indices to labels. """
return {index: label for index, label in
enumerate(["pad"] + sorted(list(labels)))} | [
"def",
"make_indices_to_labels",
"(",
"labels",
":",
"Set",
"[",
"str",
"]",
")",
"->",
"Dict",
"[",
"int",
",",
"str",
"]",
":",
"return",
"{",
"index",
":",
"label",
"for",
"index",
",",
"label",
"in",
"enumerate",
"(",
"[",
"\"pad\"",
"]",
"+",
... | Creates a mapping from indices to labels. | [
"Creates",
"a",
"mapping",
"from",
"indices",
"to",
"labels",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/preprocess/labels.py#L81-L85 | train |
persephone-tools/persephone | persephone/datasets/na.py | preprocess_french | def preprocess_french(trans, fr_nlp, remove_brackets_content=True):
""" Takes a list of sentences in french and preprocesses them."""
if remove_brackets_content:
trans = pangloss.remove_content_in_brackets(trans, "[]")
# Not sure why I have to split and rejoin, but that fixes a Spacy token
# er... | python | def preprocess_french(trans, fr_nlp, remove_brackets_content=True):
""" Takes a list of sentences in french and preprocesses them."""
if remove_brackets_content:
trans = pangloss.remove_content_in_brackets(trans, "[]")
# Not sure why I have to split and rejoin, but that fixes a Spacy token
# er... | [
"def",
"preprocess_french",
"(",
"trans",
",",
"fr_nlp",
",",
"remove_brackets_content",
"=",
"True",
")",
":",
"if",
"remove_brackets_content",
":",
"trans",
"=",
"pangloss",
".",
"remove_content_in_brackets",
"(",
"trans",
",",
"\"[]\"",
")",
"# Not sure why I hav... | Takes a list of sentences in french and preprocesses them. | [
"Takes",
"a",
"list",
"of",
"sentences",
"in",
"french",
"and",
"preprocesses",
"them",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/datasets/na.py#L209-L220 | train |
persephone-tools/persephone | persephone/datasets/na.py | trim_wavs | def trim_wavs(org_wav_dir=ORG_WAV_DIR,
tgt_wav_dir=TGT_WAV_DIR,
org_xml_dir=ORG_XML_DIR):
""" Extracts sentence-level transcriptions, translations and wavs from the
Na Pangloss XML and WAV files. But otherwise doesn't preprocess them."""
logging.info("Trimming wavs...")
if ... | python | def trim_wavs(org_wav_dir=ORG_WAV_DIR,
tgt_wav_dir=TGT_WAV_DIR,
org_xml_dir=ORG_XML_DIR):
""" Extracts sentence-level transcriptions, translations and wavs from the
Na Pangloss XML and WAV files. But otherwise doesn't preprocess them."""
logging.info("Trimming wavs...")
if ... | [
"def",
"trim_wavs",
"(",
"org_wav_dir",
"=",
"ORG_WAV_DIR",
",",
"tgt_wav_dir",
"=",
"TGT_WAV_DIR",
",",
"org_xml_dir",
"=",
"ORG_XML_DIR",
")",
":",
"logging",
".",
"info",
"(",
"\"Trimming wavs...\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"("... | Extracts sentence-level transcriptions, translations and wavs from the
Na Pangloss XML and WAV files. But otherwise doesn't preprocess them. | [
"Extracts",
"sentence",
"-",
"level",
"transcriptions",
"translations",
"and",
"wavs",
"from",
"the",
"Na",
"Pangloss",
"XML",
"and",
"WAV",
"files",
".",
"But",
"otherwise",
"doesn",
"t",
"preprocess",
"them",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/datasets/na.py#L222-L265 | train |
persephone-tools/persephone | persephone/datasets/na.py | prepare_labels | def prepare_labels(label_type, org_xml_dir=ORG_XML_DIR, label_dir=LABEL_DIR):
""" Prepare the neural network output targets."""
if not os.path.exists(os.path.join(label_dir, "TEXT")):
os.makedirs(os.path.join(label_dir, "TEXT"))
if not os.path.exists(os.path.join(label_dir, "WORDLIST")):
os... | python | def prepare_labels(label_type, org_xml_dir=ORG_XML_DIR, label_dir=LABEL_DIR):
""" Prepare the neural network output targets."""
if not os.path.exists(os.path.join(label_dir, "TEXT")):
os.makedirs(os.path.join(label_dir, "TEXT"))
if not os.path.exists(os.path.join(label_dir, "WORDLIST")):
os... | [
"def",
"prepare_labels",
"(",
"label_type",
",",
"org_xml_dir",
"=",
"ORG_XML_DIR",
",",
"label_dir",
"=",
"LABEL_DIR",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"label_dir",
",",
"\"TEXT\"",
")",
... | Prepare the neural network output targets. | [
"Prepare",
"the",
"neural",
"network",
"output",
"targets",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/datasets/na.py#L267-L289 | train |
persephone-tools/persephone | persephone/datasets/na.py | prepare_untran | def prepare_untran(feat_type, tgt_dir, untran_dir):
""" Preprocesses untranscribed audio."""
org_dir = str(untran_dir)
wav_dir = os.path.join(str(tgt_dir), "wav", "untranscribed")
feat_dir = os.path.join(str(tgt_dir), "feat", "untranscribed")
if not os.path.isdir(wav_dir):
os.makedirs(wav_di... | python | def prepare_untran(feat_type, tgt_dir, untran_dir):
""" Preprocesses untranscribed audio."""
org_dir = str(untran_dir)
wav_dir = os.path.join(str(tgt_dir), "wav", "untranscribed")
feat_dir = os.path.join(str(tgt_dir), "feat", "untranscribed")
if not os.path.isdir(wav_dir):
os.makedirs(wav_di... | [
"def",
"prepare_untran",
"(",
"feat_type",
",",
"tgt_dir",
",",
"untran_dir",
")",
":",
"org_dir",
"=",
"str",
"(",
"untran_dir",
")",
"wav_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"str",
"(",
"tgt_dir",
")",
",",
"\"wav\"",
",",
"\"untranscribed\... | Preprocesses untranscribed audio. | [
"Preprocesses",
"untranscribed",
"audio",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/datasets/na.py#L292-L337 | train |
persephone-tools/persephone | persephone/datasets/na.py | prepare_feats | def prepare_feats(feat_type, org_wav_dir=ORG_WAV_DIR, feat_dir=FEAT_DIR, tgt_wav_dir=TGT_WAV_DIR,
org_xml_dir=ORG_XML_DIR, label_dir=LABEL_DIR):
""" Prepare the input features."""
if not os.path.isdir(TGT_DIR):
os.makedirs(TGT_DIR)
if not os.path.isdir(FEAT_DIR):
os.maked... | python | def prepare_feats(feat_type, org_wav_dir=ORG_WAV_DIR, feat_dir=FEAT_DIR, tgt_wav_dir=TGT_WAV_DIR,
org_xml_dir=ORG_XML_DIR, label_dir=LABEL_DIR):
""" Prepare the input features."""
if not os.path.isdir(TGT_DIR):
os.makedirs(TGT_DIR)
if not os.path.isdir(FEAT_DIR):
os.maked... | [
"def",
"prepare_feats",
"(",
"feat_type",
",",
"org_wav_dir",
"=",
"ORG_WAV_DIR",
",",
"feat_dir",
"=",
"FEAT_DIR",
",",
"tgt_wav_dir",
"=",
"TGT_WAV_DIR",
",",
"org_xml_dir",
"=",
"ORG_XML_DIR",
",",
"label_dir",
"=",
"LABEL_DIR",
")",
":",
"if",
"not",
"os",... | Prepare the input features. | [
"Prepare",
"the",
"input",
"features",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/datasets/na.py#L340-L402 | train |
persephone-tools/persephone | persephone/datasets/na.py | get_story_prefixes | def get_story_prefixes(label_type, label_dir=LABEL_DIR):
""" Gets the Na text prefixes. """
prefixes = [prefix for prefix in os.listdir(os.path.join(label_dir, "TEXT"))
if prefix.endswith(".%s" % label_type)]
prefixes = [os.path.splitext(os.path.join("TEXT", prefix))[0]
for p... | python | def get_story_prefixes(label_type, label_dir=LABEL_DIR):
""" Gets the Na text prefixes. """
prefixes = [prefix for prefix in os.listdir(os.path.join(label_dir, "TEXT"))
if prefix.endswith(".%s" % label_type)]
prefixes = [os.path.splitext(os.path.join("TEXT", prefix))[0]
for p... | [
"def",
"get_story_prefixes",
"(",
"label_type",
",",
"label_dir",
"=",
"LABEL_DIR",
")",
":",
"prefixes",
"=",
"[",
"prefix",
"for",
"prefix",
"in",
"os",
".",
"listdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"label_dir",
",",
"\"TEXT\"",
")",
")",
... | Gets the Na text prefixes. | [
"Gets",
"the",
"Na",
"text",
"prefixes",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/datasets/na.py#L404-L410 | train |
persephone-tools/persephone | persephone/datasets/na.py | get_stories | def get_stories(label_type):
""" Returns a list of the stories in the Na corpus. """
prefixes = get_story_prefixes(label_type)
texts = list(set([prefix.split(".")[0].split("/")[1] for prefix in prefixes]))
return texts | python | def get_stories(label_type):
""" Returns a list of the stories in the Na corpus. """
prefixes = get_story_prefixes(label_type)
texts = list(set([prefix.split(".")[0].split("/")[1] for prefix in prefixes]))
return texts | [
"def",
"get_stories",
"(",
"label_type",
")",
":",
"prefixes",
"=",
"get_story_prefixes",
"(",
"label_type",
")",
"texts",
"=",
"list",
"(",
"set",
"(",
"[",
"prefix",
".",
"split",
"(",
"\".\"",
")",
"[",
"0",
"]",
".",
"split",
"(",
"\"/\"",
")",
"... | Returns a list of the stories in the Na corpus. | [
"Returns",
"a",
"list",
"of",
"the",
"stories",
"in",
"the",
"Na",
"corpus",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/datasets/na.py#L456-L461 | train |
persephone-tools/persephone | persephone/datasets/na.py | Corpus.make_data_splits | def make_data_splits(self, max_samples, valid_story=None, test_story=None):
"""Split data into train, valid and test groups"""
# TODO Make this also work with wordlists.
if valid_story or test_story:
if not (valid_story and test_story):
raise PersephoneException(
... | python | def make_data_splits(self, max_samples, valid_story=None, test_story=None):
"""Split data into train, valid and test groups"""
# TODO Make this also work with wordlists.
if valid_story or test_story:
if not (valid_story and test_story):
raise PersephoneException(
... | [
"def",
"make_data_splits",
"(",
"self",
",",
"max_samples",
",",
"valid_story",
"=",
"None",
",",
"test_story",
"=",
"None",
")",
":",
"# TODO Make this also work with wordlists.",
"if",
"valid_story",
"or",
"test_story",
":",
"if",
"not",
"(",
"valid_story",
"and... | Split data into train, valid and test groups | [
"Split",
"data",
"into",
"train",
"valid",
"and",
"test",
"groups"
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/datasets/na.py#L537-L558 | train |
persephone-tools/persephone | persephone/datasets/na.py | Corpus.output_story_prefixes | def output_story_prefixes(self):
""" Writes the set of prefixes to a file this is useful for pretty
printing in results.latex_output. """
if not self.test_story:
raise NotImplementedError(
"I want to write the prefixes to a file"
"called <test_story>_... | python | def output_story_prefixes(self):
""" Writes the set of prefixes to a file this is useful for pretty
printing in results.latex_output. """
if not self.test_story:
raise NotImplementedError(
"I want to write the prefixes to a file"
"called <test_story>_... | [
"def",
"output_story_prefixes",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"test_story",
":",
"raise",
"NotImplementedError",
"(",
"\"I want to write the prefixes to a file\"",
"\"called <test_story>_prefixes.txt, but there's no test_story.\"",
")",
"fn",
"=",
"os",
"... | Writes the set of prefixes to a file this is useful for pretty
printing in results.latex_output. | [
"Writes",
"the",
"set",
"of",
"prefixes",
"to",
"a",
"file",
"this",
"is",
"useful",
"for",
"pretty",
"printing",
"in",
"results",
".",
"latex_output",
"."
] | f94c63e4d5fe719fb1deba449b177bb299d225fb | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/datasets/na.py#L560-L572 | train |
KxSystems/pyq | setup.py | add_data_file | def add_data_file(data_files, target, source):
"""Add an entry to data_files"""
for t, f in data_files:
if t == target:
break
else:
data_files.append((target, []))
f = data_files[-1][1]
if source not in f:
f.append(source) | python | def add_data_file(data_files, target, source):
"""Add an entry to data_files"""
for t, f in data_files:
if t == target:
break
else:
data_files.append((target, []))
f = data_files[-1][1]
if source not in f:
f.append(source) | [
"def",
"add_data_file",
"(",
"data_files",
",",
"target",
",",
"source",
")",
":",
"for",
"t",
",",
"f",
"in",
"data_files",
":",
"if",
"t",
"==",
"target",
":",
"break",
"else",
":",
"data_files",
".",
"append",
"(",
"(",
"target",
",",
"[",
"]",
... | Add an entry to data_files | [
"Add",
"an",
"entry",
"to",
"data_files"
] | ad7b807abde94615a7344aaa930bb01fb1552cc5 | https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/setup.py#L145-L154 | train |
KxSystems/pyq | setup.py | get_q_home | def get_q_home(env):
"""Derive q home from the environment"""
q_home = env.get('QHOME')
if q_home:
return q_home
for v in ['VIRTUAL_ENV', 'HOME']:
prefix = env.get(v)
if prefix:
q_home = os.path.join(prefix, 'q')
if os.path.isdir(q_home):
r... | python | def get_q_home(env):
"""Derive q home from the environment"""
q_home = env.get('QHOME')
if q_home:
return q_home
for v in ['VIRTUAL_ENV', 'HOME']:
prefix = env.get(v)
if prefix:
q_home = os.path.join(prefix, 'q')
if os.path.isdir(q_home):
r... | [
"def",
"get_q_home",
"(",
"env",
")",
":",
"q_home",
"=",
"env",
".",
"get",
"(",
"'QHOME'",
")",
"if",
"q_home",
":",
"return",
"q_home",
"for",
"v",
"in",
"[",
"'VIRTUAL_ENV'",
",",
"'HOME'",
"]",
":",
"prefix",
"=",
"env",
".",
"get",
"(",
"v",
... | Derive q home from the environment | [
"Derive",
"q",
"home",
"from",
"the",
"environment"
] | ad7b807abde94615a7344aaa930bb01fb1552cc5 | https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/setup.py#L185-L200 | train |
KxSystems/pyq | setup.py | get_q_version | def get_q_version(q_home):
"""Return version of q installed at q_home"""
with open(os.path.join(q_home, 'q.k')) as f:
for line in f:
if line.startswith('k:'):
return line[2:5]
return '2.2' | python | def get_q_version(q_home):
"""Return version of q installed at q_home"""
with open(os.path.join(q_home, 'q.k')) as f:
for line in f:
if line.startswith('k:'):
return line[2:5]
return '2.2' | [
"def",
"get_q_version",
"(",
"q_home",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"q_home",
",",
"'q.k'",
")",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"if",
"line",
".",
"startswith",
"(",
"'k:'",
")",
":",
... | Return version of q installed at q_home | [
"Return",
"version",
"of",
"q",
"installed",
"at",
"q_home"
] | ad7b807abde94615a7344aaa930bb01fb1552cc5 | https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/setup.py#L230-L236 | train |
KxSystems/pyq | src/pyq/cmd.py | Cmd.precmd | def precmd(self, line):
"""Support for help"""
if line.startswith('help'):
if not q("`help in key`.q"):
try:
q("\\l help.q")
except kerr:
return '-1"no help available - install help.q"'
if line == 'help':
... | python | def precmd(self, line):
"""Support for help"""
if line.startswith('help'):
if not q("`help in key`.q"):
try:
q("\\l help.q")
except kerr:
return '-1"no help available - install help.q"'
if line == 'help':
... | [
"def",
"precmd",
"(",
"self",
",",
"line",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"'help'",
")",
":",
"if",
"not",
"q",
"(",
"\"`help in key`.q\"",
")",
":",
"try",
":",
"q",
"(",
"\"\\\\l help.q\"",
")",
"except",
"kerr",
":",
"return",
"'-... | Support for help | [
"Support",
"for",
"help"
] | ad7b807abde94615a7344aaa930bb01fb1552cc5 | https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/src/pyq/cmd.py#L35-L45 | train |
KxSystems/pyq | src/pyq/cmd.py | Cmd.onecmd | def onecmd(self, line):
"""Interpret the line"""
if line == '\\':
return True
elif line == 'EOF':
print('\r', end='')
return True
else:
try:
v = q(line)
except kerr as e:
print("'%s" % e.args[0])
... | python | def onecmd(self, line):
"""Interpret the line"""
if line == '\\':
return True
elif line == 'EOF':
print('\r', end='')
return True
else:
try:
v = q(line)
except kerr as e:
print("'%s" % e.args[0])
... | [
"def",
"onecmd",
"(",
"self",
",",
"line",
")",
":",
"if",
"line",
"==",
"'\\\\'",
":",
"return",
"True",
"elif",
"line",
"==",
"'EOF'",
":",
"print",
"(",
"'\\r'",
",",
"end",
"=",
"''",
")",
"return",
"True",
"else",
":",
"try",
":",
"v",
"=",
... | Interpret the line | [
"Interpret",
"the",
"line"
] | ad7b807abde94615a7344aaa930bb01fb1552cc5 | https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/src/pyq/cmd.py#L47-L62 | train |
KxSystems/pyq | src/pyq/_pt_run.py | run | def run(q_prompt=False):
"""Run a prompt-toolkit based REPL"""
lines, columns = console_size()
q(r'\c %d %d' % (lines, columns))
if len(sys.argv) > 1:
try:
q(r'\l %s' % sys.argv[1])
except kerr as e:
print(e)
raise SystemExit(1)
else:
... | python | def run(q_prompt=False):
"""Run a prompt-toolkit based REPL"""
lines, columns = console_size()
q(r'\c %d %d' % (lines, columns))
if len(sys.argv) > 1:
try:
q(r'\l %s' % sys.argv[1])
except kerr as e:
print(e)
raise SystemExit(1)
else:
... | [
"def",
"run",
"(",
"q_prompt",
"=",
"False",
")",
":",
"lines",
",",
"columns",
"=",
"console_size",
"(",
")",
"q",
"(",
"r'\\c %d %d'",
"%",
"(",
"lines",
",",
"columns",
")",
")",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
">",
"1",
":",
"try",... | Run a prompt-toolkit based REPL | [
"Run",
"a",
"prompt",
"-",
"toolkit",
"based",
"REPL"
] | ad7b807abde94615a7344aaa930bb01fb1552cc5 | https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/src/pyq/_pt_run.py#L32-L46 | train |
KxSystems/pyq | src/pyq/_n.py | get_unit | def get_unit(a):
"""Extract the time unit from array's dtype"""
typestr = a.dtype.str
i = typestr.find('[')
if i == -1:
raise TypeError("Expected a datetime64 array, not %s", a.dtype)
return typestr[i + 1: -1] | python | def get_unit(a):
"""Extract the time unit from array's dtype"""
typestr = a.dtype.str
i = typestr.find('[')
if i == -1:
raise TypeError("Expected a datetime64 array, not %s", a.dtype)
return typestr[i + 1: -1] | [
"def",
"get_unit",
"(",
"a",
")",
":",
"typestr",
"=",
"a",
".",
"dtype",
".",
"str",
"i",
"=",
"typestr",
".",
"find",
"(",
"'['",
")",
"if",
"i",
"==",
"-",
"1",
":",
"raise",
"TypeError",
"(",
"\"Expected a datetime64 array, not %s\"",
",",
"a",
"... | Extract the time unit from array's dtype | [
"Extract",
"the",
"time",
"unit",
"from",
"array",
"s",
"dtype"
] | ad7b807abde94615a7344aaa930bb01fb1552cc5 | https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/src/pyq/_n.py#L50-L56 | train |
KxSystems/pyq | src/pyq/_n.py | k2a | def k2a(a, x):
"""Rescale data from a K object x to array a.
"""
func, scale = None, 1
t = abs(x._t)
# timestamp (12), month (13), date (14) or datetime (15)
if 12 <= t <= 15:
unit = get_unit(a)
attr, shift, func, scale = _UNIT[unit]
a[:] = getattr(x, attr).data
... | python | def k2a(a, x):
"""Rescale data from a K object x to array a.
"""
func, scale = None, 1
t = abs(x._t)
# timestamp (12), month (13), date (14) or datetime (15)
if 12 <= t <= 15:
unit = get_unit(a)
attr, shift, func, scale = _UNIT[unit]
a[:] = getattr(x, attr).data
... | [
"def",
"k2a",
"(",
"a",
",",
"x",
")",
":",
"func",
",",
"scale",
"=",
"None",
",",
"1",
"t",
"=",
"abs",
"(",
"x",
".",
"_t",
")",
"# timestamp (12), month (13), date (14) or datetime (15)",
"if",
"12",
"<=",
"t",
"<=",
"15",
":",
"unit",
"=",
"get_... | Rescale data from a K object x to array a. | [
"Rescale",
"data",
"from",
"a",
"K",
"object",
"x",
"to",
"array",
"a",
"."
] | ad7b807abde94615a7344aaa930bb01fb1552cc5 | https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/src/pyq/_n.py#L118-L145 | train |
KxSystems/pyq | src/pyq/__init__.py | K.show | def show(self, start=0, geometry=None, output=None):
"""pretty-print data to the console
(similar to q.show, but uses python stdout by default)
>>> x = q('([k:`x`y`z]a:1 2 3;b:10 20 30)')
>>> x.show() # doctest: +NORMALIZE_WHITESPACE
k| a b
-| ----
x| 1 10
... | python | def show(self, start=0, geometry=None, output=None):
"""pretty-print data to the console
(similar to q.show, but uses python stdout by default)
>>> x = q('([k:`x`y`z]a:1 2 3;b:10 20 30)')
>>> x.show() # doctest: +NORMALIZE_WHITESPACE
k| a b
-| ----
x| 1 10
... | [
"def",
"show",
"(",
"self",
",",
"start",
"=",
"0",
",",
"geometry",
"=",
"None",
",",
"output",
"=",
"None",
")",
":",
"if",
"output",
"is",
"None",
":",
"output",
"=",
"sys",
".",
"stdout",
"if",
"geometry",
"is",
"None",
":",
"geometry",
"=",
... | pretty-print data to the console
(similar to q.show, but uses python stdout by default)
>>> x = q('([k:`x`y`z]a:1 2 3;b:10 20 30)')
>>> x.show() # doctest: +NORMALIZE_WHITESPACE
k| a b
-| ----
x| 1 10
y| 2 20
z| 3 30
the first optional argument... | [
"pretty",
"-",
"print",
"data",
"to",
"the",
"console"
] | ad7b807abde94615a7344aaa930bb01fb1552cc5 | https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/src/pyq/__init__.py#L377-L435 | train |
KxSystems/pyq | src/pyq/__init__.py | K.select | def select(self, columns=(), by=(), where=(), **kwds):
"""select from self
>>> t = q('([]a:1 2 3; b:10 20 30)')
>>> t.select('a', where='b > 20').show()
a
-
3
"""
return self._seu('select', columns, by, where, kwds) | python | def select(self, columns=(), by=(), where=(), **kwds):
"""select from self
>>> t = q('([]a:1 2 3; b:10 20 30)')
>>> t.select('a', where='b > 20').show()
a
-
3
"""
return self._seu('select', columns, by, where, kwds) | [
"def",
"select",
"(",
"self",
",",
"columns",
"=",
"(",
")",
",",
"by",
"=",
"(",
")",
",",
"where",
"=",
"(",
")",
",",
"*",
"*",
"kwds",
")",
":",
"return",
"self",
".",
"_seu",
"(",
"'select'",
",",
"columns",
",",
"by",
",",
"where",
",",... | select from self
>>> t = q('([]a:1 2 3; b:10 20 30)')
>>> t.select('a', where='b > 20').show()
a
-
3 | [
"select",
"from",
"self"
] | ad7b807abde94615a7344aaa930bb01fb1552cc5 | https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/src/pyq/__init__.py#L465-L474 | train |
KxSystems/pyq | src/pyq/__init__.py | K.exec_ | def exec_(self, columns=(), by=(), where=(), **kwds):
"""exec from self
>>> t = q('([]a:1 2 3; b:10 20 30)')
>>> t.exec_('a', where='b > 10').show()
2 3
"""
return self._seu('exec', columns, by, where, kwds) | python | def exec_(self, columns=(), by=(), where=(), **kwds):
"""exec from self
>>> t = q('([]a:1 2 3; b:10 20 30)')
>>> t.exec_('a', where='b > 10').show()
2 3
"""
return self._seu('exec', columns, by, where, kwds) | [
"def",
"exec_",
"(",
"self",
",",
"columns",
"=",
"(",
")",
",",
"by",
"=",
"(",
")",
",",
"where",
"=",
"(",
")",
",",
"*",
"*",
"kwds",
")",
":",
"return",
"self",
".",
"_seu",
"(",
"'exec'",
",",
"columns",
",",
"by",
",",
"where",
",",
... | exec from self
>>> t = q('([]a:1 2 3; b:10 20 30)')
>>> t.exec_('a', where='b > 10').show()
2 3 | [
"exec",
"from",
"self"
] | ad7b807abde94615a7344aaa930bb01fb1552cc5 | https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/src/pyq/__init__.py#L476-L483 | train |
KxSystems/pyq | src/pyq/__init__.py | K.update | def update(self, columns=(), by=(), where=(), **kwds):
"""update from self
>>> t = q('([]a:1 2 3; b:10 20 30)')
>>> t.update('a*2',
... where='b > 20').show() # doctest: +NORMALIZE_WHITESPACE
a b
----
1 10
2 20
6 30
"""
r... | python | def update(self, columns=(), by=(), where=(), **kwds):
"""update from self
>>> t = q('([]a:1 2 3; b:10 20 30)')
>>> t.update('a*2',
... where='b > 20').show() # doctest: +NORMALIZE_WHITESPACE
a b
----
1 10
2 20
6 30
"""
r... | [
"def",
"update",
"(",
"self",
",",
"columns",
"=",
"(",
")",
",",
"by",
"=",
"(",
")",
",",
"where",
"=",
"(",
")",
",",
"*",
"*",
"kwds",
")",
":",
"return",
"self",
".",
"_seu",
"(",
"'update'",
",",
"columns",
",",
"by",
",",
"where",
",",... | update from self
>>> t = q('([]a:1 2 3; b:10 20 30)')
>>> t.update('a*2',
... where='b > 20').show() # doctest: +NORMALIZE_WHITESPACE
a b
----
1 10
2 20
6 30 | [
"update",
"from",
"self"
] | ad7b807abde94615a7344aaa930bb01fb1552cc5 | https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/src/pyq/__init__.py#L485-L497 | train |
KxSystems/pyq | src/pyq/__init__.py | K.dict | def dict(cls, *args, **kwds):
"""Construct a q dictionary
K.dict() -> new empty q dictionary (q('()!()')
K.dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
K.dict(iterable) -> new dictionary initialized from an iterable
yield... | python | def dict(cls, *args, **kwds):
"""Construct a q dictionary
K.dict() -> new empty q dictionary (q('()!()')
K.dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
K.dict(iterable) -> new dictionary initialized from an iterable
yield... | [
"def",
"dict",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"if",
"args",
":",
"if",
"len",
"(",
"args",
")",
">",
"1",
":",
"raise",
"TypeError",
"(",
"\"Too many positional arguments\"",
")",
"x",
"=",
"args",
"[",
"0",
"]",
"... | Construct a q dictionary
K.dict() -> new empty q dictionary (q('()!()')
K.dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
K.dict(iterable) -> new dictionary initialized from an iterable
yielding (key, value) pairs
K.dict(**k... | [
"Construct",
"a",
"q",
"dictionary"
] | ad7b807abde94615a7344aaa930bb01fb1552cc5 | https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/src/pyq/__init__.py#L558-L595 | train |
KxSystems/pyq | src/pyq/magic.py | logical_lines | def logical_lines(lines):
"""Merge lines into chunks according to q rules"""
if isinstance(lines, string_types):
lines = StringIO(lines)
buf = []
for line in lines:
if buf and not line.startswith(' '):
chunk = ''.join(buf).strip()
if chunk:
yield c... | python | def logical_lines(lines):
"""Merge lines into chunks according to q rules"""
if isinstance(lines, string_types):
lines = StringIO(lines)
buf = []
for line in lines:
if buf and not line.startswith(' '):
chunk = ''.join(buf).strip()
if chunk:
yield c... | [
"def",
"logical_lines",
"(",
"lines",
")",
":",
"if",
"isinstance",
"(",
"lines",
",",
"string_types",
")",
":",
"lines",
"=",
"StringIO",
"(",
"lines",
")",
"buf",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"if",
"buf",
"and",
"not",
"line",
... | Merge lines into chunks according to q rules | [
"Merge",
"lines",
"into",
"chunks",
"according",
"to",
"q",
"rules"
] | ad7b807abde94615a7344aaa930bb01fb1552cc5 | https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/src/pyq/magic.py#L23-L38 | train |
KxSystems/pyq | src/pyq/magic.py | q | def q(line, cell=None, _ns=None):
"""Run q code.
Options:
-l (dir|script) - pre-load database or script
-h host:port - execute on the given host
-o var - send output to a variable named var.
-i var1,..,varN - input variables
-1/-2 - redirect stdout/stderr
"""
if cell ... | python | def q(line, cell=None, _ns=None):
"""Run q code.
Options:
-l (dir|script) - pre-load database or script
-h host:port - execute on the given host
-o var - send output to a variable named var.
-i var1,..,varN - input variables
-1/-2 - redirect stdout/stderr
"""
if cell ... | [
"def",
"q",
"(",
"line",
",",
"cell",
"=",
"None",
",",
"_ns",
"=",
"None",
")",
":",
"if",
"cell",
"is",
"None",
":",
"return",
"pyq",
".",
"q",
"(",
"line",
")",
"if",
"_ns",
"is",
"None",
":",
"_ns",
"=",
"vars",
"(",
"sys",
".",
"modules"... | Run q code.
Options:
-l (dir|script) - pre-load database or script
-h host:port - execute on the given host
-o var - send output to a variable named var.
-i var1,..,varN - input variables
-1/-2 - redirect stdout/stderr | [
"Run",
"q",
"code",
"."
] | ad7b807abde94615a7344aaa930bb01fb1552cc5 | https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/src/pyq/magic.py#L50-L121 | train |
KxSystems/pyq | src/pyq/magic.py | load_ipython_extension | def load_ipython_extension(ipython):
"""Register %q and %%q magics and pretty display for K objects"""
ipython.register_magic_function(q, 'line_cell')
fmr = ipython.display_formatter.formatters['text/plain']
fmr.for_type(pyq.K, _q_formatter) | python | def load_ipython_extension(ipython):
"""Register %q and %%q magics and pretty display for K objects"""
ipython.register_magic_function(q, 'line_cell')
fmr = ipython.display_formatter.formatters['text/plain']
fmr.for_type(pyq.K, _q_formatter) | [
"def",
"load_ipython_extension",
"(",
"ipython",
")",
":",
"ipython",
".",
"register_magic_function",
"(",
"q",
",",
"'line_cell'",
")",
"fmr",
"=",
"ipython",
".",
"display_formatter",
".",
"formatters",
"[",
"'text/plain'",
"]",
"fmr",
".",
"for_type",
"(",
... | Register %q and %%q magics and pretty display for K objects | [
"Register",
"%q",
"and",
"%%q",
"magics",
"and",
"pretty",
"display",
"for",
"K",
"objects"
] | ad7b807abde94615a7344aaa930bb01fb1552cc5 | https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/src/pyq/magic.py#L129-L133 | train |
KxSystems/pyq | src/pyq/ptk.py | get_prompt_tokens | def get_prompt_tokens(_):
"""Return a list of tokens for the prompt"""
namespace = q(r'\d')
if namespace == '.':
namespace = ''
return [(Token.Generic.Prompt, 'q%s)' % namespace)] | python | def get_prompt_tokens(_):
"""Return a list of tokens for the prompt"""
namespace = q(r'\d')
if namespace == '.':
namespace = ''
return [(Token.Generic.Prompt, 'q%s)' % namespace)] | [
"def",
"get_prompt_tokens",
"(",
"_",
")",
":",
"namespace",
"=",
"q",
"(",
"r'\\d'",
")",
"if",
"namespace",
"==",
"'.'",
":",
"namespace",
"=",
"''",
"return",
"[",
"(",
"Token",
".",
"Generic",
".",
"Prompt",
",",
"'q%s)'",
"%",
"namespace",
")",
... | Return a list of tokens for the prompt | [
"Return",
"a",
"list",
"of",
"tokens",
"for",
"the",
"prompt"
] | ad7b807abde94615a7344aaa930bb01fb1552cc5 | https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/src/pyq/ptk.py#L48-L53 | train |
KxSystems/pyq | src/pyq/ptk.py | cmdloop | def cmdloop(self, intro=None):
"""A Cmd.cmdloop implementation"""
style = style_from_pygments(BasicStyle, style_dict)
self.preloop()
stop = None
while not stop:
line = prompt(get_prompt_tokens=get_prompt_tokens, lexer=lexer,
get_bottom_toolbar_tokens=get_bottom_toolbar_... | python | def cmdloop(self, intro=None):
"""A Cmd.cmdloop implementation"""
style = style_from_pygments(BasicStyle, style_dict)
self.preloop()
stop = None
while not stop:
line = prompt(get_prompt_tokens=get_prompt_tokens, lexer=lexer,
get_bottom_toolbar_tokens=get_bottom_toolbar_... | [
"def",
"cmdloop",
"(",
"self",
",",
"intro",
"=",
"None",
")",
":",
"style",
"=",
"style_from_pygments",
"(",
"BasicStyle",
",",
"style_dict",
")",
"self",
".",
"preloop",
"(",
")",
"stop",
"=",
"None",
"while",
"not",
"stop",
":",
"line",
"=",
"prompt... | A Cmd.cmdloop implementation | [
"A",
"Cmd",
".",
"cmdloop",
"implementation"
] | ad7b807abde94615a7344aaa930bb01fb1552cc5 | https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/src/pyq/ptk.py#L90-L107 | train |
mapbox/snuggs | snuggs/__init__.py | eval | def eval(source, kwd_dict=None, **kwds):
"""Evaluate a snuggs expression.
Parameters
----------
source : str
Expression source.
kwd_dict : dict
A dict of items that form the evaluation context. Deprecated.
kwds : dict
A dict of items that form the valuation context.
... | python | def eval(source, kwd_dict=None, **kwds):
"""Evaluate a snuggs expression.
Parameters
----------
source : str
Expression source.
kwd_dict : dict
A dict of items that form the evaluation context. Deprecated.
kwds : dict
A dict of items that form the valuation context.
... | [
"def",
"eval",
"(",
"source",
",",
"kwd_dict",
"=",
"None",
",",
"*",
"*",
"kwds",
")",
":",
"kwd_dict",
"=",
"kwd_dict",
"or",
"kwds",
"with",
"ctx",
"(",
"kwd_dict",
")",
":",
"return",
"handleLine",
"(",
"source",
")"
] | Evaluate a snuggs expression.
Parameters
----------
source : str
Expression source.
kwd_dict : dict
A dict of items that form the evaluation context. Deprecated.
kwds : dict
A dict of items that form the valuation context.
Returns
-------
object | [
"Evaluate",
"a",
"snuggs",
"expression",
"."
] | 7517839178accf78ae9624b7186d03b77f837e02 | https://github.com/mapbox/snuggs/blob/7517839178accf78ae9624b7186d03b77f837e02/snuggs/__init__.py#L208-L227 | train |
josiahcarlson/parse-crontab | crontab/_crontab.py | CronTab._make_matchers | def _make_matchers(self, crontab):
'''
This constructs the full matcher struct.
'''
crontab = _aliases.get(crontab, crontab)
ct = crontab.split()
if len(ct) == 5:
ct.insert(0, '0')
ct.append('*')
elif len(ct) == 6:
ct.insert(0, ... | python | def _make_matchers(self, crontab):
'''
This constructs the full matcher struct.
'''
crontab = _aliases.get(crontab, crontab)
ct = crontab.split()
if len(ct) == 5:
ct.insert(0, '0')
ct.append('*')
elif len(ct) == 6:
ct.insert(0, ... | [
"def",
"_make_matchers",
"(",
"self",
",",
"crontab",
")",
":",
"crontab",
"=",
"_aliases",
".",
"get",
"(",
"crontab",
",",
"crontab",
")",
"ct",
"=",
"crontab",
".",
"split",
"(",
")",
"if",
"len",
"(",
"ct",
")",
"==",
"5",
":",
"ct",
".",
"in... | This constructs the full matcher struct. | [
"This",
"constructs",
"the",
"full",
"matcher",
"struct",
"."
] | b2bd254cf14e8c83e502615851b0d4b62f73ab15 | https://github.com/josiahcarlson/parse-crontab/blob/b2bd254cf14e8c83e502615851b0d4b62f73ab15/crontab/_crontab.py#L361-L377 | train |
josiahcarlson/parse-crontab | crontab/_crontab.py | CronTab.next | def next(self, now=None, increments=_increments, delta=True, default_utc=WARN_CHANGE):
'''
How long to wait in seconds before this crontab entry can next be
executed.
'''
if default_utc is WARN_CHANGE and (isinstance(now, _number_types) or (now and not now.tzinfo) or now is None)... | python | def next(self, now=None, increments=_increments, delta=True, default_utc=WARN_CHANGE):
'''
How long to wait in seconds before this crontab entry can next be
executed.
'''
if default_utc is WARN_CHANGE and (isinstance(now, _number_types) or (now and not now.tzinfo) or now is None)... | [
"def",
"next",
"(",
"self",
",",
"now",
"=",
"None",
",",
"increments",
"=",
"_increments",
",",
"delta",
"=",
"True",
",",
"default_utc",
"=",
"WARN_CHANGE",
")",
":",
"if",
"default_utc",
"is",
"WARN_CHANGE",
"and",
"(",
"isinstance",
"(",
"now",
",",
... | How long to wait in seconds before this crontab entry can next be
executed. | [
"How",
"long",
"to",
"wait",
"in",
"seconds",
"before",
"this",
"crontab",
"entry",
"can",
"next",
"be",
"executed",
"."
] | b2bd254cf14e8c83e502615851b0d4b62f73ab15 | https://github.com/josiahcarlson/parse-crontab/blob/b2bd254cf14e8c83e502615851b0d4b62f73ab15/crontab/_crontab.py#L390-L458 | train |
sanand0/xmljson | xmljson/__init__.py | XMLData._tostring | def _tostring(value):
'''Convert value to XML compatible string'''
if value is True:
value = 'true'
elif value is False:
value = 'false'
elif value is None:
value = ''
return unicode(value) | python | def _tostring(value):
'''Convert value to XML compatible string'''
if value is True:
value = 'true'
elif value is False:
value = 'false'
elif value is None:
value = ''
return unicode(value) | [
"def",
"_tostring",
"(",
"value",
")",
":",
"if",
"value",
"is",
"True",
":",
"value",
"=",
"'true'",
"elif",
"value",
"is",
"False",
":",
"value",
"=",
"'false'",
"elif",
"value",
"is",
"None",
":",
"value",
"=",
"''",
"return",
"unicode",
"(",
"val... | Convert value to XML compatible string | [
"Convert",
"value",
"to",
"XML",
"compatible",
"string"
] | 2ecc2065fe7c87b3d282d362289927f13ce7f8b0 | https://github.com/sanand0/xmljson/blob/2ecc2065fe7c87b3d282d362289927f13ce7f8b0/xmljson/__init__.py#L61-L69 | train |
sanand0/xmljson | xmljson/__init__.py | XMLData._fromstring | def _fromstring(value):
'''Convert XML string value to None, boolean, int or float'''
# NOTE: Is this even possible ?
if value is None:
return None
# FIXME: In XML, booleans are either 0/false or 1/true (lower-case !)
if value.lower() == 'true':
return Tr... | python | def _fromstring(value):
'''Convert XML string value to None, boolean, int or float'''
# NOTE: Is this even possible ?
if value is None:
return None
# FIXME: In XML, booleans are either 0/false or 1/true (lower-case !)
if value.lower() == 'true':
return Tr... | [
"def",
"_fromstring",
"(",
"value",
")",
":",
"# NOTE: Is this even possible ?",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"# FIXME: In XML, booleans are either 0/false or 1/true (lower-case !)",
"if",
"value",
".",
"lower",
"(",
")",
"==",
"'true'",
":",
"r... | Convert XML string value to None, boolean, int or float | [
"Convert",
"XML",
"string",
"value",
"to",
"None",
"boolean",
"int",
"or",
"float"
] | 2ecc2065fe7c87b3d282d362289927f13ce7f8b0 | https://github.com/sanand0/xmljson/blob/2ecc2065fe7c87b3d282d362289927f13ce7f8b0/xmljson/__init__.py#L72-L97 | train |
pysal/esda | esda/join_counts.py | Join_Counts.by_col | def by_col(cls, df, cols, w=None, inplace=False, pvalue='sim', outvals=None, **stat_kws):
"""
Function to compute a Join_Count statistic on a dataframe
Arguments
---------
df : pandas.DataFrame
a pandas dataframe with a geometry column
... | python | def by_col(cls, df, cols, w=None, inplace=False, pvalue='sim', outvals=None, **stat_kws):
"""
Function to compute a Join_Count statistic on a dataframe
Arguments
---------
df : pandas.DataFrame
a pandas dataframe with a geometry column
... | [
"def",
"by_col",
"(",
"cls",
",",
"df",
",",
"cols",
",",
"w",
"=",
"None",
",",
"inplace",
"=",
"False",
",",
"pvalue",
"=",
"'sim'",
",",
"outvals",
"=",
"None",
",",
"*",
"*",
"stat_kws",
")",
":",
"if",
"outvals",
"is",
"None",
":",
"outvals"... | Function to compute a Join_Count statistic on a dataframe
Arguments
---------
df : pandas.DataFrame
a pandas dataframe with a geometry column
cols : string or list of string
name or list of names of columns to use to co... | [
"Function",
"to",
"compute",
"a",
"Join_Count",
"statistic",
"on",
"a",
"dataframe"
] | 2fafc6ec505e153152a86601d3e0fba080610c20 | https://github.com/pysal/esda/blob/2fafc6ec505e153152a86601d3e0fba080610c20/esda/join_counts.py#L171-L214 | train |
pysal/esda | esda/moran.py | Moran_BV_matrix | def Moran_BV_matrix(variables, w, permutations=0, varnames=None):
"""
Bivariate Moran Matrix
Calculates bivariate Moran between all pairs of a set of variables.
Parameters
----------
variables : array or pandas.DataFrame
sequence of variables to be assessed
w ... | python | def Moran_BV_matrix(variables, w, permutations=0, varnames=None):
"""
Bivariate Moran Matrix
Calculates bivariate Moran between all pairs of a set of variables.
Parameters
----------
variables : array or pandas.DataFrame
sequence of variables to be assessed
w ... | [
"def",
"Moran_BV_matrix",
"(",
"variables",
",",
"w",
",",
"permutations",
"=",
"0",
",",
"varnames",
"=",
"None",
")",
":",
"try",
":",
"# check if pandas is installed",
"import",
"pandas",
"if",
"isinstance",
"(",
"variables",
",",
"pandas",
".",
"DataFrame"... | Bivariate Moran Matrix
Calculates bivariate Moran between all pairs of a set of variables.
Parameters
----------
variables : array or pandas.DataFrame
sequence of variables to be assessed
w : W
a spatial weights object
permutations : int
... | [
"Bivariate",
"Moran",
"Matrix"
] | 2fafc6ec505e153152a86601d3e0fba080610c20 | https://github.com/pysal/esda/blob/2fafc6ec505e153152a86601d3e0fba080610c20/esda/moran.py#L464-L537 | train |
pysal/esda | esda/moran.py | _Moran_BV_Matrix_array | def _Moran_BV_Matrix_array(variables, w, permutations=0, varnames=None):
"""
Base calculation for MORAN_BV_Matrix
"""
if varnames is None:
varnames = ['x{}'.format(i) for i in range(k)]
k = len(variables)
rk = list(range(0, k - 1))
results = {}
for i in rk:
for j in rang... | python | def _Moran_BV_Matrix_array(variables, w, permutations=0, varnames=None):
"""
Base calculation for MORAN_BV_Matrix
"""
if varnames is None:
varnames = ['x{}'.format(i) for i in range(k)]
k = len(variables)
rk = list(range(0, k - 1))
results = {}
for i in rk:
for j in rang... | [
"def",
"_Moran_BV_Matrix_array",
"(",
"variables",
",",
"w",
",",
"permutations",
"=",
"0",
",",
"varnames",
"=",
"None",
")",
":",
"if",
"varnames",
"is",
"None",
":",
"varnames",
"=",
"[",
"'x{}'",
".",
"format",
"(",
"i",
")",
"for",
"i",
"in",
"r... | Base calculation for MORAN_BV_Matrix | [
"Base",
"calculation",
"for",
"MORAN_BV_Matrix"
] | 2fafc6ec505e153152a86601d3e0fba080610c20 | https://github.com/pysal/esda/blob/2fafc6ec505e153152a86601d3e0fba080610c20/esda/moran.py#L540-L558 | train |
pysal/esda | esda/moran.py | Moran_BV.by_col | def by_col(cls, df, x, y=None, w=None, inplace=False, pvalue='sim', outvals=None, **stat_kws):
"""
Function to compute a Moran_BV statistic on a dataframe
Arguments
---------
df : pandas.DataFrame
a pandas dataframe with a geometry column
... | python | def by_col(cls, df, x, y=None, w=None, inplace=False, pvalue='sim', outvals=None, **stat_kws):
"""
Function to compute a Moran_BV statistic on a dataframe
Arguments
---------
df : pandas.DataFrame
a pandas dataframe with a geometry column
... | [
"def",
"by_col",
"(",
"cls",
",",
"df",
",",
"x",
",",
"y",
"=",
"None",
",",
"w",
"=",
"None",
",",
"inplace",
"=",
"False",
",",
"pvalue",
"=",
"'sim'",
",",
"outvals",
"=",
"None",
",",
"*",
"*",
"stat_kws",
")",
":",
"return",
"_bivariate_han... | Function to compute a Moran_BV statistic on a dataframe
Arguments
---------
df : pandas.DataFrame
a pandas dataframe with a geometry column
X : list of strings
column name or list of column names to use as X values t... | [
"Function",
"to",
"compute",
"a",
"Moran_BV",
"statistic",
"on",
"a",
"dataframe"
] | 2fafc6ec505e153152a86601d3e0fba080610c20 | https://github.com/pysal/esda/blob/2fafc6ec505e153152a86601d3e0fba080610c20/esda/moran.py#L415-L461 | train |
pysal/esda | esda/moran.py | Moran_Rate.by_col | def by_col(cls, df, events, populations, w=None, inplace=False,
pvalue='sim', outvals=None, swapname='', **stat_kws):
"""
Function to compute a Moran_Rate statistic on a dataframe
Arguments
---------
df : pandas.DataFrame
a pand... | python | def by_col(cls, df, events, populations, w=None, inplace=False,
pvalue='sim', outvals=None, swapname='', **stat_kws):
"""
Function to compute a Moran_Rate statistic on a dataframe
Arguments
---------
df : pandas.DataFrame
a pand... | [
"def",
"by_col",
"(",
"cls",
",",
"df",
",",
"events",
",",
"populations",
",",
"w",
"=",
"None",
",",
"inplace",
"=",
"False",
",",
"pvalue",
"=",
"'sim'",
",",
"outvals",
"=",
"None",
",",
"swapname",
"=",
"''",
",",
"*",
"*",
"stat_kws",
")",
... | Function to compute a Moran_Rate statistic on a dataframe
Arguments
---------
df : pandas.DataFrame
a pandas dataframe with a geometry column
events : string or list of strings
one or more names where events are stored
... | [
"Function",
"to",
"compute",
"a",
"Moran_Rate",
"statistic",
"on",
"a",
"dataframe"
] | 2fafc6ec505e153152a86601d3e0fba080610c20 | https://github.com/pysal/esda/blob/2fafc6ec505e153152a86601d3e0fba080610c20/esda/moran.py#L679-L758 | train |
pysal/esda | esda/smoothing.py | flatten | def flatten(l, unique=True):
"""flatten a list of lists
Parameters
----------
l : list
of lists
unique : boolean
whether or not only unique items are wanted (default=True)
Returns
-------
list
of single items
Examples
----... | python | def flatten(l, unique=True):
"""flatten a list of lists
Parameters
----------
l : list
of lists
unique : boolean
whether or not only unique items are wanted (default=True)
Returns
-------
list
of single items
Examples
----... | [
"def",
"flatten",
"(",
"l",
",",
"unique",
"=",
"True",
")",
":",
"l",
"=",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"x",
"+",
"y",
",",
"l",
")",
"if",
"not",
"unique",
":",
"return",
"list",
"(",
"l",
")",
"return",
"list",
"(",
"set",
... | flatten a list of lists
Parameters
----------
l : list
of lists
unique : boolean
whether or not only unique items are wanted (default=True)
Returns
-------
list
of single items
Examples
--------
Creating a sample list who... | [
"flatten",
"a",
"list",
"of",
"lists"
] | 2fafc6ec505e153152a86601d3e0fba080610c20 | https://github.com/pysal/esda/blob/2fafc6ec505e153152a86601d3e0fba080610c20/esda/smoothing.py#L32-L63 | train |
pysal/esda | esda/smoothing.py | weighted_median | def weighted_median(d, w):
"""A utility function to find a median of d based on w
Parameters
----------
d : array
(n, 1), variable for which median will be found
w : array
(n, 1), variable on which d's median will be decided
Notes
-----
... | python | def weighted_median(d, w):
"""A utility function to find a median of d based on w
Parameters
----------
d : array
(n, 1), variable for which median will be found
w : array
(n, 1), variable on which d's median will be decided
Notes
-----
... | [
"def",
"weighted_median",
"(",
"d",
",",
"w",
")",
":",
"dtype",
"=",
"[",
"(",
"'w'",
",",
"'%s'",
"%",
"w",
".",
"dtype",
")",
",",
"(",
"'v'",
",",
"'%s'",
"%",
"d",
".",
"dtype",
")",
"]",
"d_w",
"=",
"np",
".",
"array",
"(",
"list",
"(... | A utility function to find a median of d based on w
Parameters
----------
d : array
(n, 1), variable for which median will be found
w : array
(n, 1), variable on which d's median will be decided
Notes
-----
d and w are arranged in the sam... | [
"A",
"utility",
"function",
"to",
"find",
"a",
"median",
"of",
"d",
"based",
"on",
"w"
] | 2fafc6ec505e153152a86601d3e0fba080610c20 | https://github.com/pysal/esda/blob/2fafc6ec505e153152a86601d3e0fba080610c20/esda/smoothing.py#L66-L113 | train |
pysal/esda | esda/smoothing.py | sum_by_n | def sum_by_n(d, w, n):
"""A utility function to summarize a data array into n values
after weighting the array with another weight array w
Parameters
----------
d : array
(t, 1), numerical values
w : array
(t, 1), numerical values for weigh... | python | def sum_by_n(d, w, n):
"""A utility function to summarize a data array into n values
after weighting the array with another weight array w
Parameters
----------
d : array
(t, 1), numerical values
w : array
(t, 1), numerical values for weigh... | [
"def",
"sum_by_n",
"(",
"d",
",",
"w",
",",
"n",
")",
":",
"t",
"=",
"len",
"(",
"d",
")",
"h",
"=",
"t",
"//",
"n",
"#must be floor!",
"d",
"=",
"d",
"*",
"w",
"return",
"np",
".",
"array",
"(",
"[",
"sum",
"(",
"d",
"[",
"i",
":",
"i",
... | A utility function to summarize a data array into n values
after weighting the array with another weight array w
Parameters
----------
d : array
(t, 1), numerical values
w : array
(t, 1), numerical values for weighting
n : integer
... | [
"A",
"utility",
"function",
"to",
"summarize",
"a",
"data",
"array",
"into",
"n",
"values",
"after",
"weighting",
"the",
"array",
"with",
"another",
"weight",
"array",
"w"
] | 2fafc6ec505e153152a86601d3e0fba080610c20 | https://github.com/pysal/esda/blob/2fafc6ec505e153152a86601d3e0fba080610c20/esda/smoothing.py#L116-L160 | train |
pysal/esda | esda/smoothing.py | crude_age_standardization | def crude_age_standardization(e, b, n):
"""A utility function to compute rate through crude age standardization
Parameters
----------
e : array
(n*h, 1), event variable measured for each age group across n spatial units
b : array
(n*h, 1), populat... | python | def crude_age_standardization(e, b, n):
"""A utility function to compute rate through crude age standardization
Parameters
----------
e : array
(n*h, 1), event variable measured for each age group across n spatial units
b : array
(n*h, 1), populat... | [
"def",
"crude_age_standardization",
"(",
"e",
",",
"b",
",",
"n",
")",
":",
"r",
"=",
"e",
"*",
"1.0",
"/",
"b",
"b_by_n",
"=",
"sum_by_n",
"(",
"b",
",",
"1.0",
",",
"n",
")",
"age_weight",
"=",
"b",
"*",
"1.0",
"/",
"b_by_n",
".",
"repeat",
"... | A utility function to compute rate through crude age standardization
Parameters
----------
e : array
(n*h, 1), event variable measured for each age group across n spatial units
b : array
(n*h, 1), population at risk variable measured for each age grou... | [
"A",
"utility",
"function",
"to",
"compute",
"rate",
"through",
"crude",
"age",
"standardization"
] | 2fafc6ec505e153152a86601d3e0fba080610c20 | https://github.com/pysal/esda/blob/2fafc6ec505e153152a86601d3e0fba080610c20/esda/smoothing.py#L163-L213 | train |
pysal/esda | esda/smoothing.py | direct_age_standardization | def direct_age_standardization(e, b, s, n, alpha=0.05):
"""A utility function to compute rate through direct age standardization
Parameters
----------
e : array
(n*h, 1), event variable measured for each age group across n spatial units
b : array
... | python | def direct_age_standardization(e, b, s, n, alpha=0.05):
"""A utility function to compute rate through direct age standardization
Parameters
----------
e : array
(n*h, 1), event variable measured for each age group across n spatial units
b : array
... | [
"def",
"direct_age_standardization",
"(",
"e",
",",
"b",
",",
"s",
",",
"n",
",",
"alpha",
"=",
"0.05",
")",
":",
"age_weight",
"=",
"(",
"1.0",
"/",
"b",
")",
"*",
"(",
"s",
"*",
"1.0",
"/",
"sum_by_n",
"(",
"s",
",",
"1.0",
",",
"n",
")",
"... | A utility function to compute rate through direct age standardization
Parameters
----------
e : array
(n*h, 1), event variable measured for each age group across n spatial units
b : array
(n*h, 1), population at risk variable measured for each age gro... | [
"A",
"utility",
"function",
"to",
"compute",
"rate",
"through",
"direct",
"age",
"standardization"
] | 2fafc6ec505e153152a86601d3e0fba080610c20 | https://github.com/pysal/esda/blob/2fafc6ec505e153152a86601d3e0fba080610c20/esda/smoothing.py#L216-L298 | train |
pysal/esda | esda/smoothing.py | indirect_age_standardization | def indirect_age_standardization(e, b, s_e, s_b, n, alpha=0.05):
"""A utility function to compute rate through indirect age standardization
Parameters
----------
e : array
(n*h, 1), event variable measured for each age group across n spatial units
b : array
... | python | def indirect_age_standardization(e, b, s_e, s_b, n, alpha=0.05):
"""A utility function to compute rate through indirect age standardization
Parameters
----------
e : array
(n*h, 1), event variable measured for each age group across n spatial units
b : array
... | [
"def",
"indirect_age_standardization",
"(",
"e",
",",
"b",
",",
"s_e",
",",
"s_b",
",",
"n",
",",
"alpha",
"=",
"0.05",
")",
":",
"smr",
"=",
"standardized_mortality_ratio",
"(",
"e",
",",
"b",
",",
"s_e",
",",
"s_b",
",",
"n",
")",
"s_r_all",
"=",
... | A utility function to compute rate through indirect age standardization
Parameters
----------
e : array
(n*h, 1), event variable measured for each age group across n spatial units
b : array
(n*h, 1), population at risk variable measured for each age g... | [
"A",
"utility",
"function",
"to",
"compute",
"rate",
"through",
"indirect",
"age",
"standardization"
] | 2fafc6ec505e153152a86601d3e0fba080610c20 | https://github.com/pysal/esda/blob/2fafc6ec505e153152a86601d3e0fba080610c20/esda/smoothing.py#L301-L379 | train |
pysal/esda | esda/tabular.py | _univariate_handler | def _univariate_handler(df, cols, stat=None, w=None, inplace=True,
pvalue = 'sim', outvals = None, swapname='', **kwargs):
"""
Compute a univariate descriptive statistic `stat` over columns `cols` in
`df`.
Parameters
----------
df : pandas.DataFrame
... | python | def _univariate_handler(df, cols, stat=None, w=None, inplace=True,
pvalue = 'sim', outvals = None, swapname='', **kwargs):
"""
Compute a univariate descriptive statistic `stat` over columns `cols` in
`df`.
Parameters
----------
df : pandas.DataFrame
... | [
"def",
"_univariate_handler",
"(",
"df",
",",
"cols",
",",
"stat",
"=",
"None",
",",
"w",
"=",
"None",
",",
"inplace",
"=",
"True",
",",
"pvalue",
"=",
"'sim'",
",",
"outvals",
"=",
"None",
",",
"swapname",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
... | Compute a univariate descriptive statistic `stat` over columns `cols` in
`df`.
Parameters
----------
df : pandas.DataFrame
the dataframe containing columns to compute the descriptive
statistics
cols : string or list of strings
on... | [
"Compute",
"a",
"univariate",
"descriptive",
"statistic",
"stat",
"over",
"columns",
"cols",
"in",
"df",
"."
] | 2fafc6ec505e153152a86601d3e0fba080610c20 | https://github.com/pysal/esda/blob/2fafc6ec505e153152a86601d3e0fba080610c20/esda/tabular.py#L10-L98 | train |
pysal/esda | esda/tabular.py | _bivariate_handler | def _bivariate_handler(df, x, y=None, w=None, inplace=True, pvalue='sim',
outvals=None, **kwargs):
"""
Compute a descriptive bivariate statistic over two sets of columns, `x` and
`y`, contained in `df`.
Parameters
----------
df : pandas.DataFrame
... | python | def _bivariate_handler(df, x, y=None, w=None, inplace=True, pvalue='sim',
outvals=None, **kwargs):
"""
Compute a descriptive bivariate statistic over two sets of columns, `x` and
`y`, contained in `df`.
Parameters
----------
df : pandas.DataFrame
... | [
"def",
"_bivariate_handler",
"(",
"df",
",",
"x",
",",
"y",
"=",
"None",
",",
"w",
"=",
"None",
",",
"inplace",
"=",
"True",
",",
"pvalue",
"=",
"'sim'",
",",
"outvals",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"real_swapname",
"=",
"kwargs"... | Compute a descriptive bivariate statistic over two sets of columns, `x` and
`y`, contained in `df`.
Parameters
----------
df : pandas.DataFrame
dataframe in which columns `x` and `y` are contained
x : string or list of strings
one or more colum... | [
"Compute",
"a",
"descriptive",
"bivariate",
"statistic",
"over",
"two",
"sets",
"of",
"columns",
"x",
"and",
"y",
"contained",
"in",
"df",
"."
] | 2fafc6ec505e153152a86601d3e0fba080610c20 | https://github.com/pysal/esda/blob/2fafc6ec505e153152a86601d3e0fba080610c20/esda/tabular.py#L100-L154 | train |
pysal/esda | esda/tabular.py | _swap_ending | def _swap_ending(s, ending, delim='_'):
"""
Replace the ending of a string, delimited into an arbitrary
number of chunks by `delim`, with the ending provided
Parameters
----------
s : string
string to replace endings
ending : string
string used to ... | python | def _swap_ending(s, ending, delim='_'):
"""
Replace the ending of a string, delimited into an arbitrary
number of chunks by `delim`, with the ending provided
Parameters
----------
s : string
string to replace endings
ending : string
string used to ... | [
"def",
"_swap_ending",
"(",
"s",
",",
"ending",
",",
"delim",
"=",
"'_'",
")",
":",
"parts",
"=",
"[",
"x",
"for",
"x",
"in",
"s",
".",
"split",
"(",
"delim",
")",
"[",
":",
"-",
"1",
"]",
"if",
"x",
"!=",
"''",
"]",
"parts",
".",
"append",
... | Replace the ending of a string, delimited into an arbitrary
number of chunks by `delim`, with the ending provided
Parameters
----------
s : string
string to replace endings
ending : string
string used to replace ending of `s`
delim : string
... | [
"Replace",
"the",
"ending",
"of",
"a",
"string",
"delimited",
"into",
"an",
"arbitrary",
"number",
"of",
"chunks",
"by",
"delim",
"with",
"the",
"ending",
"provided"
] | 2fafc6ec505e153152a86601d3e0fba080610c20 | https://github.com/pysal/esda/blob/2fafc6ec505e153152a86601d3e0fba080610c20/esda/tabular.py#L156-L177 | train |
symengine/symengine.py | symengine/compatibility.py | is_sequence | def is_sequence(i, include=None):
"""
Return a boolean indicating whether ``i`` is a sequence in the SymPy
sense. If anything that fails the test below should be included as
being a sequence for your application, set 'include' to that object's
type; multiple types should be passed as a tuple of type... | python | def is_sequence(i, include=None):
"""
Return a boolean indicating whether ``i`` is a sequence in the SymPy
sense. If anything that fails the test below should be included as
being a sequence for your application, set 'include' to that object's
type; multiple types should be passed as a tuple of type... | [
"def",
"is_sequence",
"(",
"i",
",",
"include",
"=",
"None",
")",
":",
"return",
"(",
"hasattr",
"(",
"i",
",",
"'__getitem__'",
")",
"and",
"iterable",
"(",
"i",
")",
"or",
"bool",
"(",
"include",
")",
"and",
"isinstance",
"(",
"i",
",",
"include",
... | Return a boolean indicating whether ``i`` is a sequence in the SymPy
sense. If anything that fails the test below should be included as
being a sequence for your application, set 'include' to that object's
type; multiple types should be passed as a tuple of types.
Note: although generators can generate... | [
"Return",
"a",
"boolean",
"indicating",
"whether",
"i",
"is",
"a",
"sequence",
"in",
"the",
"SymPy",
"sense",
".",
"If",
"anything",
"that",
"fails",
"the",
"test",
"below",
"should",
"be",
"included",
"as",
"being",
"a",
"sequence",
"for",
"your",
"applic... | 1366cf98ceaade339c5dd24ae3381a0e63ea9dad | https://github.com/symengine/symengine.py/blob/1366cf98ceaade339c5dd24ae3381a0e63ea9dad/symengine/compatibility.py#L245-L282 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.