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_retries ) except : print ( "Cleaning up temp dir..." , file = sys . stderr ) raise
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 : stderr = open ( stderr_filename , "w" ) else : stderr = None subprocess . check_call ( command_list , stdin = stdin , stdout = stdout , stderr = stderr , env = env ) if stdin_filename : stdin . close ( ) if stdout_filename : stdout . close ( ) if stderr_filename : stderr . close ( ) return
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 = subprocess . Popen ( command_list , shell = False , stdin = None , stdout = None , stderr = None , close_fds = True , env = env ) return p
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 : if curr_secs > timeout : print ( "Process time has exceeded timeout, terminating it." ) p . terminate ( ) return False time . sleep ( 0.1 ) curr_secs += 0.1 p . join ( ) return True
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" , input_doc_fname ] try : gs_output = get_external_subprocess_output ( gs_run_command , print_output = True , indent_string = " " , env = gs_environment ) except subprocess . CalledProcessError : print ( "\nError in pdfCropMargins: Ghostscript returned a non-zero exit" "\nstatus when attempting to fix the file:\n " , input_doc_fname , file = sys . stderr ) cleanup_and_exit ( 1 ) except UnicodeDecodeError : print ( "\nWarning in pdfCropMargins: In attempting to repair the PDF file" "\nGhostscript produced a message containing characters which cannot" "\nbe decoded by the 'utf-8' codec. Ignoring and hoping for the best." , file = sys . stderr ) return temp_file_name
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 = "-dUseTrimBox" if "a" in full_page_box : box_arg = "-dUseArtBox" if "b" in full_page_box : box_arg = "-dUseBleedBox" gs_run_command = [ gs_executable , "-dSAFER" , "-dNOPAUSE" , "-dBATCH" , "-sDEVICE=bbox" , box_arg , "-r" + res , input_doc_fname ] try : gs_output = get_external_subprocess_output ( gs_run_command , print_output = False , indent_string = " " , env = gs_environment ) except UnicodeDecodeError : print ( "\nError in pdfCropMargins: In attempting to get the bounding boxes" "\nGhostscript encountered characters which cannot be decoded by the" "\n'utf-8' codec." , file = sys . stderr ) cleanup_and_exit ( 1 ) bounding_box_list = [ ] for line in gs_output : split_line = line . split ( ) if split_line and split_line [ 0 ] == r"%%HiResBoundingBox:" : del split_line [ 0 ] if len ( split_line ) != 4 : print ( "\nWarning from pdfCropMargins: Ignoring this unparsable line" "\nwhen finding the bounding boxes with Ghostscript:" , line , "\n" , file = sys . stderr ) continue bounding_box_list . append ( [ float ( split_line [ 0 ] ) , float ( split_line [ 1 ] ) , float ( split_line [ 2 ] ) , float ( split_line [ 3 ] ) ] ) if not bounding_box_list : print ( "\nError in pdfCropMargins: Ghostscript failed to find any bounding" "\nboxes in the document." , file = sys . stderr ) cleanup_and_exit ( 1 ) return bounding_box_list
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 : command = [ pdftoppm_executable ] + extra_args + [ "-r" , res_x , pdf_file_name , root_output_file_path ] else : command = [ pdftoppm_executable ] + extra_args + [ "-rx" , res_x , "-ry" , res_y , pdf_file_name , root_output_file_path ] comm_output = get_external_subprocess_output ( command ) return comm_output
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=" + root_output_file_path + "-%06d.png" , pdf_file_name ] comm_output = get_external_subprocess_output ( command , env = gs_environment ) return comm_output
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 , "\nwas not found or failed to execute correctly.\n" , file = sys . stderr ) return
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...\n" , file = sys . stderr ) except SystemExit : exit_code = sys . exc_info ( ) [ 1 ] print ( ) except : print ( "\nCaught an unexpected exception in the pdfCropMargins program." , file = sys . stderr ) print ( "Unexpected error: " , sys . exc_info ( ) [ 0 ] , file = sys . stderr ) print ( "Error message : " , sys . exc_info ( ) [ 1 ] , file = sys . stderr ) print ( ) exit_code = 1 import traceback max_traceback_length = 30 traceback . print_tb ( sys . exc_info ( ) [ 2 ] , limit = max_traceback_length ) finally : for i in range ( 30 ) : try : cleanup_and_exit ( exit_code ) except ( KeyboardInterrupt , EOFError ) : continue
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_num ) full_page_box = get_full_page_box_assigning_media_and_crop ( curr_page ) if args . verbose and not quiet : print ( "\t" + str ( page_num + 1 ) , " rot =" , curr_page . rotationAngle , "\t" , full_page_box ) ordinary_box = [ float ( b ) for b in full_page_box ] full_page_box_list . append ( ordinary_box ) rotation_list . append ( curr_page . rotationAngle ) return full_page_box_list , rotation_list
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_cropped_by_this_program = False old_producer_string = metadata_info . producer if old_producer_string and old_producer_string . endswith ( producer_mod ) : if args . verbose : print ( "\nThe document was already cropped at least once by this program." ) already_cropped_by_this_program = True producer_mod = "" def st ( item ) : if item is None : return "" else : return item output_info_dict . update ( { NameObject ( "/Author" ) : createStringObject ( st ( metadata_info . author ) ) , NameObject ( "/Creator" ) : createStringObject ( st ( metadata_info . creator ) ) , NameObject ( "/Producer" ) : createStringObject ( st ( metadata_info . producer ) + producer_mod ) , NameObject ( "/Subject" ) : createStringObject ( st ( metadata_info . subject ) ) , NameObject ( "/Title" ) : createStringObject ( st ( metadata_info . title ) ) } ) return already_cropped_by_this_program
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 it was modified by another program after that. Trying the" "\nundo anyway..." , file = sys . stderr ) if args . restore and args . verbose : print ( "\nRestoring the document to margins saved for each page in the ArtBox." ) if args . verbose and not args . restore : print ( "\nNew full page sizes after cropping, in PDF format (lbrt):" ) for page_num in range ( input_doc . getNumPages ( ) ) : curr_page = input_doc . getPage ( page_num ) curr_page . rotateClockwise ( curr_page . rotationAngle ) if args . restore : if not curr_page . artBox : print ( "\nWarning from pdfCropMargins: Attempting to restore pages from" "\nthe ArtBox in each page, but page" , page_num , "has no readable" "\nArtBox. Leaving that page unchanged." , file = sys . stderr ) continue curr_page . mediaBox = curr_page . artBox curr_page . cropBox = curr_page . artBox continue if not args . noundosave and not already_cropped_by_this_program : curr_page . artBox = intersect_boxes ( curr_page . mediaBox , curr_page . cropBox ) curr_page . mediaBox = curr_page . originalMediaBox curr_page . cropBox = curr_page . originalCropBox if page_num not in page_nums_to_crop : continue new_cropped_box = RectangleObject ( crop_list [ page_num ] ) if args . verbose : print ( "\t" + str ( page_num + 1 ) + "\t" , new_cropped_box ) if not args . boxesToSet : args . boxesToSet = [ "m" , "c" ] if "m" in args . boxesToSet : curr_page . mediaBox = new_cropped_box if "c" in args . boxesToSet : curr_page . cropBox = new_cropped_box if "t" in args . boxesToSet : curr_page . trimBox = new_cropped_box if "a" in args . boxesToSet : curr_page . artBox = new_cropped_box if "b" in args . boxesToSet : curr_page . bleedBox = new_cropped_box return
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 ( input_doc , value ) for key , value in root_object . items ( ) } elif isinstance ( root_object , list ) : return [ root_objects_not_indirect ( input_doc , item ) for item in root_object ] elif isinstance ( root_object , IndirectObject ) : return input_doc . getObject ( root_object ) else : return root_object doc_cat_whitelist = args . docCatWhitelist . split ( ) if "ALL" in doc_cat_whitelist : doc_cat_whitelist = [ "ALL" ] doc_cat_blacklist = args . docCatBlacklist . split ( ) if "ALL" in doc_cat_blacklist : doc_cat_blacklist = [ "ALL" ] if not copy_document_catalog or ( not doc_cat_whitelist and doc_cat_blacklist == [ "ALL" ] ) : if args . verbose : print ( "\nNot copying any document catalog items to the cropped document." ) else : try : root_object = input_doc . trailer [ "/Root" ] copied_items = [ ] skipped_items = [ ] for key , value in root_object . items ( ) : if key == "/Pages" : skipped_items . append ( key ) continue if doc_cat_whitelist != [ "ALL" ] and key not in doc_cat_whitelist : if doc_cat_blacklist == [ "ALL" ] or key in doc_cat_blacklist : skipped_items . append ( key ) continue copied_items . append ( key ) output_doc . _root_object [ NameObject ( key ) ] = value if args . verbose : print ( "\nCopied these items from the document catalog:\n " , end = "" ) print ( * copied_items ) print ( "Skipped copy of these items from the document catalog:\n " , end = "" ) print ( * skipped_items ) except ( KeyboardInterrupt , EOFError ) : raise except : print ( "\nWarning: The document catalog data could not be copied to the" "\nnew, cropped document. Try fixing the PDF document using" "\n'--gsFix' if you have Ghostscript installed." , file = sys . stderr ) output_doc = PdfFileWriter ( ) for page in [ input_doc . getPage ( i ) for i in range ( input_doc . getNumPages ( ) ) ] : output_doc . addPage ( page ) tmp_output_doc = PdfFileWriter ( ) for page in [ tmp_input_doc . getPage ( i ) for i in range ( tmp_input_doc . getNumPages ( ) ) ] : tmp_output_doc . addPage ( page ) already_cropped_by_this_program = set_cropped_metadata ( input_doc , output_doc , metadata_info ) return output_doc , tmp_output_doc , already_cropped_by_this_program
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 bound to an application, ' + 'and no application in current context' )
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_traceback ) )
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 . open ( "w" ) as f : print ( utter . text , file = f )
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 . end_time , utter . text ) ) return filtered_utters
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 utterances if not is_too_short ( utter ) ]
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 ( ( m + 1 , n + 1 ) , dtype = np . int16 ) for i in range ( 1 , m + 1 ) : distance [ i , 0 ] = distance [ i - 1 , 0 ] + ins_cost ( source [ i - 1 ] ) for j in range ( 1 , n + 1 ) : distance [ 0 , j ] = distance [ 0 , j - 1 ] + ins_cost ( target [ j - 1 ] ) for j in range ( 1 , n + 1 ) : for i in range ( 1 , m + 1 ) : distance [ i , j ] = min ( distance [ i - 1 , j ] + ins_cost ( source [ i - 1 ] ) , distance [ i - 1 , j - 1 ] + sub_cost ( source [ i - 1 ] , target [ j - 1 ] ) , distance [ i , j - 1 ] + del_cost ( target [ j - 1 ] ) ) return int ( distance [ len ( source ) , len ( target ) ] )
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_phonemes ] transcripts . append ( transcript ) return transcripts
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_dense_decoded:0" ) -> List [ List [ str ] ] : if not input_paths : raise PersephoneException ( "No untranscribed WAVs to transcribe." ) model_path_prefix = str ( model_path_prefix ) for p in input_paths : if not p . exists ( ) : raise PersephoneException ( "The WAV file path {} does not exist" . format ( p ) ) preprocessed_file_paths = [ ] for p in input_paths : prefix = p . stem feature_file_ext = ".{}.npy" . format ( feature_type ) conventional_npy_location = p . parent . parent / "feat" / ( Path ( prefix + feature_file_ext ) ) if conventional_npy_location . exists ( ) : preprocessed_file_paths . append ( conventional_npy_location ) else : if not feat_dir : feat_dir = p . parent . parent / "feat" if not feat_dir . is_dir ( ) : os . makedirs ( str ( feat_dir ) ) mono16k_wav_path = feat_dir / "{}.wav" . format ( prefix ) feat_path = feat_dir / "{}.{}.npy" . format ( prefix , feature_type ) feat_extract . convert_wav ( p , mono16k_wav_path ) preprocessed_file_paths . append ( feat_path ) if feat_dir : feat_extract . from_dir ( feat_dir , feature_type ) fn_batches = utils . make_batches ( preprocessed_file_paths , batch_size ) metagraph = load_metagraph ( model_path_prefix ) with tf . Session ( ) as sess : metagraph . restore ( sess , model_path_prefix ) for fn_batch in fn_batches : batch_x , batch_x_lens = utils . load_batch_x ( fn_batch ) feed_dict = { batch_x_name : batch_x , batch_x_lens_name : batch_x_lens } dense_decoded = sess . run ( output_name , feed_dict = feed_dict ) indices_to_labels = labels . make_indices_to_labels ( label_set ) human_readable = dense_to_human_readable ( dense_decoded , indices_to_labels ) return human_readable
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 . saved_model_path , "{}" . format ( self . saved_model_path ) logger . info ( "restoring model from %s" , self . saved_model_path ) saver . restore ( sess , self . saved_model_path ) test_x , test_x_lens , test_y = self . corpus_reader . test_batch ( ) feed_dict = { self . batch_x : test_x , self . batch_x_lens : test_x_lens , self . batch_y : test_y } test_ler , dense_decoded , dense_ref = sess . run ( [ self . ler , self . dense_decoded , self . dense_ref ] , feed_dict = feed_dict ) hyps , refs = self . corpus_reader . human_readable_hyp_ref ( dense_decoded , dense_ref ) hyps_dir = os . path . join ( self . exp_dir , "test" ) if not os . path . isdir ( hyps_dir ) : os . mkdir ( hyps_dir ) with open ( os . path . join ( hyps_dir , "hyps" ) , "w" , encoding = ENCODING ) as hyps_f : for hyp in hyps : print ( " " . join ( hyp ) , file = hyps_f ) with open ( os . path . join ( hyps_dir , "refs" ) , "w" , encoding = ENCODING ) as refs_f : for ref in refs : print ( " " . join ( ref ) , file = refs_f ) test_per = utils . batch_per ( hyps , refs ) assert test_per == test_ler with open ( os . path . join ( hyps_dir , "test_per" ) , "w" , encoding = ENCODING ) as per_f : print ( "LER: %f" % ( test_ler ) , file = per_f )
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 . warning ( "train and valid have overlapping items: {}" . format ( train_s & valid_s ) ) raise PersephoneException ( "train and valid have overlapping items: {}" . format ( train_s & valid_s ) ) if train_s & test_s : logger . warning ( "train and test have overlapping items: {}" . format ( train_s & test_s ) ) raise PersephoneException ( "train and test have overlapping items: {}" . format ( train_s & test_s ) ) if valid_s & test_s : logger . warning ( "valid and test have overlapping items: {}" . format ( valid_s & test_s ) ) raise PersephoneException ( "valid and test have overlapping items: {}" . format ( valid_s & test_s ) )
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 prefixes ] else : pass return [ ]
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 ) ) phonemes = set ( ) for fn in os . listdir ( str ( label_dir ) ) : if fn . endswith ( str ( label_type ) ) : with ( label_dir / fn ) . open ( "r" , encoding = ENCODING ) as f : try : line_phonemes = set ( f . readline ( ) . split ( ) ) except UnicodeDecodeError : logger . error ( "Unicode decode error on file %s" , fn ) print ( "Unicode decode error on file {}" . format ( fn ) ) raise phonemes = phonemes . union ( line_phonemes ) return phonemes
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 : Tuple [ str , ... ] = ( "xv" , "rf" ) ) -> CorpusT : if not label_segmenter : raise ValueError ( "A label segmenter must be provided via label_segmenter" ) if isinstance ( tgt_dir , str ) : tgt_dir = Path ( tgt_dir ) utterances = elan . utterances_from_dir ( org_dir , tier_prefixes = tier_prefixes ) if utterance_filter : utterances = [ utter for utter in utterances if utterance_filter ( utter ) ] utterances = utterance . remove_duplicates ( utterances ) if label_segmenter : utterances = [ label_segmenter . segment_labels ( utter ) for utter in utterances ] utterances = utterance . remove_empty_text ( utterances ) utterances = utterance . remove_too_short ( utterances ) tgt_dir . mkdir ( parents = True , exist_ok = True ) utterance . write_transcriptions ( utterances , ( tgt_dir / "label" ) , label_type , lazy = lazy ) wav . extract_wavs ( utterances , ( tgt_dir / "wav" ) , lazy = lazy ) corpus = cls ( feat_type , label_type , tgt_dir , labels = label_segmenter . labels , speakers = speakers ) corpus . utterances = utterances return corpus
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 supplied path requires a 'wav' subdirectory." ) self . feat_dir . mkdir ( parents = True , exist_ok = True ) if not self . label_dir . is_dir ( ) : raise PersephoneException ( "The supplied path requires a 'label' subdirectory." )
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 ( list ( labels ) ) ) } return label_to_index , index_to_label
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 ) continue prefix = os . path . basename ( os . path . splitext ( str ( path ) ) [ 0 ] ) mono16k_wav_path = self . feat_dir / "{}.wav" . format ( prefix ) feat_path = self . feat_dir / "{}.{}.npy" . format ( prefix , self . feat_type ) if not feat_path . is_file ( ) : should_extract_feats = True if not mono16k_wav_path . is_file ( ) : feat_extract . convert_wav ( path , mono16k_wav_path ) if should_extract_feats : feat_extract . from_dir ( self . feat_dir , self . feat_type )
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, validation and tests specified by files" ) self . train_prefixes = self . read_prefixes ( self . train_prefix_fn ) self . valid_prefixes = self . read_prefixes ( self . valid_prefix_fn ) self . test_prefixes = self . read_prefixes ( self . test_prefix_fn ) return prefixes = self . determine_prefixes ( ) prefixes = utils . filter_by_size ( self . feat_dir , prefixes , self . feat_type , max_samples ) if not train_f_exists and not valid_f_exists and not test_f_exists : logger . debug ( "No files supplied to define the split for training, validation" " and tests. Using default." ) train_prefixes , valid_prefixes , test_prefixes = self . divide_prefixes ( prefixes ) self . train_prefixes = train_prefixes self . valid_prefixes = valid_prefixes self . test_prefixes = test_prefixes self . write_prefixes ( train_prefixes , self . train_prefix_fn ) self . write_prefixes ( valid_prefixes , self . valid_prefix_fn ) self . write_prefixes ( test_prefixes , self . test_prefix_fn ) elif not train_f_exists and valid_f_exists and test_f_exists : self . valid_prefixes = self . read_prefixes ( self . valid_prefix_fn ) self . test_prefixes = self . read_prefixes ( self . test_prefix_fn ) train_prefixes = list ( set ( prefixes ) - set ( self . valid_prefixes ) ) self . train_prefixes = list ( set ( train_prefixes ) - set ( self . test_prefixes ) ) self . write_prefixes ( self . train_prefixes , self . train_prefix_fn ) else : raise NotImplementedError ( "The following case has not been implemented:" + "{} exists - {}\n" . format ( self . train_prefix_fn , train_f_exists ) + "{} exists - {}\n" . format ( self . valid_prefix_fn , valid_f_exists ) + "{} exists - {}\n" . format ( self . test_prefix_fn , test_f_exists ) )
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" , "valid" , "test" ] ) ratios = Ratios ( .90 , .05 , .05 ) train_end = int ( ratios . train * len ( prefixes ) ) valid_end = int ( train_end + ratios . valid * len ( prefixes ) ) if valid_end == len ( prefixes ) : valid_end -= 1 if train_end == valid_end : train_end -= 1 random . seed ( seed ) random . shuffle ( prefixes ) train_prefixes = prefixes [ : train_end ] valid_prefixes = prefixes [ train_end : valid_end ] test_prefixes = prefixes [ valid_end : ] assert train_prefixes , "Got empty set for training data" assert valid_prefixes , "Got empty set for validation data" assert test_prefixes , "Got empty set for testing data" return train_prefixes , valid_prefixes , test_prefixes
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 ValueError ( "Feature matrix of shape %s unexpected" % str ( feats . shape ) ) return self . _num_feats
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 ] return feat_fns , label_fns
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 ( ) . strip ( ) print ( "Transcription: {}" . format ( transcript ) ) subprocess . run ( [ "play" , str ( wav_fn ) ] )
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 , ) + matrix . shape [ 1 : ] ) result [ : matrix . shape [ 0 ] ] = matrix return result
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 ( utterances [ 0 ] . shape [ 1 : ] ) batch = np . zeros ( shape ) for i , utt in enumerate ( utterances ) : batch [ i ] = zero_pad ( utt , max_len ) if flatten : batch = collapse ( batch , time_major = time_major ) return batch , np . array ( utter_lens )
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 ( ref ) return macro_per / len ( hyps )
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 float ( length_line [ - 1 ] )
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" , "imi" , "ane" , "kubba" , "kab" , "a-" , "ad" , "a" , "mak" , "selim" , "ngai" , "en" , "yo" , "wud" , "mani" , "yak" , "manu" , "ka-" , "mong" , "manga" , "ka-" , "mane" , "kala" , "name" , "kayo" , "kare" , "laik" , "bale" , "ni" , "rey" , "bu" , "re" , "iman" , "bom" , "wam" , "alu" , "nan" , "kure" , "kuri" , "wam" , "ka" , "ng" , "yi" , "na" , "m" , "arri" , "e" , "kele" , "arri" , "nga" , "kakan" , "ai" , "ning" , "mala" , "ti" , "wolk" , "bo" , "andi" , "ken" , "ba" , "aa" , "kun" , "bini" , "wo" , "bim" , "man" , "bord" , "al" , "mah" , "won" , "ku" , "ay" , "belen" , "wen" , "yah" , "muni" , "bah" , "di" , "mm" , "anu" , "nane" , "ma" , "kum" , "birri" , "ray" , "h" , "kane" , "mumu" , "bi" , "ah" , "i-" , "n" , "mi" , "bedman" , "rud" , "le" , "babu" , "da" , "kakkak" , "yun" , "ande" , "naw" , "kam" , "bolk" , "woy" , "u" , "bi-" , ] ) EN_WORDS_NOT_IN_EN_DICT = set ( [ "screenprinting" ] ) en_words = en_words . difference ( NA_WORDS_IN_EN_DICT ) en_words = en_words | EN_WORDS_NOT_IN_EN_DICT return en_words
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 : continue input ( )
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 in enumerate ( annotations ) : eaf_stem = eafob . eaf_path . stem utter_id = "{}.{}.{}" . format ( eaf_stem , tier_name , i ) start_time = eafob . time_origin + annotation [ 0 ] end_time = eafob . time_origin + annotation [ 1 ] text = annotation [ 2 ] utterance = Utterance ( eafob . media_path , eafob . eaf_path , utter_id , start_time , end_time , text , speaker ) tier_utterances . append ( utterance ) return tier_utterances
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_prefixes : if tier_name . startswith ( tier_prefix ) : utterances . extend ( utterances_from_tier ( eaf , tier_name ) ) break return utterances
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 ( eaf_path , tier_prefixes ) utterances . extend ( eaf_utterances ) return utterances
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 , encoding = ENCODING ) as targets_f : target_indices = self . corpus . labels_to_indices ( targets_f . readline ( ) . split ( ) ) batch_targets_list . append ( target_indices ) batch_targets = utils . target_list_to_sparse_tensor ( batch_targets_list ) return batch_inputs , batch_inputs_lens , batch_targets
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 ) ) yield self . load_batch ( fn_batch ) else : raise StopIteration
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 . indices_to_labels ( hyp ) refs . append ( ref ) hyps . append ( hyp ) return hyps , refs
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 ) return transcripts
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 = [ train_fn [ 0 ] for train_fn in self . train_fns ] num_train_frames = get_number_of_frames ( train_fns ) total_frames += num_train_frames num_valid_frames = get_number_of_frames ( self . corpus . get_valid_fns ( ) [ 0 ] ) total_frames += num_valid_frames num_test_frames = get_number_of_frames ( self . corpus . get_test_fns ( ) [ 0 ] ) total_frames += num_test_frames print ( "Train duration: %0.3f" % numframes_to_minutes ( num_train_frames ) ) print ( "Validation duration: %0.3f" % numframes_to_minutes ( num_valid_frames ) ) print ( "Test duration: %0.3f" % numframes_to_minutes ( num_test_frames ) ) print ( "Total duration: %0.3f" % numframes_to_minutes ( total_frames ) )
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" ) desc = { } desc [ "topology" ] = { "batch_x_name" : self . batch_x . name , "batch_x_lens_name" : self . batch_x_lens . name , "dense_decoded_name" : self . dense_decoded . name } desc [ "model_type" ] = str ( self . __class__ ) for key , val in self . __dict__ . items ( ) : if isinstance ( val , int ) : desc [ str ( key ) ] = val elif isinstance ( val , tf . Tensor ) : desc [ key ] = { "type" : "tf.Tensor" , "name" : val . name , "shape" : str ( val . shape ) , "dtype" : str ( val . dtype ) , "value" : str ( val ) , } elif isinstance ( val , tf . SparseTensor ) : desc [ key ] = { "type" : "tf.SparseTensor" , "value" : str ( val ) , } else : desc [ str ( key ) ] = str ( val ) with open ( json_path , "w" ) as json_desc_f : json . dump ( desc , json_desc_f , skipkeys = True )
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 ] ) delta_feat = python_speech_features . delta ( feat , 2 ) delta_delta_feat = python_speech_features . delta ( delta_feat , 2 ) all_feats = [ feat , delta_feat , delta_delta_feat ] if not flat : all_feats = np . array ( all_feats ) all_feats = np . swapaxes ( all_feats , 0 , 1 ) all_feats = np . swapaxes ( all_feats , 1 , 2 ) else : all_feats = np . concatenate ( all_feats , axis = 1 ) feat_fn = wav_path [ : - 3 ] + "fbank.npy" np . save ( feat_fn , all_feats )
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_feats = np . swapaxes ( all_feats , 1 , 2 ) feat_fn = wav_path [ : - 3 ] + "mfcc13_d.npy" np . save ( feat_fn , all_feats )
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 . exists ( os . path . join ( dirname , "%s.%s.npy" % ( prefix , feat_type ) ) ) : return False return True if all_wavs_processed ( ) : logger . info ( "All WAV files already preprocessed" ) return if feat_type == "pitch" or feat_type == "fbank_and_pitch" : kaldi_pitch ( dirname , dirname ) for filename in os . listdir ( dirname ) : logger . info ( "Preparing %s features for %s" , feat_type , filename ) path = os . path . join ( dirname , filename ) if path . endswith ( ".wav" ) : if empty_wav ( path ) : raise PersephoneException ( "Can't extract features for {} since it is an empty WAV file. Remove it from the corpus." . format ( path ) ) if feat_type == "fbank" : fbank ( path ) elif feat_type == "fbank_and_pitch" : fbank ( path ) prefix = os . path . splitext ( filename ) [ 0 ] combine_fbank_and_pitch ( dirname , prefix ) elif feat_type == "pitch" : pass elif feat_type == "mfcc13_d" : mfcc ( path ) else : logger . warning ( "Feature type not found: %s" , feat_type ) raise PersephoneException ( "Feature type not found: %s" % feat_type )
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 open ( wav_scp_path , "w" ) as wav_scp : for prefix in prefixes : logger . info ( "Writing wav file: %s" , os . path . join ( wav_dir , prefix + ".wav" ) ) print ( prefix , os . path . join ( wav_dir , prefix + ".wav" ) , file = wav_scp ) pitch_scp_path = os . path . join ( feat_dir , "pitch_feats.scp" ) with open ( pitch_scp_path , "w" ) as pitch_scp : for prefix in prefixes : logger . info ( "Writing scp file: %s" , os . path . join ( feat_dir , prefix + ".pitch.txt" ) ) print ( prefix , os . path . join ( feat_dir , prefix + ".pitch.txt" ) , file = pitch_scp ) args = [ os . path . join ( config . KALDI_ROOT , "src/featbin/compute-kaldi-pitch-feats" ) , "scp:%s" % ( wav_scp_path ) , "scp,t:%s" % pitch_scp_path ] logger . info ( "Extracting pitch features from wavs listed in {}" . format ( wav_scp_path ) ) subprocess . run ( args ) for fn in os . listdir ( feat_dir ) : if fn . endswith ( ".pitch.txt" ) : pitch_feats = [ ] with open ( os . path . join ( feat_dir , fn ) ) as f : for line in f : sp = line . split ( ) if len ( sp ) > 1 : pitch_feats . append ( [ float ( sp [ 0 ] ) , float ( sp [ 1 ] ) ] ) prefix , _ = os . path . splitext ( fn ) out_fn = prefix + ".npy" a = np . array ( pitch_feats ) np . save ( os . path . join ( feat_dir , out_fn ) , a )
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 , out_path , start_time , end_time )
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_ext = in_path . suffix [ 1 : ] out_ext = out_path . suffix [ 1 : ] audio = AudioSegment . from_file ( str ( in_path ) , in_ext ) trimmed = audio [ start_time : end_time ] trimmed . export ( str ( out_path ) , format = out_ext , parameters = [ "-ac" , "1" , "-ar" , "16000" ] )
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 = [ config . SOX_PATH , str ( in_path ) , str ( out_path ) , "trim" , str ( start_time_secs ) , "=" + str ( end_time_secs ) ] logger . info ( "Cropping file %s, from start time %d (seconds) to end time %d (seconds), outputting to %s" , in_path , start_time_secs , end_time_secs , out_path ) subprocess . run ( args , check = True )
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 {} already exists and lazy == {}; not " "writing." . format ( out_wav_path , lazy ) ) continue logger . info ( "File {} does not exist and lazy == {}; creating " "it." . format ( out_wav_path , lazy ) ) trim_wav_ms ( utter . org_media_path , out_wav_path , utter . start_time , utter . end_time )
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 . readlines ( ) hyps = [ filter_labels ( line . split ( ) , labels ) for line in lines ] with open ( refs_path ) as refs_f : lines = refs_f . readlines ( ) refs = [ filter_labels ( line . split ( ) , labels ) for line in lines ] only_empty = True for entry in hyps : if entry is not [ ] : only_empty = False break if only_empty : return - 1 return utils . batch_per ( hyps , refs )
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 ( ) , file = out_f ) print ( "\\begin{document}\n" "\\begin{longtable}{ll}" , file = out_f ) print ( r"\toprule" , file = out_f ) for sent in zip ( prefixes , alignments_ ) : prefix = sent [ 0 ] alignments = sent [ 1 : ] print ( "Utterance ID: &" , prefix . strip ( ) . replace ( r"_" , r"\_" ) , r"\\" , file = out_f ) for i , alignment in enumerate ( alignments ) : ref_list = [ ] hyp_list = [ ] for arrow in alignment : if arrow [ 0 ] == arrow [ 1 ] : ref_list . append ( arrow [ 0 ] ) hyp_list . append ( arrow [ 1 ] ) else : ref_list . append ( "\\hl{%s}" % arrow [ 0 ] ) hyp_list . append ( "\\hl{%s}" % arrow [ 1 ] ) print ( "Ref: &" , "" . join ( ref_list ) , r"\\" , file = out_f ) print ( "Hyp: &" , "" . join ( hyp_list ) , r"\\" , file = out_f ) print ( r"\midrule" , file = out_f ) print ( r"\end{longtable}" , file = out_f ) print ( r"\end{document}" , file = out_f )
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_counter = Counter ( ) for alignment in alignments : arrow_counter . update ( alignment ) ref_total = Counter ( ) for alignment in alignments : ref_total . update ( [ arrow [ 0 ] for arrow in alignment ] ) labels = [ label for label , count in sorted ( ref_total . items ( ) , key = lambda x : x [ 1 ] , reverse = True ) if label != "" ] [ : max_width ] format_pieces = [ ] fmt = "{:3} " * ( len ( labels ) + 1 ) format_pieces . append ( fmt . format ( " " , * labels ) ) fmt = "{:3} " + ( "{:<3} " * ( len ( labels ) ) ) for ref in labels : ref_results = [ arrow_counter [ ( ref , hyp ) ] for hyp in labels ] format_pieces . append ( fmt . format ( ref , * ref_results ) ) return "\n" . join ( format_pieces )
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 [ 1 ] ) ) hyps_prefixes . sort ( key = utter_id_key ) with out_fn . open ( "w" ) as out_f : print ( latex_header ( ) , file = out_f ) print ( "\\begin{document}\n" "\\begin{longtable}{ll}" , file = out_f ) print ( r"\toprule" , file = out_f ) for hyp , prefix in hyps_prefixes : print ( "Utterance ID: &" , prefix . strip ( ) . replace ( r"_" , r"\_" ) , "\\\\" , file = out_f ) print ( "Hypothesis: &" , hyp , r"\\" , file = out_f ) print ( "\\midrule" , file = out_f ) print ( r"\end{longtable}" , file = out_f ) print ( r"\end{document}" , file = out_f )
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 trans
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 ( tgt_wav_dir , "WORDLIST" ) ) : os . makedirs ( os . path . join ( tgt_wav_dir , "WORDLIST" ) ) for fn in os . listdir ( org_xml_dir ) : path = os . path . join ( org_xml_dir , fn ) prefix , _ = os . path . splitext ( fn ) if os . path . isdir ( path ) : continue if not path . endswith ( ".xml" ) : continue logging . info ( "Trimming wavs from {}" . format ( fn ) ) rec_type , _ , times , _ = pangloss . get_sents_times_and_translations ( path ) for i , ( start_time , end_time ) in enumerate ( times ) : if prefix . endswith ( "PLUSEGG" ) : in_wav_path = os . path . join ( org_wav_dir , prefix . upper ( ) [ : - len ( "PLUSEGG" ) ] ) + ".wav" else : in_wav_path = os . path . join ( org_wav_dir , prefix . upper ( ) ) + ".wav" headmic_path = os . path . join ( org_wav_dir , prefix . upper ( ) ) + "_HEADMIC.wav" if os . path . isfile ( headmic_path ) : in_wav_path = headmic_path out_wav_path = os . path . join ( tgt_wav_dir , rec_type , "%s.%d.wav" % ( prefix , i ) ) if not os . path . isfile ( in_wav_path ) : raise PersephoneException ( "{} not a file." . format ( in_wav_path ) ) start_time = start_time * ureg . seconds end_time = end_time * ureg . seconds wav . trim_wav_ms ( Path ( in_wav_path ) , Path ( out_wav_path ) , start_time . to ( ureg . milliseconds ) . magnitude , end_time . to ( ureg . milliseconds ) . magnitude )
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 . join ( label_dir , "WORDLIST" ) ) for path in Path ( org_xml_dir ) . glob ( "*.xml" ) : fn = path . name prefix , _ = os . path . splitext ( fn ) rec_type , sents , _ , _ = pangloss . get_sents_times_and_translations ( str ( path ) ) sents = [ preprocess_na ( sent , label_type ) for sent in sents ] for i , sent in enumerate ( sents ) : if sent . strip ( ) == "" : continue out_fn = "%s.%d.%s" % ( prefix , i , label_type ) sent_path = os . path . join ( label_dir , rec_type , out_fn ) with open ( sent_path , "w" ) as sent_f : print ( sent , file = sent_f )
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 . isdir ( feat_dir ) : os . makedirs ( feat_dir ) for fn in os . listdir ( org_dir ) : in_path = os . path . join ( org_dir , fn ) prefix , _ = os . path . splitext ( fn ) mono16k_wav_path = os . path . join ( wav_dir , "%s.wav" % prefix ) if not os . path . isfile ( mono16k_wav_path ) : feat_extract . convert_wav ( Path ( in_path ) , Path ( mono16k_wav_path ) ) wav_fns = os . listdir ( wav_dir ) with ( tgt_dir / "untranscribed_prefixes.txt" ) . open ( "w" ) as prefix_f : for fn in wav_fns : in_fn = os . path . join ( wav_dir , fn ) prefix , _ = os . path . splitext ( fn ) split_id = 0 start , end = 0 , 10 length = utils . wav_length ( in_fn ) while True : sub_wav_prefix = "{}.{}" . format ( prefix , split_id ) print ( sub_wav_prefix , file = prefix_f ) out_fn = os . path . join ( feat_dir , "{}.wav" . format ( sub_wav_prefix ) ) start_time = start * ureg . seconds end_time = end * ureg . seconds if not Path ( out_fn ) . is_file ( ) : wav . trim_wav_ms ( Path ( in_fn ) , Path ( out_fn ) , start_time . to ( ureg . milliseconds ) . magnitude , end_time . to ( ureg . milliseconds ) . magnitude ) if end > length : break start += 10 end += 10 split_id += 1 feat_extract . from_dir ( Path ( os . path . join ( feat_dir ) ) , feat_type = feat_type )
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 ( os . path . join ( feat_dir , "WORDLIST" ) ) : os . makedirs ( os . path . join ( feat_dir , "WORDLIST" ) ) if not os . path . isdir ( os . path . join ( feat_dir , "TEXT" ) ) : os . makedirs ( os . path . join ( feat_dir , "TEXT" ) ) trim_wavs ( org_wav_dir = org_wav_dir , tgt_wav_dir = tgt_wav_dir , org_xml_dir = org_xml_dir ) prefixes = [ ] for fn in os . listdir ( os . path . join ( tgt_wav_dir , "WORDLIST" ) ) : if fn . endswith ( ".wav" ) : pre , _ = os . path . splitext ( fn ) prefixes . append ( os . path . join ( "WORDLIST" , pre ) ) for fn in os . listdir ( os . path . join ( tgt_wav_dir , "TEXT" ) ) : if fn . endswith ( ".wav" ) : pre , _ = os . path . splitext ( fn ) prefixes . append ( os . path . join ( "TEXT" , pre ) ) if feat_type == "phonemes_onehot" : import numpy as np for prefix in prefixes : label_fn = os . path . join ( label_dir , "%s.phonemes" % prefix ) out_fn = os . path . join ( feat_dir , "%s.phonemes_onehot" % prefix ) try : with open ( label_fn ) as label_f : labels = label_f . readlines ( ) [ 0 ] . split ( ) except FileNotFoundError : continue indices = [ PHONEMES_TO_INDICES [ label ] for label in labels ] one_hots = [ [ 0 ] * len ( PHONEMES ) for _ in labels ] for i , index in enumerate ( indices ) : one_hots [ i ] [ index ] = 1 one_hots = np . array ( one_hots ) np . save ( out_fn , one_hots ) else : for prefix in prefixes : wav_fn = os . path . join ( tgt_wav_dir , "%s.wav" % prefix ) mono16k_wav_fn = os . path . join ( feat_dir , "%s.wav" % prefix ) if not os . path . isfile ( mono16k_wav_fn ) : logging . info ( "Normalizing wav {} to a 16k 16KHz mono {}" . format ( wav_fn , mono16k_wav_fn ) ) feat_extract . convert_wav ( wav_fn , mono16k_wav_fn ) feat_extract . from_dir ( Path ( os . path . join ( feat_dir , "WORDLIST" ) ) , feat_type = feat_type ) feat_extract . from_dir ( Path ( os . path . join ( feat_dir , "TEXT" ) ) , feat_type = feat_type )
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 prefixes
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 , test = make_story_splits ( valid_story , test_story , max_samples , self . label_type , tgt_dir = str ( self . tgt_dir ) ) else : train , valid , test = make_data_splits ( self . label_type , train_rec_type = self . train_rec_type , max_samples = max_samples , tgt_dir = str ( self . tgt_dir ) ) self . train_prefixes = train self . valid_prefixes = valid self . test_prefixes = test
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 self . test_prefixes : print ( utter_id . split ( "/" ) [ 1 ] , file = f )
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' ) if os . path . isdir ( q_home ) : return q_home raise RuntimeError ( 'No suitable QHOME.' )
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