idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
245,700 | def ensure_no_set_overlap ( train : Sequence [ str ] , valid : Sequence [ str ] , test : Sequence [ str ] ) -> None : logger . debug ( "Ensuring that the training, validation and test data sets have no overlap" ) train_s = set ( train ) valid_s = set ( valid ) test_s = set ( test ) if train_s & valid_s : logger . warni... | Ensures no test set data has creeped into the training set . | 266 | 15 |
245,701 | def get_untranscribed_prefixes_from_file ( target_directory : Path ) -> List [ str ] : untranscribed_prefix_fn = target_directory / "untranscribed_prefixes.txt" if untranscribed_prefix_fn . exists ( ) : with untranscribed_prefix_fn . open ( ) as f : prefixes = f . readlines ( ) return [ prefix . strip ( ) for prefix in... | The file untranscribed_prefixes . txt will specify prefixes which do not have an associated transcription file if placed in the target directory . | 145 | 30 |
245,702 | def determine_labels ( target_dir : Path , label_type : str ) -> Set [ str ] : logger . info ( "Finding phonemes of type %s in directory %s" , label_type , target_dir ) label_dir = target_dir / "label/" if not label_dir . is_dir ( ) : raise FileNotFoundError ( "The directory {} does not exist." . format ( target_dir ) ... | Returns a set of all phonemes found in the corpus . Assumes that WAV files and label files are split into utterances and segregated in a directory which contains a wav subdirectory and label subdirectory . | 252 | 44 |
245,703 | def from_elan ( cls : Type [ CorpusT ] , org_dir : Path , tgt_dir : Path , feat_type : str = "fbank" , label_type : str = "phonemes" , utterance_filter : Callable [ [ Utterance ] , bool ] = None , label_segmenter : Optional [ LabelSegmenter ] = None , speakers : List [ str ] = None , lazy : bool = True , tier_prefixes ... | Construct a Corpus from ELAN files . | 608 | 8 |
245,704 | def set_and_check_directories ( self , tgt_dir : Path ) -> None : logger . info ( "Setting up directories for corpus in %s" , tgt_dir ) # Check directories exist. if not tgt_dir . is_dir ( ) : raise FileNotFoundError ( "The directory {} does not exist." . format ( tgt_dir ) ) if not self . wav_dir . is_dir ( ) : raise ... | Make sure that the required directories exist in the target directory . set variables accordingly . | 167 | 16 |
245,705 | def initialize_labels ( self , labels : Set [ str ] ) -> Tuple [ dict , dict ] : logger . debug ( "Creating mappings for labels" ) label_to_index = { label : index for index , label in enumerate ( [ "pad" ] + sorted ( list ( labels ) ) ) } index_to_label = { index : phn for index , phn in enumerate ( [ "pad" ] + sorted... | Create mappings from label to index and index to label | 116 | 11 |
245,706 | def prepare_feats ( self ) -> None : 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" : logger . info ( "Non wav file found in wav directory: %s" , path ) cont... | Prepares input features | 301 | 4 |
245,707 | 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 ( ) test_f_exists = self . test_prefix_fn . is_file ( ) if train_f_exists and valid_f_exists and test_f_exists : logger . debug ( "Split for training, valid... | Splits the utterances into training validation and test sets . | 665 | 12 |
245,708 | def divide_prefixes ( prefixes : List [ str ] , seed : int = 0 ) -> Tuple [ List [ str ] , List [ str ] , List [ str ] ] : if len ( prefixes ) < 3 : raise PersephoneException ( "{} cannot be split into 3 groups as it only has {} items" . format ( prefixes , len ( prefixes ) ) ) Ratios = namedtuple ( "Ratios" , [ "train... | Divide data into training validation and test subsets | 348 | 10 |
245,709 | 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 . | 44 | 11 |
245,710 | 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 . | 43 | 11 |
245,711 | 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 channels of multiple feats self . _num_feats = feats . shape [ 1 ] * feats . shape [ 2 ] elif len... | The number of features per time step in the corpus . | 163 | 11 |
245,712 | 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 ( self . label_dir / ( "%s.%s" % ( prefix , self . label_type ) ... | Fetches the file paths to the features files and labels files corresponding to the provided list of features | 134 | 20 |
245,713 | 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 . | 43 | 10 |
245,714 | 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 . | 43 | 10 |
245,715 | 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 ) with label_fn . open ( ) as f : transcript = f . read ( ) . stri... | Used to play the WAV files and compare with the transcription . | 135 | 13 |
245,716 | 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 . | 78 | 14 |
245,717 | 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 ) ) raise ValueError result = np . zeros ( ( to_length , ) + matri... | Zero pads along the 0th dimension to make sure the utterance array x is of length to_length . | 112 | 22 |
245,718 | 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_size = len ( path_batch ) shape = ( batch_size , max_len ) + tuple ( utteran... | Loads a batch of input features given a list of paths to numpy arrays in that batch . | 178 | 20 |
245,719 | 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 ] macro_per += distance . edit_distance ( ref , hyp ) / len ( r... | Calculates the phoneme error rate of a batch . | 130 | 12 |
245,720 | 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 = [ prefix for prefix , length in prefix_lens if length <= ma... | 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 . | 104 | 59 |
245,721 | 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_line [ 0 ] == "Length" return fl... | Returns the length of the WAV file in seconds . | 123 | 11 |
245,722 | 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_words_path . parent ) ] ) | Fetches a repository containing English words . | 103 | 9 |
245,723 | 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" , "o" , "yaw" , "i" , "bi" , "aye" , "im... | Returns a list of English words which can be used to filter out code - switched sentences . | 682 | 18 |
245,724 | 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 annotation in eafob . get_annotation_data_for_tier ( tier ) : print ( "\t\t" , annotation ) except KeyError... | A function to explore the tiers of ELAN files . | 117 | 11 |
245,725 | 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 . | 50 | 10 |
245,726 | 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 = sort_annotations ( list ( eafob . get_annotation_data_for_t... | Returns utterances found in the given Eaf object in the given tier . | 252 | 15 |
245,727 | 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 ( eaf . tiers ) ) : # Sorting for determinis... | Extracts utterances in tiers that start with tier_prefixes found in the ELAN . eaf XML file at eaf_path . | 157 | 30 |
245,728 | 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 = [ ] for eaf_path in eaf_dir . glob ( "**/*.eaf" ) : eaf_utterances = utterances_from_eaf ... | Returns the utterances found in ELAN files in a directory . | 135 | 13 |
245,729 | 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 = inverse [ 0 ] target_fn_batch = inverse [ 1 ] batch_inputs , batch_inputs_lens = u... | Loads a batch with the given prefixes . The prefixes is the full path to the training example minus the extension . | 245 | 25 |
245,730 | def train_batch_gen ( self ) -> Iterator : if len ( self . train_fns ) == 0 : raise PersephoneException ( """No training data available; cannot generate training batches.""" ) # Create batches of batch_size and shuffle them. fn_batches = self . make_batches ( self . train_fns ) if self . rand : random . shuffle ( fn_ba... | Returns a generator that outputs batches in the training data . | 143 | 11 |
245,731 | 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 . | 44 | 10 |
245,732 | 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 , flatten = False ) yield batch_inputs , batch_inputs_lens , fn_batch | A batch generator for all the untranscribed data . | 106 | 11 |
245,733 | 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 != 0 ] ref = self . corpus . indices_to_labels ( ref ) hyp = self . corpus . i... | Returns a human readable version of the hypothesis for manual inspection along with the reference . | 150 | 16 |
245,734 | 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_labels ( non_empty_phonemes ) transcripts . append ( transcript ) re... | Returns a human readable version of a dense representation of either or reference to facilitate simple manual inspection . | 104 | 19 |
245,735 | def calc_time ( self ) -> None : def get_number_of_frames ( feat_fns ) : """ fns: A list of numpy files which contain a number of feature frames. """ total = 0 for feat_fn in feat_fns : num_frames = len ( np . load ( feat_fn ) ) total += num_frames return total def numframes_to_minutes ( num_frames ) : # TODO Assumes 1... | Prints statistics about the the total duration of recordings in the corpus . | 385 | 14 |
245,736 | 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 . | 47 | 11 |
245,737 | 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 json_path = os . path . join ( self . exp_dir , "model_description.json... | Writes a description of the model to the exp_dir . | 444 | 13 |
245,738 | 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 | 56 | 7 |
245,739 | 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 . | 72 | 8 |
245,740 | 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 = np . hstack ( [ energy , fbank_feat ] ... | Currently grabs log Mel filterbank deltas and double deltas . | 306 | 15 |
245,741 | 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 the first dimension for easy length norma... | Grabs MFCC features with energy and derivates . | 182 | 11 |
245,742 | 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 : """ True if all wavs in the directory have corresponding numpy feature file; False otherwise. """ for fn in os . listd... | Performs feature extraction from the WAV files in a directory . | 504 | 13 |
245,743 | 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 . | 100 | 16 |
245,744 | 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" : prefixes . append ( prefix ) wav_scp_path = os . path . ... | Extract Kaldi pitch features . Assumes 16k mono wav files . | 623 | 16 |
245,745 | 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 . | 70 | 10 |
245,746 | 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 . | 45 | 14 |
245,747 | 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 trim_wav_pydub ( in_path , out_path , start_time , end_time ) except subprocess ... | Extracts part of a WAV File . | 186 | 10 |
245,748 | 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 ( start_time , end_time ) ) if out_path . is_file ( ) : return # TO... | Crops the wav file . | 318 | 7 |
245,749 | 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_secs ( start_time ) end_time_secs = millisecs_to_secs ( end_time ) args = ... | 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 . | 226 | 34 |
245,750 | 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 if lazy and out_wav_path . is_file ( ) : logger . info ( "File... | Extracts WAVs from the media files associated with a list of Utterance objects and stores it in a target directory . | 200 | 27 |
245,751 | 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 . | 51 | 13 |
245,752 | 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 ( hyps_path ) as hyps_f : lines = hyps_f . rea... | Returns the error rate of hypotheses in hyps_path against references in refs_path after filtering only for labels in labels . | 250 | 26 |
245,753 | 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 ) for hyp , ref in zip ( hyps , refs ) ] with out_fn . open ( "w" ) as out_f : print ( latex_header ( ) , fil... | Output the hypotheses and references to a LaTeX source file for pretty printing . | 442 | 15 |
245,754 | 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 label set by reading raise NotImplementedError ( ) alignments = [ min_edit_distance_align ( ref , hyp ) for hy... | Formats a confusion matrix over substitutions ignoring insertions and deletions . | 344 | 15 |
245,755 | 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_prefix prefix_split = prefix . split ( "." ) return ( prefix_split [ 0 ] , int ( prefix_split... | Formats automatic hypotheses that have not previously been transcribed in LaTeX . | 313 | 15 |
245,756 | 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 . | 80 | 11 |
245,757 | 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 . | 55 | 9 |
245,758 | 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_nlp ( " " . join ( trans . split ( ) [ : ] ) ) #trans = fr_n... | Takes a list of sentences in french and preprocesses them . | 134 | 14 |
245,759 | 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" ) ) if not os . path . exists ( os . path . join (... | Extracts sentence - level transcriptions translations and wavs from the Na Pangloss XML and WAV files . But otherwise doesn t preprocess them . | 609 | 33 |
245,760 | 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 . makedirs ( os . path ... | Prepare the neural network output targets . | 333 | 8 |
245,761 | 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 ( wav_dir ) if not os . path . i... | Preprocesses untranscribed audio . | 607 | 8 |
245,762 | 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 ) : os . makedirs ( FEAT_DIR ) if not os . path . isdir... | Prepare the input features . | 889 | 6 |
245,763 | 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 ] for prefix in prefixes ] return prefix... | Gets the Na text prefixes . | 105 | 8 |
245,764 | 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 . | 60 | 11 |
245,765 | 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 ( "We need a valid story if we specify a test story " "and vice versa. This shouldn't be requ... | Split data into train valid and test groups | 228 | 8 |
245,766 | 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 . join ( TGT_DIR , "%s_prefixes.txt" % self . test_story ) with open ( fn , "w" ) as f : for utter_id in se... | Writes the set of prefixes to a file this is useful for pretty printing in results . latex_output . | 131 | 23 |
245,767 | 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 | 70 | 7 |
245,768 | 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 ) : return q_home if WINDOWS : q_home = os . path . join ( env [ 'SystemDrive' ] , r'\q' )... | Derive q home from the environment | 151 | 7 |
245,769 | 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 | 65 | 9 |
245,770 | 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 line == 'help' : line += "`" return line | Support for help | 79 | 3 |
245,771 | 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 : print ( "'%s" % e . args [ 0 ] ) else : if v != q ( '::' ) : v . show ( ) return False | Interpret the line | 89 | 4 |
245,772 | 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 : del sys . argv [ 1 ] if q_prompt : q ( ) ptp . run ( ) | Run a prompt - toolkit based REPL | 110 | 8 |
245,773 | 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 | 70 | 10 |
245,774 | 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 += shift # timespan (16), minute (17), second (18) or time (19) elif 16 <=... | Rescale data from a K object x to array a . | 227 | 13 |
245,775 | 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 : start += q . count ( self ) # Make sure nil is not passed to a q function if self . _id ( ) != n... | pretty - print data to the console | 154 | 7 |
245,776 | def select ( self , columns = ( ) , by = ( ) , where = ( ) , * * kwds ) : return self . _seu ( 'select' , columns , by , where , kwds ) | select from self | 48 | 3 |
245,777 | def exec_ ( self , columns = ( ) , by = ( ) , where = ( ) , * * kwds ) : return self . _seu ( 'exec' , columns , by , where , kwds ) | exec from self | 49 | 3 |
245,778 | def update ( self , columns = ( ) , by = ( ) , where = ( ) , * * kwds ) : return self . _seu ( 'update' , columns , by , where , kwds ) | update from self | 48 | 3 |
245,779 | 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 except AttributeError : for k , v in x : keys . append ( k ) vals . append ( v ) else : keys = x_keys ( ) vals = [ x [ k ] for k in keys... | Construct a q dictionary | 184 | 4 |
245,780 | 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 buf [ : ] = [ ] buf . append ( line ) chunk = '' . join ( buf ) . strip ( ) if chunk : y... | Merge lines into chunks according to q rules | 96 | 9 |
245,781 | 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 opt , value in getopt ( line . split ( ) , "h:l:o:i:12" ) [ 0 ] : if opt == '-l' : pr... | Run q code . | 554 | 4 |
245,782 | 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 | 68 | 14 |
245,783 | 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 | 50 | 8 |
245,784 | 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_bottom_toolbar_tokens , history = history , style = style , true_color = T... | A Cmd . cmdloop implementation | 191 | 7 |
245,785 | def eval ( source , kwd_dict = None , * * kwds ) : kwd_dict = kwd_dict or kwds with ctx ( kwd_dict ) : return handleLine ( source ) | Evaluate a snuggs expression . | 48 | 9 |
245,786 | def _make_matchers ( self , crontab ) : 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 , '0' ) _assert ( len ( ct ) == 7 , "improper number of cron entries specified; got %i need 5 to 7" % ( ... | This constructs the full matcher struct . | 163 | 8 |
245,787 | def next ( self , now = None , increments = _increments , delta = True , default_utc = WARN_CHANGE ) : if default_utc is WARN_CHANGE and ( isinstance ( now , _number_types ) or ( now and not now . tzinfo ) or now is None ) : warnings . warn ( WARNING_CHANGE_MESSAGE , FutureWarning , 2 ) default_utc = False now = now or... | How long to wait in seconds before this crontab entry can next be executed . | 720 | 17 |
245,788 | def _tostring ( value ) : if value is True : value = 'true' elif value is False : value = 'false' elif value is None : value = '' return unicode ( value ) | Convert value to XML compatible string | 45 | 7 |
245,789 | 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' : return True elif value . lower ( ) == 'false' : return False # FIXME: Using int() or float() is eating whitespaces unintendedl... | Convert XML string value to None boolean int or float | 147 | 11 |
245,790 | def by_col ( cls , df , cols , w = None , inplace = False , pvalue = 'sim' , outvals = None , * * stat_kws ) : if outvals is None : outvals = [ ] outvals . extend ( [ 'bb' , 'p_sim_bw' , 'p_sim_bb' ] ) pvalue = '' return _univariate_handler ( df , cols , w = w , inplace = inplace , pvalue = pvalue , outvals = outvals ,... | Function to compute a Join_Count statistic on a dataframe | 139 | 12 |
245,791 | def Moran_BV_matrix ( variables , w , permutations = 0 , varnames = None ) : try : # check if pandas is installed import pandas if isinstance ( variables , pandas . DataFrame ) : # if yes use variables as df and convert to numpy_array varnames = pandas . Index . tolist ( variables . columns ) variables_n = [ ] for var ... | Bivariate Moran Matrix | 159 | 4 |
245,792 | def _Moran_BV_Matrix_array ( variables , w , permutations = 0 , varnames = None ) : 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 range ( i + 1 , k ) : y1 = variables [ i ] y2 = variables [ j ] ... | Base calculation for MORAN_BV_Matrix | 227 | 10 |
245,793 | def by_col ( cls , df , x , y = None , w = None , inplace = False , pvalue = 'sim' , outvals = None , * * stat_kws ) : return _bivariate_handler ( df , x , y = y , w = w , inplace = inplace , pvalue = pvalue , outvals = outvals , swapname = cls . __name__ . lower ( ) , stat = cls , * * stat_kws ) | Function to compute a Moran_BV statistic on a dataframe | 108 | 13 |
245,794 | def by_col ( cls , df , events , populations , w = None , inplace = False , pvalue = 'sim' , outvals = None , swapname = '' , * * stat_kws ) : if not inplace : new = df . copy ( ) cls . by_col ( new , events , populations , w = w , inplace = True , pvalue = pvalue , outvals = outvals , swapname = swapname , * * stat_kw... | Function to compute a Moran_Rate statistic on a dataframe | 468 | 12 |
245,795 | def flatten ( l , unique = True ) : l = reduce ( lambda x , y : x + y , l ) if not unique : return list ( l ) return list ( set ( l ) ) | flatten a list of lists | 43 | 6 |
245,796 | def weighted_median ( d , w ) : dtype = [ ( 'w' , '%s' % w . dtype ) , ( 'v' , '%s' % d . dtype ) ] d_w = np . array ( list ( zip ( w , d ) ) , dtype = dtype ) d_w . sort ( order = 'v' ) reordered_w = d_w [ 'w' ] . cumsum ( ) cumsum_threshold = reordered_w [ - 1 ] * 1.0 / 2 median_inx = ( reordered_w >= cumsum_threshol... | A utility function to find a median of d based on w | 214 | 12 |
245,797 | 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 + h ] ) for i in range ( 0 , t , h ) ] ) | A utility function to summarize a data array into n values after weighting the array with another weight array w | 65 | 21 |
245,798 | 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 ( len ( e ) // n ) return sum_by_n ( r , age_weight , n ) | A utility function to compute rate through crude age standardization | 84 | 11 |
245,799 | 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 ) . repeat ( len ( s ) // n ) ) adjusted_r = sum_by_n ( e , age_weight , n ) var_estimate = sum_by_n ( e , np . square ( age_weight ) , n ) g_a = np . square ( adjusted_r ) / var_estimate g_b ... | A utility function to compute rate through direct age standardization | 392 | 11 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.