idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
57,800
def remove_program_temp_directory ( ) : if os . path . exists ( program_temp_directory ) : max_retries = 3 curr_retries = 0 time_between_retries = 1 while True : try : shutil . rmtree ( program_temp_directory ) break except IOError : curr_retries += 1 if curr_retries > max_retries : raise time . sleep ( time_between_re...
Remove the global temp directory and all its contents .
57,801
def call_external_subprocess ( command_list , stdin_filename = None , stdout_filename = None , stderr_filename = None , env = None ) : if stdin_filename : stdin = open ( stdin_filename , "r" ) else : stdin = None if stdout_filename : stdout = open ( stdout_filename , "w" ) else : stdout = None if stderr_filename : stde...
Run the command and arguments in the command_list . Will search the system PATH for commands to execute but no shell is started . Redirects any selected outputs to the given filename . Waits for command completion .
57,802
def run_external_subprocess_in_background ( command_list , env = None ) : if system_os == "Windows" : DETACHED_PROCESS = 0x00000008 p = subprocess . Popen ( command_list , shell = False , stdin = None , stdout = None , stderr = None , close_fds = True , creationflags = DETACHED_PROCESS , env = env ) else : p = subproce...
Runs the command and arguments in the list as a background process .
57,803
def function_call_with_timeout ( fun_name , fun_args , secs = 5 ) : from multiprocessing import Process , Queue p = Process ( target = fun_name , args = tuple ( fun_args ) ) p . start ( ) curr_secs = 0 no_timeout = False if secs == 0 : no_timeout = True else : timeout = secs while p . is_alive ( ) and not no_timeout : ...
Run a Python function with a timeout . No interprocess communication or return values are handled . Setting secs to 0 gives infinite timeout .
57,804
def fix_pdf_with_ghostscript_to_tmp_file ( input_doc_fname ) : if not gs_executable : init_and_test_gs_executable ( exit_on_fail = True ) temp_file_name = get_temporary_filename ( extension = ".pdf" ) gs_run_command = [ gs_executable , "-dSAFER" , "-o" , temp_file_name , "-dPDFSETTINGS=/prepress" , "-sDEVICE=pdfwrite" ...
Attempt to fix a bad PDF file with a Ghostscript command writing the output PDF to a temporary file and returning the filename . Caller is responsible for deleting the file .
57,805
def get_bounding_box_list_ghostscript ( input_doc_fname , res_x , res_y , full_page_box ) : if not gs_executable : init_and_test_gs_executable ( exit_on_fail = True ) res = str ( res_x ) + "x" + str ( res_y ) box_arg = "-dUseMediaBox" if "c" in full_page_box : box_arg = "-dUseCropBox" if "t" in full_page_box : box_arg ...
Call Ghostscript to get the bounding box list . Cannot set a threshold with this method .
57,806
def render_pdf_file_to_image_files_pdftoppm_ppm ( pdf_file_name , root_output_file_path , res_x = 150 , res_y = 150 , extra_args = None ) : if extra_args is None : extra_args = [ ] if not pdftoppm_executable : init_and_test_pdftoppm_executable ( prefer_local = False , exit_on_fail = True ) if old_pdftoppm_version : com...
Use the pdftoppm program to render a PDF file to . png images . The root_output_file_path is prepended to all the output files which have numbers and extensions added . Extra arguments can be passed as a list in extra_args . Return the command output .
57,807
def render_pdf_file_to_image_files_pdftoppm_pgm ( pdf_file_name , root_output_file_path , res_x = 150 , res_y = 150 ) : comm_output = render_pdf_file_to_image_files_pdftoppm_ppm ( pdf_file_name , root_output_file_path , res_x , res_y , [ "-gray" ] ) return comm_output
Same as renderPdfFileToImageFile_pdftoppm_ppm but with - gray option for pgm .
57,808
def render_pdf_file_to_image_files__ghostscript_png ( pdf_file_name , root_output_file_path , res_x = 150 , res_y = 150 ) : if not gs_executable : init_and_test_gs_executable ( exit_on_fail = True ) command = [ gs_executable , "-dBATCH" , "-dNOPAUSE" , "-sDEVICE=pnggray" , "-r" + res_x + "x" + res_y , "-sOutputFile=" +...
Use Ghostscript to render a PDF file to . png images . The root_output_file_path is prepended to all the output files which have numbers and extensions added . Return the command output .
57,809
def show_preview ( viewer_path , pdf_file_name ) : try : cmd = [ viewer_path , pdf_file_name ] run_external_subprocess_in_background ( cmd ) except ( subprocess . CalledProcessError , OSError , IOError ) as e : print ( "\nWarning from pdfCropMargins: The argument to the '--viewer' option:" "\n " , viewer_path , "\nwa...
Run the PDF viewer at the path viewer_path on the file pdf_file_name .
57,810
def main ( ) : cleanup_and_exit = sys . exit exit_code = 0 try : from . import external_program_calls as ex cleanup_and_exit = ex . cleanup_and_exit from . import main_pdfCropMargins main_pdfCropMargins . main_crop ( ) except ( KeyboardInterrupt , EOFError ) : print ( "\nGot a KeyboardInterrupt, cleaning up and exiting...
Run main catching any exceptions and cleaning up the temp directories .
57,811
def get_full_page_box_list_assigning_media_and_crop ( input_doc , quiet = False ) : full_page_box_list = [ ] rotation_list = [ ] if args . verbose and not quiet : print ( "\nOriginal full page sizes, in PDF format (lbrt):" ) for page_num in range ( input_doc . getNumPages ( ) ) : curr_page = input_doc . getPage ( page_...
Get a list of all the full - page box values for each page . The argument input_doc should be a PdfFileReader object . The boxes on the list are in the simple 4 - float list format used by this program not RectangleObject format .
57,812
def set_cropped_metadata ( input_doc , output_doc , metadata_info ) : if not metadata_info : class MetadataInfo ( object ) : author = "" creator = "" producer = "" subject = "" title = "" metadata_info = MetadataInfo ( ) output_info_dict = output_doc . _info . getObject ( ) producer_mod = PRODUCER_MODIFIER already_crop...
Set the metadata for the output document . Mostly just copied over but Producer has a string appended to indicate that this program modified the file . That allows for the undo operation to make sure that this program cropped the file in the first place .
57,813
def apply_crop_list ( crop_list , input_doc , page_nums_to_crop , already_cropped_by_this_program ) : if args . restore and not already_cropped_by_this_program : print ( "\nWarning from pdfCropMargins: The Producer string indicates that" "\neither this document was not previously cropped by pdfCropMargins" "\nor else i...
Apply the crop list to the pages of the input PdfFileReader object .
57,814
def setup_output_document ( input_doc , tmp_input_doc , metadata_info , copy_document_catalog = True ) : output_doc = PdfFileWriter ( ) def root_objects_not_indirect ( input_doc , root_object ) : if isinstance ( root_object , dict ) : return { root_objects_not_indirect ( input_doc , key ) : root_objects_not_indirect ( ...
Create the output PdfFileWriter objects and copy over the relevant info .
57,815
def setdefault ( self , key , value ) : try : super ( FlaskConfigStorage , self ) . setdefault ( key , value ) except RuntimeError : self . _defaults . __setitem__ ( key , value )
We may not always be connected to an app but we still need to provide a way to the base environment to set it s defaults .
57,816
def _app ( self ) : if self . app is not None : return self . app ctx = _request_ctx_stack . top if ctx is not None : return ctx . app try : from flask import _app_ctx_stack app_ctx = _app_ctx_stack . top if app_ctx is not None : return app_ctx . app except ImportError : pass raise RuntimeError ( 'assets instance not b...
The application object to work with ; this is either the app that we have been bound to or the current application .
57,817
def from_yaml ( self , path ) : bundles = YAMLLoader ( path ) . load_bundles ( ) for name in bundles : self . register ( name , bundles [ name ] )
Register bundles from a YAML configuration file
57,818
def from_module ( self , path ) : bundles = PythonLoader ( path ) . load_bundles ( ) for name in bundles : self . register ( name , bundles [ name ] )
Register bundles from a Python module
57,819
def handle_unhandled_exception ( exc_type , exc_value , exc_traceback ) : if issubclass ( exc_type , KeyboardInterrupt ) : sys . __excepthook__ ( exc_type , exc_value , exc_traceback ) return logger = logging . getLogger ( __name__ ) logger . critical ( "Unhandled exception" , exc_info = ( exc_type , exc_value , exc_tr...
Handler for unhandled exceptions that will write to the logs
57,820
def write_transcriptions ( utterances : List [ Utterance ] , tgt_dir : Path , ext : str , lazy : bool ) -> None : tgt_dir . mkdir ( parents = True , exist_ok = True ) for utter in utterances : out_path = tgt_dir / "{}.{}" . format ( utter . prefix , ext ) if lazy and out_path . is_file ( ) : continue with out_path . op...
Write the utterance transcriptions to files in the tgt_dir . Is lazy and checks if the file already exists .
57,821
def remove_duplicates ( utterances : List [ Utterance ] ) -> List [ Utterance ] : filtered_utters = [ ] utter_set = set ( ) for utter in utterances : if ( utter . start_time , utter . end_time , utter . text ) in utter_set : continue filtered_utters . append ( utter ) utter_set . add ( ( utter . start_time , utter . en...
Removes utterances with the same start_time end_time and text . Other metadata isn t considered .
57,822
def make_speaker_utters ( utterances : List [ Utterance ] ) -> Dict [ str , List [ Utterance ] ] : speaker_utters = defaultdict ( list ) for utter in utterances : speaker_utters [ utter . speaker ] . append ( utter ) return speaker_utters
Creates a dictionary mapping from speakers to their utterances .
57,823
def remove_too_short ( utterances : List [ Utterance ] , _winlen = 25 , winstep = 10 ) -> List [ Utterance ] : def is_too_short ( utterance : Utterance ) -> bool : charlen = len ( utterance . text ) if ( duration ( utterance ) / winstep ) < charlen : return True else : return False return [ utter for utter in utterance...
Removes utterances that will probably have issues with CTC because of the number of frames being less than the number of tokens in the transcription . Assuming char tokenization to minimize false negatives .
57,824
def min_edit_distance ( source : Sequence [ T ] , target : Sequence [ T ] , ins_cost : Callable [ ... , int ] = lambda _x : 1 , del_cost : Callable [ ... , int ] = lambda _x : 1 , sub_cost : Callable [ ... , int ] = lambda x , y : 0 if x == y else 1 ) -> int : n = len ( target ) m = len ( source ) distance = np . zeros...
Calculates the minimum edit distance between two sequences .
57,825
def word_error_rate ( ref : Sequence [ T ] , hyp : Sequence [ T ] ) -> float : if len ( ref ) == 0 : raise EmptyReferenceException ( "Cannot calculating word error rate against a length 0 " "reference sequence." ) distance = min_edit_distance ( ref , hyp ) return 100 * float ( distance ) / len ( ref )
Calculate the word error rate of a sequence against a reference .
57,826
def dense_to_human_readable ( dense_repr : Sequence [ Sequence [ int ] ] , index_to_label : Dict [ int , str ] ) -> 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 = [ index_to_label [ index ] for index in non_empty_phone...
Converts a dense representation of model decoded output into human readable using a mapping from indices to labels .
57,827
def decode ( model_path_prefix : Union [ str , Path ] , input_paths : Sequence [ Path ] , label_set : Set [ str ] , * , feature_type : str = "fbank" , batch_size : int = 64 , feat_dir : Optional [ Path ] = None , batch_x_name : str = "batch_x:0" , batch_x_lens_name : str = "batch_x_lens:0" , output_name : str = "hyp_de...
Use an existing tensorflow model that exists on disk to decode WAV files .
57,828
def eval ( self , restore_model_path : Optional [ str ] = None ) -> None : saver = tf . train . Saver ( ) with tf . Session ( config = allow_growth_config ) as sess : if restore_model_path : logger . info ( "restoring model from %s" , restore_model_path ) saver . restore ( sess , restore_model_path ) else : assert self...
Evaluates the model on a test set .
57,829
def output_best_scores ( self , best_epoch_str : str ) -> None : BEST_SCORES_FILENAME = "best_scores.txt" with open ( os . path . join ( self . exp_dir , BEST_SCORES_FILENAME ) , "w" , encoding = ENCODING ) as best_f : print ( best_epoch_str , file = best_f , flush = True )
Output best scores to the filesystem
57,830
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 .
57,831
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 .
57,832
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 .
57,833
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 .
57,834
def set_and_check_directories ( self , tgt_dir : Path ) -> None : logger . info ( "Setting up directories for corpus in %s" , tgt_dir ) if not tgt_dir . is_dir ( ) : raise FileNotFoundError ( "The directory {} does not exist." . format ( tgt_dir ) ) if not self . wav_dir . is_dir ( ) : raise PersephoneException ( "The ...
Make sure that the required directories exist in the target directory . set variables accordingly .
57,835
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
57,836
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
57,837
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 .
57,838
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
57,839
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 .
57,840
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 .
57,841
def num_feats ( self ) : if not self . _num_feats : filename = self . get_train_fns ( ) [ 0 ] [ 0 ] feats = np . load ( filename ) if len ( feats . shape ) == 3 : self . _num_feats = feats . shape [ 1 ] * feats . shape [ 2 ] elif len ( feats . shape ) == 2 : self . _num_feats = feats . shape [ 1 ] else : raise ValueErr...
The number of features per time step in the corpus .
57,842
def prefixes_to_fns ( self , prefixes : List [ str ] ) -> Tuple [ List [ str ] , List [ str ] ] : 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 ) ) ) for prefix in prefixes ]...
Fetches the file paths to the features files and labels files corresponding to the provided list of features
57,843
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 .
57,844
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 .
57,845
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 .
57,846
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 .
57,847
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 .
57,848
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 .
57,849
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 .
57,850
def filter_by_size ( feat_dir : Path , prefixes : List [ str ] , feat_type : str , max_samples : int ) -> List [ str ] : prefix_lens = get_prefix_lens ( Path ( feat_dir ) , prefixes , feat_type ) prefixes = [ prefix for prefix , length in prefix_lens if length <= max_samples ] return prefixes
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 .
57,851
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 .
57,852
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 .
57,853
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 .
57,854
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 .
57,855
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 .
57,856
def utterances_from_tier ( eafob : Eaf , tier_name : str ) -> List [ Utterance ] : try : speaker = eafob . tiers [ tier_name ] [ 2 ] [ "PARTICIPANT" ] except KeyError : speaker = None tier_utterances = [ ] annotations = sort_annotations ( list ( eafob . get_annotation_data_for_tier ( tier_name ) ) ) for i , annotation ...
Returns utterances found in the given Eaf object in the given tier .
57,857
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 ) ) : for tier_prefix in tier_...
Extracts utterances in tiers that start with tier_prefixes found in the ELAN . eaf XML file at eaf_path .
57,858
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 .
57,859
def load_batch ( self , fn_batch ) : inverse = list ( zip ( * fn_batch ) ) feat_fn_batch = inverse [ 0 ] target_fn_batch = inverse [ 1 ] batch_inputs , batch_inputs_lens = utils . load_batch_x ( feat_fn_batch , flatten = False ) batch_targets_list = [ ] for targets_path in target_fn_batch : with open ( targets_path , e...
Loads a batch with the given prefixes . The prefixes is the full path to the training example minus the extension .
57,860
def train_batch_gen ( self ) -> Iterator : if len ( self . train_fns ) == 0 : raise PersephoneException ( ) fn_batches = self . make_batches ( self . train_fns ) if self . rand : random . shuffle ( fn_batches ) for fn_batch in fn_batches : logger . debug ( "Batch of training filenames: %s" , pprint . pformat ( fn_batch...
Returns a generator that outputs batches in the training data .
57,861
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 .
57,862
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 .
57,863
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 .
57,864
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 .
57,865
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 def numframes_to_minutes ( num_frames ) : minutes = ( ( num_frames * 10 ) / 1000 ) / 60 return minutes total_frames = 0 train_fns = [ t...
Prints statistics about the the total duration of recordings in the corpus .
57,866
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 .
57,867
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 .
57,868
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
57,869
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 .
57,870
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 .
57,871
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 ) all_feats = np . swapaxes ( all_feats , 0 , 1 ) all_f...
Grabs MFCC features with energy and derivates .
57,872
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 = os . path . splitext ( fn ) if ext == ".wav" : if not os . path . ...
Performs feature extraction from the WAV files in a directory .
57,873
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 .
57,874
def kaldi_pitch ( wav_dir : str , feat_dir : str ) -> None : logger . debug ( "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 . join ( feat_dir , "wavs.scp" ) with...
Extract Kaldi pitch features . Assumes 16k mono wav files .
57,875
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 .
57,876
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 .
57,877
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 : trim_wav_pydub ( in_path , out_path , start_time , end_time ) except subprocess . CalledProcessError : trim_wav_pydub ( in_path ...
Extracts part of a WAV File .
57,878
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 in_e...
Crops the wav file .
57,879
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 .
57,880
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 .
57,881
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 .
57,882
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 .
57,883
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 .
57,884
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 : raise NotImplementedError ( ) alignments = [ min_edit_distance_align ( ref , hyp ) for hyp , ref in zip ( hyps , refs ) ] arrow_cou...
Formats a confusion matrix over substitutions ignoring insertions and deletions .
57,885
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 .
57,886
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 .
57,887
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 .
57,888
def preprocess_french ( trans , fr_nlp , remove_brackets_content = True ) : if remove_brackets_content : trans = pangloss . remove_content_in_brackets ( trans , "[]" ) trans = fr_nlp ( " " . join ( trans . split ( ) [ : ] ) ) trans = " " . join ( [ token . lower_ for token in trans if not token . is_punct ] ) return tr...
Takes a list of sentences in french and preprocesses them .
57,889
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 .
57,890
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 .
57,891
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 .
57,892
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 .
57,893
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 .
57,894
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 .
57,895
def make_data_splits ( self , max_samples , valid_story = None , test_story = None ) : 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 required but for " "now it is." ) train , valid...
Split data into train valid and test groups
57,896
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 .
57,897
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
57,898
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
57,899
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