Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function: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." ]
Please provide a description of the function:def num_feats(self): 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 there are multiple...
[ " The number of features per time step in the corpus. " ]
Please provide a description of the function:def prefixes_to_fns(self, prefixes: List[str]) -> Tuple[List[str], List[str]]: # TODO Return pathlib.Paths feat_fns = [str(self.feat_dir / ("%s.%s.npy" % (prefix, self.feat_type))) for prefix in prefixes] label_fns = [str(...
[ " Fetches the file paths to the features files and labels files\n corresponding to the provided list of features" ]
Please provide a description of the function: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.\n\n Outputs a Tuple of size 2, where the first element is a list of paths\n to input features files, one per utterance. The second element is a list\n of paths to the transcriptions.\n " ]
Please provide a description of the function: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." ]
Please provide a description of the function:def review(self) -> None: for prefix in self.determine_prefixes(): print("Utterance: {}".format(prefix)) wav_fn = self.feat_dir / "{}.wav".format(prefix) label_fn = self.label_dir / "{}.{}".format(prefix,self.label_type) ...
[ " Used to play the WAV files and compare with the transcription. " ]
Please provide a description of the function: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.open("wb") as f: pickle.dump(self, f)
[ " Pickles the Corpus object in a file in tgt_dir. " ]
Please provide a description of the function:def is_git_directory_clean(path_to_repo: Path, search_parent_dirs: bool = True, check_untracked: bool = False) -> None: repo = Repo(str(path_to_repo), search_parent_directories=search_parent_dirs) logger.debu...
[ "\n Check that the git working directory is in a clean state\n and raise exceptions if not.\n :path_to_repo: The path of the git repo\n " ]
Please provide a description of the function:def target_list_to_sparse_tensor(target_list): indices = [] vals = [] for t_i, target in enumerate(target_list): for seq_i, val in enumerate(target): indices.append([t_i, seq_i]) vals.append(val) shape = [len(target_list),...
[ " Make tensorflow SparseTensor from list of targets, with each element in\n the list being a list or array with the values of the target sequence\n (e.g., the integer values of a character map for an ASR target string) See\n https://github.com/tensorflow/tensorflow/blob/master/tensorflow/\n contrib/ctc/...
Please provide a description of the function:def zero_pad(matrix, 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 {}" " to length {}".format(matrix.shape[0], to_length)) ...
[ " Zero pads along the 0th dimension to make sure the utterance array\n x is of length to_length." ]
Please provide a description of the function:def collapse(batch_x, time_major=False): new_batch_x = [] for utterance in batch_x: swapped = np.swapaxes(utterance, 0, 1) concatenated = np.concatenate(swapped, axis=1) new_batch_x.append(concatenated) new_batch_x = np.array(new_bat...
[ " Converts timit into an array of format (batch_size, freq x num_deltas,\n time). Essentially, multiple channels are collapsed to one. " ]
Please provide a description of the function:def load_batch_x(path_batch, flatten = False, time_major = False): utterances = [np.load(str(path)) for path in path_batch] utter_lens = [utterance.shape[0] for utterance in utterances] max_len = max(utter_lens) batch_s...
[ " Loads a batch of input features given a list of paths to numpy\n arrays in that batch." ]
Please provide a description of the function:def batch_per(hyps: Sequence[Sequence[T]], refs: Sequence[Sequence[T]]) -> float: 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] ...
[ " Calculates the phoneme error rate of a batch." ]
Please provide a description of the function:def get_prefixes(dirname: str, extension: str) -> List[str]: prefixes = [] for root, _, filenames in os.walk(dirname): for filename in filenames: if filename.endswith(extension): # Then it's an input feature file and its pref...
[ " Returns a list of prefixes to files in the directory (which might be a whole\n corpus, or a train/valid/test subset. The prefixes include the path leading\n up to it, but only the filename up until the first observed period '.'\n " ]
Please provide a description of the function: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. prefix_lens = get_prefix_lens(Path(feat_dir), prefixes, feat_type) prefixes = [p...
[ " Sorts the files by their length and returns those with less\n than or equal to max_samples length. Returns the filename prefixes of\n those files. The main job of the method is to filter, but the sorting\n may give better efficiency when doing dynamic batching unless it gets\n shuffled downstream.\n ...
Please provide a description of the function:def wav_length(fn: str) -> float: 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 length_lin...
[ " Returns the length of the WAV file in seconds." ]
Please provide a description of the function:def make_batches(paths: Sequence[Path], batch_size: int) -> List[Sequence[Path]]: return [paths[i:i+batch_size] for i in range(0, len(paths), batch_size)]
[ " Group utterances into batches for decoding. " ]
Please provide a description of the function: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(): subprocess.run(["git", "clone", ENGLISH_WORDS_URL, str(en...
[ " Fetches a repository containing English words. " ]
Please provide a description of the function: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 = set([word.strip().lower() for word in raw_words]) NA_WORDS_IN_EN_DICT = set(["kore", "nani", "karri", "imi", ...
[ "\n Returns a list of English words which can be used to filter out\n code-switched sentences.\n " ]
Please provide a description of the function: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 in tier_names: print("\t", tier) try: for a...
[ "\n A function to explore the tiers of ELAN files.\n " ]
Please provide a description of the function:def segment_str(text: str, phoneme_inventory: Set[str] = PHONEMES) -> str: text = text.lower() text = segment_into_tokens(text, phoneme_inventory) return text
[ "\n Takes as input a string in Kunwinjku and segments it into phoneme-like\n units based on the standard orthographic rules specified at\n http://bininjgunwok.org.au/\n " ]
Please provide a description of the function:def sort_annotations(annotations: List[Tuple[int, int, str]] ) -> List[Tuple[int, int, str]]: return sorted(annotations, key=lambda x: x[0])
[ " Sorts the annotations by their start_time. " ]
Please provide a description of the function:def utterances_from_tier(eafob: Eaf, tier_name: str) -> List[Utterance]: try: speaker = eafob.tiers[tier_name][2]["PARTICIPANT"] except KeyError: speaker = None # We don't know the name of the speaker. tier_utterances = [] annotations ...
[ " Returns utterances found in the given Eaf object in the given tier." ]
Please provide a description of the function:def utterances_from_eaf(eaf_path: Path, tier_prefixes: Tuple[str, ...]) -> List[Utterance]: if not eaf_path.is_file(): raise FileNotFoundError("Cannot find {}".format(eaf_path)) eaf = Eaf(eaf_path) utterances = [] for tier_name in sorted(list(e...
[ "\n Extracts utterances in tiers that start with tier_prefixes found in the ELAN .eaf XML file\n at eaf_path.\n\n For example, if xv@Mark is a tier in the eaf file, and\n tier_prefixes = [\"xv\"], then utterances from that tier will be gathered.\n " ]
Please provide a description of the function:def utterances_from_dir(eaf_dir: Path, tier_prefixes: Tuple[str, ...]) -> List[Utterance]: logger.info( "EAF from directory: {}, searching with tier_prefixes {}".format( eaf_dir, tier_prefixes)) utterances = [] f...
[ " Returns the utterances found in ELAN files in a directory.\n\n Recursively explores the directory, gathering ELAN files and extracting\n utterances from them for tiers that start with the specified prefixes.\n\n Args:\n eaf_dir: A path to the directory to be searched\n tier_prefixes: Stings...
Please provide a description of the function:def initialize_media_descriptor(self) -> None: for md in self.media_descriptors: media_path = self.get_media_path(md) if media_path.is_file(): self.media_descriptor = md return raise FileNotFo...
[ "\n Returns the media descriptor for the first media descriptor where\n the file can be found.\n ", "Cannot find media file corresponding to {}.\n Tried looking for the following files: {}.\n " ]
Please provide a description of the function: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)) feat_fn_batch ...
[ " Loads a batch with the given prefixes. The prefixes is the full path to the\n training example minus the extension.\n " ]
Please provide a description of the function:def make_batches(self, utterance_fns: Sequence[Path]) -> List[Sequence[Path]]: return utils.make_batches(utterance_fns, self.batch_size)
[ " Group utterances into batches for decoding. " ]
Please provide a description of the function:def train_batch_gen(self) -> Iterator: if len(self.train_fns) == 0: raise PersephoneException() # Create batches of batch_size and shuffle them. fn_batches = self.make_batches(self.train_fns) if self.rand: ...
[ " Returns a generator that outputs batches in the training data.", "No training data available; cannot\n generate training batches." ]
Please provide a description of the function: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." ]
Please provide a description of the function: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_inputs, batch_inputs_lens = utils.load_batch_x(fn_batch, ...
[ " A batch generator for all the untranscribed data. " ]
Please provide a description of the function:def human_readable_hyp_ref(self, dense_decoded, dense_y): hyps = [] refs = [] for i in range(len(dense_decoded)): ref = [phn_i for phn_i in dense_y[i] if phn_i != 0] hyp = [phn_i for phn_i in dense_decoded[i] if phn_i...
[ " Returns a human readable version of the hypothesis for manual\n inspection, along with the reference.\n " ]
Please provide a description of the function:def human_readable(self, dense_repr: Sequence[Sequence[int]]) -> List[List[str]]: transcripts = [] for dense_r in dense_repr: non_empty_phonemes = [phn_i for phn_i in dense_r if phn_i != 0] transcript = self.corpus.indices_to...
[ " Returns a human readable version of a dense representation of\n either or reference to facilitate simple manual inspection.\n " ]
Please provide a description of the function:def calc_time(self) -> None: def get_number_of_frames(feat_fns): total = 0 for feat_fn in feat_fns: num_frames = len(np.load(feat_fn)) total += num_frames return total ...
[ "\n Prints statistics about the the total duration of recordings in the\n corpus.\n ", " fns: A list of numpy files which contain a number of feature\n frames. " ]
Please provide a description of the function: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. " ]
Please provide a description of the function:def write_desc(self) -> None: 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) import json...
[ " Writes a description of the model to the exp_dir. " ]
Please provide a description of the function:def empty_wav(wav_path: Union[Path, str]) -> bool: with wave.open(str(wav_path), 'rb') as wav_f: return wav_f.getnframes() == 0
[ "Check if a wav contains data" ]
Please provide a description of the function:def extract_energy(rate, sig): 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
[ " Extracts the energy of frames. " ]
Please provide a description of the function:def fbank(wav_path, flat=True): (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(rate, sig) feat = n...
[ " Currently grabs log Mel filterbank, deltas and double deltas." ]
Please provide a description of the function:def mfcc(wav_path): (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) # Make time t...
[ " Grabs MFCC features with energy and derivates. " ]
Please provide a description of the function:def from_dir(dirpath: Path, feat_type: str) -> None: logger.info("Extracting features from directory {}".format(dirpath)) dirname = str(dirpath) def all_wavs_processed() -> bool: for fn in os.listdir(dirname): prefix, ext = o...
[ " Performs feature extraction from the WAV files in a directory.\n\n Args:\n dirpath: A `Path` to the directory where the WAV files reside.\n feat_type: The type of features that are being used.\n ", "\n True if all wavs in the directory have corresponding numpy feature\n file; F...
Please provide a description of the function:def convert_wav(org_wav_fn: Path, tgt_wav_fn: Path) -> None: if not org_wav_fn.exists(): raise FileNotFoundError args = [config.FFMPEG_PATH, "-i", str(org_wav_fn), "-ac", "1", "-ar", "16000", str(tgt_wav_fn)] subprocess.run(args)
[ " Converts the wav into a 16bit mono 16000Hz wav.\n\n Args:\n org_wav_fn: A `Path` to the original wave file\n tgt_wav_fn: The `Path` to output the processed wave file\n " ]
Please provide a description of the function: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 os.listdir(wav_dir): prefix, ext = os.path.splitext(fn) if ext == ".wav": ...
[ " Extract Kaldi pitch features. Assumes 16k mono wav files." ]
Please provide a description of the function:def get_exp_dir_num(parent_dir: str) -> int: return max([int(fn.split(".")[0]) for fn in os.listdir(parent_dir) if fn.split(".")[0].isdigit()] + [-1])
[ " Gets the number of the current experiment directory." ]
Please provide a description of the function:def _prepare_directory(directory_path: str) -> str: exp_num = get_exp_dir_num(directory_path) exp_num = exp_num + 1 exp_dir = os.path.join(directory_path, str(exp_num)) if not os.path.isdir(exp_dir): os.makedirs(exp_dir) return exp_dir
[ "\n Prepare the directory structure required for the experiment\n :returns: returns the name of the newly created directory\n " ]
Please provide a description of the function:def prep_exp_dir(directory=EXP_DIR): if not os.path.isdir(directory): os.makedirs(directory) exp_dir = _prepare_directory(directory) try: # Get the directory this file is in, so we can grab the git repo. dirname = os.path.dirname(os.p...
[ " Prepares an experiment directory by copying the code in this directory\n to it as is, and setting the logger to write to files in that directory.\n Copies a git hash of the most changes at git HEAD into the directory to\n keep the experiment results in sync with the version control system.\n :director...
Please provide a description of the function: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. " ]
Please provide a description of the function: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, end_time) except FileNotFoundError: # Then sox isn't installed, so use pydub/ffmpeg ...
[ " Extracts part of a WAV File.\n\n First attempts to call sox. If sox is unavailable, it backs off to\n pydub+ffmpeg.\n\n Args:\n in_path: A path to the source file to extract a portion of\n out_path: A path describing the to-be-created WAV file.\n start_time: The point in the source W...
Please provide a description of the function: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(out_path, in_path) + " using a start_time of {} and an end_time of {}".format(st...
[ " Crops the wav file. " ]
Please provide a description of the function:def trim_wav_sox(in_path: Path, out_path: Path, start_time: int, end_time: int) -> None: if out_path.is_file(): logger.info("Output path %s already exists, not trimming file", out_path) return start_time_secs = millisecs_to_sec...
[ " Crops the wav file at in_fn so that the audio between start_time and\n end_time is output to out_fn. Measured in milliseconds.\n " ]
Please provide a description of the function:def extract_wavs(utterances: List[Utterance], tgt_dir: Path, lazy: bool) -> None: tgt_dir.mkdir(parents=True, exist_ok=True) for utter in utterances: wav_fn = "{}.{}".format(utter.prefix, "wav") out_wav_path = tgt_dir / wav_fn ...
[ " Extracts WAVs from the media files associated with a list of Utterance\n objects and stores it in a target directory.\n\n Args:\n utterances: A list of Utterance objects, which include information\n about the source media file, and the offset of the utterance in the\n media_file...
Please provide a description of the function:def filter_labels(sent: Sequence[str], labels: Set[str] = None) -> List[str]: if labels: return [tok for tok in sent if tok in labels] return list(sent)
[ " Returns only the tokens present in the sentence that are in labels." ]
Please provide a description of the function:def filtered_error_rate(hyps_path: Union[str, Path], refs_path: Union[str, Path], labels: Set[str]) -> float: if isinstance(hyps_path, Path): hyps_path = str(hyps_path) if isinstance(refs_path, Path): refs_path = str(refs_path) with open(hyp...
[ " Returns the error rate of hypotheses in hyps_path against references in refs_path after filtering only for labels in labels.\n " ]
Please provide a description of the function:def fmt_latex_output(hyps: Sequence[Sequence[str]], refs: Sequence[Sequence[str]], prefixes: Sequence[str], out_fn: Path, ) -> None: alignments_ = [min_edit_distance_align(ref, hyp) ...
[ " Output the hypotheses and references to a LaTeX source file for\n pretty printing.\n " ]
Please provide a description of the function:def fmt_error_types(hyps: Sequence[Sequence[str]], refs: Sequence[Sequence[str]] ) -> str: alignments = [min_edit_distance_align(ref, hyp) for hyp, ref in zip(hyps, refs)] arrow_counter = Counter() # typ...
[ " Format some information about different error types: insertions, deletions and substitutions." ]
Please provide a description of the function:def fmt_confusion_matrix(hyps: Sequence[Sequence[str]], refs: Sequence[Sequence[str]], label_set: Set[str] = None, max_width: int = 25) -> str: if not label_set: # Then determine the...
[ " Formats a confusion matrix over substitutions, ignoring insertions\n and deletions. " ]
Please provide a description of the function:def fmt_latex_untranscribed(hyps: Sequence[Sequence[str]], prefixes: Sequence[str], out_fn: Path) -> None: hyps_prefixes = list(zip(hyps, prefixes)) def utter_id_key(hyp_prefix): hyp, prefix = hyp_...
[ " Formats automatic hypotheses that have not previously been\n transcribed in LaTeX. " ]
Please provide a description of the function:def segment_into_chars(utterance: str) -> str: if not isinstance(utterance, str): raise TypeError("Input type must be a string. Got {}.".format(type(utterance))) utterance.strip() utterance = utterance.replace(" ", "") return " ".join(utterance...
[ " Segments an utterance into space delimited characters. " ]
Please provide a description of the function:def segment_into_tokens(utterance: str, token_inventory: Iterable[str]): if not isinstance(utterance, str): raise TypeError("Input type must be a string. Got {}.".format(type(utterance))) # Token inventory needs to be hashable for speed token_inven...
[ "\n Segments an utterance (a string) into tokens based on an inventory of\n tokens (a list or set of strings).\n\n The approach: Given the rest of the utterance, find the largest token (in\n character length) that is found in the token_inventory, and treat that as a\n token before segmenting the rest...
Please provide a description of the function:def make_indices_to_labels(labels: Set[str]) -> Dict[int, str]: return {index: label for index, label in enumerate(["pad"] + sorted(list(labels)))}
[ " Creates a mapping from indices to labels. " ]
Please provide a description of the function:def preprocess_na(sent, label_type): if label_type == "phonemes_and_tones": phonemes = True tones = True tgm = True elif label_type == "phonemes_and_tones_no_tgm": phonemes = True tones = True tgm = False elif ...
[ "Preprocess Na sentences\n\n Args:\n sent: A sentence\n label_type: The type of label provided\n ", "Pop phonemes off a sentence one at a time", " Returns a sequence of phonemes and pipes (word delimiters). Tones,\n syllable boundaries, whitespace are all removed." ]
Please provide a description of the function: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 have to split and rejoin, but that fixes a Spacy token # error. trans = fr_...
[ " Takes a list of sentences in french and preprocesses them." ]
Please provide a description of the function: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(os.path.join(tgt_wav_dir, "TEXT")): os.makedirs(os.path.join(tgt_wav_dir, "TEXT...
[ " Extracts sentence-level transcriptions, translations and wavs from the\n Na Pangloss XML and WAV files. But otherwise doesn't preprocess them." ]
Please provide a description of the function: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")): os.makedirs(os.path.join(label_dir, "TEXT")) if not os.path.exists(os.path.join(label_dir, "WORDLIST")): os.mak...
[ " Prepare the neural network output targets." ]
Please provide a description of the function:def prepare_untran(feat_type, tgt_dir, untran_dir): 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(w...
[ " Preprocesses untranscribed audio." ]
Please provide a description of the function: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.path.isdir(TGT_DIR): os.makedirs(TGT_DIR) if not os.path.isdir(FEAT_DIR): ...
[ " Prepare the input features." ]
Please provide a description of the function:def get_story_prefixes(label_type, label_dir=LABEL_DIR): 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] ...
[ " Gets the Na text prefixes. " ]
Please provide a description of the function:def make_data_splits(label_type, train_rec_type="text_and_wordlist", max_samples=1000, seed=0, tgt_dir=TGT_DIR): feat_dir = os.path.join(tgt_dir, "feat") test_prefix_fn=os.path.join(tgt_dir, "test_prefixes.txt") valid_prefix_fn=os.path....
[ " Creates a file with a list of prefixes (identifiers) of utterances to\n include in the test set. Test utterances must never be wordlists. Assumes\n preprocessing of label dir has already been done." ]
Please provide a description of the function:def get_stories(label_type): prefixes = get_story_prefixes(label_type) texts = list(set([prefix.split(".")[0].split("/")[1] for prefix in prefixes])) return texts
[ " Returns a list of the stories in the Na corpus. " ]
Please provide a description of the function: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 test_story): raise PersephoneException( ...
[ "Split data into train, valid and test groups" ]
Please provide a description of the function: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.path.jo...
[ " Writes the set of prefixes to a file this is useful for pretty\n printing in results.latex_output. " ]
Please provide a description of the function:def get_sents_times_and_translations(xml_fn): tree = ElementTree.parse(xml_fn) root = tree.getroot() if "WORDLIST" in root.tag or root.tag == "TEXT": transcriptions = [] times = [] translations = [] for child in root: ...
[ " Given an XML filename, loads the transcriptions, their start/end times,\n and translations. " ]
Please provide a description of the function:def add_data_file(data_files, target, source): 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)
[ "Add an entry to data_files" ]
Please provide a description of the function: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) if prefix: q_home = os.path.join(prefix, 'q') if os.path.isdir(q_home): ...
[ "Derive q home from the environment" ]
Please provide a description of the function: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 line[2:5] return '2.2'
[ "Return version of q installed at q_home" ]
Please provide a description of the function:def precmd(self, line): 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 ...
[ "Support for help" ]
Please provide a description of the function:def onecmd(self, line): if line == '\\': return True elif line == 'EOF': print('\r', end='') return True else: try: v = q(line) except kerr as e: prin...
[ "Interpret the line" ]
Please provide a description of the function:def console_size(fd=1): try: import fcntl import termios import struct except ImportError: size = os.getenv('LINES', 25), os.getenv('COLUMNS', 80) else: size = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, ...
[ "Return console size as a (LINES, COLUMNS) tuple" ]
Please provide a description of the function:def run(q_prompt=False): 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: ...
[ "Run a prompt-toolkit based REPL" ]
Please provide a description of the function:def get_unit(a): 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]
[ "Extract the time unit from array's dtype" ]
Please provide a description of the function: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_unit(a) attr, shift, func, scale = _UNIT[unit] a[:] = getattr(x, attr).data a += shif...
[ "Rescale data from a K object x to array a.\n\n " ]
Please provide a description of the function:def array(self, dtype=None): t = self._t # timestamp (12) through last enum (76) if 11 <= t < 77: dtype = dtypeof(self) a = numpy.empty(len(self), dtype) k2a(a, self) return a # table (98) if t == 98: if dtype ...
[ "An implementation of __array__()" ]
Please provide a description of the function:def show(self, start=0, geometry=None, output=None): if output is None: output = sys.stdout if geometry is None: geometry = q.value(kp("\\c")) else: geometry = self._I(geometry) if start < 0: ...
[ "pretty-print data to the console\n\n (similar to q.show, but uses python stdout by default)\n\n >>> x = q('([k:`x`y`z]a:1 2 3;b:10 20 30)')\n >>> x.show() # doctest: +NORMALIZE_WHITESPACE\n k| a b\n -| ----\n x| 1 10\n y| 2 20\n z| 3 30\n\n the first ...
Please provide a description of the function:def select(self, columns=(), by=(), where=(), **kwds): return self._seu('select', columns, by, where, kwds)
[ "select from self\n\n >>> t = q('([]a:1 2 3; b:10 20 30)')\n >>> t.select('a', where='b > 20').show()\n a\n -\n 3\n " ]
Please provide a description of the function:def exec_(self, columns=(), by=(), where=(), **kwds): return self._seu('exec', columns, by, where, kwds)
[ "exec from self\n\n >>> t = q('([]a:1 2 3; b:10 20 30)')\n >>> t.exec_('a', where='b > 10').show()\n 2 3\n " ]
Please provide a description of the function:def update(self, columns=(), by=(), where=(), **kwds): return self._seu('update', columns, by, where, kwds)
[ "update from self\n\n >>> t = q('([]a:1 2 3; b:10 20 30)')\n >>> t.update('a*2',\n ... where='b > 20').show() # doctest: +NORMALIZE_WHITESPACE\n a b\n ----\n 1 10\n 2 20\n 6 30\n " ]
Please provide a description of the function:def dict(cls, *args, **kwds): if args: if len(args) > 1: raise TypeError("Too many positional arguments") x = args[0] keys = [] vals = [] try: x_keys = x.keys ...
[ "Construct a q dictionary\n\n K.dict() -> new empty q dictionary (q('()!()')\n K.dict(mapping) -> new dictionary initialized from a mapping object's\n (key, value) pairs\n K.dict(iterable) -> new dictionary initialized from an iterable\n yielding (key, value) pairs\n ...
Please provide a description of the function:def logical_lines(lines): 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 chunk ...
[ "Merge lines into chunks according to q rules" ]
Please provide a description of the function:def q(line, cell=None, _ns=None): if cell is None: return pyq.q(line) if _ns is None: _ns = vars(sys.modules['__main__']) input = output = None preload = [] outs = {} try: h = pyq.q('0i') if line: for ...
[ "Run q code.\n\n Options:\n -l (dir|script) - pre-load database or script\n -h host:port - execute on the given host\n -o var - send output to a variable named var.\n -i var1,..,varN - input variables\n -1/-2 - redirect stdout/stderr\n " ]
Please provide a description of the function:def load_ipython_extension(ipython): ipython.register_magic_function(q, 'line_cell') fmr = ipython.display_formatter.formatters['text/plain'] fmr.for_type(pyq.K, _q_formatter)
[ "Register %q and %%q magics and pretty display for K objects" ]
Please provide a description of the function: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" ]
Please provide a description of the function:def cmdloop(self, intro=None): 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_bott...
[ "A Cmd.cmdloop implementation" ]
Please provide a description of the function:def get_completions(self, document, complete_event): # Detect a file handle m = HSYM_RE.match(document.text_before_cursor) if m: text = m.group(1) doc = Document(text, len(text)) for c in self.path_complete...
[ "Yield completions" ]
Please provide a description of the function:def eval(source, kwd_dict=None, **kwds): kwd_dict = kwd_dict or kwds with ctx(kwd_dict): return handleLine(source)
[ "Evaluate a snuggs expression.\n\n Parameters\n ----------\n source : str\n Expression source.\n kwd_dict : dict\n A dict of items that form the evaluation context. Deprecated.\n kwds : dict\n A dict of items that form the valuation context.\n\n Returns\n -------\n objec...
Please provide a description of the function:def _parse_crontab(self, which, entry): ''' This parses a single crontab field and returns the data necessary for this matcher to accept the proper values. See the README for information about what is accepted. ''' # this han...
[]
Please provide a description of the function: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('*') ...
[]
Please provide a description of the function: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...
[]
Please provide a description of the function: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)
[]
Please provide a description of the function: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 v...
[]
Please provide a description of the function:def etree(self, data, root=None): '''Convert data structure into a list of etree.Element''' result = self.list() if root is None else root if isinstance(data, (self.dict, dict)): for key, value in data.items(): value_is_lis...
[]