signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
---|---|---|---|
@classmethod<EOL><INDENT>def _get_voters(cls, session, owner_id, poll_id, answer_id):<DEDENT> | from .users import User<EOL>return session.fetch_items("<STR_LIT>", User._get_users, count=<NUM_LIT:100>, owner_id=owner_id, poll_id=poll_id, answer_ids=answer_id)<EOL> | https://vk.com/dev/polls.getVoters | f2458:c1:m2 |
def _convert_list2str(self, fields): | if isinstance(fields, tuple) or isinstance(fields, list):<EOL><INDENT>return '<STR_LIT:U+002C>'.join(fields)<EOL><DEDENT>return fields<EOL> | :param fields: ('bdate', 'domain')
:return: 'bdate,domain' | f2459:c0:m4 |
def grouper(iterable, n): | for i in range(<NUM_LIT:0>, len(iterable), n):<EOL><INDENT>yield iterable[i:i+n]<EOL><DEDENT> | grouper([0,1,2,3,4], 3) --> [(0,1,2), (3,4)] | f2463:m0 |
def get_city(self): | response = self._session.fetch("<STR_LIT>", user_ids=self.id, fields="<STR_LIT>")[<NUM_LIT:0>]<EOL>if response.get('<STR_LIT>'):<EOL><INDENT>return City.from_json(self._session, response.get('<STR_LIT>'))<EOL><DEDENT> | :return: City or None | f2463:c0:m5 |
def get_country(self): | response = self._session.fetch("<STR_LIT>", user_ids=self.id, fields="<STR_LIT>")[<NUM_LIT:0>]<EOL>if response.get('<STR_LIT>'):<EOL><INDENT>return Country.from_json(self._session, response.get('<STR_LIT>'))<EOL><DEDENT> | :return: Country or None | f2463:c0:m11 |
@classmethod<EOL><INDENT>def _sex(cls, sex):<DEDENT> | sex_items = {<EOL><NUM_LIT:1>: '<STR_LIT>',<EOL><NUM_LIT:2>: '<STR_LIT>'<EOL>}<EOL>return sex_items.get(sex)<EOL> | :param sex: {integer}
:return: {string, None} | f2463:c0:m13 |
def get_followers(self): | response = self._session.fetch_items("<STR_LIT>", self.from_json, self._session, count=<NUM_LIT:1000>, user_id=self.id, fields=self.USER_FIELDS)<EOL>return response<EOL> | https://vk.com/dev/users.getFollowers | f2463:c0:m17 |
@staticmethod<EOL><INDENT>def _get_user(session, slug_or_user_id):<DEDENT> | user_json_items = session.fetch('<STR_LIT>', user_ids=slug_or_user_id, fields=User.USER_FIELDS)<EOL>return User.from_json(session, user_json_items[<NUM_LIT:0>])<EOL> | :param slug_or_user_id: str or int
:return: User | f2463:c0:m38 |
@staticmethod<EOL><INDENT>def _get_comments(session, group_or_user_id, wall_id):<DEDENT> | return session.fetch_items("<STR_LIT>", Comment.from_json, count=<NUM_LIT:100>, owner_id=group_or_user_id, post_id=wall_id, need_likes=<NUM_LIT:1>)<EOL> | https://vk.com/dev/wall.getComments | f2465:c0:m1 |
@staticmethod<EOL><INDENT>def _get_comments_count(session, group_or_user_id, wall_id):<DEDENT> | response = session.fetch("<STR_LIT>", count=<NUM_LIT:100>, owner_id=group_or_user_id, post_id=wall_id)<EOL>return response.get('<STR_LIT:count>')<EOL> | https://vk.com/dev/wall.getComments | f2465:c0:m2 |
def get_likes(self): | from .users import User<EOL>return self._session.fetch_items('<STR_LIT>', User._get_user, count=<NUM_LIT:100>, type='<STR_LIT>', owner_id=self.from_id, item_id=self.id)<EOL> | https://vk.com/dev/likes.getList | f2466:c0:m3 |
def get_likes_count(self): | response = self._session.fetch('<STR_LIT>', count=<NUM_LIT:1>, type='<STR_LIT>', owner_id=self.from_id, item_id=self.id)<EOL>likes_count = response.get('<STR_LIT:count>')<EOL>return likes_count<EOL> | https://vk.com/dev/likes.getList | f2466:c0:m4 |
def get_reposts(self): | return self._session.fetch_items('<STR_LIT>', self.from_json, count=<NUM_LIT:1000>, owner_id=self.from_id, post_id=self.id)<EOL> | https://vk.com/dev/wall.getReposts | f2466:c0:m5 |
@staticmethod<EOL><INDENT>def _get_walls(session, owner_id):<DEDENT> | return session.fetch_items("<STR_LIT>", Wall.from_json, <NUM_LIT:100>, owner_id=owner_id)<EOL> | https://vk.com/dev/wall.get | f2466:c0:m12 |
@staticmethod<EOL><INDENT>def _wall_post(session, owner_id, message=None, attachments=None, from_group=True):<DEDENT> | response = session.fetch("<STR_LIT>", owner_id=owner_id, message=message, attachments=attachments, from_group=from_group)<EOL>return response<EOL> | https://vk.com/dev/wall.post
attachments: "photo100172_166443618,photo-1_265827614" | f2466:c0:m14 |
def ctc_beam_search_decoder(probs_seq,<EOL>alphabet,<EOL>beam_size,<EOL>cutoff_prob=<NUM_LIT:1.0>,<EOL>cutoff_top_n=<NUM_LIT>,<EOL>scorer=None): | beam_results = swigwrapper.ctc_beam_search_decoder(<EOL>probs_seq, alphabet.config_file(), beam_size, cutoff_prob, cutoff_top_n,<EOL>scorer)<EOL>beam_results = [(res.probability, alphabet.decode(res.tokens)) for res in beam_results]<EOL>return beam_results<EOL> | Wrapper for the CTC Beam Search Decoder.
:param probs_seq: 2-D list of probability distributions over each time
step, with each element being a list of normalized
probabilities over alphabet and blank.
:type probs_seq: 2-D list
:param alphabet: alphabet list.
:alphabet: Alphabet
:param beam_size: Width for beam search.
:type beam_size: int
:param cutoff_prob: Cutoff probability in pruning,
default 1.0, no pruning.
:type cutoff_prob: float
:param cutoff_top_n: Cutoff number in pruning, only top cutoff_top_n
characters with highest probs in alphabet will be
used in beam search, default 40.
:type cutoff_top_n: int
:param scorer: External scorer for partially decoded sentence, e.g. word
count or language model.
:type scorer: Scorer
:return: List of tuples of log probability and sentence as decoding
results, in descending order of the probability.
:rtype: list | f2470:m0 |
def ctc_beam_search_decoder_batch(probs_seq,<EOL>seq_lengths,<EOL>alphabet,<EOL>beam_size,<EOL>num_processes,<EOL>cutoff_prob=<NUM_LIT:1.0>,<EOL>cutoff_top_n=<NUM_LIT>,<EOL>scorer=None): | batch_beam_results = swigwrapper.ctc_beam_search_decoder_batch(<EOL>probs_seq, seq_lengths, alphabet.config_file(), beam_size, num_processes,<EOL>cutoff_prob, cutoff_top_n, scorer)<EOL>batch_beam_results = [<EOL>[(res.probability, alphabet.decode(res.tokens)) for res in beam_results]<EOL>for beam_results in batch_beam_results<EOL>]<EOL>return batch_beam_results<EOL> | Wrapper for the batched CTC beam search decoder.
:param probs_seq: 3-D list with each element as an instance of 2-D list
of probabilities used by ctc_beam_search_decoder().
:type probs_seq: 3-D list
:param alphabet: alphabet list.
:alphabet: Alphabet
:param beam_size: Width for beam search.
:type beam_size: int
:param num_processes: Number of parallel processes.
:type num_processes: int
:param cutoff_prob: Cutoff probability in alphabet pruning,
default 1.0, no pruning.
:type cutoff_prob: float
:param cutoff_top_n: Cutoff number in pruning, only top cutoff_top_n
characters with highest probs in alphabet will be
used in beam search, default 40.
:type cutoff_top_n: int
:param num_processes: Number of parallel processes.
:type num_processes: int
:param scorer: External scorer for partially decoded sentence, e.g. word
count or language model.
:type scorer: Scorer
:return: List of tuples of log probability and sentence as decoding
results, in descending order of the probability.
:rtype: list | f2470:m1 |
def variable_on_cpu(name, shape, initializer): | <EOL>with tf.device(Config.cpu_device):<EOL><INDENT>var = tf.get_variable(name=name, shape=shape, initializer=initializer)<EOL><DEDENT>return var<EOL> | r"""
Next we concern ourselves with graph creation.
However, before we do so we must introduce a utility function ``variable_on_cpu()``
used to create a variable in CPU memory. | f2476:m0 |
def calculate_mean_edit_distance_and_loss(iterator, dropout, reuse): | <EOL>(batch_x, batch_seq_len), batch_y = iterator.get_next()<EOL>logits, _ = create_model(batch_x, batch_seq_len, dropout, reuse=reuse)<EOL>total_loss = tf.nn.ctc_loss(labels=batch_y, inputs=logits, sequence_length=batch_seq_len)<EOL>avg_loss = tf.reduce_mean(total_loss)<EOL>return avg_loss<EOL> | r'''
This routine beam search decodes a mini-batch and calculates the loss and mean edit distance.
Next to total and average loss it returns the mean edit distance,
the decoded result and the batch's original Y. | f2476:m6 |
def get_tower_results(iterator, optimizer, dropout_rates): | <EOL>tower_avg_losses = []<EOL>tower_gradients = []<EOL>with tf.variable_scope(tf.get_variable_scope()):<EOL><INDENT>for i in range(len(Config.available_devices)):<EOL><INDENT>device = Config.available_devices[i]<EOL>with tf.device(device):<EOL><INDENT>with tf.name_scope('<STR_LIT>' % i):<EOL><INDENT>avg_loss = calculate_mean_edit_distance_and_loss(iterator, dropout_rates, reuse=i > <NUM_LIT:0>)<EOL>tf.get_variable_scope().reuse_variables()<EOL>tower_avg_losses.append(avg_loss)<EOL>gradients = optimizer.compute_gradients(avg_loss)<EOL>tower_gradients.append(gradients)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>avg_loss_across_towers = tf.reduce_mean(tower_avg_losses, <NUM_LIT:0>)<EOL>tf.summary.scalar(name='<STR_LIT>', tensor=avg_loss_across_towers, collections=['<STR_LIT>'])<EOL>return tower_gradients, avg_loss_across_towers<EOL> | r'''
With this preliminary step out of the way, we can for each GPU introduce a
tower for which's batch we calculate and return the optimization gradients
and the average loss across towers. | f2476:m8 |
def average_gradients(tower_gradients): | <EOL>average_grads = []<EOL>with tf.device(Config.cpu_device):<EOL><INDENT>for grad_and_vars in zip(*tower_gradients):<EOL><INDENT>grads = []<EOL>for g, _ in grad_and_vars:<EOL><INDENT>expanded_g = tf.expand_dims(g, <NUM_LIT:0>)<EOL>grads.append(expanded_g)<EOL><DEDENT>grad = tf.concat(grads, <NUM_LIT:0>)<EOL>grad = tf.reduce_mean(grad, <NUM_LIT:0>)<EOL>grad_and_var = (grad, grad_and_vars[<NUM_LIT:0>][<NUM_LIT:1>])<EOL>average_grads.append(grad_and_var)<EOL><DEDENT><DEDENT>return average_grads<EOL> | r'''
A routine for computing each variable's average of the gradients obtained from the GPUs.
Note also that this code acts as a synchronization point as it requires all
GPUs to be finished with their mini-batch before it can run to completion. | f2476:m9 |
def log_variable(variable, gradient=None): | name = variable.name.replace('<STR_LIT::>', '<STR_LIT:_>')<EOL>mean = tf.reduce_mean(variable)<EOL>tf.summary.scalar(name='<STR_LIT>' % name, tensor=mean)<EOL>tf.summary.scalar(name='<STR_LIT>' % name, tensor=tf.sqrt(tf.reduce_mean(tf.square(variable - mean))))<EOL>tf.summary.scalar(name='<STR_LIT>' % name, tensor=tf.reduce_max(variable))<EOL>tf.summary.scalar(name='<STR_LIT>' % name, tensor=tf.reduce_min(variable))<EOL>tf.summary.histogram(name=name, values=variable)<EOL>if gradient is not None:<EOL><INDENT>if isinstance(gradient, tf.IndexedSlices):<EOL><INDENT>grad_values = gradient.values<EOL><DEDENT>else:<EOL><INDENT>grad_values = gradient<EOL><DEDENT>if grad_values is not None:<EOL><INDENT>tf.summary.histogram(name='<STR_LIT>' % name, values=grad_values)<EOL><DEDENT><DEDENT> | r'''
We introduce a function for logging a tensor variable's current state.
It logs scalar values for the mean, standard deviation, minimum and maximum.
Furthermore it logs a histogram of its state and (if given) of an optimization gradient. | f2476:m10 |
def log_grads_and_vars(grads_and_vars): | for gradient, variable in grads_and_vars:<EOL><INDENT>log_variable(variable, gradient=gradient)<EOL><DEDENT> | r'''
Let's also introduce a helper function for logging collections of gradient/variable tuples. | f2476:m11 |
def export(): | log_info('<STR_LIT>')<EOL>from tensorflow.python.framework.ops import Tensor, Operation<EOL>inputs, outputs, _ = create_inference_graph(batch_size=FLAGS.export_batch_size, n_steps=FLAGS.n_steps, tflite=FLAGS.export_tflite)<EOL>output_names_tensors = [tensor.op.name for tensor in outputs.values() if isinstance(tensor, Tensor)]<EOL>output_names_ops = [op.name for op in outputs.values() if isinstance(op, Operation)]<EOL>output_names = "<STR_LIT:U+002C>".join(output_names_tensors + output_names_ops)<EOL>if not FLAGS.export_tflite:<EOL><INDENT>mapping = {v.op.name: v for v in tf.global_variables() if not v.op.name.startswith('<STR_LIT>')}<EOL><DEDENT>else:<EOL><INDENT>def fixup(name):<EOL><INDENT>if name.startswith('<STR_LIT>'):<EOL><INDENT>return name.replace('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>return name<EOL><DEDENT>mapping = {fixup(v.op.name): v for v in tf.global_variables()}<EOL><DEDENT>saver = tf.train.Saver(mapping)<EOL>checkpoint = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir)<EOL>checkpoint_path = checkpoint.model_checkpoint_path<EOL>output_filename = '<STR_LIT>'<EOL>if FLAGS.remove_export:<EOL><INDENT>if os.path.isdir(FLAGS.export_dir):<EOL><INDENT>log_info('<STR_LIT>')<EOL>shutil.rmtree(FLAGS.export_dir)<EOL><DEDENT><DEDENT>try:<EOL><INDENT>output_graph_path = os.path.join(FLAGS.export_dir, output_filename)<EOL>if not os.path.isdir(FLAGS.export_dir):<EOL><INDENT>os.makedirs(FLAGS.export_dir)<EOL><DEDENT>def do_graph_freeze(output_file=None, output_node_names=None, variables_blacklist=None):<EOL><INDENT>return freeze_graph.freeze_graph_with_def_protos(<EOL>input_graph_def=tf.get_default_graph().as_graph_def(),<EOL>input_saver_def=saver.as_saver_def(),<EOL>input_checkpoint=checkpoint_path,<EOL>output_node_names=output_node_names,<EOL>restore_op_name=None,<EOL>filename_tensor_name=None,<EOL>output_graph=output_file,<EOL>clear_devices=False,<EOL>variable_names_blacklist=variables_blacklist,<EOL>initializer_nodes='<STR_LIT>')<EOL><DEDENT>if not FLAGS.export_tflite:<EOL><INDENT>frozen_graph = do_graph_freeze(output_node_names=output_names, variables_blacklist='<STR_LIT>')<EOL>frozen_graph.version = int(file_relative_read('<STR_LIT>').strip())<EOL>metadata = frozen_graph.node.add()<EOL>metadata.name = '<STR_LIT>'<EOL>metadata.op = '<STR_LIT>'<EOL>metadata.attr['<STR_LIT>'].i = FLAGS.audio_sample_rate<EOL>metadata.attr['<STR_LIT>'].i = FLAGS.feature_win_len<EOL>metadata.attr['<STR_LIT>'].i = FLAGS.feature_win_step<EOL>if FLAGS.export_language:<EOL><INDENT>metadata.attr['<STR_LIT>'].s = FLAGS.export_language.encode('<STR_LIT:ascii>')<EOL><DEDENT>with open(output_graph_path, '<STR_LIT:wb>') as fout:<EOL><INDENT>fout.write(frozen_graph.SerializeToString())<EOL><DEDENT><DEDENT>else:<EOL><INDENT>frozen_graph = do_graph_freeze(output_node_names=output_names, variables_blacklist='<STR_LIT>')<EOL>output_tflite_path = os.path.join(FLAGS.export_dir, output_filename.replace('<STR_LIT>', '<STR_LIT>'))<EOL>converter = tf.lite.TFLiteConverter(frozen_graph, input_tensors=inputs.values(), output_tensors=outputs.values())<EOL>converter.post_training_quantize = True<EOL>converter.allow_custom_ops = True<EOL>tflite_model = converter.convert()<EOL>with open(output_tflite_path, '<STR_LIT:wb>') as fout:<EOL><INDENT>fout.write(tflite_model)<EOL><DEDENT>log_info('<STR_LIT>'.format(os.path.basename(output_tflite_path)))<EOL><DEDENT>log_info('<STR_LIT>' % (FLAGS.export_dir))<EOL><DEDENT>except RuntimeError as e:<EOL><INDENT>log_error(str(e))<EOL><DEDENT> | r'''
Restores the trained variables into a simpler graph that will be exported for serving. | f2476:m17 |
def parse_args(args): | parser = argparse.ArgumentParser(<EOL>description="<STR_LIT>"<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>",<EOL>action="<STR_LIT:version>",<EOL>version="<STR_LIT>".format(ver=__version__),<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>action="<STR_LIT>",<EOL>required=False,<EOL>help="<STR_LIT>",<EOL>dest="<STR_LIT>",<EOL>const=logging.INFO,<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>action="<STR_LIT>",<EOL>required=False,<EOL>help="<STR_LIT>",<EOL>dest="<STR_LIT>",<EOL>const=logging.DEBUG,<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT:-c>",<EOL>"<STR_LIT>",<EOL>required=True,<EOL>help="<STR_LIT>",<EOL>dest="<STR_LIT>",<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>required=True,<EOL>help="<STR_LIT>",<EOL>dest="<STR_LIT>",<EOL>)<EOL>return parser.parse_args(args)<EOL> | Parse command line parameters
Args:
args ([str]): Command line parameters as list of strings
Returns:
:obj:`argparse.Namespace`: command line parameters namespace | f2482:m0 |
def setup_logging(level): | format = "<STR_LIT>"<EOL>logging.basicConfig(<EOL>level=level, stream=sys.stdout, format=format, datefmt="<STR_LIT>"<EOL>)<EOL> | Setup basic logging
Args:
level (int): minimum log level for emitting messages | f2482:m1 |
def main(args): | args = parse_args(args)<EOL>setup_logging(args.loglevel)<EOL>_logger.info("<STR_LIT>")<EOL>_logger.info("<STR_LIT>")<EOL>csv = GramVaaniCSV(args.csv_filename)<EOL>_logger.info("<STR_LIT>")<EOL>downloader = GramVaaniDownloader(csv, args.target_dir)<EOL>mp3_directory = downloader.download()<EOL>_logger.info("<STR_LIT>")<EOL>converter = GramVaaniConverter(args.target_dir, mp3_directory)<EOL>wav_directory = converter.convert()<EOL>datasets = GramVaaniDataSets(args.target_dir, wav_directory, csv)<EOL>datasets.create()<EOL>datasets.save()<EOL>_logger.info("<STR_LIT>")<EOL> | Main entry point allowing external calls
Args:
args ([str]): command line parameter list | f2482:m2 |
def download(self): | mp3_directory = self._pre_download()<EOL>self.data.swifter.apply(func=lambda arg: self._download(*arg, mp3_directory), axis=<NUM_LIT:1>, raw=True)<EOL>return mp3_directory<EOL> | Downloads the data associated with this instance
Return:
mp3_directory (os.path): The directory into which the associated mp3's were downloaded | f2482:c1:m1 |
def convert(self): | wav_directory = self._pre_convert()<EOL>for mp3_filename in self.mp3_directory.glob('<STR_LIT>'):<EOL><INDENT>wav_filename = path.join(wav_directory, os.path.splitext(os.path.basename(mp3_filename))[<NUM_LIT:0>] + "<STR_LIT>")<EOL>if not path.exists(wav_filename):<EOL><INDENT>_logger.debug("<STR_LIT>" % (mp3_filename, wav_filename))<EOL>transformer = Transformer()<EOL>transformer.convert(samplerate=SAMPLE_RATE, n_channels=N_CHANNELS, bitdepth=BITDEPTH)<EOL>transformer.build(str(mp3_filename), str(wav_filename))<EOL><DEDENT>else:<EOL><INDENT>_logger.debug("<STR_LIT>" % (mp3_filename, wav_filename))<EOL><DEDENT><DEDENT>return wav_directory<EOL> | Converts the mp3's associated with this instance to wav's
Return:
wav_directory (os.path): The directory into which the associated wav's were downloaded | f2482:c2:m1 |
def exec_command(command, cwd=None): | rc = None<EOL>stdout = stderr = None<EOL>if ssh_conn is None:<EOL><INDENT>ld_library_path = {'<STR_LIT>': '<STR_LIT>' % os.environ.get('<STR_LIT>', '<STR_LIT>')}<EOL>p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, env=ld_library_path, cwd=cwd)<EOL>stdout, stderr = p.communicate()<EOL>rc = p.returncode<EOL><DEDENT>else:<EOL><INDENT>final_command = command if cwd is None else '<STR_LIT>' % (cwd, '<STR_LIT>', command)<EOL>ssh_stdin, ssh_stdout, ssh_stderr = ssh_conn.exec_command(final_command)<EOL>stdout = '<STR_LIT>'.join(ssh_stdout.readlines())<EOL>stderr = '<STR_LIT>'.join(ssh_stderr.readlines())<EOL>rc = ssh_stdout.channel.recv_exit_status()<EOL><DEDENT>return rc, stdout, stderr<EOL> | r'''
Helper to exec locally (subprocess) or remotely (paramiko) | f2486:m0 |
def get_arch_string(): | rc, stdout, stderr = exec_command('<STR_LIT>')<EOL>if rc > <NUM_LIT:0>:<EOL><INDENT>raise AssertionError('<STR_LIT>')<EOL><DEDENT>stdout = stdout.lower().strip()<EOL>if not '<STR_LIT>' in stdout:<EOL><INDENT>raise AssertionError('<STR_LIT>')<EOL><DEDENT>if '<STR_LIT>' in stdout:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>if '<STR_LIT>' in stdout:<EOL><INDENT>nv_rc, nv_stdout, nv_stderr = exec_command('<STR_LIT>')<EOL>nv_stdout = nv_stdout.lower().strip()<EOL>if '<STR_LIT>' in nv_stdout:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT><DEDENT>raise AssertionError('<STR_LIT>', stdout)<EOL> | r'''
Check local or remote system arch, to produce TaskCluster proper link. | f2486:m2 |
def extract_native_client_tarball(dir): | assert_valid_dir(dir)<EOL>target_tarball = os.path.join(dir, '<STR_LIT>')<EOL>if os.path.isfile(target_tarball) and os.stat(target_tarball).st_size == <NUM_LIT:0>:<EOL><INDENT>return<EOL><DEDENT>subprocess.check_call(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>'], cwd=dir)<EOL>subprocess.check_call(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>'], cwd=dir)<EOL>os.unlink(os.path.join(dir, '<STR_LIT>'))<EOL>open(target_tarball, '<STR_LIT:w>').close()<EOL> | r'''
Download a native_client.tar.xz file from TaskCluster and extract it to dir. | f2486:m4 |
def is_zip_file(models): | ext = os.path.splitext(models[<NUM_LIT:0>])[<NUM_LIT:1>]<EOL>return (len(models) == <NUM_LIT:1>) and (ext == '<STR_LIT>')<EOL> | r'''
Ensure that a path is a zip file by:
- checking length is 1
- checking extension is '.zip' | f2486:m5 |
def maybe_inspect_zip(models): | if not(is_zip_file(models)):<EOL><INDENT>return models<EOL><DEDENT>if len(models) > <NUM_LIT:1>:<EOL><INDENT>return models<EOL><DEDENT>if len(models) < <NUM_LIT:1>:<EOL><INDENT>raise AssertionError('<STR_LIT>')<EOL><DEDENT>return zipfile.ZipFile(models[<NUM_LIT:0>]).namelist()<EOL> | r'''
Detect if models is a list of protocolbuffer files or a ZIP file.
If the latter, then unzip it and return the list of protocolbuffer files
that were inside. | f2486:m6 |
def all_files(models=[]): | def nsort(a, b):<EOL><INDENT>fa = os.path.basename(a).split('<STR_LIT:.>')<EOL>fb = os.path.basename(b).split('<STR_LIT:.>')<EOL>elements_to_remove = []<EOL>assert len(fa) == len(fb)<EOL>for i in range(<NUM_LIT:0>, len(fa)):<EOL><INDENT>if fa[i] == fb[i]:<EOL><INDENT>elements_to_remove.append(fa[i])<EOL><DEDENT><DEDENT>for e in elements_to_remove:<EOL><INDENT>fa.remove(e)<EOL>fb.remove(e)<EOL><DEDENT>assert len(fa) == len(fb)<EOL>assert len(fa) == <NUM_LIT:1><EOL>fa = keep_only_digits(fa[<NUM_LIT:0>])<EOL>fb = keep_only_digits(fb[<NUM_LIT:0>])<EOL>if fa < fb:<EOL><INDENT>return -<NUM_LIT:1><EOL><DEDENT>if fa == fb:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>if fa > fb:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT><DEDENT>base = list(map(lambda x: os.path.abspath(x), maybe_inspect_zip(models)))<EOL>base.sort(cmp=nsort)<EOL>return base<EOL> | r'''
Return a list of full path of files matching 'models', sorted in human
numerical order (i.e., 0 1 2 ..., 10 11 12, ..., 100, ..., 1000).
Files are supposed to be named identically except one variable component
e.g. the list,
test.weights.e5.lstm1200.ldc93s1.pb
test.weights.e5.lstm1000.ldc93s1.pb
test.weights.e5.lstm800.ldc93s1.pb
gets sorted:
test.weights.e5.lstm800.ldc93s1.pb
test.weights.e5.lstm1000.ldc93s1.pb
test.weights.e5.lstm1200.ldc93s1.pb | f2486:m7 |
def setup_tempdir(dir, models, wav, alphabet, lm_binary, trie, binaries): | if dir is None:<EOL><INDENT>dir = tempfile.mkdtemp(suffix='<STR_LIT>')<EOL><DEDENT>sorted_models = all_files(models=models)<EOL>if binaries is None:<EOL><INDENT>maybe_download_binaries(dir)<EOL><DEDENT>else:<EOL><INDENT>print('<STR_LIT>' % (binaries))<EOL>shutil.copy2(binaries, dir)<EOL><DEDENT>extract_native_client_tarball(dir)<EOL>filenames = map(lambda x: os.path.join(dir, os.path.basename(x)), sorted_models)<EOL>missing_models = filter(lambda x: not os.path.isfile(x), filenames)<EOL>if len(missing_models) > <NUM_LIT:0>:<EOL><INDENT>if is_zip_file(models):<EOL><INDENT>print('<STR_LIT>' % (models[<NUM_LIT:0>], dir))<EOL>zipfile.ZipFile(models[<NUM_LIT:0>]).extractall(path=dir)<EOL>print('<STR_LIT>' % models[<NUM_LIT:0>])<EOL><DEDENT>else:<EOL><INDENT>for f in sorted_models:<EOL><INDENT>print('<STR_LIT>' % (f, dir))<EOL>shutil.copy2(f, dir)<EOL><DEDENT><DEDENT><DEDENT>for extra_file in [ wav, alphabet, lm_binary, trie ]:<EOL><INDENT>if extra_file and not os.path.isfile(os.path.join(dir, os.path.basename(extra_file))):<EOL><INDENT>print('<STR_LIT>' % (extra_file, dir))<EOL>shutil.copy2(extra_file, dir)<EOL><DEDENT><DEDENT>if ssh_conn:<EOL><INDENT>copy_tree(dir)<EOL><DEDENT>return dir, sorted_models<EOL> | r'''
Copy models, libs and binary to a directory (new one if dir is None) | f2486:m10 |
def teardown_tempdir(dir): | if ssh_conn:<EOL><INDENT>delete_tree(dir)<EOL><DEDENT>assert_valid_dir(dir)<EOL>shutil.rmtree(dir)<EOL> | r'''
Cleanup temporary directory. | f2486:m11 |
def get_sshconfig(): | with open(os.path.expanduser('<STR_LIT>')) as f:<EOL><INDENT>cfg = paramiko.SSHConfig()<EOL>cfg.parse(f)<EOL>ret_dict = {}<EOL>for d in cfg._config:<EOL><INDENT>_copy = dict(d)<EOL>del _copy['<STR_LIT:host>']<EOL>for host in d['<STR_LIT:host>']:<EOL><INDENT>ret_dict[host] = _copy['<STR_LIT>']<EOL><DEDENT><DEDENT>return ret_dict<EOL><DEDENT> | r'''
Read user's SSH configuration file | f2486:m12 |
def establish_ssh(target=None, auto_trust=False, allow_agent=True, look_keys=True): | def password_prompt(username, hostname):<EOL><INDENT>r'''<STR_LIT>'''<EOL>return getpass.getpass('<STR_LIT>' % (username, hostname))<EOL><DEDENT>ssh_conn = None<EOL>if target is not None:<EOL><INDENT>ssh_conf = get_sshconfig()<EOL>cfg = {<EOL>'<STR_LIT>': None,<EOL>'<STR_LIT:port>': <NUM_LIT>,<EOL>'<STR_LIT>': allow_agent,<EOL>'<STR_LIT>': look_keys<EOL>}<EOL>if ssh_conf.has_key(target):<EOL><INDENT>user_config = ssh_conf.get(target)<EOL>if user_config.has_key('<STR_LIT:user>') and not user_config.has_key('<STR_LIT:username>'):<EOL><INDENT>user_config['<STR_LIT:username>'] = user_config['<STR_LIT:user>']<EOL>del user_config['<STR_LIT:user>']<EOL><DEDENT>for k in ('<STR_LIT:username>', '<STR_LIT>', '<STR_LIT:port>'):<EOL><INDENT>if k in user_config:<EOL><INDENT>cfg[k] = user_config[k]<EOL><DEDENT><DEDENT>if '<STR_LIT>' in user_config:<EOL><INDENT>cfg['<STR_LIT>'] = user_config['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>cfg['<STR_LIT:password>'] = password_prompt(cfg['<STR_LIT:username>'], cfg['<STR_LIT>'] or target)<EOL><DEDENT>if '<STR_LIT>' in user_config:<EOL><INDENT>cfg['<STR_LIT>'] = paramiko.ProxyCommand(user_config['<STR_LIT>'])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>cfg['<STR_LIT:username>'] = target.split('<STR_LIT:@>')[<NUM_LIT:0>]<EOL>cfg['<STR_LIT>'] = target.split('<STR_LIT:@>')[<NUM_LIT:1>].split('<STR_LIT::>')[<NUM_LIT:0>]<EOL>cfg['<STR_LIT:password>'] = password_prompt(cfg['<STR_LIT:username>'], cfg['<STR_LIT>'])<EOL>try:<EOL><INDENT>cfg['<STR_LIT:port>'] = int(target.split('<STR_LIT:@>')[<NUM_LIT:1>].split('<STR_LIT::>')[<NUM_LIT:1>])<EOL><DEDENT>except IndexError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>ssh_conn = paramiko.SSHClient()<EOL>if auto_trust:<EOL><INDENT>ssh_conn.set_missing_host_key_policy(paramiko.AutoAddPolicy())<EOL><DEDENT>ssh_conn.connect(**cfg)<EOL><DEDENT>return ssh_conn<EOL> | r'''
Establish a SSH connection to a remote host. It should be able to use
SSH's config file Host name declarations. By default, will not automatically
add trust for hosts, will use SSH agent and will try to load keys. | f2486:m13 |
def run_benchmarks(dir, models, wav, alphabet, lm_binary=None, trie=None, iters=-<NUM_LIT:1>): | assert_valid_dir(dir)<EOL>inference_times = [ ]<EOL>for model in models:<EOL><INDENT>model_filename = model<EOL>current_model = {<EOL>'<STR_LIT:name>': model,<EOL>'<STR_LIT>': [ ],<EOL>'<STR_LIT>': numpy.infty,<EOL>'<STR_LIT>': numpy.infty<EOL>}<EOL>if lm_binary and trie:<EOL><INDENT>cmdline = '<STR_LIT>' % (model_filename, alphabet, lm_binary, trie, wav)<EOL><DEDENT>else:<EOL><INDENT>cmdline = '<STR_LIT>' % (model_filename, alphabet, wav)<EOL><DEDENT>for it in range(iters):<EOL><INDENT>sys.stdout.write('<STR_LIT>' % (os.path.basename(model), (it+<NUM_LIT:1>), iters))<EOL>sys.stdout.flush()<EOL>rc, stdout, stderr = exec_command(cmdline, cwd=dir)<EOL>if rc == <NUM_LIT:0>:<EOL><INDENT>inference_time = float(stdout.split('<STR_LIT:\n>')[<NUM_LIT:1>].split('<STR_LIT:=>')[-<NUM_LIT:1>])<EOL>current_model['<STR_LIT>'].append(inference_time)<EOL><DEDENT>else:<EOL><INDENT>print('<STR_LIT>' % (cmdline, rc))<EOL>print('<STR_LIT>' % stdout)<EOL>print('<STR_LIT>' % stderr)<EOL>raise AssertionError('<STR_LIT>' % (rc))<EOL><DEDENT><DEDENT>sys.stdout.write('<STR_LIT:\n>')<EOL>sys.stdout.flush()<EOL>current_model['<STR_LIT>'] = numpy.mean(current_model['<STR_LIT>'])<EOL>current_model['<STR_LIT>'] = numpy.std(current_model['<STR_LIT>'])<EOL>inference_times.append(current_model)<EOL><DEDENT>return inference_times<EOL> | r'''
Core of the running of the benchmarks. We will run on all of models, against
the WAV file provided as wav, and the provided alphabet. | f2486:m14 |
def produce_csv(input, output): | output.write('<STR_LIT>')<EOL>for model_data in input:<EOL><INDENT>output.write('<STR_LIT>' % (model_data['<STR_LIT:name>'], model_data['<STR_LIT>'], model_data['<STR_LIT>']))<EOL><DEDENT>output.flush()<EOL>output.close()<EOL>print("<STR_LIT>" % output.name)<EOL> | r'''
Take an input dictionnary and write it to the object-file output. | f2486:m15 |
def _parallel_downloader(voxforge_url, archive_dir, total, counter): | def download(d):<EOL><INDENT>"""<STR_LIT>"""<EOL>(i, file) = d<EOL>download_url = voxforge_url + '<STR_LIT:/>' + file<EOL>c = counter.increment()<EOL>print('<STR_LIT>'.format(i+<NUM_LIT:1>, c, total))<EOL>maybe_download(filename_of(download_url), archive_dir, download_url)<EOL><DEDENT>return download<EOL> | Generate a function to download a file based on given parameters
This works by currying the above given arguments into a closure
in the form of the following function.
:param voxforge_url: the base voxforge URL
:param archive_dir: the location to store the downloaded file
:param total: the total number of files to download
:param counter: an atomic counter to keep track of # of downloaded files
:return: a function that actually downloads a file given these params | f2491:m0 |
def __init__(self, start_count=<NUM_LIT:0>): | self.__lock = threading.Lock()<EOL>self.__count = start_count<EOL> | Initialize the counter
:param start_count: the number to start counting at | f2491:c0:m0 |
def increment(self, amount=<NUM_LIT:1>): | self.__lock.acquire()<EOL>self.__count += amount<EOL>v = self.value()<EOL>self.__lock.release()<EOL>return v<EOL> | Increments the counter by the given amount
:param amount: the amount to increment by (default 1)
:return: the incremented value of the counter | f2491:c0:m1 |
def value(self): | return self.__count<EOL> | Returns the current value of the counter (not atomic) | f2491:c0:m2 |
def reduce_filename(f): | f = os.path.basename(f).split('<STR_LIT:.>')<EOL>return keep_only_digits(f[-<NUM_LIT:3>])<EOL> | r'''
Expects something like /tmp/tmpAjry4Gdsbench/test.weights.e5.XXX.YYY.pb
Where XXX is a variation on the model size for example
And where YYY is a const related to the training dataset | f2493:m0 |
def calculate_report(labels, decodings, distances, losses): | samples = pmap(process_decode_result, zip(labels, decodings, distances, losses))<EOL>samples_wer, samples_cer = wer_cer_batch(labels, decodings)<EOL>samples.sort(key=lambda s: s.loss)<EOL>samples.sort(key=lambda s: s.wer, reverse=True)<EOL>return samples_wer, samples_cer, samples<EOL> | r'''
This routine will calculate a WER report.
It'll compute the `mean` WER and create ``Sample`` objects of the ``report_count`` top lowest
loss items from the provided WER results tuple (only items with WER!=0 and ordered by their WER). | f2499:m2 |
def get_available_gpus(): | local_device_protos = device_lib.list_local_devices()<EOL>return [x.name for x in local_device_protos if x.device_type == '<STR_LIT>']<EOL> | r"""
Returns the number of GPUs available on this system. | f2500:m0 |
def parse_stm_file(stm_file): | stm_segments = []<EOL>with codecs.open(stm_file, encoding="<STR_LIT:utf-8>") as stm_lines:<EOL><INDENT>for stm_line in stm_lines:<EOL><INDENT>stmSegment = STMSegment(stm_line)<EOL>if not "<STR_LIT>" == stmSegment.transcript:<EOL><INDENT>stm_segments.append(stmSegment)<EOL><DEDENT><DEDENT><DEDENT>return stm_segments<EOL> | r"""
Parses an STM file at ``stm_file`` into a list of :class:`STMSegment`. | f2501:m0 |
def text_to_char_array(original, alphabet): | return np.asarray([alphabet.label_from_string(c) for c in original])<EOL> | r"""
Given a Python string ``original``, remove unsupported characters, map characters
to integers and return a numpy array representing the processed string. | f2504:m0 |
def wer_cer_batch(originals, results): | <EOL>assert len(originals) == len(results)<EOL>total_cer = <NUM_LIT:0.0><EOL>total_char_length = <NUM_LIT:0.0><EOL>total_wer = <NUM_LIT:0.0><EOL>total_word_length = <NUM_LIT:0.0><EOL>for original, result in zip(originals, results):<EOL><INDENT>total_cer += levenshtein(original, result)<EOL>total_char_length += len(original)<EOL>total_wer += levenshtein(original.split(), result.split())<EOL>total_word_length += len(original.split())<EOL><DEDENT>return total_wer / total_word_length, total_cer / total_char_length<EOL> | r"""
The WER is defined as the editing/Levenshtein distance on word level
divided by the amount of words in the original text.
In case of the original having more words (N) than the result and both
being totally different (all N words resulting in 1 edit operation each),
the WER will always be 1 (N / N = 1). | f2504:m1 |
def levenshtein(a, b): | n, m = len(a), len(b)<EOL>if n > m:<EOL><INDENT>a, b = b, a<EOL>n, m = m, n<EOL><DEDENT>current = list(range(n+<NUM_LIT:1>))<EOL>for i in range(<NUM_LIT:1>, m+<NUM_LIT:1>):<EOL><INDENT>previous, current = current, [i]+[<NUM_LIT:0>]*n<EOL>for j in range(<NUM_LIT:1>, n+<NUM_LIT:1>):<EOL><INDENT>add, delete = previous[j]+<NUM_LIT:1>, current[j-<NUM_LIT:1>]+<NUM_LIT:1><EOL>change = previous[j-<NUM_LIT:1>]<EOL>if a[j-<NUM_LIT:1>] != b[i-<NUM_LIT:1>]:<EOL><INDENT>change = change + <NUM_LIT:1><EOL><DEDENT>current[j] = min(add, delete, change)<EOL><DEDENT><DEDENT>return current[n]<EOL> | Calculates the Levenshtein distance between a and b. | f2504:m2 |
def keep_only_digits(s): | fs = '<STR_LIT>'<EOL>for c in s:<EOL><INDENT>if c.isdigit():<EOL><INDENT>fs += c<EOL><DEDENT><DEDENT>return int(fs)<EOL> | r'''
local helper to just keep digits | f2507:m0 |
def to_sparse_tuple(sequence): | indices = np.asarray(list(zip([<NUM_LIT:0>]*len(sequence), range(len(sequence)))), dtype=np.int64)<EOL>shape = np.asarray([<NUM_LIT:1>, len(sequence)], dtype=np.int64)<EOL>return indices, sequence, shape<EOL> | r"""Creates a sparse representention of ``sequence``.
Returns a tuple with (indices, values, shape) | f2508:m4 |
@pyqtSlot()<EOL><INDENT>def run(self):<DEDENT> | <EOL>try:<EOL><INDENT>transcript = self.fn(*self.args, **self.kwargs)<EOL><DEDENT>except:<EOL><INDENT>traceback.print_exc()<EOL>exctype, value = sys.exc_info()[:<NUM_LIT:2>]<EOL>self.signals.error.emit((exctype, value, traceback.format_exc()))<EOL><DEDENT>else:<EOL><INDENT>self.signals.result.emit(transcript)<EOL><DEDENT>finally:<EOL><INDENT>self.signals.finished.emit()<EOL><DEDENT> | Initialise the runner function with the passed args, kwargs | f2509:c1:m1 |
def read_wave(path): | with contextlib.closing(wave.open(path, '<STR_LIT:rb>')) as wf:<EOL><INDENT>num_channels = wf.getnchannels()<EOL>assert num_channels == <NUM_LIT:1><EOL>sample_width = wf.getsampwidth()<EOL>assert sample_width == <NUM_LIT:2><EOL>sample_rate = wf.getframerate()<EOL>assert sample_rate in (<NUM_LIT>, <NUM_LIT>, <NUM_LIT>)<EOL>frames = wf.getnframes()<EOL>pcm_data = wf.readframes(frames)<EOL>duration = frames / sample_rate<EOL>return pcm_data, sample_rate, duration<EOL><DEDENT> | Reads a .wav file.
Takes the path, and returns (PCM audio data, sample rate). | f2511:m0 |
def write_wave(path, audio, sample_rate): | with contextlib.closing(wave.open(path, '<STR_LIT:wb>')) as wf:<EOL><INDENT>wf.setnchannels(<NUM_LIT:1>)<EOL>wf.setsampwidth(<NUM_LIT:2>)<EOL>wf.setframerate(sample_rate)<EOL>wf.writeframes(audio)<EOL><DEDENT> | Writes a .wav file.
Takes path, PCM audio data, and sample rate. | f2511:m1 |
def frame_generator(frame_duration_ms, audio, sample_rate): | n = int(sample_rate * (frame_duration_ms / <NUM_LIT>) * <NUM_LIT:2>)<EOL>offset = <NUM_LIT:0><EOL>timestamp = <NUM_LIT:0.0><EOL>duration = (float(n) / sample_rate) / <NUM_LIT><EOL>while offset + n < len(audio):<EOL><INDENT>yield Frame(audio[offset:offset + n], timestamp, duration)<EOL>timestamp += duration<EOL>offset += n<EOL><DEDENT> | Generates audio frames from PCM audio data.
Takes the desired frame duration in milliseconds, the PCM data, and
the sample rate.
Yields Frames of the requested duration. | f2511:m2 |
def vad_collector(sample_rate, frame_duration_ms,<EOL>padding_duration_ms, vad, frames): | num_padding_frames = int(padding_duration_ms / frame_duration_ms)<EOL>ring_buffer = collections.deque(maxlen=num_padding_frames)<EOL>triggered = False<EOL>voiced_frames = []<EOL>for frame in frames:<EOL><INDENT>is_speech = vad.is_speech(frame.bytes, sample_rate)<EOL>if not triggered:<EOL><INDENT>ring_buffer.append((frame, is_speech))<EOL>num_voiced = len([f for f, speech in ring_buffer if speech])<EOL>if num_voiced > <NUM_LIT> * ring_buffer.maxlen:<EOL><INDENT>triggered = True<EOL>for f, s in ring_buffer:<EOL><INDENT>voiced_frames.append(f)<EOL><DEDENT>ring_buffer.clear()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>voiced_frames.append(frame)<EOL>ring_buffer.append((frame, is_speech))<EOL>num_unvoiced = len([f for f, speech in ring_buffer if not speech])<EOL>if num_unvoiced > <NUM_LIT> * ring_buffer.maxlen:<EOL><INDENT>triggered = False<EOL>yield b'<STR_LIT>'.join([f.bytes for f in voiced_frames])<EOL>ring_buffer.clear()<EOL>voiced_frames = []<EOL><DEDENT><DEDENT><DEDENT>if triggered:<EOL><INDENT>pass<EOL><DEDENT>if voiced_frames:<EOL><INDENT>yield b'<STR_LIT>'.join([f.bytes for f in voiced_frames])<EOL><DEDENT> | Filters out non-voiced audio frames.
Given a webrtcvad.Vad and a source of audio frames, yields only
the voiced audio.
Uses a padded, sliding window algorithm over the audio frames.
When more than 90% of the frames in the window are voiced (as
reported by the VAD), the collector triggers and begins yielding
audio frames. Then the collector waits until 90% of the frames in
the window are unvoiced to detrigger.
The window is padded at the front and back to provide a small
amount of silence or the beginnings/endings of speech around the
voiced frames.
Arguments:
sample_rate - The audio sample rate, in Hz.
frame_duration_ms - The frame duration in milliseconds.
padding_duration_ms - The amount to pad the window, in milliseconds.
vad - An instance of webrtcvad.Vad.
frames - a source of audio frames (sequence or generator).
Returns: A generator that yields PCM audio data. | f2511:m3 |
def resample(self, data, input_rate): | data16 = np.fromstring(string=data, dtype=np.int16)<EOL>resample_size = int(len(data16) / self.input_rate * self.RATE_PROCESS)<EOL>resample = signal.resample(data16, resample_size)<EOL>resample16 = np.array(resample, dtype=np.int16)<EOL>return resample16.tostring()<EOL> | Microphone may not support our native processing sampling rate, so
resample from input_rate to RATE_PROCESS here for webrtcvad and
deepspeech
Args:
data (binary): Input audio stream
input_rate (int): Input audio rate to resample from | f2513:c0:m1 |
def read_resampled(self): | return self.resample(data=self.buffer_queue.get(),<EOL>input_rate=self.input_rate)<EOL> | Return a block of audio data resampled to 16000hz, blocking if necessary. | f2513:c0:m2 |
def read(self): | return self.buffer_queue.get()<EOL> | Return a block of audio data, blocking if necessary. | f2513:c0:m3 |
def frame_generator(self): | if self.input_rate == self.RATE_PROCESS:<EOL><INDENT>while True:<EOL><INDENT>yield self.read()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>while True:<EOL><INDENT>yield self.read_resampled()<EOL><DEDENT><DEDENT> | Generator that yields all audio frames from microphone. | f2513:c1:m1 |
def vad_collector(self, padding_ms=<NUM_LIT>, ratio=<NUM_LIT>, frames=None): | if frames is None: frames = self.frame_generator()<EOL>num_padding_frames = padding_ms // self.frame_duration_ms<EOL>ring_buffer = collections.deque(maxlen=num_padding_frames)<EOL>triggered = False<EOL>for frame in frames:<EOL><INDENT>is_speech = self.vad.is_speech(frame, self.sample_rate)<EOL>if not triggered:<EOL><INDENT>ring_buffer.append((frame, is_speech))<EOL>num_voiced = len([f for f, speech in ring_buffer if speech])<EOL>if num_voiced > ratio * ring_buffer.maxlen:<EOL><INDENT>triggered = True<EOL>for f, s in ring_buffer:<EOL><INDENT>yield f<EOL><DEDENT>ring_buffer.clear()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>yield frame<EOL>ring_buffer.append((frame, is_speech))<EOL>num_unvoiced = len([f for f, speech in ring_buffer if not speech])<EOL>if num_unvoiced > ratio * ring_buffer.maxlen:<EOL><INDENT>triggered = False<EOL>yield None<EOL>ring_buffer.clear()<EOL><DEDENT><DEDENT><DEDENT> | Generator that yields series of consecutive audio frames comprising each utterence, separated by yielding a single None.
Determines voice activity by ratio of frames in padding_ms. Uses a buffer to include padding_ms prior to being triggered.
Example: (frame, ..., frame, None, frame, ..., frame, None, ...)
|---utterence---| |---utterence---| | f2513:c1:m2 |
def sparse_tensor_value_to_texts(value, alphabet): | return sparse_tuple_to_texts((value.indices, value.values, value.dense_shape), alphabet)<EOL> | r"""
Given a :class:`tf.SparseTensor` ``value``, return an array of Python strings
representing its values, converting tokens to strings using ``alphabet``. | f2514:m0 |
def __init__(self, url, urlSchemes=None): | self._urlApi = url<EOL>self._urlSchemes = {}<EOL>self._initRequestHeaders()<EOL>self._urllib = urllib2<EOL>if urlSchemes is not None:<EOL><INDENT>for urlScheme in urlSchemes:<EOL><INDENT>self.addUrlScheme(urlScheme)<EOL><DEDENT><DEDENT>self._implicitFormat = self._urlApi.find('<STR_LIT>') != -<NUM_LIT:1><EOL> | Create a new OEmbedEndpoint object.
Args:
url: The url of a provider API (API endpoint).
urlSchemes: A list of URL schemes for this endpoint. | f2517:c8:m0 |
def addUrlScheme(self, url): | <EOL>if not isinstance(url, str):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if not url in self._urlSchemes:<EOL><INDENT>self._urlSchemes[url] = OEmbedUrlScheme(url)<EOL><DEDENT> | Add a url scheme to this endpoint. It takes a url string and create
the OEmbedUrlScheme object internally.
Args:
url: The url string that represents a url scheme to add. | f2517:c8:m2 |
def delUrlScheme(self, url): | if url in self._urlSchemes:<EOL><INDENT>del self._urlSchemes[url]<EOL><DEDENT> | Remove an OEmbedUrlScheme from the list of schemes.
Args:
url: The url used as key for the urlSchems dict. | f2517:c8:m3 |
def clearUrlSchemes(self): | self._urlSchemes.clear()<EOL> | Clear the schemes in this endpoint. | f2517:c8:m4 |
def getUrlSchemes(self): | return self._urlSchemes<EOL> | Get the url schemes in this endpoint.
Returns:
A dict of OEmbedUrlScheme objects. k => url, v => OEmbedUrlScheme | f2517:c8:m5 |
def match(self, url): | try:<EOL><INDENT>urlSchemes = self._urlSchemes.itervalues() <EOL><DEDENT>except AttributeError:<EOL><INDENT>urlSchemes = self._urlSchemes.values() <EOL><DEDENT>for urlScheme in urlSchemes:<EOL><INDENT>if urlScheme.match(url):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL> | Try to find if url matches against any of the schemes within this
endpoint.
Args:
url: The url to match against each scheme
Returns:
True if a matching scheme was found for the url, False otherwise | f2517:c8:m6 |
def request(self, url, **opt): | params = opt<EOL>params['<STR_LIT:url>'] = url<EOL>urlApi = self._urlApi<EOL>if '<STR_LIT>' in params and self._implicitFormat:<EOL><INDENT>urlApi = self._urlApi.replace('<STR_LIT>', params['<STR_LIT>'])<EOL>del params['<STR_LIT>']<EOL><DEDENT>if '<STR_LIT:?>' in urlApi:<EOL><INDENT>return "<STR_LIT>" % (urlApi, urllib.urlencode(params))<EOL><DEDENT>else:<EOL><INDENT>return "<STR_LIT>" % (urlApi, urllib.urlencode(params))<EOL><DEDENT> | Format the input url and optional parameters, and provides the final url
where to get the given resource.
Args:
url: The url of an OEmbed resource.
**opt: Parameters passed to the url.
Returns:
The complete url of the endpoint and resource. | f2517:c8:m7 |
def get(self, url, **opt): | return self.fetch(self.request(url, **opt))<EOL> | Convert the resource url to a complete url and then fetch the
data from it.
Args:
url: The url of an OEmbed resource.
**opt: Parameters passed to the url.
Returns:
OEmbedResponse object according to data fetched | f2517:c8:m8 |
def fetch(self, url): | opener = self._urllib.build_opener()<EOL>opener.addheaders = self._requestHeaders.items()<EOL>response = opener.open(url)<EOL>headers = response.info()<EOL>raw = response.read()<EOL>raw = raw.decode('<STR_LIT:utf8>')<EOL>if not '<STR_LIT:Content-Type>' in headers:<EOL><INDENT>raise OEmbedError('<STR_LIT>')<EOL><DEDENT>if headers['<STR_LIT:Content-Type>'].find('<STR_LIT>') != -<NUM_LIT:1> orheaders['<STR_LIT:Content-Type>'].find('<STR_LIT>') != -<NUM_LIT:1>:<EOL><INDENT>response = OEmbedResponse.newFromXML(raw)<EOL><DEDENT>elif headers['<STR_LIT:Content-Type>'].find('<STR_LIT:application/json>') != -<NUM_LIT:1> orheaders['<STR_LIT:Content-Type>'].find('<STR_LIT>') != -<NUM_LIT:1> orheaders['<STR_LIT:Content-Type>'].find('<STR_LIT>') != -<NUM_LIT:1>:<EOL><INDENT>response = OEmbedResponse.newFromJSON(raw)<EOL><DEDENT>else:<EOL><INDENT>raise OEmbedError('<STR_LIT>' % headers['<STR_LIT:Content-Type>'])<EOL><DEDENT>return response<EOL> | Fetch url and create a response object according to the mime-type.
Args:
url: The url to fetch data from
Returns:
OEmbedResponse object according to data fetched | f2517:c8:m9 |
def setUrllib(self, urllib): | self._urllib = urllib<EOL> | Override the default urllib implementation.
Args:
urllib: an instance that supports the same API as the urllib2 module | f2517:c8:m10 |
def setUserAgent(self, user_agent): | self._requestHeaders['<STR_LIT>'] = user_agent<EOL> | Override the default user agent
Args:
user_agent: a string that should be send to the server as the User-agent | f2517:c8:m11 |
def __init__(self, url): | self._url = url<EOL>if url.startswith('<STR_LIT>'):<EOL><INDENT>self._regex = re.compile(url[<NUM_LIT:6>:])<EOL><DEDENT>else:<EOL><INDENT>self._regex = re.compile(url.replace('<STR_LIT:.>', '<STR_LIT>').replace('<STR_LIT:*>', '<STR_LIT>'))<EOL><DEDENT> | Create a new OEmbedUrlScheme instance.
Args;
url: The url scheme. It also takes the wildcard character (*). | f2517:c9:m0 |
def getUrl(self): | return self._url<EOL> | Get the url scheme.
Returns:
The url scheme. | f2517:c9:m1 |
def match(self, url): | return self._regex.match(url) is not None<EOL> | Match the url against this scheme.
Args:
url: The url to match against this scheme.
Returns:
True if a match was found for the url, False otherwise | f2517:c9:m2 |
def addEndpoint(self, endpoint): | self._endpoints.append(endpoint)<EOL> | Add a new OEmbedEndpoint to be manage by the consumer.
Args:
endpoint: An instance of an OEmbedEndpoint class. | f2517:c10:m1 |
def delEndpoint(self, endpoint): | self._endpoints.remove(endpoint)<EOL> | Remove an OEmbedEnpoint from this consumer.
Args:
endpoint: An instance of an OEmbedEndpoint class. | f2517:c10:m2 |
def clearEndpoints(self): | del self._endpoints[:]<EOL> | Clear all the endpoints managed by this consumer. | f2517:c10:m3 |
def getEndpoints(self): | return self._endpoints<EOL> | Get the list of endpoints.
Returns:
The list of endpoints in this consumer. | f2517:c10:m4 |
def embed(self, url, format='<STR_LIT>', **opt): | if format not in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>raise OEmbedInvalidRequest('<STR_LIT>')<EOL><DEDENT>opt['<STR_LIT>'] = format<EOL>return self._request(url, **opt)<EOL> | Get an OEmbedResponse from one of the providers configured in this
consumer according to the resource url.
Args:
url: The url of the resource to get.
format: Desired response format.
**opt: Optional parameters to pass in the url to the provider.
Returns:
OEmbedResponse object. | f2517:c10:m7 |
def publish(): | os.system("<STR_LIT>")<EOL> | Publish to Pypi | f2518:m0 |
def filter_factory(global_conf, **local_conf): | conf = global_conf.copy()<EOL>conf.update(local_conf)<EOL>def visible(app):<EOL><INDENT>return VisibleFilter(app, conf)<EOL><DEDENT>return visible<EOL> | Returns a WSGI filter app for use with paste.deploy. | f2522:m0 |
def _is_whitelisted(self, req): | if not self.roles_whitelist:<EOL><INDENT>return False<EOL><DEDENT>if not hasattr(req, '<STR_LIT>'):<EOL><INDENT>self.log.info("<STR_LIT>")<EOL>return False<EOL><DEDENT>if not hasattr(req.context, '<STR_LIT>'):<EOL><INDENT>self.log.info("<STR_LIT>")<EOL>return False<EOL><DEDENT>roles = req.context.roles<EOL>self.log.debug("<STR_LIT>",<EOL>'<STR_LIT:U+0020>'.join(roles))<EOL>for key in self.roles_whitelist:<EOL><INDENT>if key in roles:<EOL><INDENT>self.log.debug("<STR_LIT>", key)<EOL>return True<EOL><DEDENT><DEDENT>return False<EOL> | Return True if role is whitelisted or roles cannot be determined. | f2522:c0:m3 |
def filter_factory(global_conf, **local_conf): | conf = global_conf.copy()<EOL>conf.update(local_conf)<EOL>def blacklist(app):<EOL><INDENT>return BlacklistFilter(app, conf)<EOL><DEDENT>return blacklist<EOL> | Returns a WSGI filter app for use with paste.deploy. | f2523:m0 |
def get_error(exc): | if isinstance(exc, HTTPError):<EOL><INDENT>return exc.response.status_code, text(exc.response.content)<EOL><DEDENT>if isinstance(exc, Timeout):<EOL><INDENT>return <NUM_LIT>, exc<EOL><DEDENT>if isinstance(exc, Http404):<EOL><INDENT>return <NUM_LIT>, exc<EOL><DEDENT>if isinstance(exc, PermissionDenied):<EOL><INDENT>return <NUM_LIT>, exc<EOL><DEDENT>if isinstance(exc, SuspiciousOperation):<EOL><INDENT>return <NUM_LIT>, exc<EOL><DEDENT>return <NUM_LIT>, exc<EOL> | Return the appropriate HTTP status code according to the Exception/Error. | f2524:m0 |
@property<EOL><INDENT>def content_type(self):<DEDENT> | if '<STR_LIT>' in self.request.META:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT> | Return content-type of the response.
For a JSONResponseMixin, the obvious answer is ``application/json``.
But Internet Explorer v8 can't handle this content-type and instead
of processing it as a normal AJAX data response, it tries to download
it.
We're tricking this behaviour by sending back a ``text/html``
content-type header instead. | f2524:c0:m0 |
@cached_property<EOL><INDENT>def registry(self):<DEDENT> | return get_agnocomplete_registry()<EOL> | Return the agnocomplete registry (cached) | f2524:c1:m0 |
def get_agnocomplete_context(self): | return self.request.user<EOL> | Return the view current user.
You may want to change this value by overrding this method. | f2524:c2:m0 |
def get_form_kwargs(self): | data = super(UserContextFormViewMixin, self).get_form_kwargs()<EOL>data.update({<EOL>'<STR_LIT:user>': self.get_agnocomplete_context(),<EOL>})<EOL>return data<EOL> | Return the form kwargs.
This method injects the context variable, defined in
:meth:`get_agnocomplete_context`. Override this method to adjust it to
your needs. | f2524:c2:m1 |
def get_dataset(self, **kwargs): | return tuple(self.registry.keys())<EOL> | Return the registry key set. | f2524:c3:m0 |
def get_klass(self): | <EOL>if hasattr(self, '<STR_LIT>') and self.klass:<EOL><INDENT>return self.klass<EOL><DEDENT>raise ImproperlyConfiguredView("<STR_LIT>")<EOL> | Return the agnocomplete class to be used with the eventual query. | f2524:c4:m0 |
def get_klass(self): | <EOL>klass_name = self.kwargs.get('<STR_LIT>', None)<EOL>klass = self.registry.get(klass_name, None)<EOL>if not klass:<EOL><INDENT>raise Http404("<STR_LIT>".format(klass_name))<EOL><DEDENT>return klass<EOL> | Return the agnocomplete class to be used with the eventual query. | f2524:c5:m0 |
def set_agnocomplete(self, klass_or_instance, user): | <EOL>if isinstance(klass_or_instance, six.string_types):<EOL><INDENT>registry = get_agnocomplete_registry()<EOL>if klass_or_instance not in registry:<EOL><INDENT>raise UnregisteredAgnocompleteException(<EOL>"<STR_LIT>".format(klass_or_instance) <EOL>)<EOL><DEDENT>klass_or_instance = registry[klass_or_instance]<EOL><DEDENT>if not isinstance(klass_or_instance, AgnocompleteBase):<EOL><INDENT>klass_or_instance = klass_or_instance(user=user)<EOL><DEDENT>if isinstance(klass_or_instance, AgnocompleteBase):<EOL><INDENT>klass_or_instance.set_agnocomplete_field(self)<EOL><DEDENT>self.agnocomplete = klass_or_instance<EOL>self.agnocomplete.user = user<EOL> | Handling the assignation of the agnocomplete object inside the field.
A developer may want to use a class or an instance of an
:class:`AgnocompleteBase` class to configure her field.
Ex::
from agnocomplete import Fields
class SearchForm(forms.Form):
search_class = fields.AgnocompleteField(AgnocompleteColor)
search_class2 = fields.AgnocompleteField('AgnocompleteColor')
search_instance = fields.AgnocompleteField(
AgnocompleteColor(page_size=3))
if it's a :class: being passed as a parameter, it'll be
instantiated using the default parameters. If it's a string, it'll
be instanciated also, using the name of the class as the key to
fetch the actual class. | f2527:c0:m1 |
def get_agnocomplete_context(self): | return getattr(self, AGNOCOMPLETE_USER_ATTRIBUTE, None)<EOL> | Return the agnocomplete user variable, if set. | f2527:c0:m2 |
def transmit_agnocomplete_context(self): | <EOL>if hasattr(self, AGNOCOMPLETE_USER_ATTRIBUTE):<EOL><INDENT>user = self.get_agnocomplete_context()<EOL>if user:<EOL><INDENT>self.agnocomplete.user = user<EOL><DEDENT>return user<EOL><DEDENT> | Assign the user context to the agnocomplete class, if any. | f2527:c0:m3 |
def clean(self, *args, **kwargs): | self.transmit_agnocomplete_context()<EOL>return super(AgnocompleteMixin, self).clean(*args, **kwargs)<EOL> | Potentially, these fields should validate against context-based
queries.
If a context variable has been transmitted to the field, it's being
used to 'reset' the queryset and make sure the chosen item fits to
the user context. | f2527:c0:m4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.