code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def batch_to_head_dim(self, tensor: torch.Tensor) -> torch.Tensor:
r"""
Reshape the tensor from `[batch_size, seq_len, dim]` to `[batch_size // heads, seq_len, dim * heads]`. `heads`
is the number of heads initialized while constructing the `Attention` class.
Args:
tensor (`... |
Reshape the tensor from `[batch_size, seq_len, dim]` to `[batch_size // heads, seq_len, dim * heads]`. `heads`
is the number of heads initialized while constructing the `Attention` class.
Args:
tensor (`torch.Tensor`): The tensor to reshape.
Returns:
`torch.Ten... | batch_to_head_dim | python | VAST-AI-Research/TripoSR | tsr/models/transformer/attention.py | https://github.com/VAST-AI-Research/TripoSR/blob/master/tsr/models/transformer/attention.py | MIT |
def head_to_batch_dim(self, tensor: torch.Tensor, out_dim: int = 3) -> torch.Tensor:
r"""
Reshape the tensor from `[batch_size, seq_len, dim]` to `[batch_size, seq_len, heads, dim // heads]` `heads` is
the number of heads initialized while constructing the `Attention` class.
Args:
... |
Reshape the tensor from `[batch_size, seq_len, dim]` to `[batch_size, seq_len, heads, dim // heads]` `heads` is
the number of heads initialized while constructing the `Attention` class.
Args:
tensor (`torch.Tensor`): The tensor to reshape.
out_dim (`int`, *optional*, de... | head_to_batch_dim | python | VAST-AI-Research/TripoSR | tsr/models/transformer/attention.py | https://github.com/VAST-AI-Research/TripoSR/blob/master/tsr/models/transformer/attention.py | MIT |
def get_attention_scores(
self,
query: torch.Tensor,
key: torch.Tensor,
attention_mask: torch.Tensor = None,
) -> torch.Tensor:
r"""
Compute the attention scores.
Args:
query (`torch.Tensor`): The query tensor.
key (`torch.Tensor`): Th... |
Compute the attention scores.
Args:
query (`torch.Tensor`): The query tensor.
key (`torch.Tensor`): The key tensor.
attention_mask (`torch.Tensor`, *optional*): The attention mask to use. If `None`, no mask is applied.
Returns:
`torch.Tensor`: T... | get_attention_scores | python | VAST-AI-Research/TripoSR | tsr/models/transformer/attention.py | https://github.com/VAST-AI-Research/TripoSR/blob/master/tsr/models/transformer/attention.py | MIT |
def prepare_attention_mask(
self,
attention_mask: torch.Tensor,
target_length: int,
batch_size: int,
out_dim: int = 3,
) -> torch.Tensor:
r"""
Prepare the attention mask for the attention computation.
Args:
attention_mask (`torch.Tensor`):... |
Prepare the attention mask for the attention computation.
Args:
attention_mask (`torch.Tensor`):
The attention mask to prepare.
target_length (`int`):
The target length of the attention mask. This is the length of the attention mask after padding... | prepare_attention_mask | python | VAST-AI-Research/TripoSR | tsr/models/transformer/attention.py | https://github.com/VAST-AI-Research/TripoSR/blob/master/tsr/models/transformer/attention.py | MIT |
def norm_encoder_hidden_states(
self, encoder_hidden_states: torch.Tensor
) -> torch.Tensor:
r"""
Normalize the encoder hidden states. Requires `self.norm_cross` to be specified when constructing the
`Attention` class.
Args:
encoder_hidden_states (`torch.Tensor`)... |
Normalize the encoder hidden states. Requires `self.norm_cross` to be specified when constructing the
`Attention` class.
Args:
encoder_hidden_states (`torch.Tensor`): Hidden states of the encoder.
Returns:
`torch.Tensor`: The normalized encoder hidden states.
... | norm_encoder_hidden_states | python | VAST-AI-Research/TripoSR | tsr/models/transformer/attention.py | https://github.com/VAST-AI-Research/TripoSR/blob/master/tsr/models/transformer/attention.py | MIT |
def forward(
self,
hidden_states: torch.Tensor,
encoder_hidden_states: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
encoder_attention_mask: Optional[torch.Tensor] = None,
):
"""
The [`Transformer1DModel`] forward method.
... |
The [`Transformer1DModel`] forward method.
Args:
hidden_states (`torch.LongTensor` of shape `(batch size, num latent pixels)` if discrete, `torch.FloatTensor` of shape `(batch size, channel, height, width)` if continuous):
Input `hidden_states`.
encoder_hidden_s... | forward | python | VAST-AI-Research/TripoSR | tsr/models/transformer/transformer_1d.py | https://github.com/VAST-AI-Research/TripoSR/blob/master/tsr/models/transformer/transformer_1d.py | MIT |
def log_metric(
accelerator,
metrics: Dict,
train_time: float,
step: int,
epoch: int,
learning_rate: float = None,
prefix: str = "train",
):
"""Helper function to log all training/evaluation metrics with the correct prefixes and styling."""
log_metrics = {}
for k, v in metrics.it... | Helper function to log all training/evaluation metrics with the correct prefixes and styling. | log_metric | python | huggingface/distil-whisper | training/run_distillation.py | https://github.com/huggingface/distil-whisper/blob/master/training/run_distillation.py | MIT |
def log_pred(
accelerator,
pred_str: List[str],
label_str: List[str],
norm_pred_str: List[str],
norm_label_str: List[str],
step: int,
prefix: str = "eval",
num_lines: int = 200000,
):
"""Helper function to log target/predicted transcriptions to weights and biases (wandb)."""
if a... | Helper function to log target/predicted transcriptions to weights and biases (wandb). | log_pred | python | huggingface/distil-whisper | training/run_distillation.py | https://github.com/huggingface/distil-whisper/blob/master/training/run_distillation.py | MIT |
def convert_dataset_str_to_list(
dataset_names,
dataset_config_names,
splits=None,
text_column_names=None,
dataset_samples=None,
default_split="train",
) -> List[Dict]:
"""
Given three lists of dataset names, configs and splits, this function groups the corresponding
names/configs/sp... |
Given three lists of dataset names, configs and splits, this function groups the corresponding
names/configs/splits. Each dataset is assigned a unique dictionary with these metadata values, and the
function returns a list of dictionaries, one for each dataset.
| convert_dataset_str_to_list | python | huggingface/distil-whisper | training/run_distillation.py | https://github.com/huggingface/distil-whisper/blob/master/training/run_distillation.py | MIT |
def sorted_checkpoints(output_dir=None, checkpoint_prefix="checkpoint") -> List[str]:
"""Helper function to sort saved checkpoints from oldest to newest."""
ordering_and_checkpoint_path = []
glob_checkpoints = [str(x) for x in Path(output_dir).glob(f"{checkpoint_prefix}-*") if os.path.isdir(x)]
glob_ch... | Helper function to sort saved checkpoints from oldest to newest. | sorted_checkpoints | python | huggingface/distil-whisper | training/run_distillation.py | https://github.com/huggingface/distil-whisper/blob/master/training/run_distillation.py | MIT |
def sorted_best_checkpoints(output_dir=None, checkpoint_prefix="checkpoint"):
"""Helper function to sort saved best checkpoints."""
ordering_and_checkpoint_path = []
glob_checkpoints = [str(x) for x in Path(output_dir).glob(f"{checkpoint_prefix}-*") if os.path.isdir(x)]
for path in glob_checkpoints:
... | Helper function to sort saved best checkpoints. | sorted_best_checkpoints | python | huggingface/distil-whisper | training/run_distillation.py | https://github.com/huggingface/distil-whisper/blob/master/training/run_distillation.py | MIT |
def rotate_checkpoints(save_total_limit=None, output_dir=None, checkpoint_prefix="checkpoint", sorting_fn=sorted_checkpoints) -> None:
"""Helper function to delete old checkpoints."""
if save_total_limit is None or save_total_limit <= 0:
return
# Check if we should delete older checkpoint(s)
che... | Helper function to delete old checkpoints. | rotate_checkpoints | python | huggingface/distil-whisper | training/run_distillation.py | https://github.com/huggingface/distil-whisper/blob/master/training/run_distillation.py | MIT |
def get_parameter_names(model, forbidden_layer_types, forbidden_module=None):
"""
Returns the names of the model parameters that are not inside a forbidden layer or forbidden module.
Can be used to get a subset of parameter names for decay masks, or to exclude parameters from an optimiser
(e.g. if the m... |
Returns the names of the model parameters that are not inside a forbidden layer or forbidden module.
Can be used to get a subset of parameter names for decay masks, or to exclude parameters from an optimiser
(e.g. if the module is frozen).
| get_parameter_names | python | huggingface/distil-whisper | training/run_distillation.py | https://github.com/huggingface/distil-whisper/blob/master/training/run_distillation.py | MIT |
def prepare_train_dataset(batch):
"""
Pre-process the raw dataset in a three stage process:
1. Convert the audio arrays to log-mel spectrogram inputs
2. Possibly filter the timestamp tokens from the token ids (depending on the timestamp probability)
3. Possibly add pr... |
Pre-process the raw dataset in a three stage process:
1. Convert the audio arrays to log-mel spectrogram inputs
2. Possibly filter the timestamp tokens from the token ids (depending on the timestamp probability)
3. Possibly add prompt tokens if conditioning on previous text ... | prepare_train_dataset | python | huggingface/distil-whisper | training/run_distillation.py | https://github.com/huggingface/distil-whisper/blob/master/training/run_distillation.py | MIT |
def shift_tokens_right(label_ids: np.array, decoder_start_token_id: int) -> np.ndarray:
"""
Shift label ids one token to the right.
"""
shifted_label_ids = np.zeros_like(label_ids)
shifted_label_ids[:, 1:] = label_ids[:, :-1]
shifted_label_ids[:, 0] = decoder_start_token_id
return shifted_l... |
Shift label ids one token to the right.
| shift_tokens_right | python | huggingface/distil-whisper | training/run_pseudo_labelling.py | https://github.com/huggingface/distil-whisper/blob/master/training/run_pseudo_labelling.py | MIT |
def log_metric(
accelerator,
metrics: Dict,
train_time: float,
prefix: str = "eval",
):
"""Helper function to log all evaluation metrics with the correct prefixes and styling."""
log_metrics = {}
for k, v in metrics.items():
log_metrics[f"{prefix}/{k}"] = v
log_metrics[f"{prefix}... | Helper function to log all evaluation metrics with the correct prefixes and styling. | log_metric | python | huggingface/distil-whisper | training/run_pseudo_labelling.py | https://github.com/huggingface/distil-whisper/blob/master/training/run_pseudo_labelling.py | MIT |
def create_learning_rate_fn(
num_train_steps: int, lr_scheduler_type: str, num_warmup_steps: int, learning_rate: float
) -> Callable[[int], jnp.array]:
"""Returns a linear warmup, linear_decay learning rate function."""
lr_scheduler_types = ("linear", "constant_with_warmup")
if lr_scheduler_type not in... | Returns a linear warmup, linear_decay learning rate function. | create_learning_rate_fn | python | huggingface/distil-whisper | training/flax/convert_train_state_to_hf.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/convert_train_state_to_hf.py | MIT |
def apply_gradients(self, *, grads, **kwargs):
"""Updates `step`, `params`, `opt_state` and `**kwargs` in return value, clipping the
gradients by the maximum grad norm.
Note that internally this function calls `.tx.update()` followed by a call
to `optax.apply_updates()` to update `param... | Updates `step`, `params`, `opt_state` and `**kwargs` in return value, clipping the
gradients by the maximum grad norm.
Note that internally this function calls `.tx.update()` followed by a call
to `optax.apply_updates()` to update `params` and `opt_state`.
Args:
grads: Gradie... | apply_gradients | python | huggingface/distil-whisper | training/flax/convert_train_state_to_hf.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/convert_train_state_to_hf.py | MIT |
def get_data_loader(
seed: int,
dataset: IterableDataset,
batch_size: int,
data_collator: FlaxDataCollatorSpeechSeq2SeqWithPadding,
shuffle: bool = True,
drop_last: bool = True,
dataloader_num_workers: int = 0,
skip_batches: int = 0,
pin_memory: bool = True,
prefetch_size: int = ... |
Returns batches of size `batch_size` from `dataset`. If `drop_last` is set to `False`, the final batch may be incomplete,
and range in size from 1 to `batch_size`. Shuffle batches if `shuffle` is `True`.
Args:
seed (int): Numpy seed for generating pseudo random numbers. Used if shuffling the datas... | get_data_loader | python | huggingface/distil-whisper | training/flax/run_distillation.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/run_distillation.py | MIT |
def create(cls, *, apply_fn, params, tx, to_dtype: to_fp32, **kwargs):
"""Creates a new instance with `step=0` and initialized `opt_state`."""
# downcast optimizer state to bf16 if mixed-precision training
opt_state = tx.init(to_dtype(params))
return cls(
step=0,
... | Creates a new instance with `step=0` and initialized `opt_state`. | create | python | huggingface/distil-whisper | training/flax/run_distillation.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/run_distillation.py | MIT |
def get_layers_to_supervise(student_layers: int, teacher_layers: int) -> dict:
"""Helper function to map the student layer i to the teacher layer j whose output we'd like them to emulate. Used
for MSE loss terms in distillation (hidden-states and activations). Student layers are paired with teacher layers
i... | Helper function to map the student layer i to the teacher layer j whose output we'd like them to emulate. Used
for MSE loss terms in distillation (hidden-states and activations). Student layers are paired with teacher layers
in equal increments, e.g. for a 12-layer model distilled to a 3-layer model, student la... | get_layers_to_supervise | python | huggingface/distil-whisper | training/flax/run_distillation.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/run_distillation.py | MIT |
def _np_extract_fbank_features(self, waveform: np.array) -> np.ndarray:
"""
Compute the log-mel spectrogram of the provided audio using torch filters. Using the torch implementation
computes stft filter banks approx 5x faster than its numpy counterpart, which is the native implementation
... |
Compute the log-mel spectrogram of the provided audio using torch filters. Using the torch implementation
computes stft filter banks approx 5x faster than its numpy counterpart, which is the native implementation
in transformers, and matches to within 1e-5 abs tolerance.
| _np_extract_fbank_features | python | huggingface/distil-whisper | training/flax/run_distillation.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/run_distillation.py | MIT |
def get_data_loader(
dataset: Dataset,
batch_size: int,
data_collator: FlaxDataCollatorSpeechSeq2SeqWithPadding,
dataloader_num_workers: int = 0,
pin_memory: bool = True,
) -> DataLoader:
"""
Returns batches of size `batch_size` from `dataset`. If `drop_last` is set to `False`, the final bat... |
Returns batches of size `batch_size` from `dataset`. If `drop_last` is set to `False`, the final batch may be incomplete,
and range in size from 1 to `batch_size`. Shuffle batches if `shuffle` is `True`.
Args:
dataset (Dataset): dataset from which to load the data.
batch_size (int): how ma... | get_data_loader | python | huggingface/distil-whisper | training/flax/run_eval.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/run_eval.py | MIT |
def loss_fn(logits, labels, label_smoothing_factor=0.0):
"""
The label smoothing implementation is adapted from Flax's official example:
https://github.com/google/flax/blob/87a211135c6a377c8f29048a1cac3840e38b9da4/examples/wmt/train.py#L104
"""
vocab_size = logits.shape[-1]
... |
The label smoothing implementation is adapted from Flax's official example:
https://github.com/google/flax/blob/87a211135c6a377c8f29048a1cac3840e38b9da4/examples/wmt/train.py#L104
| loss_fn | python | huggingface/distil-whisper | training/flax/run_eval.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/run_eval.py | MIT |
def get_data_loader(
rng: jax.random.PRNGKey,
dataset: Dataset,
batch_size: int,
data_collator: FlaxDataCollatorSpeechSeq2SeqWithPadding,
shuffle: bool = True,
drop_last: bool = True,
dataloader_num_workers: int = 0,
pin_memory: bool = True,
) -> DataLoader:
"""
Returns batches o... |
Returns batches of size `batch_size` from `dataset`. If `drop_last` is set to `False`, the final batch may be incomplete,
and range in size from 1 to `batch_size`. Shuffle batches if `shuffle` is `True`.
Args:
rng (List(int)): JAX rng for generating pseudo random numbers. Used if shuffling the dat... | get_data_loader | python | huggingface/distil-whisper | training/flax/run_finetuning.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/run_finetuning.py | MIT |
def nd_dense_init(scale, mode, distribution):
"""Initializer with in_axis, out_axis set at call time."""
def init_fn(key, shape, dtype, in_axis, out_axis):
fn = variance_scaling(scale, mode, distribution, in_axis, out_axis)
return fn(key, shape, dtype)
return init_fn | Initializer with in_axis, out_axis set at call time. | nd_dense_init | python | huggingface/distil-whisper | training/flax/distil_whisper/layers.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py | MIT |
def __call__(
self,
inputs_q: Array,
inputs_kv: Array,
mask: Optional[Array] = None,
bias: Optional[Array] = None,
*,
decode: bool = False,
deterministic: bool = False,
) -> Array:
"""Applies multi-head dot product attention on the input data.
... | Applies multi-head dot product attention on the input data.
Projects the inputs into multi-headed query, key, and value vectors,
applies dot-product attention and project the results to an output vector.
There are two modes: decoding and non-decoding (e.g., training). The mode is
deter... | __call__ | python | huggingface/distil-whisper | training/flax/distil_whisper/layers.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py | MIT |
def __call__(self, inputs: Array) -> Array:
"""Applies a linear transformation to the inputs along multiple dimensions.
Args:
inputs: The nd-array to be transformed.
Returns:
The transformed input.
"""
features = _canonicalize_tuple(self.features)
ax... | Applies a linear transformation to the inputs along multiple dimensions.
Args:
inputs: The nd-array to be transformed.
Returns:
The transformed input.
| __call__ | python | huggingface/distil-whisper | training/flax/distil_whisper/layers.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py | MIT |
def _convert_to_activation_function(fn_or_string: Union[str, Callable]) -> Callable:
"""Convert a string to an activation function."""
if fn_or_string == "linear":
return lambda x: x
elif isinstance(fn_or_string, str):
return getattr(nn, fn_or_string)
elif callable(fn_or_string):
... | Convert a string to an activation function. | _convert_to_activation_function | python | huggingface/distil-whisper | training/flax/distil_whisper/layers.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py | MIT |
def __call__(self, inputs: Array) -> Array:
"""Embeds the inputs along the last dimension.
Args:
inputs: input data, all dimensions are considered batch dimensions.
Returns:
Output which is embedded input data. The output shape follows the input,
with an addition... | Embeds the inputs along the last dimension.
Args:
inputs: input data, all dimensions are considered batch dimensions.
Returns:
Output which is embedded input data. The output shape follows the input,
with an additional `features` dimension appended.
| __call__ | python | huggingface/distil-whisper | training/flax/distil_whisper/layers.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py | MIT |
def attend(self, query: Array) -> Array:
"""Attend over the embedding using a query array.
Args:
query: array with last dimension equal the feature depth `features` of the
embedding.
Returns:
An array with final dim `num_embeddings` corresponding to the batched
... | Attend over the embedding using a query array.
Args:
query: array with last dimension equal the feature depth `features` of the
embedding.
Returns:
An array with final dim `num_embeddings` corresponding to the batched
inner-product of the array of query vector... | attend | python | huggingface/distil-whisper | training/flax/distil_whisper/layers.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py | MIT |
def _relative_position_bucket(relative_position, bidirectional=True, num_buckets=32, max_distance=128):
"""Translate relative position to a bucket number for relative attention.
The relative position is defined as memory_position - query_position, i.e.
the distance in tokens from the attending ... | Translate relative position to a bucket number for relative attention.
The relative position is defined as memory_position - query_position, i.e.
the distance in tokens from the attending position to the attended-to
position. If bidirectional=False, then positive relative positions are
... | _relative_position_bucket | python | huggingface/distil-whisper | training/flax/distil_whisper/layers.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py | MIT |
def __call__(self, qlen, klen, bidirectional=True):
"""Produce relative position embedding attention biases.
Args:
qlen: attention query length.
klen: attention key length.
bidirectional: whether to allow positive memory-query relative position
embeddings.
... | Produce relative position embedding attention biases.
Args:
qlen: attention query length.
klen: attention key length.
bidirectional: whether to allow positive memory-query relative position
embeddings.
Returns:
output: `(1, len, q_len, k_len)` attent... | __call__ | python | huggingface/distil-whisper | training/flax/distil_whisper/layers.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py | MIT |
def __call__(self, x):
"""Applies layer normalization on the input.
Args:
x: the inputs
Returns:
Normalized inputs (the same shape as inputs).
"""
x = jnp.asarray(x, jnp.float32)
features = x.shape[-1]
mean = jnp.mean(x, axis=-1, keepdims=True)... | Applies layer normalization on the input.
Args:
x: the inputs
Returns:
Normalized inputs (the same shape as inputs).
| __call__ | python | huggingface/distil-whisper | training/flax/distil_whisper/layers.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py | MIT |
def make_attention_mask(
query_input: Array,
key_input: Array,
pairwise_fn: Callable = jnp.multiply,
extra_batch_dims: int = 0,
dtype: DType = jnp.float32,
) -> Array:
"""Mask-making helper for attention weights.
In case of 1d inputs (i.e., `[batch, len_q]`, `[batch, len_kv]`, the
atten... | Mask-making helper for attention weights.
In case of 1d inputs (i.e., `[batch, len_q]`, `[batch, len_kv]`, the
attention weights will be `[batch, heads, len_q, len_kv]` and this
function will produce `[batch, 1, len_q, len_kv]`.
Args:
query_input: a batched, flat input of query_length size
... | make_attention_mask | python | huggingface/distil-whisper | training/flax/distil_whisper/layers.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py | MIT |
def make_causal_mask(x: Array, extra_batch_dims: int = 0, dtype: DType = jnp.float32) -> Array:
"""Make a causal mask for self-attention.
In case of 1d inputs (i.e., `[batch, len]`, the self-attention weights
will be `[batch, heads, len, len]` and this function will produce a
causal mask of shape `[bat... | Make a causal mask for self-attention.
In case of 1d inputs (i.e., `[batch, len]`, the self-attention weights
will be `[batch, heads, len, len]` and this function will produce a
causal mask of shape `[batch, 1, len, len]`.
Note that a causal mask does not depend on the values of x; it only depends on
... | make_causal_mask | python | huggingface/distil-whisper | training/flax/distil_whisper/layers.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py | MIT |
def combine_masks(*masks: Optional[Array], dtype: DType = jnp.float32):
"""Combine attention masks.
Args:
*masks: set of attention mask arguments to combine, some can be None.
dtype: final mask dtype
Returns:
Combined mask, reduced by logical and, returns None if no masks given.
"""
... | Combine attention masks.
Args:
*masks: set of attention mask arguments to combine, some can be None.
dtype: final mask dtype
Returns:
Combined mask, reduced by logical and, returns None if no masks given.
| combine_masks | python | huggingface/distil-whisper | training/flax/distil_whisper/layers.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py | MIT |
def combine_biases(*masks: Optional[Array]):
"""Combine attention biases.
Args:
*masks: set of attention bias arguments to combine, some can be None.
Returns:
Combined mask, reduced by summation, returns None if no masks given.
"""
masks = [m for m in masks if m is not None]
if not... | Combine attention biases.
Args:
*masks: set of attention bias arguments to combine, some can be None.
Returns:
Combined mask, reduced by summation, returns None if no masks given.
| combine_biases | python | huggingface/distil-whisper | training/flax/distil_whisper/layers.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py | MIT |
def make_decoder_mask(
decoder_target_tokens: Array,
dtype: DType,
decoder_causal_attention: Optional[Array] = None,
decoder_segment_ids: Optional[Array] = None,
) -> Array:
"""Compute the self-attention mask for a decoder.
Decoder mask is formed by combining a causal mask, a padding mask and a... | Compute the self-attention mask for a decoder.
Decoder mask is formed by combining a causal mask, a padding mask and an
optional packing mask. If decoder_causal_attention is passed, it makes the
masking non-causal for positions that have value of 1.
A prefix LM is applied to a dataset which has a noti... | make_decoder_mask | python | huggingface/distil-whisper | training/flax/distil_whisper/layers.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py | MIT |
def canonicalize_padding(padding: PaddingLike, rank: int) -> LaxPadding:
""" "Canonicalizes conv padding to a jax.lax supported format."""
if isinstance(padding, str):
return padding
if isinstance(padding, int):
return [(padding, padding)] * rank
if isinstance(padding, Sequence) and len(... | "Canonicalizes conv padding to a jax.lax supported format. | canonicalize_padding | python | huggingface/distil-whisper | training/flax/distil_whisper/layers.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py | MIT |
def _conv_dimension_numbers(input_shape):
"""Computes the dimension numbers based on the input shape."""
ndim = len(input_shape)
lhs_spec = (0, ndim - 1) + tuple(range(1, ndim - 1))
rhs_spec = (ndim - 1, ndim - 2) + tuple(range(0, ndim - 2))
out_spec = lhs_spec
return lax.ConvDimensionNumbers(lh... | Computes the dimension numbers based on the input shape. | _conv_dimension_numbers | python | huggingface/distil-whisper | training/flax/distil_whisper/layers.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py | MIT |
def __call__(self, inputs: Array) -> Array:
"""Applies a (potentially unshared) convolution to the inputs.
Args:
inputs: input data with dimensions (*batch_dims, spatial_dims...,
features). This is the channels-last convention, i.e. NHWC for a 2d
convolution and NDHWC ... | Applies a (potentially unshared) convolution to the inputs.
Args:
inputs: input data with dimensions (*batch_dims, spatial_dims...,
features). This is the channels-last convention, i.e. NHWC for a 2d
convolution and NDHWC for a 3D convolution. Note: this is different from
... | __call__ | python | huggingface/distil-whisper | training/flax/distil_whisper/layers.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/layers.py | MIT |
def convert_unroll_to_scan(self, params: Union[Dict, FrozenDict]):
r"""
Convert a `PyTree` of unrolled model parameters to a scanned block of model parameters. This method can be used
to explicitly convert the model parameters to scanned format. This returns a new `params` tree and does not
... |
Convert a `PyTree` of unrolled model parameters to a scanned block of model parameters. This method can be used
to explicitly convert the model parameters to scanned format. This returns a new `params` tree and does not
convert the `params` in place.
To illustrate the workings of this ... | convert_unroll_to_scan | python | huggingface/distil-whisper | training/flax/distil_whisper/modeling_flax_whisper.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/modeling_flax_whisper.py | MIT |
def convert_scan_to_unroll(self, params: Union[Dict, FrozenDict]):
r"""
Convert a `PyTree` of scanned model parameters to an unrolled stack of model parameters. This method can be
used to explicitly convert the model parameters to unrolled format. This returns a new `params` tree and does
... |
Convert a `PyTree` of scanned model parameters to an unrolled stack of model parameters. This method can be
used to explicitly convert the model parameters to unrolled format. This returns a new `params` tree and does
not convert the `params` in place.
To illustrate the workings of thi... | convert_scan_to_unroll | python | huggingface/distil-whisper | training/flax/distil_whisper/modeling_flax_whisper.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/modeling_flax_whisper.py | MIT |
def init_cache(self, batch_size, max_length, encoder_outputs):
r"""
Args:
batch_size (`int`):
batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache.
max_length (`int`):
maximum possible length for auto-r... |
Args:
batch_size (`int`):
batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache.
max_length (`int`):
maximum possible length for auto-regressive decoding. Defines the sequence length of the initialized
... | init_cache | python | huggingface/distil-whisper | training/flax/distil_whisper/modeling_flax_whisper.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/modeling_flax_whisper.py | MIT |
def encode(
self,
input_features: jnp.ndarray,
attention_mask: Optional[jnp.ndarray] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
train: bool = False,
params: dict = None... |
Returns:
Example:
```python
>>> from transformers import WhisperProcessor, FlaxWhisperForConditionalGeneration
>>> from datasets import load_dataset
>>> processor = WhisperProcessor.from_pretrained("openai/whisper-tiny.en")
>>> model = FlaxWhisperForConditiona... | encode | python | huggingface/distil-whisper | training/flax/distil_whisper/modeling_flax_whisper.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/modeling_flax_whisper.py | MIT |
def decode(
self,
decoder_input_ids,
encoder_outputs,
encoder_attention_mask: Optional[jnp.ndarray] = None,
decoder_attention_mask: Optional[jnp.ndarray] = None,
decoder_position_ids: Optional[jnp.ndarray] = None,
past_key_values: dict = None,
output_atten... |
Returns:
Example:
```python
>>> from transformers import WhisperProcessor, FlaxWhisperForConditionalGeneration
>>> from datasets import load_dataset
>>> processor = WhisperProcessor.from_pretrained("openai/whisper-tiny.en")
>>> model = FlaxWhisperForConditiona... | decode | python | huggingface/distil-whisper | training/flax/distil_whisper/modeling_flax_whisper.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/modeling_flax_whisper.py | MIT |
def pjit_with_cpu_fallback(
fun: Callable, # pylint: disable=g-bare-generic
in_axis_resources,
out_axis_resources,
static_argnums: Union[int, Sequence[int]] = (),
donate_argnums: Union[int, Sequence[int]] = (),
backend: Optional[str] = None,
):
"""Wrapper for pjit that calls normal jit on c... | Wrapper for pjit that calls normal jit on cpu. | pjit_with_cpu_fallback | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def with_sharding_constraint(x, axis_resources):
"""Wrapper for pjit with_sharding_constraint, no-op on cpu or outside pjit."""
if jax.devices()[0].platform == "cpu" or not global_mesh_defined():
return x
else:
return jax.experimental.pjit.with_sharding_constraint(x, axis_resources) | Wrapper for pjit with_sharding_constraint, no-op on cpu or outside pjit. | with_sharding_constraint | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def bounds_from_last_device(last_device: JaxDevice) -> HardwareMesh:
"""Get the bound from the given last device."""
# Must be passed the device at the highest-coordinate corner of the
# relevant mesh, which is a requirement we know is satisfied by the last
# device in jax.devices().
if hasattr(last... | Get the bound from the given last device. | bounds_from_last_device | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def get_coords(device: JaxDevice) -> HardwareMesh:
"""Returns the coordinates of the given device."""
if hasattr(device, "coords"):
return (*device.coords, device.core_on_chip)
return (device.process_index, device.id % jax.local_device_count()) | Returns the coordinates of the given device. | get_coords | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def global_mesh_defined():
"""Checks if global xmap/pjit mesh resource environment is defined."""
maps_env = jax.experimental.maps.thread_resources.env
return maps_env.physical_mesh.devices.shape != () # pylint: disable=g-explicit-bool-comparison | Checks if global xmap/pjit mesh resource environment is defined. | global_mesh_defined | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def get_mesh(
model_parallel_submesh: HardwareMesh,
input_devices: Sequence[JaxDevice] = (),
input_local_devices: Sequence[JaxDevice] = (),
tile_by_host_if_needed: bool = True,
backend: Optional[str] = None,
) -> Mesh:
"""Construct an xmap/pjit Mesh for the given model-parallel submesh.
The... | Construct an xmap/pjit Mesh for the given model-parallel submesh.
The resulting mesh has two resource axes: 'model', with the provided submesh
shape, and 'data', which covers the rest of the mesh.
Args:
model_parallel_submesh: a HardwareMesh spec, namely (x,y,z,core) on TPU for
a single mode... | get_mesh | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def dh_dd_mh_md(g: int, m: int, l: int) -> Tuple[int, int, int, int]:
"""Split a global mesh dimension into four tiling components.
Args:
g: global mesh bounds dimension size
m: model-parallel submesh bounds dimension size
l: local submesh bounds dimens... | Split a global mesh dimension into four tiling components.
Args:
g: global mesh bounds dimension size
m: model-parallel submesh bounds dimension size
l: local submesh bounds dimension size
Returns:
The resulting tuple divides the dimensio... | dh_dd_mh_md | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def get_gpu_mesh(num_partitions: int) -> Mesh:
"""Mesh for GPUs that preferentially places 'model' on NVLink."""
nvlink_size = jax.local_device_count()
dcn_size = jax.process_count()
nvlink_mp = min(num_partitions, nvlink_size)
nvlink_dp, extra1 = divmod(nvlink_size, nvlink_mp)
dcn_mp, extra2 = ... | Mesh for GPUs that preferentially places 'model' on NVLink. | get_gpu_mesh | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def default_mesh(
num_partitions: int,
model_parallel_submesh: Optional[HardwareMesh] = None,
backend: Optional[str] = None,
) -> Mesh:
"""Attempt to return a default mesh for simple cases.
Args:
num_partitions: number of partitions to use, will be ignored if
model_parallel_submesh is... | Attempt to return a default mesh for simple cases.
Args:
num_partitions: number of partitions to use, will be ignored if
model_parallel_submesh is provided.
model_parallel_submesh: 4-tuple that specifies the x,y,z,c submesh to use as
the model-parallel device tile.
backend: get de... | default_mesh | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def get_local_chunk_info(
self, global_shape: Tuple[int, ...], mesh_axes: Sequence[Optional[str]]
) -> LocalChunkInfo:
"""Get the local chunk info for a given array shape and sharded axes.
Args:
global_shape: the global, unsharded shape of the array to chunk.
mesh_axes: ... | Get the local chunk info for a given array shape and sharded axes.
Args:
global_shape: the global, unsharded shape of the array to chunk.
mesh_axes: a sequence of names (or None) of equal rank to `global_shape`
that specifies which mesh dimensions the array is sharded along.
... | get_local_chunk_info | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def standard_logical_axis_rules(
activation_partitioning_dims: int = 1,
parameter_partitioning_dims: int = 1,
additional_rules: Optional[LogicalAxisRules] = None,
) -> LogicalAxisRules:
"""Default sharding rules for T5X model in terms of logical axis names.
Args:
activation_partitioning_dims:... | Default sharding rules for T5X model in terms of logical axis names.
Args:
activation_partitioning_dims: enables 2-D activation sharding when set to 2.
parameter_partitioning_dims: enables 2-D parameter sharding when set to 2.
additional_rules: additional rules (a sequence of tuples) that will be... | standard_logical_axis_rules | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def _id_fn(x, ix):
"""Identity function for copying parameters to the devices, sharded."""
# A pure identity such as `lambda x, *: x` can get optimized away, so we
# include a random.split as a cheap function that cannot be optimized away.
y = random.split(random.PRNGKey(jnp.array(ix, dtype=jnp.uint32))... | Identity function for copying parameters to the devices, sharded. | _id_fn | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def __init__(
self,
num_partitions: Optional[int] = None,
model_parallel_submesh: Optional[HardwareMesh] = None,
params_on_devices: bool = True,
backend: Optional[str] = None,
):
"""Configures the partitioner.
Args:
num_partitions: the number of par... | Configures the partitioner.
Args:
num_partitions: the number of partitions to use. Ignored if
`model_parallel_submesh` is provided.
model_parallel_submesh: 4-tuple that specifies the x,y,z,c submesh to use
as the model-parallel device tile. This submesh is used for t... | __init__ | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def get_data_layout(self, batch_size: Optional[int] = None, host_index: Optional[int] = None) -> DataLayout:
"""Returns filled `DataLayout` based on the partitioned model layout.
Args:
batch_size: if set, indicates the requested batch size. The exception will
be raised if this bat... | Returns filled `DataLayout` based on the partitioned model layout.
Args:
batch_size: if set, indicates the requested batch size. The exception will
be raised if this batch size is not compatible with the layout. If not
set, the batch size is inferred from the layout.
... | get_data_layout | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def get_local_chunk_info(
self, global_shape: Tuple[int, ...], mesh_axes: Sequence[Optional[str]]
) -> LocalChunkInfo:
"""Returns the local chunk info for a given array shape and sharded axes."""
return self._local_chunker.get_local_chunk_info(global_shape, mesh_axes) | Returns the local chunk info for a given array shape and sharded axes. | get_local_chunk_info | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def move_params_to_devices(self, train_state: TrainState, train_state_axes: TrainState) -> TrainState:
"""Moves the optimizer parameters to devices."""
p_id_fn = self.partition(
_id_fn,
in_axis_resources=(train_state_axes, None),
out_axis_resources=(train_state_axes, ... | Moves the optimizer parameters to devices. | move_params_to_devices | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def get_logical_axes(self, train_state: TrainState) -> TrainState:
"""Returns a copy of TrainState with Optional[AxisNames] as leaves."""
# By default, return None for the logical axes.
return train_state.restore_state(jax.tree_map(lambda x: None, train_state.state_dict())) | Returns a copy of TrainState with Optional[AxisNames] as leaves. | get_logical_axes | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def partition(
self,
fn: Callable, # pylint: disable=g-bare-generic
in_axis_resources,
out_axis_resources,
static_argnums: Union[int, Sequence[int]] = (),
donate_argnums: Union[int, Sequence[int]] = (),
) -> PartitionedCallable:
"""Partitions the computation ... | Partitions the computation using partitioner-specific implementation.
Args:
fn: the function to partition.
in_axis_resources: Pytree of structure matching that of arguments to `fn`,
with all actual arguments replaced by resource assignment
specifications. It is also ... | partition | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def __init__(
self,
num_partitions: Optional[int] = None,
model_parallel_submesh: Optional[HardwareMesh] = None,
params_on_devices: bool = True,
backend: Optional[str] = None,
logical_axis_rules: Optional[LogicalAxisRules] = None,
use_cpu_pjit: Optional[bool] = Fa... | PjitPartitioner constructor.
See https://github.com/google-research/text-to-text-transfer-transformer/blob/main/README.mdx/usage/partitioning for details.
Args:
num_partitions: an integer that specifies the size of the model parallel
submesh to be automatically selected for the c... | __init__ | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def partition(
self,
fn: Callable, # pylint: disable=g-bare-generic
in_axis_resources,
out_axis_resources,
static_argnums: Union[int, Sequence[int]] = (),
donate_argnums: Union[int, Sequence[int]] = (),
) -> PjittedFnWithContext:
"""Partitions the function us... | Partitions the function using jax.pjit. | partition | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def get_mesh_axes(self, train_state: TrainState) -> TrainState:
"""Returns a copy of TrainState with Optional[PartitionSpecs] as leaves."""
logical_axes = self.get_logical_axes(train_state)
def _logical_to_mesh_axes(param_name, logical_axes):
if logical_axes is None:
... | Returns a copy of TrainState with Optional[PartitionSpecs] as leaves. | get_mesh_axes | python | huggingface/distil-whisper | training/flax/distil_whisper/partitioner.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/partitioner.py | MIT |
def __init__(
self,
checkpoint="openai/whisper-large-v2",
dtype=jnp.float32,
batch_size=None,
max_length=None,
**kwargs,
):
"""
Args
checkpoint (`str`, *optional*, defaults to `"openai/whisper-large-v2"):
The Whisper checkpo... |
Args
checkpoint (`str`, *optional*, defaults to `"openai/whisper-large-v2"):
The Whisper checkpoint to use with the pipeline. Must be an available checkpoint on the Hugging Face Hub
with Flax weights.
dtype (`jax.numpy.dtype`, *optional*, defaults to `jax... | __init__ | python | huggingface/distil-whisper | training/flax/distil_whisper/pipeline.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/pipeline.py | MIT |
def __call__(
self,
inputs,
chunk_length_s=30.0,
stride_length_s=None,
batch_size=None,
language=None,
task=None,
return_timestamps=None,
num_beams=1,
length_penalty=1.0,
do_sample=False,
top_k=50,
temperature=1.0,
... |
Transcribe an audio input sequence to a text transcription, optionally with timestamps.
Args:
inputs (`np.ndarray` or `bytes` or `str` or `dict`):
The inputs is either:
- `str` that is the filename of the audio file, the file will be read at the correct ... | __call__ | python | huggingface/distil-whisper | training/flax/distil_whisper/pipeline.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/pipeline.py | MIT |
def _split_variables_and_axes(
variables_and_axes: FrozenVariableDict,
) -> Tuple[FrozenVariableDict, FrozenVariableDict]:
"""Splits `variables_and_axes` into two separate dicts with the same keys."""
# For each `key`, `key_axes` (if any) are its axes in `variables_and_axes`.
variables = {}
axes = {... | Splits `variables_and_axes` into two separate dicts with the same keys. | _split_variables_and_axes | python | huggingface/distil-whisper | training/flax/distil_whisper/train_state.py | https://github.com/huggingface/distil-whisper/blob/master/training/flax/distil_whisper/train_state.py | MIT |
def emailUser(profile, SUBJECT="", BODY=""):
"""
sends an email.
Arguments:
profile -- contains information related to the user (e.g., email
address)
SUBJECT -- subject line of the email
BODY -- body text of the email
"""
def generateSMSEmail(profile):
... |
sends an email.
Arguments:
profile -- contains information related to the user (e.g., email
address)
SUBJECT -- subject line of the email
BODY -- body text of the email
| emailUser | python | jasperproject/jasper-client | client/app_utils.py | https://github.com/jasperproject/jasper-client/blob/master/client/app_utils.py | MIT |
def generateSMSEmail(profile):
"""
Generates an email from a user's phone number based on their carrier.
"""
if profile['carrier'] is None or not profile['phone_number']:
return None
return str(profile['phone_number']) + "@" + profile['carrier'] |
Generates an email from a user's phone number based on their carrier.
| generateSMSEmail | python | jasperproject/jasper-client | client/app_utils.py | https://github.com/jasperproject/jasper-client/blob/master/client/app_utils.py | MIT |
def getTimezone(profile):
"""
Returns the pytz timezone for a given profile.
Arguments:
profile -- contains information related to the user (e.g., email
address)
"""
try:
return timezone(profile['timezone'])
except:
return None |
Returns the pytz timezone for a given profile.
Arguments:
profile -- contains information related to the user (e.g., email
address)
| getTimezone | python | jasperproject/jasper-client | client/app_utils.py | https://github.com/jasperproject/jasper-client/blob/master/client/app_utils.py | MIT |
def generateTinyURL(URL):
"""
Generates a compressed URL.
Arguments:
URL -- the original URL to-be compressed
"""
target = "http://tinyurl.com/api-create.php?url=" + URL
response = urllib2.urlopen(target)
return response.read() |
Generates a compressed URL.
Arguments:
URL -- the original URL to-be compressed
| generateTinyURL | python | jasperproject/jasper-client | client/app_utils.py | https://github.com/jasperproject/jasper-client/blob/master/client/app_utils.py | MIT |
def __init__(self, mic, profile):
"""
Instantiates a new Brain object, which cross-references user
input with a list of modules. Note that the order of brain.modules
matters, as the Brain will cease execution on the first module
that accepts a given input.
Arguments:
... |
Instantiates a new Brain object, which cross-references user
input with a list of modules. Note that the order of brain.modules
matters, as the Brain will cease execution on the first module
that accepts a given input.
Arguments:
mic -- used to interact with the user (f... | __init__ | python | jasperproject/jasper-client | client/brain.py | https://github.com/jasperproject/jasper-client/blob/master/client/brain.py | MIT |
def get_modules(cls):
"""
Dynamically loads all the modules in the modules folder and sorts
them by the PRIORITY key. If no PRIORITY is defined for a given
module, a priority of 0 is assumed.
"""
logger = logging.getLogger(__name__)
locations = [jasperpath.PLUGIN... |
Dynamically loads all the modules in the modules folder and sorts
them by the PRIORITY key. If no PRIORITY is defined for a given
module, a priority of 0 is assumed.
| get_modules | python | jasperproject/jasper-client | client/brain.py | https://github.com/jasperproject/jasper-client/blob/master/client/brain.py | MIT |
def query(self, texts):
"""
Passes user input to the appropriate module, testing it against
each candidate module's isValid function.
Arguments:
text -- user input, typically speech, to be parsed by a module
"""
for module in self.modules:
for text in... |
Passes user input to the appropriate module, testing it against
each candidate module's isValid function.
Arguments:
text -- user input, typically speech, to be parsed by a module
| query | python | jasperproject/jasper-client | client/brain.py | https://github.com/jasperproject/jasper-client/blob/master/client/brain.py | MIT |
def handleForever(self):
"""
Delegates user input to the handling function when activated.
"""
self._logger.info("Starting to handle conversation with keyword '%s'.",
self.persona)
while True:
# Print notifications until empty
not... |
Delegates user input to the handling function when activated.
| handleForever | python | jasperproject/jasper-client | client/conversation.py | https://github.com/jasperproject/jasper-client/blob/master/client/conversation.py | MIT |
def check_network_connection(server="www.google.com"):
"""
Checks if jasper can connect a network server.
Arguments:
server -- (optional) the server to connect with (Default:
"www.google.com")
Returns:
True or False
"""
logger = logging.getLogger(__name__)
... |
Checks if jasper can connect a network server.
Arguments:
server -- (optional) the server to connect with (Default:
"www.google.com")
Returns:
True or False
| check_network_connection | python | jasperproject/jasper-client | client/diagnose.py | https://github.com/jasperproject/jasper-client/blob/master/client/diagnose.py | MIT |
def check_executable(executable):
"""
Checks if an executable exists in $PATH.
Arguments:
executable -- the name of the executable (e.g. "echo")
Returns:
True or False
"""
logger = logging.getLogger(__name__)
logger.debug("Checking executable '%s'...", executable)
execu... |
Checks if an executable exists in $PATH.
Arguments:
executable -- the name of the executable (e.g. "echo")
Returns:
True or False
| check_executable | python | jasperproject/jasper-client | client/diagnose.py | https://github.com/jasperproject/jasper-client/blob/master/client/diagnose.py | MIT |
def check_python_import(package_or_module):
"""
Checks if a python package or module is importable.
Arguments:
package_or_module -- the package or module name to check
Returns:
True or False
"""
logger = logging.getLogger(__name__)
logger.debug("Checking python import '%s'.... |
Checks if a python package or module is importable.
Arguments:
package_or_module -- the package or module name to check
Returns:
True or False
| check_python_import | python | jasperproject/jasper-client | client/diagnose.py | https://github.com/jasperproject/jasper-client/blob/master/client/diagnose.py | MIT |
def get_pip_requirements(fname=os.path.join(jasperpath.LIB_PATH,
'requirements.txt')):
"""
Gets the PIP requirements from a text file. If the files does not exists
or is not readable, it returns None
Arguments:
fname -- (optional) the requirement text... |
Gets the PIP requirements from a text file. If the files does not exists
or is not readable, it returns None
Arguments:
fname -- (optional) the requirement text file (Default:
"client/requirements.txt")
Returns:
A list of pip requirement objects or None
| get_pip_requirements | python | jasperproject/jasper-client | client/diagnose.py | https://github.com/jasperproject/jasper-client/blob/master/client/diagnose.py | MIT |
def get_git_revision():
"""
Gets the current git revision hash as hex string. If the git executable is
missing or git is unable to get the revision, None is returned
Returns:
A hex string or None
"""
logger = logging.getLogger(__name__)
if not check_executable('git'):
logger... |
Gets the current git revision hash as hex string. If the git executable is
missing or git is unable to get the revision, None is returned
Returns:
A hex string or None
| get_git_revision | python | jasperproject/jasper-client | client/diagnose.py | https://github.com/jasperproject/jasper-client/blob/master/client/diagnose.py | MIT |
def run():
"""
Performs a series of checks against the system and writes the results to
the logging system.
Returns:
The number of failed checks as integer
"""
logger = logging.getLogger(__name__)
# Set loglevel of this module least to info
loglvl = logger.getEffectiveLevel()
... |
Performs a series of checks against the system and writes the results to
the logging system.
Returns:
The number of failed checks as integer
| run | python | jasperproject/jasper-client | client/diagnose.py | https://github.com/jasperproject/jasper-client/blob/master/client/diagnose.py | MIT |
def __init__(self, speaker, passive_stt_engine, active_stt_engine):
"""
Initiates the pocketsphinx instance.
Arguments:
speaker -- handles platform-independent audio output
passive_stt_engine -- performs STT while Jasper is in passive listen
mode
... |
Initiates the pocketsphinx instance.
Arguments:
speaker -- handles platform-independent audio output
passive_stt_engine -- performs STT while Jasper is in passive listen
mode
acive_stt_engine -- performs STT while Jasper is in active listen mode
... | __init__ | python | jasperproject/jasper-client | client/mic.py | https://github.com/jasperproject/jasper-client/blob/master/client/mic.py | MIT |
def passiveListen(self, PERSONA):
"""
Listens for PERSONA in everyday sound. Times out after LISTEN_TIME, so
needs to be restarted.
"""
THRESHOLD_MULTIPLIER = 1.8
RATE = 16000
CHUNK = 1024
# number of seconds to allow to establish threshold
THRES... |
Listens for PERSONA in everyday sound. Times out after LISTEN_TIME, so
needs to be restarted.
| passiveListen | python | jasperproject/jasper-client | client/mic.py | https://github.com/jasperproject/jasper-client/blob/master/client/mic.py | MIT |
def activeListen(self, THRESHOLD=None, LISTEN=True, MUSIC=False):
"""
Records until a second of silence or times out after 12 seconds
Returns the first matching string or None
"""
options = self.activeListenToAllOptions(THRESHOLD, LISTEN, MUSIC)
if options:
... |
Records until a second of silence or times out after 12 seconds
Returns the first matching string or None
| activeListen | python | jasperproject/jasper-client | client/mic.py | https://github.com/jasperproject/jasper-client/blob/master/client/mic.py | MIT |
def activeListenToAllOptions(self, THRESHOLD=None, LISTEN=True,
MUSIC=False):
"""
Records until a second of silence or times out after 12 seconds
Returns a list of the matching options or None
"""
RATE = 16000
CHUNK = 1024
... |
Records until a second of silence or times out after 12 seconds
Returns a list of the matching options or None
| activeListenToAllOptions | python | jasperproject/jasper-client | client/mic.py | https://github.com/jasperproject/jasper-client/blob/master/client/mic.py | MIT |
def handleEmailNotifications(self, lastDate):
"""Places new Gmail notifications in the Notifier's queue."""
emails = Gmail.fetchUnreadEmails(self.profile, since=lastDate)
if emails:
lastDate = Gmail.getMostRecentDate(emails)
def styleEmail(e):
return "New email f... | Places new Gmail notifications in the Notifier's queue. | handleEmailNotifications | python | jasperproject/jasper-client | client/notifier.py | https://github.com/jasperproject/jasper-client/blob/master/client/notifier.py | MIT |
def getNotification(self):
"""Returns a notification. Note that this function is consuming."""
try:
notif = self.q.get(block=False)
return notif
except Queue.Empty:
return None | Returns a notification. Note that this function is consuming. | getNotification | python | jasperproject/jasper-client | client/notifier.py | https://github.com/jasperproject/jasper-client/blob/master/client/notifier.py | MIT |
def getAllNotifications(self):
"""
Return a list of notifications in chronological order.
Note that this function is consuming, so consecutive calls
will yield different results.
"""
notifs = []
notif = self.getNotification()
while notif:
... |
Return a list of notifications in chronological order.
Note that this function is consuming, so consecutive calls
will yield different results.
| getAllNotifications | python | jasperproject/jasper-client | client/notifier.py | https://github.com/jasperproject/jasper-client/blob/master/client/notifier.py | MIT |
def __init__(self, vocabulary, hmm_dir="/usr/local/share/" +
"pocketsphinx/model/hmm/en_US/hub4wsj_sc_8k"):
"""
Initiates the pocketsphinx instance.
Arguments:
vocabulary -- a PocketsphinxVocabulary instance
hmm_dir -- the path of the Hidden Markov Mode... |
Initiates the pocketsphinx instance.
Arguments:
vocabulary -- a PocketsphinxVocabulary instance
hmm_dir -- the path of the Hidden Markov Model (HMM)
| __init__ | python | jasperproject/jasper-client | client/stt.py | https://github.com/jasperproject/jasper-client/blob/master/client/stt.py | MIT |
def transcribe(self, fp):
"""
Performs STT, transcribing an audio file and returning the result.
Arguments:
fp -- a file object containing audio data
"""
fp.seek(44)
# FIXME: Can't use the Decoder.decode_raw() here, because
# pocketsphinx segfaults ... |
Performs STT, transcribing an audio file and returning the result.
Arguments:
fp -- a file object containing audio data
| transcribe | python | jasperproject/jasper-client | client/stt.py | https://github.com/jasperproject/jasper-client/blob/master/client/stt.py | MIT |
def __init__(self, api_key=None, language='en-us'):
# FIXME: get init args from config
"""
Arguments:
api_key - the public api key which allows access to Google APIs
"""
self._logger = logging.getLogger(__name__)
self._request_url = None
self._language = N... |
Arguments:
api_key - the public api key which allows access to Google APIs
| __init__ | python | jasperproject/jasper-client | client/stt.py | https://github.com/jasperproject/jasper-client/blob/master/client/stt.py | MIT |
def transcribe(self, fp):
"""
Performs STT via the Google Speech API, transcribing an audio file and
returning an English string.
Arguments:
audio_file_path -- the path to the .wav file to be transcribed
"""
if not self.api_key:
self._logger.critical... |
Performs STT via the Google Speech API, transcribing an audio file and
returning an English string.
Arguments:
audio_file_path -- the path to the .wav file to be transcribed
| transcribe | python | jasperproject/jasper-client | client/stt.py | https://github.com/jasperproject/jasper-client/blob/master/client/stt.py | MIT |
def get_engine_by_slug(slug=None):
"""
Returns:
An STT Engine implementation available on the current platform
Raises:
ValueError if no speaker implementation is supported on this platform
"""
if not slug or type(slug) is not str:
raise TypeError("Invalid slug '%s'", slug)
... |
Returns:
An STT Engine implementation available on the current platform
Raises:
ValueError if no speaker implementation is supported on this platform
| get_engine_by_slug | python | jasperproject/jasper-client | client/stt.py | https://github.com/jasperproject/jasper-client/blob/master/client/stt.py | MIT |
def get_engine_by_slug(slug=None):
"""
Returns:
A speaker implementation available on the current platform
Raises:
ValueError if no speaker implementation is supported on this platform
"""
if not slug or type(slug) is not str:
raise TypeError("Invalid slug '%s'", slug)
... |
Returns:
A speaker implementation available on the current platform
Raises:
ValueError if no speaker implementation is supported on this platform
| get_engine_by_slug | python | jasperproject/jasper-client | client/tts.py | https://github.com/jasperproject/jasper-client/blob/master/client/tts.py | MIT |
def phrases_to_revision(cls, phrases):
"""
Calculates a revision from phrases by using the SHA1 hash function.
Arguments:
phrases -- a list of phrases
Returns:
A revision string for given phrases.
"""
sorted_phrases = sorted(phrases)
join... |
Calculates a revision from phrases by using the SHA1 hash function.
Arguments:
phrases -- a list of phrases
Returns:
A revision string for given phrases.
| phrases_to_revision | python | jasperproject/jasper-client | client/vocabcompiler.py | https://github.com/jasperproject/jasper-client/blob/master/client/vocabcompiler.py | MIT |
def __init__(self, name='default', path='.'):
"""
Initializes a new Vocabulary instance.
Optional Arguments:
name -- (optional) the name of the vocabulary (Default: 'default')
path -- (optional) the path in which the vocabulary exists or will
be creat... |
Initializes a new Vocabulary instance.
Optional Arguments:
name -- (optional) the name of the vocabulary (Default: 'default')
path -- (optional) the path in which the vocabulary exists or will
be created (Default: '.')
| __init__ | python | jasperproject/jasper-client | client/vocabcompiler.py | https://github.com/jasperproject/jasper-client/blob/master/client/vocabcompiler.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.