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 get_adv_losses(discriminator_real_outputs, discriminator_fake_outputs, kind): """Return the corresponding GAN losses for the generator and the discriminator.""" if kind == 'classic': loss_fn = classic_gan_losses elif kind == 'nonsaturating': loss_fn = nonsaturating...
Return the corresponding GAN losses for the generator and the discriminator.
get_adv_losses
python
salu133445/musegan
src/musegan/losses.py
https://github.com/salu133445/musegan/blob/master/src/musegan/losses.py
MIT
def classic_gan_losses(discriminator_real_outputs, discriminator_fake_outputs): """Return the classic GAN losses for the generator and the discriminator. (Generator) log(1 - sigmoid(D(G(z)))) (Discriminator) - log(sigmoid(D(x))) - log(1 - sigmoid(D(G(z)))) """ discriminator_loss_real = tf.los...
Return the classic GAN losses for the generator and the discriminator. (Generator) log(1 - sigmoid(D(G(z)))) (Discriminator) - log(sigmoid(D(x))) - log(1 - sigmoid(D(G(z))))
classic_gan_losses
python
salu133445/musegan
src/musegan/losses.py
https://github.com/salu133445/musegan/blob/master/src/musegan/losses.py
MIT
def nonsaturating_gan_losses(discriminator_real_outputs, discriminator_fake_outputs): """Return the non-saturating GAN losses for the generator and the discriminator. (Generator) -log(sigmoid(D(G(z)))) (Discriminator) -log(sigmoid(D(x))) - log(1 - sigmoid(D(G(z)))) ...
Return the non-saturating GAN losses for the generator and the discriminator. (Generator) -log(sigmoid(D(G(z)))) (Discriminator) -log(sigmoid(D(x))) - log(1 - sigmoid(D(G(z))))
nonsaturating_gan_losses
python
salu133445/musegan
src/musegan/losses.py
https://github.com/salu133445/musegan/blob/master/src/musegan/losses.py
MIT
def wasserstein_gan_losses(discriminator_real_outputs, discriminator_fake_outputs): """Return the Wasserstein GAN losses for the generator and the discriminator. (Generator) -D(G(z)) (Discriminator) D(G(z)) - D(x) """ generator_loss = -tf.reduce_mean(discriminat...
Return the Wasserstein GAN losses for the generator and the discriminator. (Generator) -D(G(z)) (Discriminator) D(G(z)) - D(x)
wasserstein_gan_losses
python
salu133445/musegan
src/musegan/losses.py
https://github.com/salu133445/musegan/blob/master/src/musegan/losses.py
MIT
def hinge_gan_losses(discriminator_real_outputs, discriminator_fake_outputs): """Return the Hinge GAN losses for the generator and the discriminator. (Generator) -D(G(z)) (Discriminator) max(0, 1 - D(x)) + max(0, 1 + D(G(z))) """ generator_loss = -tf.reduce_mean(discriminator_fake_outputs) ...
Return the Hinge GAN losses for the generator and the discriminator. (Generator) -D(G(z)) (Discriminator) max(0, 1 - D(x)) + max(0, 1 + D(G(z)))
hinge_gan_losses
python
salu133445/musegan
src/musegan/losses.py
https://github.com/salu133445/musegan/blob/master/src/musegan/losses.py
MIT
def to_chroma(pianoroll): """Return the chroma features (not normalized).""" if pianoroll.get_shape().ndims != 5: raise ValueError("Input tensor must have 5 dimensions.") remainder = pianoroll.get_shape()[3] % 12 if remainder: pianoroll = tf.pad( pianoroll, ((0, 0), (0, 0), (...
Return the chroma features (not normalized).
to_chroma
python
salu133445/musegan
src/musegan/metrics.py
https://github.com/salu133445/musegan/blob/master/src/musegan/metrics.py
MIT
def empty_bar_rate(tensor): """Return the ratio of empty bars to the total number of bars.""" if tensor.get_shape().ndims != 5: raise ValueError("Input tensor must have 5 dimensions.") return tf.reduce_mean( tf.cast(tf.reduce_any(tensor > 0.5, (2, 3)), tf.float32), (0, 1))
Return the ratio of empty bars to the total number of bars.
empty_bar_rate
python
salu133445/musegan
src/musegan/metrics.py
https://github.com/salu133445/musegan/blob/master/src/musegan/metrics.py
MIT
def n_pitches_used(tensor): """Return the number of unique pitches used per bar.""" if tensor.get_shape().ndims != 5: raise ValueError("Input tensor must have 5 dimensions.") return tf.reduce_mean(tf.reduce_sum(tf.count_nonzero(tensor, 3), 2), [0, 1])
Return the number of unique pitches used per bar.
n_pitches_used
python
salu133445/musegan
src/musegan/metrics.py
https://github.com/salu133445/musegan/blob/master/src/musegan/metrics.py
MIT
def qualified_note_rate(tensor, threshold=2): """Return the ratio of the number of the qualified notes (notes longer than `threshold` (in time step)) to the total number of notes in a piano-roll.""" if tensor.get_shape().ndims != 5: raise ValueError("Input tensor must have 5 dimensions.") def _q...
Return the ratio of the number of the qualified notes (notes longer than `threshold` (in time step)) to the total number of notes in a piano-roll.
qualified_note_rate
python
salu133445/musegan
src/musegan/metrics.py
https://github.com/salu133445/musegan/blob/master/src/musegan/metrics.py
MIT
def _qualified_note_rate(array, threshold): """Return the ratio of the number of the qualified notes (notes longer than `threshold` (in time step)) to the total number of notes in a piano-roll.""" n_tracks = array.shape[-1] reshaped = array.reshape(-1, array.shape[1] * array.shap...
Return the ratio of the number of the qualified notes (notes longer than `threshold` (in time step)) to the total number of notes in a piano-roll.
_qualified_note_rate
python
salu133445/musegan
src/musegan/metrics.py
https://github.com/salu133445/musegan/blob/master/src/musegan/metrics.py
MIT
def polyphonic_rate(tensor, threshold=2): """Return the ratio of the number of time steps where the number of pitches being played is larger than `threshold` to the total number of time steps""" if tensor.get_shape().ndims != 5: raise ValueError("Input tensor must have 5 dimensions.") n_poly = t...
Return the ratio of the number of time steps where the number of pitches being played is larger than `threshold` to the total number of time steps
polyphonic_rate
python
salu133445/musegan
src/musegan/metrics.py
https://github.com/salu133445/musegan/blob/master/src/musegan/metrics.py
MIT
def _drum_pattern_mask(n_timesteps, tolerance=0.1): """Return a drum pattern mask with the given tolerance.""" if n_timesteps not in (96, 48, 24, 72, 36, 64, 32, 16): raise ValueError("Unsupported number of timesteps for the drum in " "pattern metric.") i...
Return a drum pattern mask with the given tolerance.
_drum_pattern_mask
python
salu133445/musegan
src/musegan/metrics.py
https://github.com/salu133445/musegan/blob/master/src/musegan/metrics.py
MIT
def _scale_mask(key=3): """Return a scale mask for the given key. Default to C major scale.""" a_scale_mask = np.array([[[1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0]]], bool) return np.expand_dims(np.roll(a_scale_mask, -key, 2), -1)
Return a scale mask for the given key. Default to C major scale.
_scale_mask
python
salu133445/musegan
src/musegan/metrics.py
https://github.com/salu133445/musegan/blob/master/src/musegan/metrics.py
MIT
def _tonal_matrix(r1=1.0, r2=1.0, r3=0.5): """Compute and return a tonal matrix for computing the tonal distance [1]. Default argument values are set as suggested by the paper. [1] Christopher Harte, Mark Sandler, and Martin Gasser. Detecting harmonic change in musical audio. In Proc. A...
Compute and return a tonal matrix for computing the tonal distance [1]. Default argument values are set as suggested by the paper. [1] Christopher Harte, Mark Sandler, and Martin Gasser. Detecting harmonic change in musical audio. In Proc. ACM MM Workshop on Audio and Music Computing Mu...
_tonal_matrix
python
salu133445/musegan
src/musegan/metrics.py
https://github.com/salu133445/musegan/blob/master/src/musegan/metrics.py
MIT
def _to_tonal_space(tensor): """Return the tensor in tonal space where chroma features are normalized per beat.""" tonal_matrix = tf.constant(_tonal_matrix(), tf.float32) beat_chroma = tf.reduce_sum(tf.reshape( tensor, (-1, beat_resolution, 12, tensor.get_shape()[4])), 1) ...
Return the tensor in tonal space where chroma features are normalized per beat.
_to_tonal_space
python
salu133445/musegan
src/musegan/metrics.py
https://github.com/salu133445/musegan/blob/master/src/musegan/metrics.py
MIT
def get_train_nodes(self, x, z=None, y=None, c=None, params=None, config=None): """Return a dictionary of graph nodes for training.""" LOGGER.info("Building training nodes.") with tf.variable_scope(self.name, reuse=tf.AUTO_REUSE) as scope: nodes = {} ...
Return a dictionary of graph nodes for training.
get_train_nodes
python
salu133445/musegan
src/musegan/model.py
https://github.com/salu133445/musegan/blob/master/src/musegan/model.py
MIT
def get_predict_nodes(self, z=None, y=None, c=None, params=None, config=None): """Return a dictionary of graph nodes for training.""" LOGGER.info("Building prediction nodes.") with tf.variable_scope(self.name, reuse=tf.AUTO_REUSE): nodes = {'z': z} ...
Return a dictionary of graph nodes for training.
get_predict_nodes
python
salu133445/musegan
src/musegan/model.py
https://github.com/salu133445/musegan/blob/master/src/musegan/model.py
MIT
def _array_to_image(array, colormap=None): """Convert an array to an image array and return it.""" if array.ndim == 2: return vector_to_image(array) return pianoroll_to_image(array, colormap)
Convert an array to an image array and return it.
_array_to_image
python
salu133445/musegan
src/musegan/model.py
https://github.com/salu133445/musegan/blob/master/src/musegan/model.py
MIT
def make_sure_path_exists(path): """Create intermidate directories if the path does not exist.""" try: os.makedirs(path) except OSError as exception: if exception.errno != errno.EEXIST: raise
Create intermidate directories if the path does not exist.
make_sure_path_exists
python
salu133445/musegan
src/musegan/utils.py
https://github.com/salu133445/musegan/blob/master/src/musegan/utils.py
MIT
def update_not_none(dict1, dict2): """Update the values of keys in `dict1` with the values of the same key from `dict2` if the values in `dict2` is not None.""" for key, value in dict2.items(): if value is not None: dict1[key] = value
Update the values of keys in `dict1` with the values of the same key from `dict2` if the values in `dict2` is not None.
update_not_none
python
salu133445/musegan
src/musegan/utils.py
https://github.com/salu133445/musegan/blob/master/src/musegan/utils.py
MIT
def update_existing(dict1, dict2): """Update the values of keys in `dict1` with the values of the same key from `dict2` if the values in `dict2` is not None and the same key is in `dict1`. """ for key, value in dict2.items(): if value is not None and key in dict1: dict1[key] = value
Update the values of keys in `dict1` with the values of the same key from `dict2` if the values in `dict2` is not None and the same key is in `dict1`.
update_existing
python
salu133445/musegan
src/musegan/utils.py
https://github.com/salu133445/musegan/blob/master/src/musegan/utils.py
MIT
def load_component(component, name, class_name): """Load and return component network from file.""" imported = importlib.import_module( '.'.join(('musegan.presets', component, name))) return getattr(imported, class_name)
Load and return component network from file.
load_component
python
salu133445/musegan
src/musegan/utils.py
https://github.com/salu133445/musegan/blob/master/src/musegan/utils.py
MIT
def add_file_handler(logger, log_filepath, loglevel=FILE_LOGLEVEL, log_format=FILE_LOG_FORMAT): """Add a file handler to the logger.""" file_handler = logging.FileHandler(log_filepath) file_handler.setLevel(loglevel) file_handler.setFormatter(logging.Formatter(log_format)) logge...
Add a file handler to the logger.
add_file_handler
python
salu133445/musegan
src/musegan/utils.py
https://github.com/salu133445/musegan/blob/master/src/musegan/utils.py
MIT
def setup_loggers(log_dir, loglevel=FILE_LOGLEVEL, log_format=FILE_LOG_FORMAT): """Setup the loggers with file handlers.""" for name in logging.Logger.manager.loggerDict.keys(): if name.startswith('musegan'): add_file_handler( logging.getLogger(name), os.path.join(log_dir, na...
Setup the loggers with file handlers.
setup_loggers
python
salu133445/musegan
src/musegan/utils.py
https://github.com/salu133445/musegan/blob/master/src/musegan/utils.py
MIT
def binary_round(x): """ Rounds a tensor whose values are in [0,1] to a tensor with values in {0, 1}, using the straight through estimator for the gradient. """ g = tf.get_default_graph() with ops.name_scope("BinaryRound") as name: with g.gradient_override_map({"Round": "Identity"}): ...
Rounds a tensor whose values are in [0,1] to a tensor with values in {0, 1}, using the straight through estimator for the gradient.
binary_round
python
salu133445/musegan
src/musegan/presets/binary_ops.py
https://github.com/salu133445/musegan/blob/master/src/musegan/presets/binary_ops.py
MIT
def bernoulli_sample(x): """ Uses a tensor whose values are in [0,1] to sample a tensor with values in {0, 1}, using the straight through estimator for the gradient. E.g., if x is 0.6, bernoulliSample(x) will be 1 with probability 0.6, and 0 otherwise, and the gradient will be pass-through (identit...
Uses a tensor whose values are in [0,1] to sample a tensor with values in {0, 1}, using the straight through estimator for the gradient. E.g., if x is 0.6, bernoulliSample(x) will be 1 with probability 0.6, and 0 otherwise, and the gradient will be pass-through (identity).
bernoulli_sample
python
salu133445/musegan
src/musegan/presets/binary_ops.py
https://github.com/salu133445/musegan/blob/master/src/musegan/presets/binary_ops.py
MIT
def pass_through_sigmoid(x, slope=1): """Sigmoid that uses identity function as its gradient""" g = tf.get_default_graph() with ops.name_scope("PassThroughSigmoid") as name: with g.gradient_override_map({"Sigmoid": "Identity"}): return tf.sigmoid(x, name=name)
Sigmoid that uses identity function as its gradient
pass_through_sigmoid
python
salu133445/musegan
src/musegan/presets/binary_ops.py
https://github.com/salu133445/musegan/blob/master/src/musegan/presets/binary_ops.py
MIT
def binary_stochastic_ST(x, slope_tensor=None, pass_through=True, stochastic=True): """ Sigmoid followed by either a random sample from a bernoulli distribution according to the result (binary stochastic neuron) (default), or a sigmoid followed by a binary step function (if stoch...
Sigmoid followed by either a random sample from a bernoulli distribution according to the result (binary stochastic neuron) (default), or a sigmoid followed by a binary step function (if stochastic == False). Uses the straight through estimator. See https://arxiv.org/abs/1308.3432. Arguments: ...
binary_stochastic_ST
python
salu133445/musegan
src/musegan/presets/binary_ops.py
https://github.com/salu133445/musegan/blob/master/src/musegan/presets/binary_ops.py
MIT
def binary_stochastic_REINFORCE(x, loss_op_name="loss_by_example"): """ Sigmoid followed by a random sample from a bernoulli distribution according to the result (binary stochastic neuron). Uses the REINFORCE estimator. See https://arxiv.org/abs/1308.3432. NOTE: Requires a loss operation with name ...
Sigmoid followed by a random sample from a bernoulli distribution according to the result (binary stochastic neuron). Uses the REINFORCE estimator. See https://arxiv.org/abs/1308.3432. NOTE: Requires a loss operation with name matching the argument for loss_op_name in the graph. This loss operatio...
binary_stochastic_REINFORCE
python
salu133445/musegan
src/musegan/presets/binary_ops.py
https://github.com/salu133445/musegan/blob/master/src/musegan/presets/binary_ops.py
MIT
def _binaryStochastic_REINFORCE(op, _): """Unbiased estimator for binary stochastic function based on REINFORCE.""" loss_op_name = op.graph.get_collection("REINFORCE")[0][op.name] loss_tensor = op.graph.get_operation_by_name(loss_op_name).outputs[0] sub_tensor = op.outputs[0].consumers()[0].outputs[0] ...
Unbiased estimator for binary stochastic function based on REINFORCE.
_binaryStochastic_REINFORCE
python
salu133445/musegan
src/musegan/presets/binary_ops.py
https://github.com/salu133445/musegan/blob/master/src/musegan/presets/binary_ops.py
MIT
def binary_wrapper(pre_activations_tensor, estimator, stochastic_tensor=tf.constant(True), pass_through=True, slope_tensor=tf.constant(1.0)): """ Turns a layer of pre-activations (logits) into a layer of binary stochastic neurons Keyword arguments: *estimator: ...
Turns a layer of pre-activations (logits) into a layer of binary stochastic neurons Keyword arguments: *estimator: either ST or REINFORCE *stochastic_tensor: a boolean tensor indicating whether to sample from a bernoulli distribution (True, default) or use a step_function (e.g., fo...
binary_wrapper
python
salu133445/musegan
src/musegan/presets/binary_ops.py
https://github.com/salu133445/musegan/blob/master/src/musegan/presets/binary_ops.py
MIT
def eval(self, batch, output_type=0, quiet=False, save_fig=False, fig_dir='./'): """ Evaluate one batch of bars according to eval_map and eval_pair Args: batch (tensor): The input tensor. output_type (int): 0 for scalar (mean of list), 1 for list quiet (bool):...
Evaluate one batch of bars according to eval_map and eval_pair Args: batch (tensor): The input tensor. output_type (int): 0 for scalar (mean of list), 1 for list quiet (bool): if true, print the values save_fig (bool): if true, plot figures and save them ...
eval
python
salu133445/musegan
v1/musegan/eval/metrics.py
https://github.com/salu133445/musegan/blob/master/v1/musegan/eval/metrics.py
MIT
def get_placeholder(default_tensor=None, shape=None, name=None): """Return a placeholder_wirh_default if default_tensor given, otherwise a new placeholder is created and return""" if default_tensor is not None: return default_tensor else: if shape is None: raise ValueError('One o...
Return a placeholder_wirh_default if default_tensor given, otherwise a new placeholder is created and return
get_placeholder
python
salu133445/musegan
v1/musegan/libs/ops.py
https://github.com/salu133445/musegan/blob/master/v1/musegan/libs/ops.py
MIT
def batch_norm(tensor_in, apply=True): """ Apply a batch normalization layer on the input tensor and return the resulting tensor. Args: tensor_in (tensor): The input tensor. apply (bool): True to apply. False to bypass batch normalization. Defaults to True. Returns: tensor: The...
Apply a batch normalization layer on the input tensor and return the resulting tensor. Args: tensor_in (tensor): The input tensor. apply (bool): True to apply. False to bypass batch normalization. Defaults to True. Returns: tensor: The resulting tensor.
batch_norm
python
salu133445/musegan
v1/musegan/libs/ops.py
https://github.com/salu133445/musegan/blob/master/v1/musegan/libs/ops.py
MIT
def lrelu(tensor_in, alpha=0.2): """Apply a leaky ReLU layer on the input tensor and return the resulting tensor. (alpha defaults to 0.2)""" if tensor_in is not None: return tf.maximum(tensor_in, alpha*tensor_in) else: return tensor_in
Apply a leaky ReLU layer on the input tensor and return the resulting tensor. (alpha defaults to 0.2)
lrelu
python
salu133445/musegan
v1/musegan/libs/ops.py
https://github.com/salu133445/musegan/blob/master/v1/musegan/libs/ops.py
MIT
def relu(tensor_in): """Apply a ReLU layer on the input tensor and return the resulting tensor.""" if tensor_in is not None: return tf.nn.relu(tensor_in) else: return tensor_in
Apply a ReLU layer on the input tensor and return the resulting tensor.
relu
python
salu133445/musegan
v1/musegan/libs/ops.py
https://github.com/salu133445/musegan/blob/master/v1/musegan/libs/ops.py
MIT
def concat_cond_conv(x, condition=None): """Concatenate conditioning vector on feature map axis.""" if condition is None: return x else: reshape_shape = tf.stack([tf.shape(x)[0], 1, 1, condition.get_shape()[1]]) out_shape = tf.stack([tf.shape(x)[0], x.get_shape()[1], x.get_shape()[2]...
Concatenate conditioning vector on feature map axis.
concat_cond_conv
python
salu133445/musegan
v1/musegan/libs/ops.py
https://github.com/salu133445/musegan/blob/master/v1/musegan/libs/ops.py
MIT
def concat_cond_lin(tensor_in, condition): """Concatenate conditioning vector on feature map axis.""" if condition is None: return tensor_in else: return tf.concat([tensor_in, condition, 1])
Concatenate conditioning vector on feature map axis.
concat_cond_lin
python
salu133445/musegan
v1/musegan/libs/ops.py
https://github.com/salu133445/musegan/blob/master/v1/musegan/libs/ops.py
MIT
def concat_prev(tensor_in, condition): """Concatenate conditioning vector on feature map axis.""" if condition is None: return tensor_in else: if tensor_in.get_shape()[1:3] == condition.get_shape()[1:3]: pad_shape = tf.stack([tf.shape(tensor_in)[0], tensor_in.get_shape()[1], tens...
Concatenate conditioning vector on feature map axis.
concat_prev
python
salu133445/musegan
v1/musegan/libs/ops.py
https://github.com/salu133445/musegan/blob/master/v1/musegan/libs/ops.py
MIT
def conv2d(tensor_in, out_channels, kernels, strides, stddev=0.02, name='conv2d', reuse=None, padding='VALID'): """ Apply a 2D convolution layer on the input tensor and return the resulting tensor. Args: tensor_in (tensor): The input tensor. out_channels (int): The number of output channels...
Apply a 2D convolution layer on the input tensor and return the resulting tensor. Args: tensor_in (tensor): The input tensor. out_channels (int): The number of output channels. kernels (list of int): The size of the kernel. [kernel_height, kernel_width] strides (list of int): T...
conv2d
python
salu133445/musegan
v1/musegan/libs/ops.py
https://github.com/salu133445/musegan/blob/master/v1/musegan/libs/ops.py
MIT
def transconv2d(tensor_in, out_shape, out_channels, kernels, strides, stddev=0.02, name='transconv2d', reuse=None, padding='VALID'): """ Apply a 2D transposed convolution layer on the input tensor and return the resulting tensor. Args: tensor_in (tensor): The input tensor. o...
Apply a 2D transposed convolution layer on the input tensor and return the resulting tensor. Args: tensor_in (tensor): The input tensor. out_shape (list of int): The output shape. [height, width] out_channels (int): The number of output channels. kernels (list of int): The size...
transconv2d
python
salu133445/musegan
v1/musegan/libs/ops.py
https://github.com/salu133445/musegan/blob/master/v1/musegan/libs/ops.py
MIT
def linear(tensor_in, output_size, stddev=0.02, bias_init=0.0, name='linear', reuse=None): """ Apply a linear layer on the input tensor and return the resulting tensor. Args: tensor_in (tensor): The input tensor. output_size (int): The output size. stddev (float): The value passed t...
Apply a linear layer on the input tensor and return the resulting tensor. Args: tensor_in (tensor): The input tensor. output_size (int): The output size. stddev (float): The value passed to the truncated normal initializer for weights. Defaults to 0.02. bias_init (float): The v...
linear
python
salu133445/musegan
v1/musegan/libs/ops.py
https://github.com/salu133445/musegan/blob/master/v1/musegan/libs/ops.py
MIT
def to_chroma_tf(bar_or_track_bar, is_normalize=True): """Return the chroma tensor of the input tensor""" out_shape = tf.stack([tf.shape(bar_or_track_bar)[0], bar_or_track_bar.get_shape()[1], 12, 7, bar_or_track_bar.get_shape()[3]]) chroma = tf.reduce_sum(tf.reshape(tf.cast(bar_or_t...
Return the chroma tensor of the input tensor
to_chroma_tf
python
salu133445/musegan
v1/musegan/libs/ops.py
https://github.com/salu133445/musegan/blob/master/v1/musegan/libs/ops.py
MIT
def to_binary_tf(bar_or_track_bar, threshold=0.0, track_mode=False, melody=False): """Return the binarize tensor of the input tensor (be careful of the channel order!)""" if track_mode: # melody track if melody: melody_is_max = tf.equal(bar_or_track_bar, tf.reduce_max(bar_or_track_ba...
Return the binarize tensor of the input tensor (be careful of the channel order!)
to_binary_tf
python
salu133445/musegan
v1/musegan/libs/ops.py
https://github.com/salu133445/musegan/blob/master/v1/musegan/libs/ops.py
MIT
def to_image_tf(tensor_in, colormap=None): """Reverse the second dimension and swap the second dimension and the third dimension""" if colormap is None: colormap = get_colormap() shape = tf.stack([-1, tensor_in.get_shape()[1], tensor_in.get_shape()[2], 3]) recolored = tf.reshape(tf.matmul(tf.res...
Reverse the second dimension and swap the second dimension and the third dimension
to_image_tf
python
salu133445/musegan
v1/musegan/libs/ops.py
https://github.com/salu133445/musegan/blob/master/v1/musegan/libs/ops.py
MIT
def load_data(): """Load and return the training data.""" print('[*] Loading data...') # Load data from SharedArray if CONFIG['data']['training_data_location'] == 'sa': import SharedArray as sa x_train = sa.attach(CONFIG['data']['training_data']) # Load data from hard disk elif...
Load and return the training data.
load_data
python
salu133445/musegan
v2/main.py
https://github.com/salu133445/musegan/blob/master/v2/main.py
MIT
def get_adversarial_loss(self, discriminator, scope_to_reuse=None): """Return the adversarial losses for the generator and the discriminator.""" if self.config['gan']['type'] == 'gan': d_loss_real = tf.losses.sigmoid_cross_entropy( tf.ones_like(self.D_real.tensor_out)...
Return the adversarial losses for the generator and the discriminator.
get_adversarial_loss
python
salu133445/musegan
v2/musegan/model.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/model.py
MIT
def get_statistics(self): """Return model statistics (number of paramaters for each component).""" def get_num_parameter(var_list): """Given the variable list, return the total number of parameters. """ return int(np.sum([np.product([x.value for x in var.get_shape()])...
Return model statistics (number of paramaters for each component).
get_statistics
python
salu133445/musegan
v2/musegan/model.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/model.py
MIT
def get_num_parameter(var_list): """Given the variable list, return the total number of parameters. """ return int(np.sum([np.product([x.value for x in var.get_shape()]) for var in var_list]))
Given the variable list, return the total number of parameters.
get_num_parameter
python
salu133445/musegan
v2/musegan/model.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/model.py
MIT
def save_statistics(self, filepath=None): """Save model statistics to file. Default to save to the log directory given as a global variable.""" if filepath is None: filepath = os.path.join(self.config['log_dir'], 'model_statistics.txt') wit...
Save model statistics to file. Default to save to the log directory given as a global variable.
save_statistics
python
salu133445/musegan
v2/musegan/model.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/model.py
MIT
def save_summary(self, filepath=None): """Save model summary to file. Default to save to the log directory given as a global variable.""" if filepath is None: filepath = os.path.join(self.config['log_dir'], 'model_summary.txt') with open(filepath, 'w') as f: f.wri...
Save model summary to file. Default to save to the log directory given as a global variable.
save_summary
python
salu133445/musegan
v2/musegan/model.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/model.py
MIT
def save(self, filepath=None): """Save the model to a checkpoint file. Default to save to the log directory given as a global variable.""" if filepath is None: filepath = os.path.join(self.config['checkpoint_dir'], self.name + '.model') pri...
Save the model to a checkpoint file. Default to save to the log directory given as a global variable.
save
python
salu133445/musegan
v2/musegan/model.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/model.py
MIT
def load_latest(self, checkpoint_dir=None): """Load the model from the latest checkpoint in a directory.""" if checkpoint_dir is None: checkpoint_dir = self.config['checkpoint_dir'] print('[*] Loading checkpoint...') with open(os.path.join(checkpoint_dir, 'checkpoint')) as f:...
Load the model from the latest checkpoint in a directory.
load_latest
python
salu133445/musegan
v2/musegan/model.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/model.py
MIT
def save_samples(self, filename, samples, save_midi=False, shape=None, postfix=None): """Save samples to an image file (and a MIDI file).""" if shape is None: shape = self.config['sample_grid'] if len(samples) > self.config['num_sample']: samples = sa...
Save samples to an image file (and a MIDI file).
save_samples
python
salu133445/musegan
v2/musegan/model.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/model.py
MIT
def run_sampler(self, targets, feed_dict, save_midi=False, postfix=None): """Run the target operation with feed_dict and save the samples.""" if not isinstance(targets, list): targets = [targets] results = self.sess.run(targets, feed_dict) results = [result[:self.config['num_...
Run the target operation with feed_dict and save the samples.
run_sampler
python
salu133445/musegan
v2/musegan/model.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/model.py
MIT
def build(self, config): """Build the end-to-end generator.""" nets = OrderedDict() nets['shared'] = NeuralNet(self.tensor_in, config['net_g']['shared'], name='shared') nets['pitch_time_private'] = [ NeuralNet(nets['shared'].tensor_out, ...
Build the end-to-end generator.
build
python
salu133445/musegan
v2/musegan/bmusegan/components.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/bmusegan/components.py
MIT
def get_image_grid(images, shape, grid_width=0, grid_color=0, frame=False): """ Merge the input images and return a merged grid image. Arguments --------- images : np.array, ndim=3 The image array. Shape is (num_image, height, width). shape : list or tuple of int ...
Merge the input images and return a merged grid image. Arguments --------- images : np.array, ndim=3 The image array. Shape is (num_image, height, width). shape : list or tuple of int Shape of the image grid. (height, width) grid_width : int Width of the grid lines. Def...
get_image_grid
python
salu133445/musegan
v2/musegan/utils/image_io.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/image_io.py
MIT
def save_image(filepath, phrases, shape, inverted=True, grid_width=3, grid_color=0, frame=True): """ Save a batch of phrases to a single image grid. Arguments --------- filepath : str Path to save the image grid. phrases : np.array, ndim=5 The phrase array. Shape ...
Save a batch of phrases to a single image grid. Arguments --------- filepath : str Path to save the image grid. phrases : np.array, ndim=5 The phrase array. Shape is (num_phrase, num_bar, num_time_step, num_pitch, num_track). shape : list or tuple of int Shape o...
save_image
python
salu133445/musegan
v2/musegan/utils/image_io.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/image_io.py
MIT
def get_tonal_matrix(r1=1.0, r2=1.0, r3=0.5): """Compute and return a tonal matrix for computing the tonal distance [1]. Default argument values are set as suggested by the paper. [1] Christopher Harte, Mark Sandler, and Martin Gasser. Detecting harmonic change in musical audio. In Proc. ACM MM Worksho...
Compute and return a tonal matrix for computing the tonal distance [1]. Default argument values are set as suggested by the paper. [1] Christopher Harte, Mark Sandler, and Martin Gasser. Detecting harmonic change in musical audio. In Proc. ACM MM Workshop on Audio and Music Computing Multimedia, 2006. ...
get_tonal_matrix
python
salu133445/musegan
v2/musegan/utils/metrics.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/metrics.py
MIT
def get_qualified_note_rate(pianoroll, threshold=2): """Return the ratio of the number of the qualified notes (notes longer than `threshold` (in time step)) to the total number of notes in a piano-roll.""" padded = np.pad(pianoroll.astype(int), ((1, 1), (0, 0)), 'constant') diff = np.diff(padded, axis=0...
Return the ratio of the number of the qualified notes (notes longer than `threshold` (in time step)) to the total number of notes in a piano-roll.
get_qualified_note_rate
python
salu133445/musegan
v2/musegan/utils/metrics.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/metrics.py
MIT
def to_chroma(pianoroll): """Return the chroma features (not normalized).""" padded = np.pad(pianoroll, ((0, 0), (0, 12 - pianoroll.shape[1] % 12)), 'constant') return np.sum(np.reshape(padded, (pianoroll.shape[0], 12, -1)), 2)
Return the chroma features (not normalized).
to_chroma
python
salu133445/musegan
v2/musegan/utils/metrics.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/metrics.py
MIT
def tonal_dist(chroma1, chroma2, tonal_matrix=None): """Return the tonal distance between two chroma features.""" if tonal_matrix is None: tonal_matrix = get_tonal_matrix() warnings.warn("`tonal matrix` not specified. Use default tonal matrix", RuntimeWarning) with warn...
Return the tonal distance between two chroma features.
tonal_dist
python
salu133445/musegan
v2/musegan/utils/metrics.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/metrics.py
MIT
def plot_histogram(hist, fig_dir=None, title=None, max_hist_num=None): """Plot the histograms of the statistics""" import matplotlib.pyplot as plt hist = hist[~np.isnan(hist)] u_value = np.unique(hist) hist_num = len(u_value) if max_hist_num is not None: if len(u_value) > max_hist_num: ...
Plot the histograms of the statistics
plot_histogram
python
salu133445/musegan
v2/musegan/utils/metrics.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/metrics.py
MIT
def print_metrics_mat(self, metrics_mat): """Print the intratrack metrics as a nice formatting table""" print(' ' * 12, ' '.join(['{:^14}'.format(metric_name) for metric_name in self.metric_names])) for t, track_name in enumerate(self.track_names): ...
Print the intratrack metrics as a nice formatting table
print_metrics_mat
python
salu133445/musegan
v2/musegan/utils/metrics.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/metrics.py
MIT
def print_metrics_pair(self, pair_matrix): """Print the intertrack metrics as a nice formatting table""" for idx, pair in enumerate(self.tonal_distance_pairs): print("{:12} {:12} {:12.5f}".format( self.track_names[pair[0]], self.track_names[pair[1]], pair_matr...
Print the intertrack metrics as a nice formatting table
print_metrics_pair
python
salu133445/musegan
v2/musegan/utils/metrics.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/metrics.py
MIT
def eval(self, bars, verbose=False, mat_path=None, fig_dir=None): """Evaluate the input bars with the metrics""" score_matrix = np.empty((len(self.metric_names), len(self.track_names), bars.shape[0])) score_matrix.fill(np.nan) score_pair_matrix = np.zeros...
Evaluate the input bars with the metrics
eval
python
salu133445/musegan
v2/musegan/utils/metrics.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/metrics.py
MIT
def eval_dataset(filepath, result_dir, location, config): """Run evaluation on a dataset stored in either shared array (if `location` is 'sa') or in hard disk (if `location` is 'hd') and save the results to the given directory. """ def load_data(filepath, location): """Load and return the t...
Run evaluation on a dataset stored in either shared array (if `location` is 'sa') or in hard disk (if `location` is 'hd') and save the results to the given directory.
eval_dataset
python
salu133445/musegan
v2/musegan/utils/metrics.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/metrics.py
MIT
def load_data(filepath, location): """Load and return the training data.""" print('[*] Loading data...') # Load data from SharedArray if location == 'sa': import SharedArray as sa data = sa.attach(filepath) # Load data from hard disk elif locatio...
Load and return the training data.
load_data
python
salu133445/musegan
v2/musegan/utils/metrics.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/metrics.py
MIT
def print_mat_file(mat_path, config): """Print the score matrices stored in a file.""" metrics = Metrics(config) with np.load(mat_path) as loaded: metrics.print_metrics_mat(loaded['score_matrix_mean']) metrics.print_metrics_pair(loaded['score_pair_matrix_mean'])
Print the score matrices stored in a file.
print_mat_file
python
salu133445/musegan
v2/musegan/utils/metrics.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/metrics.py
MIT
def write_midi(filepath, pianorolls, program_nums=None, is_drums=None, track_names=None, velocity=100, tempo=120.0, beat_resolution=24): """ Write the given piano-roll(s) to a single MIDI file. Arguments --------- filepath : str Path to save the MIDI file. pianorolls : np...
Write the given piano-roll(s) to a single MIDI file. Arguments --------- filepath : str Path to save the MIDI file. pianorolls : np.array, ndim=3 The piano-roll array to be written to the MIDI file. Shape is (num_timestep, num_pitch, num_track). program_nums : int or li...
write_midi
python
salu133445/musegan
v2/musegan/utils/midi_io.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/midi_io.py
MIT
def save_midi(filepath, phrases, config): """ Save a batch of phrases to a single MIDI file. Arguments --------- filepath : str Path to save the image grid. phrases : list of np.array Phrase arrays to be saved. All arrays must have the same shape. pause : int Length ...
Save a batch of phrases to a single MIDI file. Arguments --------- filepath : str Path to save the image grid. phrases : list of np.array Phrase arrays to be saved. All arrays must have the same shape. pause : int Length of pauses (in timestep) to be inserted between ph...
save_midi
python
salu133445/musegan
v2/musegan/utils/midi_io.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/midi_io.py
MIT
def binary_round(x): """ Rounds a tensor whose values are in [0,1] to a tensor with values in {0, 1}, using the straight through estimator for the gradient. """ g = tf.get_default_graph() with ops.name_scope("BinaryRound") as name: with g.gradient_override_map({"Round": "Identity"}): ...
Rounds a tensor whose values are in [0,1] to a tensor with values in {0, 1}, using the straight through estimator for the gradient.
binary_round
python
salu133445/musegan
v2/musegan/utils/ops.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/ops.py
MIT
def bernoulli_sample(x): """ Uses a tensor whose values are in [0,1] to sample a tensor with values in {0, 1}, using the straight through estimator for the gradient. E.g., if x is 0.6, bernoulliSample(x) will be 1 with probability 0.6, and 0 otherwise, and the gradient will be pass-through (identit...
Uses a tensor whose values are in [0,1] to sample a tensor with values in {0, 1}, using the straight through estimator for the gradient. E.g., if x is 0.6, bernoulliSample(x) will be 1 with probability 0.6, and 0 otherwise, and the gradient will be pass-through (identity).
bernoulli_sample
python
salu133445/musegan
v2/musegan/utils/ops.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/ops.py
MIT
def pass_through_sigmoid(x, slope=1): """Sigmoid that uses identity function as its gradient""" g = tf.get_default_graph() with ops.name_scope("PassThroughSigmoid") as name: with g.gradient_override_map({"Sigmoid": "Identity"}): return tf.sigmoid(x, name=name)
Sigmoid that uses identity function as its gradient
pass_through_sigmoid
python
salu133445/musegan
v2/musegan/utils/ops.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/ops.py
MIT
def binary_stochastic_ST(x, slope_tensor=None, pass_through=True, stochastic=True): """ Sigmoid followed by either a random sample from a bernoulli distribution according to the result (binary stochastic neuron) (default), or a sigmoid followed by a binary step function (if stoch...
Sigmoid followed by either a random sample from a bernoulli distribution according to the result (binary stochastic neuron) (default), or a sigmoid followed by a binary step function (if stochastic == False). Uses the straight through estimator. See https://arxiv.org/abs/1308.3432. Arguments: ...
binary_stochastic_ST
python
salu133445/musegan
v2/musegan/utils/ops.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/ops.py
MIT
def binary_stochastic_REINFORCE(x, loss_op_name="loss_by_example"): """ Sigmoid followed by a random sample from a bernoulli distribution according to the result (binary stochastic neuron). Uses the REINFORCE estimator. See https://arxiv.org/abs/1308.3432. NOTE: Requires a loss operation with name ...
Sigmoid followed by a random sample from a bernoulli distribution according to the result (binary stochastic neuron). Uses the REINFORCE estimator. See https://arxiv.org/abs/1308.3432. NOTE: Requires a loss operation with name matching the argument for loss_op_name in the graph. This loss operatio...
binary_stochastic_REINFORCE
python
salu133445/musegan
v2/musegan/utils/ops.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/ops.py
MIT
def _binaryStochastic_REINFORCE(op, _): """Unbiased estimator for binary stochastic function based on REINFORCE.""" loss_op_name = op.graph.get_collection("REINFORCE")[0][op.name] loss_tensor = op.graph.get_operation_by_name(loss_op_name).outputs[0] sub_tensor = op.outputs[0].consumers()[0].outputs[0] ...
Unbiased estimator for binary stochastic function based on REINFORCE.
_binaryStochastic_REINFORCE
python
salu133445/musegan
v2/musegan/utils/ops.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/ops.py
MIT
def binary_wrapper(pre_activations_tensor, estimator, stochastic_tensor=tf.constant(True), pass_through=True, slope_tensor=tf.constant(1.0)): """ Turns a layer of pre-activations (logits) into a layer of binary stochastic neurons Keyword arguments: *estimator: ...
Turns a layer of pre-activations (logits) into a layer of binary stochastic neurons Keyword arguments: *estimator: either ST or REINFORCE *stochastic_tensor: a boolean tensor indicating whether to sample from a bernoulli distribution (True, default) or use a step_function (e.g., fo...
binary_wrapper
python
salu133445/musegan
v2/musegan/utils/ops.py
https://github.com/salu133445/musegan/blob/master/v2/musegan/utils/ops.py
MIT
def parse_arguments(): """Parse and return the command line arguments.""" parser = argparse.ArgumentParser() parser.add_argument('filepath', help="Path to the data file.") parser.add_argument('--name', help="File name to save in SharedArray. " "Default to use the o...
Parse and return the command line arguments.
parse_arguments
python
salu133445/musegan
v2/training_data/store_to_sa.py
https://github.com/salu133445/musegan/blob/master/v2/training_data/store_to_sa.py
MIT
def stream_complete(self, stream_id: int): """ When a stream is complete, we can send our response. """ try: request_data = self.stream_data[stream_id] except KeyError: # Just return, we probably 405'd this already return headers = req...
When a stream is complete, we can send our response.
stream_complete
python
python-hyper/h2
examples/asyncio/asyncio-server.py
https://github.com/python-hyper/h2/blob/master/examples/asyncio/asyncio-server.py
MIT
def receive_data(self, data: bytes, flow_controlled_length: int, stream_id: int): """ We've received some data on a stream. If that stream is one we're expecting data on, save it off (and account for the received amount of data in flow control so that the client can send more data). ...
We've received some data on a stream. If that stream is one we're expecting data on, save it off (and account for the received amount of data in flow control so that the client can send more data). Otherwise, reset the stream.
receive_data
python
python-hyper/h2
examples/asyncio/asyncio-server.py
https://github.com/python-hyper/h2/blob/master/examples/asyncio/asyncio-server.py
MIT
def stream_reset(self, stream_id): """ A stream reset was sent. Stop sending data. """ if stream_id in self.flow_control_futures: future = self.flow_control_futures.pop(stream_id) future.cancel()
A stream reset was sent. Stop sending data.
stream_reset
python
python-hyper/h2
examples/asyncio/asyncio-server.py
https://github.com/python-hyper/h2/blob/master/examples/asyncio/asyncio-server.py
MIT
async def send_data(self, data, stream_id): """ Send data according to the flow control rules. """ while data: while self.conn.local_flow_control_window(stream_id) < 1: try: await self.wait_for_flow_control(stream_id) except...
Send data according to the flow control rules.
send_data
python
python-hyper/h2
examples/asyncio/asyncio-server.py
https://github.com/python-hyper/h2/blob/master/examples/asyncio/asyncio-server.py
MIT
async def wait_for_flow_control(self, stream_id): """ Waits for a Future that fires when the flow control window is opened. """ f = asyncio.Future() self.flow_control_futures[stream_id] = f await f
Waits for a Future that fires when the flow control window is opened.
wait_for_flow_control
python
python-hyper/h2
examples/asyncio/asyncio-server.py
https://github.com/python-hyper/h2/blob/master/examples/asyncio/asyncio-server.py
MIT
def window_updated(self, stream_id, delta): """ A window update frame was received. Unblock some number of flow control Futures. """ if stream_id and stream_id in self.flow_control_futures: f = self.flow_control_futures.pop(stream_id) f.set_result(delta) ...
A window update frame was received. Unblock some number of flow control Futures.
window_updated
python
python-hyper/h2
examples/asyncio/asyncio-server.py
https://github.com/python-hyper/h2/blob/master/examples/asyncio/asyncio-server.py
MIT
def connection_made(self, transport): """ The connection has been made. Here we need to save off our transport, do basic HTTP/2 connection setup, and then start our data writing coroutine. """ self.transport = transport self.conn.initiate_connection() self...
The connection has been made. Here we need to save off our transport, do basic HTTP/2 connection setup, and then start our data writing coroutine.
connection_made
python
python-hyper/h2
examples/asyncio/wsgi-server.py
https://github.com/python-hyper/h2/blob/master/examples/asyncio/wsgi-server.py
MIT
def window_opened(self, event): """ The flow control window got opened. This is important because it's possible that we were unable to send some WSGI data because the flow control window was too small. If that happens, the sending_loop coroutine starts buffering data. A...
The flow control window got opened. This is important because it's possible that we were unable to send some WSGI data because the flow control window was too small. If that happens, the sending_loop coroutine starts buffering data. As the window gets opened, we need to unbuff...
window_opened
python
python-hyper/h2
examples/asyncio/wsgi-server.py
https://github.com/python-hyper/h2/blob/master/examples/asyncio/wsgi-server.py
MIT
async def sending_loop(self): """ A call that loops forever, attempting to send data. This sending loop contains most of the flow-control smarts of this class: it pulls data off of the asyncio queue and then attempts to send it. The difficulties here are all around flow control....
A call that loops forever, attempting to send data. This sending loop contains most of the flow-control smarts of this class: it pulls data off of the asyncio queue and then attempts to send it. The difficulties here are all around flow control. Specifically, a chunk of data ma...
sending_loop
python
python-hyper/h2
examples/asyncio/wsgi-server.py
https://github.com/python-hyper/h2/blob/master/examples/asyncio/wsgi-server.py
MIT
def request_received(self, event): """ A HTTP/2 request has been received. We need to invoke the WSGI application in a background thread to handle it. """ # First, we are going to want an object to hold all the relevant state # for this request/response. For that, we have...
A HTTP/2 request has been received. We need to invoke the WSGI application in a background thread to handle it.
request_received
python
python-hyper/h2
examples/asyncio/wsgi-server.py
https://github.com/python-hyper/h2/blob/master/examples/asyncio/wsgi-server.py
MIT
def data_frame_received(self, event): """ Data has been received by WSGI server and needs to be dispatched to a running application. Note that the flow control window is not modified here. That's deliberate: see Stream.__next__ for a longer discussion of why. """ ...
Data has been received by WSGI server and needs to be dispatched to a running application. Note that the flow control window is not modified here. That's deliberate: see Stream.__next__ for a longer discussion of why.
data_frame_received
python
python-hyper/h2
examples/asyncio/wsgi-server.py
https://github.com/python-hyper/h2/blob/master/examples/asyncio/wsgi-server.py
MIT
def reset_stream(self, event): """ A stream got forcefully reset. This is a tricky thing to deal with because WSGI doesn't really have a good notion for it. Essentially, you have to let the application run until completion, but not actually let it send any data. We do t...
A stream got forcefully reset. This is a tricky thing to deal with because WSGI doesn't really have a good notion for it. Essentially, you have to let the application run until completion, but not actually let it send any data. We do that by discarding any data we currently ha...
reset_stream
python
python-hyper/h2
examples/asyncio/wsgi-server.py
https://github.com/python-hyper/h2/blob/master/examples/asyncio/wsgi-server.py
MIT
def data_for_stream(self, stream_id, data): """ Thread-safe method called from outside the main asyncio thread in order to send data on behalf of a WSGI application. Places data being written by a stream on an asyncio queue. Returns a threading event that will fire when that dat...
Thread-safe method called from outside the main asyncio thread in order to send data on behalf of a WSGI application. Places data being written by a stream on an asyncio queue. Returns a threading event that will fire when that data is sent.
data_for_stream
python
python-hyper/h2
examples/asyncio/wsgi-server.py
https://github.com/python-hyper/h2/blob/master/examples/asyncio/wsgi-server.py
MIT
def open_flow_control_window(self, stream_id, increment): """ Opens a flow control window for the given stream by the given amount. Called from a WSGI thread. Does not return an event because there's no need to block on this action, it may take place at any time. """ def ...
Opens a flow control window for the given stream by the given amount. Called from a WSGI thread. Does not return an event because there's no need to block on this action, it may take place at any time.
open_flow_control_window
python
python-hyper/h2
examples/asyncio/wsgi-server.py
https://github.com/python-hyper/h2/blob/master/examples/asyncio/wsgi-server.py
MIT
def run_in_threadpool(self, wsgi_application, environ): """ This method should be invoked in a threadpool. At the point this method is invoked, the only safe methods to call from the original thread are ``receive_data`` and ``request_complete``: any other method is unsafe. This ...
This method should be invoked in a threadpool. At the point this method is invoked, the only safe methods to call from the original thread are ``receive_data`` and ``request_complete``: any other method is unsafe. This method handles the WSGI logic. It invokes the application callable ...
run_in_threadpool
python
python-hyper/h2
examples/asyncio/wsgi-server.py
https://github.com/python-hyper/h2/blob/master/examples/asyncio/wsgi-server.py
MIT
def read(self, size=None): """ Called by the WSGI application to read data. This method is the one of two that explicitly pumps the input data queue, which means it deals with the ``_complete`` flag and the ``END_DATA_SENTINEL``. """ # If we've already seen the E...
Called by the WSGI application to read data. This method is the one of two that explicitly pumps the input data queue, which means it deals with the ``_complete`` flag and the ``END_DATA_SENTINEL``.
read
python
python-hyper/h2
examples/asyncio/wsgi-server.py
https://github.com/python-hyper/h2/blob/master/examples/asyncio/wsgi-server.py
MIT
def readlines(self, hint=None): """ Called by the WSGI application to read several lines of data. """ data = self.read(hint) lines = data.splitlines(keepends=True) return lines
Called by the WSGI application to read several lines of data.
readlines
python
python-hyper/h2
examples/asyncio/wsgi-server.py
https://github.com/python-hyper/h2/blob/master/examples/asyncio/wsgi-server.py
MIT
def start_response(self, status, response_headers, exc_info=None): """ This is the PEP-3333 mandated start_response callable. All it does is store the headers for later sending, and return our ```write`` callable. """ if self._headers_emitted and exc_info is not None: ...
This is the PEP-3333 mandated start_response callable. All it does is store the headers for later sending, and return our ```write`` callable.
start_response
python
python-hyper/h2
examples/asyncio/wsgi-server.py
https://github.com/python-hyper/h2/blob/master/examples/asyncio/wsgi-server.py
MIT
def write(self, data): """ Provides some data to write. This function *blocks* until such time as the data is allowed by HTTP/2 flow control. This allows a client to slow or pause the response as needed. This function is not supposed to be used, according to PEP-3333, b...
Provides some data to write. This function *blocks* until such time as the data is allowed by HTTP/2 flow control. This allows a client to slow or pause the response as needed. This function is not supposed to be used, according to PEP-3333, but once we have it it beco...
write
python
python-hyper/h2
examples/asyncio/wsgi-server.py
https://github.com/python-hyper/h2/blob/master/examples/asyncio/wsgi-server.py
MIT
def _emit_headers(self): """ Sends the response headers. This is only called from the write callable and should only ever be called once. It does some minor processing (converts the status line into a status code because reason phrases are evil) and then passes the heade...
Sends the response headers. This is only called from the write callable and should only ever be called once. It does some minor processing (converts the status line into a status code because reason phrases are evil) and then passes the headers on to the server. This call expli...
_emit_headers
python
python-hyper/h2
examples/asyncio/wsgi-server.py
https://github.com/python-hyper/h2/blob/master/examples/asyncio/wsgi-server.py
MIT
def _build_environ_dict(headers, stream): """ Build the WSGI environ dictionary for a given request. To do that, we'll temporarily create a dictionary for the headers. While this isn't actually a valid way to represent headers, we know that the special headers we need can only have one appearance in...
Build the WSGI environ dictionary for a given request. To do that, we'll temporarily create a dictionary for the headers. While this isn't actually a valid way to represent headers, we know that the special headers we need can only have one appearance in the block. This code is arguably somewhat i...
_build_environ_dict
python
python-hyper/h2
examples/asyncio/wsgi-server.py
https://github.com/python-hyper/h2/blob/master/examples/asyncio/wsgi-server.py
MIT