idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
38,200
def read_samples_from_file ( self ) : self . log ( u"Loading audio data..." ) if not gf . file_can_be_read ( self . file_path ) : self . log_exc ( u"File '%s' cannot be read" % ( self . file_path ) , None , True , OSError ) convert_audio_file = ( ( self . file_format is None ) or ( ( self . rconf . safety_checks ) and ...
Load the audio samples from file into memory .
38,201
def preallocate_memory ( self , capacity ) : if capacity < 0 : raise ValueError ( u"The capacity value cannot be negative" ) if self . __samples is None : self . log ( u"Not initialized" ) self . __samples = numpy . zeros ( capacity ) self . __samples_length = 0 else : self . log ( [ u"Previous sample length was (sam...
Preallocate memory to store audio samples to avoid repeated new allocations and copies while performing several consecutive append operations .
38,202
def minimize_memory ( self ) : if self . __samples is None : self . log ( u"Not initialized, returning" ) else : self . log ( u"Initialized, minimizing memory..." ) self . preallocate_memory ( self . __samples_length ) self . log ( u"Initialized, minimizing memory... done" )
Reduce the allocated memory to the minimum required to store the current audio samples .
38,203
def add_samples ( self , samples , reverse = False ) : self . log ( u"Adding samples..." ) samples_length = len ( samples ) current_length = self . __samples_length future_length = current_length + samples_length if ( self . __samples is None ) or ( self . __samples_capacity < future_length ) : self . preallocate_memor...
Concatenate the given new samples to the current audio data .
38,204
def reverse ( self ) : if self . __samples is None : if self . file_path is None : self . log_exc ( u"AudioFile object not initialized" , None , True , AudioFileNotInitializedError ) else : self . read_samples_from_file ( ) self . log ( u"Reversing..." ) self . __samples [ 0 : self . __samples_length ] = numpy . flipud...
Reverse the audio data .
38,205
def trim ( self , begin = None , length = None ) : for variable , name in [ ( begin , "begin" ) , ( length , "length" ) ] : if ( variable is not None ) and ( not isinstance ( variable , TimeValue ) ) : raise TypeError ( u"%s is not None or TimeValue" % name ) self . log ( u"Trimming..." ) if ( begin is None ) and ( len...
Get a slice of the audio data of length seconds starting from begin seconds .
38,206
def write ( self , file_path ) : if self . __samples is None : if self . file_path is None : self . log_exc ( u"AudioFile object not initialized" , None , True , AudioFileNotInitializedError ) else : self . read_samples_from_file ( ) self . log ( [ u"Writing audio file '%s'..." , file_path ] ) try : data = ( self . aud...
Write the audio data to file . Return True on success or False otherwise .
38,207
def clear_data ( self ) : self . log ( u"Clear audio_data" ) self . __samples_capacity = 0 self . __samples_length = 0 self . __samples = None
Clear the audio data freeing memory .
38,208
def _update_length ( self ) : if ( self . audio_sample_rate is not None ) and ( self . __samples is not None ) : self . audio_length = TimeValue ( self . __samples_length ) / TimeValue ( self . audio_sample_rate )
Update the audio length property according to the length of the current audio data and audio sample rate .
38,209
def masked_middle_mfcc ( self ) : begin , end = self . _masked_middle_begin_end ( ) return ( self . masked_mfcc ) [ : , begin : end ]
Return the MFCC speech frames in the MIDDLE portion of the wave .
38,210
def masked_middle_map ( self ) : begin , end = self . _masked_middle_begin_end ( ) return self . __mfcc_mask_map [ begin : end ]
Return the map from the MFCC speech frame indices in the MIDDLE portion of the wave to the MFCC FULL frame indices .
38,211
def _binary_search_intervals ( cls , intervals , index ) : start = 0 end = len ( intervals ) - 1 while start <= end : middle_index = start + ( ( end - start ) // 2 ) middle = intervals [ middle_index ] if ( middle [ 0 ] <= index ) and ( index < middle [ 1 ] ) : return middle elif middle [ 0 ] > index : end = middle_ind...
Binary search for the interval containing index assuming there is such an interval . This function should never return None .
38,212
def middle_begin ( self , index ) : if ( index < 0 ) or ( index > self . all_length ) : raise ValueError ( u"The given index is not valid" ) self . __middle_begin = index
Set the index where MIDDLE starts .
38,213
def _compute_mfcc_c_extension ( self ) : self . log ( u"Computing MFCCs using C extension..." ) try : self . log ( u"Importing cmfcc..." ) import aeneas . cmfcc . cmfcc self . log ( u"Importing cmfcc... done" ) self . __mfcc = ( aeneas . cmfcc . cmfcc . compute_from_data ( self . audio_file . audio_samples , self . aud...
Compute MFCCs using the Python C extension cmfcc .
38,214
def _compute_mfcc_pure_python ( self ) : self . log ( u"Computing MFCCs using pure Python code..." ) try : self . __mfcc = MFCC ( rconf = self . rconf , logger = self . logger ) . compute_from_data ( self . audio_file . audio_samples , self . audio_file . audio_sample_rate ) . transpose ( ) self . log ( u"Computing MFC...
Compute MFCCs using the pure Python code .
38,215
def reverse ( self ) : self . log ( u"Reversing..." ) all_length = self . all_length self . __mfcc = self . __mfcc [ : , : : - 1 ] tmp = self . __middle_end self . __middle_end = all_length - self . __middle_begin self . __middle_begin = all_length - tmp if self . __mfcc_mask is not None : self . __mfcc_mask = self . _...
Reverse the audio file .
38,216
def run_vad ( self , log_energy_threshold = None , min_nonspeech_length = None , extend_before = None , extend_after = None ) : def _compute_runs ( array ) : if len ( array ) < 1 : return [ ] return numpy . split ( array , numpy . where ( numpy . diff ( array ) != 1 ) [ 0 ] + 1 ) self . log ( u"Creating VAD object" ) v...
Determine which frames contain speech and nonspeech and store the resulting boolean mask internally .
38,217
def set_head_middle_tail ( self , head_length = None , middle_length = None , tail_length = None ) : for variable , name in [ ( head_length , "head_length" ) , ( middle_length , "middle_length" ) , ( tail_length , "tail_length" ) ] : if ( variable is not None ) and ( not isinstance ( variable , TimeValue ) ) : raise Ty...
Set the HEAD MIDDLE TAIL explicitly .
38,218
def chars ( self ) : if self . lines is None : return 0 return sum ( [ len ( line ) for line in self . lines ] )
Return the number of characters of the text fragment not including the line separators .
38,219
def children_not_empty ( self ) : children = [ ] for child_node in self . fragments_tree . children_not_empty : child_text_file = self . get_subtree ( child_node ) child_text_file . set_language ( child_node . value . language ) children . append ( child_text_file ) return children
Return the direct not empty children of the root of the fragments tree as TextFile objects .
38,220
def characters ( self ) : chars = 0 for fragment in self . fragments : chars += fragment . characters return chars
The number of characters in this text file .
38,221
def add_fragment ( self , fragment , as_last = True ) : if not isinstance ( fragment , TextFragment ) : self . log_exc ( u"fragment is not an instance of TextFragment" , None , True , TypeError ) self . fragments_tree . add_child ( Tree ( value = fragment ) , as_last = as_last )
Add the given text fragment as the first or last child of the root node of the text file tree .
38,222
def set_language ( self , language ) : self . log ( [ u"Setting language: '%s'" , language ] ) for fragment in self . fragments : fragment . language = language
Set the given language for all the text fragments .
38,223
def _read_from_file ( self ) : if not gf . file_can_be_read ( self . file_path ) : self . log_exc ( u"File '%s' cannot be read" % ( self . file_path ) , None , True , OSError ) if self . file_format not in TextFileFormat . ALLOWED_VALUES : self . log_exc ( u"Text file format '%s' is not supported." % ( self . file_form...
Read text fragments from file .
38,224
def _mplain_word_separator ( self ) : word_separator = gf . safe_get ( self . parameters , gc . PPN_TASK_IS_TEXT_MPLAIN_WORD_SEPARATOR , u" " ) if ( word_separator is None ) or ( word_separator == "space" ) : return u" " elif word_separator == "equal" : return u"=" elif word_separator == "pipe" : return u"|" elif word_...
Get the word separator to split words in mplain format .
38,225
def _read_mplain ( self , lines ) : self . log ( u"Parsing fragments from subtitles text format" ) word_separator = self . _mplain_word_separator ( ) self . log ( [ u"Word separator is: '%s'" , word_separator ] ) lines = [ line . strip ( ) for line in lines ] pairs = [ ] i = 1 current = 0 tree = Tree ( ) while current ...
Read text fragments from a multilevel format text file .
38,226
def _read_subtitles ( self , lines ) : self . log ( u"Parsing fragments from subtitles text format" ) id_format = self . _get_id_format ( ) lines = [ line . strip ( ) for line in lines ] pairs = [ ] i = 1 current = 0 while current < len ( lines ) : line_text = lines [ current ] if len ( line_text ) > 0 : fragment_lines...
Read text fragments from a subtitles format text file .
38,227
def _read_parsed ( self , lines ) : self . log ( u"Parsing fragments from parsed text format" ) pairs = [ ] for line in lines : pieces = line . split ( gc . PARSED_TEXT_SEPARATOR ) if len ( pieces ) == 2 : identifier = pieces [ 0 ] . strip ( ) text = pieces [ 1 ] . strip ( ) if len ( identifier ) > 0 : pairs . append (...
Read text fragments from a parsed format text file .
38,228
def _read_plain ( self , lines ) : self . log ( u"Parsing fragments from plain text format" ) id_format = self . _get_id_format ( ) lines = [ line . strip ( ) for line in lines ] pairs = [ ] i = 1 for line in lines : identifier = id_format % i text = line . strip ( ) pairs . append ( ( identifier , [ text ] ) ) i += 1 ...
Read text fragments from a plain format text file .
38,229
def _read_unparsed ( self , lines ) : from bs4 import BeautifulSoup def filter_attributes ( ) : attributes = { } for attribute_name , filter_name in [ ( "class" , gc . PPN_TASK_IS_TEXT_UNPARSED_CLASS_REGEX ) , ( "id" , gc . PPN_TASK_IS_TEXT_UNPARSED_ID_REGEX ) ] : if filter_name in self . parameters : regex_string = se...
Read text fragments from an unparsed format text file .
38,230
def _get_id_format ( self ) : id_format = gf . safe_get ( self . parameters , gc . PPN_TASK_OS_FILE_ID_REGEX , self . DEFAULT_ID_FORMAT , can_return_none = False ) try : identifier = id_format % 1 except ( TypeError , ValueError ) as exc : self . log_exc ( u"String '%s' is not a valid id format" % ( id_format ) , exc ,...
Return the id regex from the parameters
38,231
def _create_text_fragments ( self , pairs ) : self . log ( u"Creating TextFragment objects" ) text_filter = self . _build_text_filter ( ) for pair in pairs : self . add_fragment ( TextFragment ( identifier = pair [ 0 ] , lines = pair [ 1 ] , filtered_lines = text_filter . apply_filter ( pair [ 1 ] ) ) )
Create text fragment objects and append them to this list .
38,232
def _build_text_filter ( self ) : text_filter = TextFilter ( logger = self . logger ) self . log ( u"Created TextFilter object" ) for key , cls , param_name in [ ( gc . PPN_TASK_IS_TEXT_FILE_IGNORE_REGEX , TextFilterIgnoreRegex , "regex" ) , ( gc . PPN_TASK_IS_TEXT_FILE_TRANSLITERATE_MAP , TextFilterTransliterate , "ma...
Build a suitable TextFilter object .
38,233
def add_filter ( self , new_filter , as_last = True ) : if as_last : self . filters . append ( new_filter ) else : self . filters = [ new_filter ] + self . filters
Compose this filter with the given new_filter filter .
38,234
def apply_filter ( self , strings ) : result = strings for filt in self . filters : result = filt . apply_filter ( result ) self . log ( [ u"Applying regex: '%s' => '%s'" , strings , result ] ) return result
Apply the text filter filter to the given list of strings .
38,235
def _build_map ( self ) : if gf . is_py2_narrow_build ( ) : self . log_warn ( u"Running on a Python 2 narrow build: be aware that Unicode chars above 0x10000 cannot be replaced correctly." ) self . trans_map = { } with io . open ( self . file_path , "r" , encoding = "utf-8" ) as file_obj : contents = file_obj . read ( ...
Read the map file at path .
38,236
def _process_map_rule ( self , line ) : result = self . REPLACE_REGEX . match ( line ) if result is not None : what = self . _process_first_group ( result . group ( 1 ) ) replacement = self . _process_second_group ( result . group ( 2 ) ) for char in what : self . trans_map [ char ] = replacement self . log ( [ u"Addin...
Process the line string containing a map rule .
38,237
def _process_first_group ( self , group ) : if "-" in group : if len ( group . split ( "-" ) ) == 2 : arr = group . split ( "-" ) start = self . _parse_codepoint ( arr [ 0 ] ) end = self . _parse_codepoint ( arr [ 1 ] ) else : start = self . _parse_codepoint ( group ) end = start result = [ ] if ( start > - 1 ) and ( e...
Process the first group of a rule .
38,238
def load_job ( self , job ) : if not isinstance ( job , Job ) : self . log_exc ( u"job is not an instance of Job" , None , True , ExecuteJobInputError ) self . job = job
Load the job from the given Job object .
38,239
def execute ( self ) : self . log ( u"Executing job" ) if self . job is None : self . log_exc ( u"The job object is None" , None , True , ExecuteJobExecutionError ) if len ( self . job ) == 0 : self . log_exc ( u"The job has no tasks" , None , True , ExecuteJobExecutionError ) job_max_tasks = self . rconf [ RuntimeConf...
Execute the job that is execute all of its tasks .
38,240
def write_output_container ( self , output_directory_path ) : self . log ( u"Writing output container for this job" ) if self . job is None : self . log_exc ( u"The job object is None" , None , True , ExecuteJobOutputError ) if len ( self . job ) == 0 : self . log_exc ( u"The job has no tasks" , None , True , ExecuteJo...
Write the output container for this job .
38,241
def clean ( self , remove_working_directory = True ) : if remove_working_directory is not None : self . log ( u"Removing working directory... " ) gf . delete_directory ( self . working_directory ) self . working_directory = None self . log ( u"Removing working directory... done" ) self . log ( u"Removing temporary dire...
Remove the temporary directory . If remove_working_directory is True remove the working directory as well otherwise just remove the temporary directory .
38,242
def _read_syncmap_file ( self , path , extension , text = False ) : syncmap = SyncMap ( logger = self . logger ) syncmap . read ( extension , path , parameters = None ) if text : return [ ( f . begin , f . end , u" " . join ( f . text_fragment . lines ) ) for f in syncmap . fragments ] return [ ( f . begin , f . end , ...
Read labels from a SyncMap file
38,243
def has_adjacent_leaves_only ( self ) : leaves = self . leaves ( ) for i in range ( len ( leaves ) - 1 ) : current_interval = leaves [ i ] . interval next_interval = leaves [ i + 1 ] . interval if not current_interval . is_adjacent_before ( next_interval ) : return False return True
Return True if the sync map fragments which are the leaves of the sync map tree are all adjacent .
38,244
def json_string ( self ) : def visit_children ( node ) : output_fragments = [ ] for child in node . children_not_empty : fragment = child . value text = fragment . text_fragment output_fragments . append ( { "id" : text . identifier , "language" : text . language , "lines" : text . lines , "begin" : gf . time_to_ssmmm ...
Return a JSON representation of the sync map .
38,245
def add_fragment ( self , fragment , as_last = True ) : if not isinstance ( fragment , SyncMapFragment ) : self . log_exc ( u"fragment is not an instance of SyncMapFragment" , None , True , TypeError ) self . fragments_tree . add_child ( Tree ( value = fragment ) , as_last = as_last )
Add the given sync map fragment as the first or last child of the root node of the sync map tree .
38,246
def output_html_for_tuning ( self , audio_file_path , output_file_path , parameters = None ) : if not gf . file_can_be_written ( output_file_path ) : self . log_exc ( u"Cannot output HTML file '%s'. Wrong permissions?" % ( output_file_path ) , None , True , OSError ) if parameters is None : parameters = { } audio_file_...
Output an HTML file for fine tuning the sync map manually .
38,247
def _create_dct_matrix ( self ) : self . s2dct = numpy . zeros ( ( self . mfcc_size , self . filter_bank_size ) ) for i in range ( 0 , self . mfcc_size ) : freq = numpy . pi * float ( i ) / self . filter_bank_size self . s2dct [ i ] = numpy . cos ( freq * numpy . arange ( 0.5 , 0.5 + self . filter_bank_size , 1.0 , 'fl...
Create the not - quite - DCT matrix as used by Sphinx and store it in self . s2dct .
38,248
def _create_mel_filter_bank ( self ) : self . filters = numpy . zeros ( ( 1 + ( self . fft_order // 2 ) , self . filter_bank_size ) , 'd' ) dfreq = float ( self . sample_rate ) / self . fft_order nyquist_frequency = self . sample_rate / 2 if self . upper_frequency > nyquist_frequency : self . log_exc ( u"Upper frequenc...
Create the Mel filter bank and store it in self . filters .
38,249
def _pre_emphasis ( self ) : self . data = numpy . append ( self . data [ 0 ] , self . data [ 1 : ] - self . emphasis_factor * self . data [ : - 1 ] )
Pre - emphasize the entire signal at once by self . emphasis_factor overwriting self . data .
38,250
def compute_from_data ( self , data , sample_rate ) : def _process_frame ( self , frame ) : frame *= self . hamming_window fft = numpy . fft . rfft ( frame , self . fft_order ) power = numpy . square ( numpy . absolute ( fft ) ) return numpy . log ( numpy . dot ( power , self . filters ) . clip ( self . CUTOFF , numpy ...
Compute MFCCs for the given audio data .
38,251
def write ( filename , rate , data ) : if hasattr ( filename , 'write' ) : fid = filename else : fid = open ( filename , 'wb' ) try : dkind = data . dtype . kind if not ( dkind == 'i' or dkind == 'f' or ( dkind == 'u' and data . dtype . itemsize == 1 ) ) : raise ValueError ( "Unsupported data type '%s'" % data . dtype ...
Write a numpy array as a WAV file
38,252
def safe_print ( msg ) : try : print ( msg ) except UnicodeEncodeError : try : encoded = msg . encode ( sys . stdout . encoding , "replace" ) decoded = encoded . decode ( sys . stdout . encoding , "replace" ) print ( decoded ) except ( UnicodeDecodeError , UnicodeEncodeError ) : print ( u"[ERRO] An unexpected error hap...
Safely print a given Unicode string to stdout possibly replacing characters non - printable in the current stdout encoding .
38,253
def print_error ( msg , color = True ) : if color and is_posix ( ) : safe_print ( u"%s[ERRO] %s%s" % ( ANSI_ERROR , msg , ANSI_END ) ) else : safe_print ( u"[ERRO] %s" % ( msg ) )
Print an error message .
38,254
def print_success ( msg , color = True ) : if color and is_posix ( ) : safe_print ( u"%s[INFO] %s%s" % ( ANSI_OK , msg , ANSI_END ) ) else : safe_print ( u"[INFO] %s" % ( msg ) )
Print a success message .
38,255
def print_warning ( msg , color = True ) : if color and is_posix ( ) : safe_print ( u"%s[WARN] %s%s" % ( ANSI_WARNING , msg , ANSI_END ) ) else : safe_print ( u"[WARN] %s" % ( msg ) )
Print a warning message .
38,256
def file_extension ( path ) : if path is None : return None ext = os . path . splitext ( os . path . basename ( path ) ) [ 1 ] if ext . startswith ( "." ) : ext = ext [ 1 : ] return ext
Return the file extension .
38,257
def mimetype_from_path ( path ) : extension = file_extension ( path ) if extension is not None : extension = extension . lower ( ) if extension in gc . MIMETYPE_MAP : return gc . MIMETYPE_MAP [ extension ] return None
Return a mimetype from the file extension .
38,258
def file_name_without_extension ( path ) : if path is None : return None return os . path . splitext ( os . path . basename ( path ) ) [ 0 ]
Return the file name without extension .
38,259
def safe_float ( string , default = None ) : value = default try : value = float ( string ) except TypeError : pass except ValueError : pass return value
Safely parse a string into a float .
38,260
def safe_int ( string , default = None ) : value = safe_float ( string , default ) if value is not None : value = int ( value ) return value
Safely parse a string into an int .
38,261
def safe_get ( dictionary , key , default_value , can_return_none = True ) : return_value = default_value try : return_value = dictionary [ key ] if ( return_value is None ) and ( not can_return_none ) : return_value = default_value except ( KeyError , TypeError ) : pass return return_value
Safely perform a dictionary get returning the default value if the key is not found .
38,262
def norm_join ( prefix , suffix ) : if ( prefix is None ) and ( suffix is None ) : return "." if prefix is None : return os . path . normpath ( suffix ) if suffix is None : return os . path . normpath ( prefix ) return os . path . normpath ( os . path . join ( prefix , suffix ) )
Join prefix and suffix paths and return the resulting path normalized .
38,263
def copytree ( source_directory , destination_directory , ignore = None ) : if os . path . isdir ( source_directory ) : if not os . path . isdir ( destination_directory ) : os . makedirs ( destination_directory ) files = os . listdir ( source_directory ) if ignore is not None : ignored = ignore ( source_directory , fil...
Recursively copy the contents of a source directory into a destination directory . Both directories must exist .
38,264
def ensure_parent_directory ( path , ensure_parent = True ) : parent_directory = os . path . abspath ( path ) if ensure_parent : parent_directory = os . path . dirname ( parent_directory ) if not os . path . exists ( parent_directory ) : try : os . makedirs ( parent_directory ) except ( IOError , OSError ) : raise OSEr...
Ensures the parent directory exists .
38,265
def can_run_c_extension ( name = None ) : def can_run_cdtw ( ) : try : import aeneas . cdtw . cdtw return True except ImportError : return False def can_run_cmfcc ( ) : try : import aeneas . cmfcc . cmfcc return True except ImportError : return False def can_run_cew ( ) : try : import aeneas . cew . cew return True exc...
Determine whether the given Python C extension loads correctly .
38,266
def run_c_extension_with_fallback ( log_function , extension , c_function , py_function , args , rconf ) : computed = False if not rconf [ u"c_extensions" ] : log_function ( u"C extensions disabled" ) elif extension not in rconf : log_function ( [ u"C extension '%s' not recognized" , extension ] ) elif not rconf [ exte...
Run a function calling a C extension falling back to a pure Python function if the former does not succeed .
38,267
def file_can_be_read ( path ) : if path is None : return False try : with io . open ( path , "rb" ) as test_file : pass return True except ( IOError , OSError ) : pass return False
Return True if the file at the given path can be read .
38,268
def file_can_be_written ( path ) : if path is None : return False try : with io . open ( path , "wb" ) as test_file : pass delete_file ( None , path ) return True except ( IOError , OSError ) : pass return False
Return True if a file can be written at the given path .
38,269
def read_file_bytes ( input_file_path ) : contents = None try : with io . open ( input_file_path , "rb" ) as input_file : contents = input_file . read ( ) except : pass return contents
Read the file at the given file path and return its contents as a byte string or None if an error occurred .
38,270
def human_readable_number ( number , suffix = "" ) : for unit in [ "" , "K" , "M" , "G" , "T" , "P" , "E" , "Z" ] : if abs ( number ) < 1024.0 : return "%3.1f%s%s" % ( number , unit , suffix ) number /= 1024.0 return "%.1f%s%s" % ( number , "Y" , suffix )
Format the given number into a human - readable string .
38,271
def safe_unichr ( codepoint ) : if is_py2_narrow_build ( ) : return ( "\\U%08x" % codepoint ) . decode ( "unicode-escape" ) elif PY2 : return unichr ( codepoint ) return chr ( codepoint )
Safely return a Unicode string of length one containing the Unicode character with given codepoint .
38,272
def safe_unicode_stdin ( string ) : if string is None : return None if is_bytes ( string ) : if FROZEN : return string . decode ( "utf-8" ) try : return string . decode ( sys . stdin . encoding ) except UnicodeDecodeError : return string . decode ( sys . stdin . encoding , "replace" ) except : return string . decode ( ...
Safely convert the given string to a Unicode string decoding using sys . stdin . encoding if needed .
38,273
def get ( self , fragment_info ) : if not self . is_cached ( fragment_info ) : raise KeyError ( u"Attempt to get text not cached" ) return self . cache [ fragment_info ]
Get the value associated with the given key .
38,274
def clear ( self ) : self . log ( u"Clearing cache..." ) for file_handler , file_info in self . cache . values ( ) : self . log ( [ u" Removing file '%s'" , file_info ] ) gf . delete_file ( file_handler , file_info ) self . _initialize_cache ( ) self . log ( u"Clearing cache... done" )
Clear the cache and remove all the files from disk .
38,275
def _language_to_voice_code ( self , language ) : voice_code = self . rconf [ RuntimeConfiguration . TTS_VOICE_CODE ] if voice_code is None : try : voice_code = self . LANGUAGE_TO_VOICE_CODE [ language ] except KeyError as exc : self . log_exc ( u"Language code '%s' not found in LANGUAGE_TO_VOICE_CODE" % ( language ) ,...
Translate a language value to a voice code .
38,276
def clear_cache ( self ) : if self . use_cache : self . log ( u"Requested to clear TTS cache" ) self . cache . clear ( )
Clear the TTS cache removing all cache files from disk .
38,277
def set_subprocess_arguments ( self , subprocess_arguments ) : self . subprocess_arguments = subprocess_arguments self . log ( [ u"Subprocess arguments: %s" , subprocess_arguments ] )
Set the list of arguments that the wrapper will pass to subprocess .
38,278
def synthesize_multiple ( self , text_file , output_file_path , quit_after = None , backwards = False ) : if text_file is None : self . log_exc ( u"text_file is None" , None , True , TypeError ) if len ( text_file ) < 1 : self . log_exc ( u"The text file has no fragments" , None , True , ValueError ) if text_file . cha...
Synthesize the text contained in the given fragment list into a WAVE file .
38,279
def _synthesize_multiple_python ( self , text_file , output_file_path , quit_after = None , backwards = False ) : self . log ( u"Synthesizing multiple via a Python call..." ) ret = self . _synthesize_multiple_generic ( helper_function = self . _synthesize_single_python_helper , text_file = text_file , output_file_path ...
Synthesize multiple fragments via a Python call .
38,280
def _synthesize_multiple_subprocess ( self , text_file , output_file_path , quit_after = None , backwards = False ) : self . log ( u"Synthesizing multiple via subprocess..." ) ret = self . _synthesize_multiple_generic ( helper_function = self . _synthesize_single_subprocess_helper , text_file = text_file , output_file_...
Synthesize multiple fragments via subprocess .
38,281
def _read_audio_data ( self , file_path ) : try : self . log ( u"Reading audio data..." ) audio_file = AudioFile ( file_path = file_path , file_format = self . OUTPUT_AUDIO_FORMAT , rconf = self . rconf , logger = self . logger ) audio_file . read_samples_from_file ( ) self . log ( [ u"Duration of '%s': %f" , file_path...
Read audio data from file .
38,282
def _loop_no_cache ( self , helper_function , num , fragment ) : self . log ( [ u"Examining fragment %d (no cache)..." , num ] ) voice_code = self . _language_to_voice_code ( fragment . language ) self . log ( u"Calling helper function" ) succeeded , data = helper_function ( text = fragment . filtered_text , voice_code...
Synthesize all fragments without using the cache
38,283
def _loop_use_cache ( self , helper_function , num , fragment ) : self . log ( [ u"Examining fragment %d (cache)..." , num ] ) fragment_info = ( fragment . language , fragment . filtered_text ) if self . cache . is_cached ( fragment_info ) : self . log ( u"Fragment cached: retrieving audio data from cache" ) file_handl...
Synthesize all fragments using the cache
38,284
def adjust ( self , aba_parameters , boundary_indices , real_wave_mfcc , text_file , allow_arbitrary_shift = False ) : self . log ( u"Called adjust" ) if boundary_indices is None : self . log_exc ( u"boundary_indices is None" , None , True , TypeError ) if not isinstance ( real_wave_mfcc , AudioFileMFCC ) : self . log_...
Adjust the boundaries of the text map using the algorithm and parameters specified in the constructor storing the sync map fragment list internally .
38,285
def append_fragment_list_to_sync_root ( self , sync_root ) : if not isinstance ( sync_root , Tree ) : self . log_exc ( u"sync_root is not a Tree object" , None , True , TypeError ) self . log ( u"Appending fragment list to sync root..." ) for fragment in self . smflist : sync_root . add_child ( Tree ( value = fragment ...
Append the sync map fragment list to the given node from a sync map tree .
38,286
def _process_zero_length ( self , nozero , allow_arbitrary_shift ) : self . log ( u"Called _process_zero_length" ) if not nozero : self . log ( u"Processing zero length intervals not requested: returning" ) return self . log ( u"Processing zero length intervals requested" ) self . log ( u" Checking and fixing..." ) du...
If nozero is True modify the sync map fragment list so that no fragment will have zero length .
38,287
def main ( ) : if FROZEN : HydraCLI ( invoke = "aeneas-cli" ) . run ( arguments = sys . argv , show_help = False ) else : HydraCLI ( invoke = "pyinstaller-aeneas-cli.py" ) . run ( arguments = sys . argv , show_help = False )
This is the aeneas - cli hydra script to be compiled by pyinstaller .
38,288
def run_vad ( self , wave_energy , log_energy_threshold = None , min_nonspeech_length = None , extend_before = None , extend_after = None ) : self . log ( u"Computing VAD for wave" ) mfcc_window_shift = self . rconf . mws self . log ( [ u"MFCC window shift (s): %.3f" , mfcc_window_shift ] ) if log_energy_thresh...
Compute the time intervals containing speech and nonspeech and return a boolean mask with speech frames set to True and nonspeech frames set to False .
38,289
def _compute_runs ( self , array ) : if len ( array ) < 1 : return [ ] return numpy . split ( array , numpy . where ( numpy . diff ( array ) != 1 ) [ 0 ] + 1 )
Compute runs as a list of arrays each containing the indices of a contiguous run .
38,290
def _rolling_window ( self , array , size ) : shape = array . shape [ : - 1 ] + ( array . shape [ - 1 ] - size + 1 , size ) strides = array . strides + ( array . strides [ - 1 ] , ) return numpy . lib . stride_tricks . as_strided ( array , shape = shape , strides = strides )
Compute rolling windows of width size of the given array .
38,291
def usage ( self ) : retval , stderr , stdout = _pysam_dispatch ( self . collection , self . dispatch , is_usage = True , catch_stdout = True ) if stderr : return stderr else : return stdout
return the samtools usage information for this command
38,292
def iterate ( infile ) : conv_subst = ( str , lambda x : int ( x ) - 1 , str , str , int , int , int , int , str , str ) conv_indel = ( str , lambda x : int ( x ) - 1 , str , str , int , int , int , int , str , str , int , int , int ) for line in infile : d = line [ : - 1 ] . split ( ) if d [ 2 ] == "*" : try : yield P...
iterate over samtools pileup - c formatted file .
38,293
def vcf2pileup ( vcf , sample ) : chromosome = vcf . contig pos = vcf . pos reference = vcf . ref allelles = [ reference ] + vcf . alt data = vcf [ sample ] genotypes = data [ "GT" ] if len ( genotypes ) > 1 : raise ValueError ( "only single genotype per position, %s" % ( str ( vcf ) ) ) genotypes = genotypes [ 0 ] if ...
convert vcf record to pileup record .
38,294
def iterate_from_vcf ( infile , sample ) : vcf = pysam . VCF ( ) vcf . connect ( infile ) if sample not in vcf . getsamples ( ) : raise KeyError ( "sample %s not vcf file" ) for row in vcf . fetch ( ) : result = vcf2pileup ( row , sample ) if result : yield result
iterate over a vcf - formatted file .
38,295
def _update_pysam_files ( cf , destdir ) : basename = os . path . basename ( destdir ) for filename in cf : if not filename : continue dest = filename + ".pysam.c" with open ( filename , encoding = "utf-8" ) as infile : lines = "" . join ( infile . readlines ( ) ) with open ( dest , "w" , encoding = "utf-8" ) as outfil...
update pysam files applying redirection of ouput
38,296
def get_include ( ) : dirname = os . path . abspath ( os . path . join ( os . path . dirname ( __file__ ) ) ) htslib_possibilities = [ os . path . join ( dirname , '..' , 'htslib' ) , os . path . join ( dirname , 'include' , 'htslib' ) ] samtool_possibilities = [ os . path . join ( dirname , '..' , 'samtools' ) , os . ...
return a list of include directories .
38,297
def get_libraries ( ) : dirname = os . path . abspath ( os . path . join ( os . path . dirname ( __file__ ) ) ) pysam_libs = [ 'libctabixproxies' , 'libcfaidx' , 'libcsamfile' , 'libcvcf' , 'libcbcf' , 'libctabix' ] if pysam . config . HTSLIB == "builtin" : pysam_libs . append ( 'libchtslib' ) so = sysconfig . get_conf...
return a list of libraries to link against .
38,298
def has_edge ( self , edge ) : u , v = edge return ( u , v ) in self . edge_properties
Return whether an edge exists .
38,299
def dump_package_data ( data , buf , format_ = FileFormat . py , skip_attributes = None ) : if format_ == FileFormat . txt : raise ValueError ( "'txt' format not supported for packages." ) data_ = dict ( ( k , v ) for k , v in data . iteritems ( ) if v is not None ) data_ = package_serialise_schema . validate ( data_ )...
Write package data to buf .