repo
stringlengths 7
55
| path
stringlengths 4
223
| func_name
stringlengths 1
134
| original_string
stringlengths 75
104k
| language
stringclasses 1
value | code
stringlengths 75
104k
| code_tokens
listlengths 19
28.4k
| docstring
stringlengths 1
46.9k
| docstring_tokens
listlengths 1
1.97k
| sha
stringlengths 40
40
| url
stringlengths 87
315
| partition
stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
tensorflow/lucid
|
lucid/optvis/objectives.py
|
class_logit
|
def class_logit(layer, label):
"""Like channel, but for softmax layers.
Args:
layer: A layer name string.
label: Either a string (refering to a label in model.labels) or an int
label position.
Returns:
Objective maximizing a logit.
"""
def inner(T):
if isinstance(label, int):
class_n = label
else:
class_n = T("labels").index(label)
logits = T(layer)
logit = tf.reduce_sum(logits[:, class_n])
return logit
return inner
|
python
|
def class_logit(layer, label):
"""Like channel, but for softmax layers.
Args:
layer: A layer name string.
label: Either a string (refering to a label in model.labels) or an int
label position.
Returns:
Objective maximizing a logit.
"""
def inner(T):
if isinstance(label, int):
class_n = label
else:
class_n = T("labels").index(label)
logits = T(layer)
logit = tf.reduce_sum(logits[:, class_n])
return logit
return inner
|
[
"def",
"class_logit",
"(",
"layer",
",",
"label",
")",
":",
"def",
"inner",
"(",
"T",
")",
":",
"if",
"isinstance",
"(",
"label",
",",
"int",
")",
":",
"class_n",
"=",
"label",
"else",
":",
"class_n",
"=",
"T",
"(",
"\"labels\"",
")",
".",
"index",
"(",
"label",
")",
"logits",
"=",
"T",
"(",
"layer",
")",
"logit",
"=",
"tf",
".",
"reduce_sum",
"(",
"logits",
"[",
":",
",",
"class_n",
"]",
")",
"return",
"logit",
"return",
"inner"
] |
Like channel, but for softmax layers.
Args:
layer: A layer name string.
label: Either a string (refering to a label in model.labels) or an int
label position.
Returns:
Objective maximizing a logit.
|
[
"Like",
"channel",
"but",
"for",
"softmax",
"layers",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/objectives.py#L442-L461
|
train
|
tensorflow/lucid
|
lucid/optvis/objectives.py
|
as_objective
|
def as_objective(obj):
"""Convert obj into Objective class.
Strings of the form "layer:n" become the Objective channel(layer, n).
Objectives are returned unchanged.
Args:
obj: string or Objective.
Returns:
Objective
"""
if isinstance(obj, Objective):
return obj
elif callable(obj):
return obj
elif isinstance(obj, str):
layer, n = obj.split(":")
layer, n = layer.strip(), int(n)
return channel(layer, n)
|
python
|
def as_objective(obj):
"""Convert obj into Objective class.
Strings of the form "layer:n" become the Objective channel(layer, n).
Objectives are returned unchanged.
Args:
obj: string or Objective.
Returns:
Objective
"""
if isinstance(obj, Objective):
return obj
elif callable(obj):
return obj
elif isinstance(obj, str):
layer, n = obj.split(":")
layer, n = layer.strip(), int(n)
return channel(layer, n)
|
[
"def",
"as_objective",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"Objective",
")",
":",
"return",
"obj",
"elif",
"callable",
"(",
"obj",
")",
":",
"return",
"obj",
"elif",
"isinstance",
"(",
"obj",
",",
"str",
")",
":",
"layer",
",",
"n",
"=",
"obj",
".",
"split",
"(",
"\":\"",
")",
"layer",
",",
"n",
"=",
"layer",
".",
"strip",
"(",
")",
",",
"int",
"(",
"n",
")",
"return",
"channel",
"(",
"layer",
",",
"n",
")"
] |
Convert obj into Objective class.
Strings of the form "layer:n" become the Objective channel(layer, n).
Objectives are returned unchanged.
Args:
obj: string or Objective.
Returns:
Objective
|
[
"Convert",
"obj",
"into",
"Objective",
"class",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/objectives.py#L464-L483
|
train
|
tensorflow/lucid
|
lucid/optvis/param/unit_balls.py
|
_constrain_L2_grad
|
def _constrain_L2_grad(op, grad):
"""Gradient for constrained optimization on an L2 unit ball.
This function projects the gradient onto the ball if you are on the boundary
(or outside!), but leaves it untouched if you are inside the ball.
Args:
op: the tensorflow op we're computing the gradient for.
grad: gradient we need to backprop
Returns:
(projected if necessary) gradient.
"""
inp = op.inputs[0]
inp_norm = tf.norm(inp)
unit_inp = inp / inp_norm
grad_projection = dot(unit_inp, grad)
parallel_grad = unit_inp * grad_projection
is_in_ball = tf.less_equal(inp_norm, 1)
is_pointed_inward = tf.less(grad_projection, 0)
allow_grad = tf.logical_or(is_in_ball, is_pointed_inward)
clip_grad = tf.logical_not(allow_grad)
clipped_grad = tf.cond(clip_grad, lambda: grad - parallel_grad, lambda: grad)
return clipped_grad
|
python
|
def _constrain_L2_grad(op, grad):
"""Gradient for constrained optimization on an L2 unit ball.
This function projects the gradient onto the ball if you are on the boundary
(or outside!), but leaves it untouched if you are inside the ball.
Args:
op: the tensorflow op we're computing the gradient for.
grad: gradient we need to backprop
Returns:
(projected if necessary) gradient.
"""
inp = op.inputs[0]
inp_norm = tf.norm(inp)
unit_inp = inp / inp_norm
grad_projection = dot(unit_inp, grad)
parallel_grad = unit_inp * grad_projection
is_in_ball = tf.less_equal(inp_norm, 1)
is_pointed_inward = tf.less(grad_projection, 0)
allow_grad = tf.logical_or(is_in_ball, is_pointed_inward)
clip_grad = tf.logical_not(allow_grad)
clipped_grad = tf.cond(clip_grad, lambda: grad - parallel_grad, lambda: grad)
return clipped_grad
|
[
"def",
"_constrain_L2_grad",
"(",
"op",
",",
"grad",
")",
":",
"inp",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
"inp_norm",
"=",
"tf",
".",
"norm",
"(",
"inp",
")",
"unit_inp",
"=",
"inp",
"/",
"inp_norm",
"grad_projection",
"=",
"dot",
"(",
"unit_inp",
",",
"grad",
")",
"parallel_grad",
"=",
"unit_inp",
"*",
"grad_projection",
"is_in_ball",
"=",
"tf",
".",
"less_equal",
"(",
"inp_norm",
",",
"1",
")",
"is_pointed_inward",
"=",
"tf",
".",
"less",
"(",
"grad_projection",
",",
"0",
")",
"allow_grad",
"=",
"tf",
".",
"logical_or",
"(",
"is_in_ball",
",",
"is_pointed_inward",
")",
"clip_grad",
"=",
"tf",
".",
"logical_not",
"(",
"allow_grad",
")",
"clipped_grad",
"=",
"tf",
".",
"cond",
"(",
"clip_grad",
",",
"lambda",
":",
"grad",
"-",
"parallel_grad",
",",
"lambda",
":",
"grad",
")",
"return",
"clipped_grad"
] |
Gradient for constrained optimization on an L2 unit ball.
This function projects the gradient onto the ball if you are on the boundary
(or outside!), but leaves it untouched if you are inside the ball.
Args:
op: the tensorflow op we're computing the gradient for.
grad: gradient we need to backprop
Returns:
(projected if necessary) gradient.
|
[
"Gradient",
"for",
"constrained",
"optimization",
"on",
"an",
"L2",
"unit",
"ball",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/param/unit_balls.py#L20-L47
|
train
|
tensorflow/lucid
|
lucid/optvis/param/unit_balls.py
|
unit_ball_L2
|
def unit_ball_L2(shape):
"""A tensorflow variable tranfomed to be constrained in a L2 unit ball.
EXPERIMENTAL: Do not use for adverserial examples if you need to be confident
they are strong attacks. We are not yet confident in this code.
"""
x = tf.Variable(tf.zeros(shape))
return constrain_L2(x)
|
python
|
def unit_ball_L2(shape):
"""A tensorflow variable tranfomed to be constrained in a L2 unit ball.
EXPERIMENTAL: Do not use for adverserial examples if you need to be confident
they are strong attacks. We are not yet confident in this code.
"""
x = tf.Variable(tf.zeros(shape))
return constrain_L2(x)
|
[
"def",
"unit_ball_L2",
"(",
"shape",
")",
":",
"x",
"=",
"tf",
".",
"Variable",
"(",
"tf",
".",
"zeros",
"(",
"shape",
")",
")",
"return",
"constrain_L2",
"(",
"x",
")"
] |
A tensorflow variable tranfomed to be constrained in a L2 unit ball.
EXPERIMENTAL: Do not use for adverserial examples if you need to be confident
they are strong attacks. We are not yet confident in this code.
|
[
"A",
"tensorflow",
"variable",
"tranfomed",
"to",
"be",
"constrained",
"in",
"a",
"L2",
"unit",
"ball",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/param/unit_balls.py#L55-L62
|
train
|
tensorflow/lucid
|
lucid/optvis/param/unit_balls.py
|
unit_ball_L_inf
|
def unit_ball_L_inf(shape, precondition=True):
"""A tensorflow variable tranfomed to be constrained in a L_inf unit ball.
Note that this code also preconditions the gradient to go in the L_inf
direction of steepest descent.
EXPERIMENTAL: Do not use for adverserial examples if you need to be confident
they are strong attacks. We are not yet confident in this code.
"""
x = tf.Variable(tf.zeros(shape))
if precondition:
return constrain_L_inf_precondition(x)
else:
return constrain_L_inf(x)
|
python
|
def unit_ball_L_inf(shape, precondition=True):
"""A tensorflow variable tranfomed to be constrained in a L_inf unit ball.
Note that this code also preconditions the gradient to go in the L_inf
direction of steepest descent.
EXPERIMENTAL: Do not use for adverserial examples if you need to be confident
they are strong attacks. We are not yet confident in this code.
"""
x = tf.Variable(tf.zeros(shape))
if precondition:
return constrain_L_inf_precondition(x)
else:
return constrain_L_inf(x)
|
[
"def",
"unit_ball_L_inf",
"(",
"shape",
",",
"precondition",
"=",
"True",
")",
":",
"x",
"=",
"tf",
".",
"Variable",
"(",
"tf",
".",
"zeros",
"(",
"shape",
")",
")",
"if",
"precondition",
":",
"return",
"constrain_L_inf_precondition",
"(",
"x",
")",
"else",
":",
"return",
"constrain_L_inf",
"(",
"x",
")"
] |
A tensorflow variable tranfomed to be constrained in a L_inf unit ball.
Note that this code also preconditions the gradient to go in the L_inf
direction of steepest descent.
EXPERIMENTAL: Do not use for adverserial examples if you need to be confident
they are strong attacks. We are not yet confident in this code.
|
[
"A",
"tensorflow",
"variable",
"tranfomed",
"to",
"be",
"constrained",
"in",
"a",
"L_inf",
"unit",
"ball",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/param/unit_balls.py#L106-L119
|
train
|
tensorflow/lucid
|
lucid/optvis/render.py
|
render_vis
|
def render_vis(model, objective_f, param_f=None, optimizer=None,
transforms=None, thresholds=(512,), print_objectives=None,
verbose=True, relu_gradient_override=True, use_fixed_seed=False):
"""Flexible optimization-base feature vis.
There's a lot of ways one might wish to customize otpimization-based
feature visualization. It's hard to create an abstraction that stands up
to all the things one might wish to try.
This function probably can't do *everything* you want, but it's much more
flexible than a naive attempt. The basic abstraction is to split the problem
into several parts. Consider the rguments:
Args:
model: The model to be visualized, from Alex' modelzoo.
objective_f: The objective our visualization maximizes.
See the objectives module for more details.
param_f: Paramaterization of the image we're optimizing.
See the paramaterization module for more details.
Defaults to a naively paramaterized [1, 128, 128, 3] image.
optimizer: Optimizer to optimize with. Either tf.train.Optimizer instance,
or a function from (graph, sess) to such an instance.
Defaults to Adam with lr .05.
transforms: A list of stochastic transformations that get composed,
which our visualization should robustly activate the network against.
See the transform module for more details.
Defaults to [transform.jitter(8)].
thresholds: A list of numbers of optimization steps, at which we should
save (and display if verbose=True) the visualization.
print_objectives: A list of objectives separate from those being optimized,
whose values get logged during the optimization.
verbose: Should we display the visualization when we hit a threshold?
This should only be used in IPython.
relu_gradient_override: Whether to use the gradient override scheme
described in lucid/misc/redirected_relu_grad.py. On by default!
use_fixed_seed: Seed the RNG with a fixed value so results are reproducible.
Off by default. As of tf 1.8 this does not work as intended, see:
https://github.com/tensorflow/tensorflow/issues/9171
Returns:
2D array of optimization results containing of evaluations of supplied
param_f snapshotted at specified thresholds. Usually that will mean one or
multiple channel visualizations stacked on top of each other.
"""
with tf.Graph().as_default() as graph, tf.Session() as sess:
if use_fixed_seed: # does not mean results are reproducible, see Args doc
tf.set_random_seed(0)
T = make_vis_T(model, objective_f, param_f, optimizer, transforms,
relu_gradient_override)
print_objective_func = make_print_objective_func(print_objectives, T)
loss, vis_op, t_image = T("loss"), T("vis_op"), T("input")
tf.global_variables_initializer().run()
images = []
try:
for i in range(max(thresholds)+1):
loss_, _ = sess.run([loss, vis_op])
if i in thresholds:
vis = t_image.eval()
images.append(vis)
if verbose:
print(i, loss_)
print_objective_func(sess)
show(np.hstack(vis))
except KeyboardInterrupt:
log.warning("Interrupted optimization at step {:d}.".format(i+1))
vis = t_image.eval()
show(np.hstack(vis))
return images
|
python
|
def render_vis(model, objective_f, param_f=None, optimizer=None,
transforms=None, thresholds=(512,), print_objectives=None,
verbose=True, relu_gradient_override=True, use_fixed_seed=False):
"""Flexible optimization-base feature vis.
There's a lot of ways one might wish to customize otpimization-based
feature visualization. It's hard to create an abstraction that stands up
to all the things one might wish to try.
This function probably can't do *everything* you want, but it's much more
flexible than a naive attempt. The basic abstraction is to split the problem
into several parts. Consider the rguments:
Args:
model: The model to be visualized, from Alex' modelzoo.
objective_f: The objective our visualization maximizes.
See the objectives module for more details.
param_f: Paramaterization of the image we're optimizing.
See the paramaterization module for more details.
Defaults to a naively paramaterized [1, 128, 128, 3] image.
optimizer: Optimizer to optimize with. Either tf.train.Optimizer instance,
or a function from (graph, sess) to such an instance.
Defaults to Adam with lr .05.
transforms: A list of stochastic transformations that get composed,
which our visualization should robustly activate the network against.
See the transform module for more details.
Defaults to [transform.jitter(8)].
thresholds: A list of numbers of optimization steps, at which we should
save (and display if verbose=True) the visualization.
print_objectives: A list of objectives separate from those being optimized,
whose values get logged during the optimization.
verbose: Should we display the visualization when we hit a threshold?
This should only be used in IPython.
relu_gradient_override: Whether to use the gradient override scheme
described in lucid/misc/redirected_relu_grad.py. On by default!
use_fixed_seed: Seed the RNG with a fixed value so results are reproducible.
Off by default. As of tf 1.8 this does not work as intended, see:
https://github.com/tensorflow/tensorflow/issues/9171
Returns:
2D array of optimization results containing of evaluations of supplied
param_f snapshotted at specified thresholds. Usually that will mean one or
multiple channel visualizations stacked on top of each other.
"""
with tf.Graph().as_default() as graph, tf.Session() as sess:
if use_fixed_seed: # does not mean results are reproducible, see Args doc
tf.set_random_seed(0)
T = make_vis_T(model, objective_f, param_f, optimizer, transforms,
relu_gradient_override)
print_objective_func = make_print_objective_func(print_objectives, T)
loss, vis_op, t_image = T("loss"), T("vis_op"), T("input")
tf.global_variables_initializer().run()
images = []
try:
for i in range(max(thresholds)+1):
loss_, _ = sess.run([loss, vis_op])
if i in thresholds:
vis = t_image.eval()
images.append(vis)
if verbose:
print(i, loss_)
print_objective_func(sess)
show(np.hstack(vis))
except KeyboardInterrupt:
log.warning("Interrupted optimization at step {:d}.".format(i+1))
vis = t_image.eval()
show(np.hstack(vis))
return images
|
[
"def",
"render_vis",
"(",
"model",
",",
"objective_f",
",",
"param_f",
"=",
"None",
",",
"optimizer",
"=",
"None",
",",
"transforms",
"=",
"None",
",",
"thresholds",
"=",
"(",
"512",
",",
")",
",",
"print_objectives",
"=",
"None",
",",
"verbose",
"=",
"True",
",",
"relu_gradient_override",
"=",
"True",
",",
"use_fixed_seed",
"=",
"False",
")",
":",
"with",
"tf",
".",
"Graph",
"(",
")",
".",
"as_default",
"(",
")",
"as",
"graph",
",",
"tf",
".",
"Session",
"(",
")",
"as",
"sess",
":",
"if",
"use_fixed_seed",
":",
"# does not mean results are reproducible, see Args doc",
"tf",
".",
"set_random_seed",
"(",
"0",
")",
"T",
"=",
"make_vis_T",
"(",
"model",
",",
"objective_f",
",",
"param_f",
",",
"optimizer",
",",
"transforms",
",",
"relu_gradient_override",
")",
"print_objective_func",
"=",
"make_print_objective_func",
"(",
"print_objectives",
",",
"T",
")",
"loss",
",",
"vis_op",
",",
"t_image",
"=",
"T",
"(",
"\"loss\"",
")",
",",
"T",
"(",
"\"vis_op\"",
")",
",",
"T",
"(",
"\"input\"",
")",
"tf",
".",
"global_variables_initializer",
"(",
")",
".",
"run",
"(",
")",
"images",
"=",
"[",
"]",
"try",
":",
"for",
"i",
"in",
"range",
"(",
"max",
"(",
"thresholds",
")",
"+",
"1",
")",
":",
"loss_",
",",
"_",
"=",
"sess",
".",
"run",
"(",
"[",
"loss",
",",
"vis_op",
"]",
")",
"if",
"i",
"in",
"thresholds",
":",
"vis",
"=",
"t_image",
".",
"eval",
"(",
")",
"images",
".",
"append",
"(",
"vis",
")",
"if",
"verbose",
":",
"print",
"(",
"i",
",",
"loss_",
")",
"print_objective_func",
"(",
"sess",
")",
"show",
"(",
"np",
".",
"hstack",
"(",
"vis",
")",
")",
"except",
"KeyboardInterrupt",
":",
"log",
".",
"warning",
"(",
"\"Interrupted optimization at step {:d}.\"",
".",
"format",
"(",
"i",
"+",
"1",
")",
")",
"vis",
"=",
"t_image",
".",
"eval",
"(",
")",
"show",
"(",
"np",
".",
"hstack",
"(",
"vis",
")",
")",
"return",
"images"
] |
Flexible optimization-base feature vis.
There's a lot of ways one might wish to customize otpimization-based
feature visualization. It's hard to create an abstraction that stands up
to all the things one might wish to try.
This function probably can't do *everything* you want, but it's much more
flexible than a naive attempt. The basic abstraction is to split the problem
into several parts. Consider the rguments:
Args:
model: The model to be visualized, from Alex' modelzoo.
objective_f: The objective our visualization maximizes.
See the objectives module for more details.
param_f: Paramaterization of the image we're optimizing.
See the paramaterization module for more details.
Defaults to a naively paramaterized [1, 128, 128, 3] image.
optimizer: Optimizer to optimize with. Either tf.train.Optimizer instance,
or a function from (graph, sess) to such an instance.
Defaults to Adam with lr .05.
transforms: A list of stochastic transformations that get composed,
which our visualization should robustly activate the network against.
See the transform module for more details.
Defaults to [transform.jitter(8)].
thresholds: A list of numbers of optimization steps, at which we should
save (and display if verbose=True) the visualization.
print_objectives: A list of objectives separate from those being optimized,
whose values get logged during the optimization.
verbose: Should we display the visualization when we hit a threshold?
This should only be used in IPython.
relu_gradient_override: Whether to use the gradient override scheme
described in lucid/misc/redirected_relu_grad.py. On by default!
use_fixed_seed: Seed the RNG with a fixed value so results are reproducible.
Off by default. As of tf 1.8 this does not work as intended, see:
https://github.com/tensorflow/tensorflow/issues/9171
Returns:
2D array of optimization results containing of evaluations of supplied
param_f snapshotted at specified thresholds. Usually that will mean one or
multiple channel visualizations stacked on top of each other.
|
[
"Flexible",
"optimization",
"-",
"base",
"feature",
"vis",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/render.py#L44-L115
|
train
|
tensorflow/lucid
|
lucid/optvis/render.py
|
make_vis_T
|
def make_vis_T(model, objective_f, param_f=None, optimizer=None,
transforms=None, relu_gradient_override=False):
"""Even more flexible optimization-base feature vis.
This function is the inner core of render_vis(), and can be used
when render_vis() isn't flexible enough. Unfortunately, it's a bit more
tedious to use:
> with tf.Graph().as_default() as graph, tf.Session() as sess:
>
> T = make_vis_T(model, "mixed4a_pre_relu:0")
> tf.initialize_all_variables().run()
>
> for i in range(10):
> T("vis_op").run()
> showarray(T("input").eval()[0])
This approach allows more control over how the visualizaiton is displayed
as it renders. It also allows a lot more flexibility in constructing
objectives / params because the session is already in scope.
Args:
model: The model to be visualized, from Alex' modelzoo.
objective_f: The objective our visualization maximizes.
See the objectives module for more details.
param_f: Paramaterization of the image we're optimizing.
See the paramaterization module for more details.
Defaults to a naively paramaterized [1, 128, 128, 3] image.
optimizer: Optimizer to optimize with. Either tf.train.Optimizer instance,
or a function from (graph, sess) to such an instance.
Defaults to Adam with lr .05.
transforms: A list of stochastic transformations that get composed,
which our visualization should robustly activate the network against.
See the transform module for more details.
Defaults to [transform.jitter(8)].
Returns:
A function T, which allows access to:
* T("vis_op") -- the operation for to optimize the visualization
* T("input") -- the visualization itself
* T("loss") -- the loss for the visualization
* T(layer) -- any layer inside the network
"""
# pylint: disable=unused-variable
t_image = make_t_image(param_f)
objective_f = objectives.as_objective(objective_f)
transform_f = make_transform_f(transforms)
optimizer = make_optimizer(optimizer, [])
global_step = tf.train.get_or_create_global_step()
init_global_step = tf.variables_initializer([global_step])
init_global_step.run()
if relu_gradient_override:
with gradient_override_map({'Relu': redirected_relu_grad,
'Relu6': redirected_relu6_grad}):
T = import_model(model, transform_f(t_image), t_image)
else:
T = import_model(model, transform_f(t_image), t_image)
loss = objective_f(T)
vis_op = optimizer.minimize(-loss, global_step=global_step)
local_vars = locals()
# pylint: enable=unused-variable
def T2(name):
if name in local_vars:
return local_vars[name]
else: return T(name)
return T2
|
python
|
def make_vis_T(model, objective_f, param_f=None, optimizer=None,
transforms=None, relu_gradient_override=False):
"""Even more flexible optimization-base feature vis.
This function is the inner core of render_vis(), and can be used
when render_vis() isn't flexible enough. Unfortunately, it's a bit more
tedious to use:
> with tf.Graph().as_default() as graph, tf.Session() as sess:
>
> T = make_vis_T(model, "mixed4a_pre_relu:0")
> tf.initialize_all_variables().run()
>
> for i in range(10):
> T("vis_op").run()
> showarray(T("input").eval()[0])
This approach allows more control over how the visualizaiton is displayed
as it renders. It also allows a lot more flexibility in constructing
objectives / params because the session is already in scope.
Args:
model: The model to be visualized, from Alex' modelzoo.
objective_f: The objective our visualization maximizes.
See the objectives module for more details.
param_f: Paramaterization of the image we're optimizing.
See the paramaterization module for more details.
Defaults to a naively paramaterized [1, 128, 128, 3] image.
optimizer: Optimizer to optimize with. Either tf.train.Optimizer instance,
or a function from (graph, sess) to such an instance.
Defaults to Adam with lr .05.
transforms: A list of stochastic transformations that get composed,
which our visualization should robustly activate the network against.
See the transform module for more details.
Defaults to [transform.jitter(8)].
Returns:
A function T, which allows access to:
* T("vis_op") -- the operation for to optimize the visualization
* T("input") -- the visualization itself
* T("loss") -- the loss for the visualization
* T(layer) -- any layer inside the network
"""
# pylint: disable=unused-variable
t_image = make_t_image(param_f)
objective_f = objectives.as_objective(objective_f)
transform_f = make_transform_f(transforms)
optimizer = make_optimizer(optimizer, [])
global_step = tf.train.get_or_create_global_step()
init_global_step = tf.variables_initializer([global_step])
init_global_step.run()
if relu_gradient_override:
with gradient_override_map({'Relu': redirected_relu_grad,
'Relu6': redirected_relu6_grad}):
T = import_model(model, transform_f(t_image), t_image)
else:
T = import_model(model, transform_f(t_image), t_image)
loss = objective_f(T)
vis_op = optimizer.minimize(-loss, global_step=global_step)
local_vars = locals()
# pylint: enable=unused-variable
def T2(name):
if name in local_vars:
return local_vars[name]
else: return T(name)
return T2
|
[
"def",
"make_vis_T",
"(",
"model",
",",
"objective_f",
",",
"param_f",
"=",
"None",
",",
"optimizer",
"=",
"None",
",",
"transforms",
"=",
"None",
",",
"relu_gradient_override",
"=",
"False",
")",
":",
"# pylint: disable=unused-variable",
"t_image",
"=",
"make_t_image",
"(",
"param_f",
")",
"objective_f",
"=",
"objectives",
".",
"as_objective",
"(",
"objective_f",
")",
"transform_f",
"=",
"make_transform_f",
"(",
"transforms",
")",
"optimizer",
"=",
"make_optimizer",
"(",
"optimizer",
",",
"[",
"]",
")",
"global_step",
"=",
"tf",
".",
"train",
".",
"get_or_create_global_step",
"(",
")",
"init_global_step",
"=",
"tf",
".",
"variables_initializer",
"(",
"[",
"global_step",
"]",
")",
"init_global_step",
".",
"run",
"(",
")",
"if",
"relu_gradient_override",
":",
"with",
"gradient_override_map",
"(",
"{",
"'Relu'",
":",
"redirected_relu_grad",
",",
"'Relu6'",
":",
"redirected_relu6_grad",
"}",
")",
":",
"T",
"=",
"import_model",
"(",
"model",
",",
"transform_f",
"(",
"t_image",
")",
",",
"t_image",
")",
"else",
":",
"T",
"=",
"import_model",
"(",
"model",
",",
"transform_f",
"(",
"t_image",
")",
",",
"t_image",
")",
"loss",
"=",
"objective_f",
"(",
"T",
")",
"vis_op",
"=",
"optimizer",
".",
"minimize",
"(",
"-",
"loss",
",",
"global_step",
"=",
"global_step",
")",
"local_vars",
"=",
"locals",
"(",
")",
"# pylint: enable=unused-variable",
"def",
"T2",
"(",
"name",
")",
":",
"if",
"name",
"in",
"local_vars",
":",
"return",
"local_vars",
"[",
"name",
"]",
"else",
":",
"return",
"T",
"(",
"name",
")",
"return",
"T2"
] |
Even more flexible optimization-base feature vis.
This function is the inner core of render_vis(), and can be used
when render_vis() isn't flexible enough. Unfortunately, it's a bit more
tedious to use:
> with tf.Graph().as_default() as graph, tf.Session() as sess:
>
> T = make_vis_T(model, "mixed4a_pre_relu:0")
> tf.initialize_all_variables().run()
>
> for i in range(10):
> T("vis_op").run()
> showarray(T("input").eval()[0])
This approach allows more control over how the visualizaiton is displayed
as it renders. It also allows a lot more flexibility in constructing
objectives / params because the session is already in scope.
Args:
model: The model to be visualized, from Alex' modelzoo.
objective_f: The objective our visualization maximizes.
See the objectives module for more details.
param_f: Paramaterization of the image we're optimizing.
See the paramaterization module for more details.
Defaults to a naively paramaterized [1, 128, 128, 3] image.
optimizer: Optimizer to optimize with. Either tf.train.Optimizer instance,
or a function from (graph, sess) to such an instance.
Defaults to Adam with lr .05.
transforms: A list of stochastic transformations that get composed,
which our visualization should robustly activate the network against.
See the transform module for more details.
Defaults to [transform.jitter(8)].
Returns:
A function T, which allows access to:
* T("vis_op") -- the operation for to optimize the visualization
* T("input") -- the visualization itself
* T("loss") -- the loss for the visualization
* T(layer) -- any layer inside the network
|
[
"Even",
"more",
"flexible",
"optimization",
"-",
"base",
"feature",
"vis",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/render.py#L118-L192
|
train
|
tensorflow/lucid
|
lucid/scratch/atlas_pipeline/grid.py
|
grid
|
def grid(metadata, layout, params):
"""
layout: numpy arrays x, y
metadata: user-defined numpy arrays with metadata
n_layer: number of cells in the layer (squared)
n_tile: number of cells in the tile (squared)
"""
x = layout["x"]
y = layout["y"]
x_min = np.min(x)
x_max = np.max(x)
y_min = np.min(y)
y_max = np.max(y)
# this creates the grid
bins = np.linspace(x_min, x_max, params["n_layer"] - 1)
xd = np.digitize(x, bins)
bins = np.linspace(y_min, y_max, params["n_layer"] - 1)
yd = np.digitize(y, bins)
# the number of tiles is the number of cells divided by the number of cells in each tile
num_tiles = int(params["n_layer"]/params["n_tile"])
print("num tiles", num_tiles)
# we will save the tiles in an array indexed by the tile coordinates
tiles = {}
for ti in range(num_tiles):
for tj in range(num_tiles):
tiles[(ti,tj)] = {
"x": [],
"y": [],
"ci": [], # cell-space x coordinate
"cj": [], # cell-space y coordinate
"gi": [], # global index
}
for i,xi in enumerate(x):
if(i % 1000 == 0 or i+1 == len(x)):
print("point", i+1, "/", len(x), end="\r")
# layout-space coordinates
yi = y[i]
# grid-space cell coordinates
ci = xd[i]
cj = yd[i]
# tile coordinate
ti = math.floor(ci / params["n_tile"])
tj = math.floor(cj / params["n_tile"])
# TODO: don't append a point if it doesn't match a filter function provided in params
filter = params.get("filter", lambda i,metadata: True)
if(filter(i, metadata=metadata)):
tiles[(ti,tj)]["x"].append(xi)
tiles[(ti,tj)]["y"].append(yi)
tiles[(ti,tj)]["ci"].append(ci)
tiles[(ti,tj)]["cj"].append(cj)
tiles[(ti,tj)]["gi"].append(i)
return tiles
|
python
|
def grid(metadata, layout, params):
"""
layout: numpy arrays x, y
metadata: user-defined numpy arrays with metadata
n_layer: number of cells in the layer (squared)
n_tile: number of cells in the tile (squared)
"""
x = layout["x"]
y = layout["y"]
x_min = np.min(x)
x_max = np.max(x)
y_min = np.min(y)
y_max = np.max(y)
# this creates the grid
bins = np.linspace(x_min, x_max, params["n_layer"] - 1)
xd = np.digitize(x, bins)
bins = np.linspace(y_min, y_max, params["n_layer"] - 1)
yd = np.digitize(y, bins)
# the number of tiles is the number of cells divided by the number of cells in each tile
num_tiles = int(params["n_layer"]/params["n_tile"])
print("num tiles", num_tiles)
# we will save the tiles in an array indexed by the tile coordinates
tiles = {}
for ti in range(num_tiles):
for tj in range(num_tiles):
tiles[(ti,tj)] = {
"x": [],
"y": [],
"ci": [], # cell-space x coordinate
"cj": [], # cell-space y coordinate
"gi": [], # global index
}
for i,xi in enumerate(x):
if(i % 1000 == 0 or i+1 == len(x)):
print("point", i+1, "/", len(x), end="\r")
# layout-space coordinates
yi = y[i]
# grid-space cell coordinates
ci = xd[i]
cj = yd[i]
# tile coordinate
ti = math.floor(ci / params["n_tile"])
tj = math.floor(cj / params["n_tile"])
# TODO: don't append a point if it doesn't match a filter function provided in params
filter = params.get("filter", lambda i,metadata: True)
if(filter(i, metadata=metadata)):
tiles[(ti,tj)]["x"].append(xi)
tiles[(ti,tj)]["y"].append(yi)
tiles[(ti,tj)]["ci"].append(ci)
tiles[(ti,tj)]["cj"].append(cj)
tiles[(ti,tj)]["gi"].append(i)
return tiles
|
[
"def",
"grid",
"(",
"metadata",
",",
"layout",
",",
"params",
")",
":",
"x",
"=",
"layout",
"[",
"\"x\"",
"]",
"y",
"=",
"layout",
"[",
"\"y\"",
"]",
"x_min",
"=",
"np",
".",
"min",
"(",
"x",
")",
"x_max",
"=",
"np",
".",
"max",
"(",
"x",
")",
"y_min",
"=",
"np",
".",
"min",
"(",
"y",
")",
"y_max",
"=",
"np",
".",
"max",
"(",
"y",
")",
"# this creates the grid",
"bins",
"=",
"np",
".",
"linspace",
"(",
"x_min",
",",
"x_max",
",",
"params",
"[",
"\"n_layer\"",
"]",
"-",
"1",
")",
"xd",
"=",
"np",
".",
"digitize",
"(",
"x",
",",
"bins",
")",
"bins",
"=",
"np",
".",
"linspace",
"(",
"y_min",
",",
"y_max",
",",
"params",
"[",
"\"n_layer\"",
"]",
"-",
"1",
")",
"yd",
"=",
"np",
".",
"digitize",
"(",
"y",
",",
"bins",
")",
"# the number of tiles is the number of cells divided by the number of cells in each tile",
"num_tiles",
"=",
"int",
"(",
"params",
"[",
"\"n_layer\"",
"]",
"/",
"params",
"[",
"\"n_tile\"",
"]",
")",
"print",
"(",
"\"num tiles\"",
",",
"num_tiles",
")",
"# we will save the tiles in an array indexed by the tile coordinates",
"tiles",
"=",
"{",
"}",
"for",
"ti",
"in",
"range",
"(",
"num_tiles",
")",
":",
"for",
"tj",
"in",
"range",
"(",
"num_tiles",
")",
":",
"tiles",
"[",
"(",
"ti",
",",
"tj",
")",
"]",
"=",
"{",
"\"x\"",
":",
"[",
"]",
",",
"\"y\"",
":",
"[",
"]",
",",
"\"ci\"",
":",
"[",
"]",
",",
"# cell-space x coordinate",
"\"cj\"",
":",
"[",
"]",
",",
"# cell-space y coordinate",
"\"gi\"",
":",
"[",
"]",
",",
"# global index",
"}",
"for",
"i",
",",
"xi",
"in",
"enumerate",
"(",
"x",
")",
":",
"if",
"(",
"i",
"%",
"1000",
"==",
"0",
"or",
"i",
"+",
"1",
"==",
"len",
"(",
"x",
")",
")",
":",
"print",
"(",
"\"point\"",
",",
"i",
"+",
"1",
",",
"\"/\"",
",",
"len",
"(",
"x",
")",
",",
"end",
"=",
"\"\\r\"",
")",
"# layout-space coordinates",
"yi",
"=",
"y",
"[",
"i",
"]",
"# grid-space cell coordinates",
"ci",
"=",
"xd",
"[",
"i",
"]",
"cj",
"=",
"yd",
"[",
"i",
"]",
"# tile coordinate",
"ti",
"=",
"math",
".",
"floor",
"(",
"ci",
"/",
"params",
"[",
"\"n_tile\"",
"]",
")",
"tj",
"=",
"math",
".",
"floor",
"(",
"cj",
"/",
"params",
"[",
"\"n_tile\"",
"]",
")",
"# TODO: don't append a point if it doesn't match a filter function provided in params",
"filter",
"=",
"params",
".",
"get",
"(",
"\"filter\"",
",",
"lambda",
"i",
",",
"metadata",
":",
"True",
")",
"if",
"(",
"filter",
"(",
"i",
",",
"metadata",
"=",
"metadata",
")",
")",
":",
"tiles",
"[",
"(",
"ti",
",",
"tj",
")",
"]",
"[",
"\"x\"",
"]",
".",
"append",
"(",
"xi",
")",
"tiles",
"[",
"(",
"ti",
",",
"tj",
")",
"]",
"[",
"\"y\"",
"]",
".",
"append",
"(",
"yi",
")",
"tiles",
"[",
"(",
"ti",
",",
"tj",
")",
"]",
"[",
"\"ci\"",
"]",
".",
"append",
"(",
"ci",
")",
"tiles",
"[",
"(",
"ti",
",",
"tj",
")",
"]",
"[",
"\"cj\"",
"]",
".",
"append",
"(",
"cj",
")",
"tiles",
"[",
"(",
"ti",
",",
"tj",
")",
"]",
"[",
"\"gi\"",
"]",
".",
"append",
"(",
"i",
")",
"return",
"tiles"
] |
layout: numpy arrays x, y
metadata: user-defined numpy arrays with metadata
n_layer: number of cells in the layer (squared)
n_tile: number of cells in the tile (squared)
|
[
"layout",
":",
"numpy",
"arrays",
"x",
"y",
"metadata",
":",
"user",
"-",
"defined",
"numpy",
"arrays",
"with",
"metadata",
"n_layer",
":",
"number",
"of",
"cells",
"in",
"the",
"layer",
"(",
"squared",
")",
"n_tile",
":",
"number",
"of",
"cells",
"in",
"the",
"tile",
"(",
"squared",
")"
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/scratch/atlas_pipeline/grid.py#L12-L68
|
train
|
tensorflow/lucid
|
lucid/scratch/atlas_pipeline/grid.py
|
write_grid_local
|
def write_grid_local(tiles, params):
"""
Write a file for each tile
"""
# TODO: this isn't being used right now, will need to be
# ported to gfile if we want to keep it
for ti,tj,tile in enumerate_tiles(tiles):
filename = "{directory}/{name}/tile_{n_layer}_{n_tile}_{ti}_{tj}".format(ti=ti, tj=tj, **params) #directory=directory, name=name, n_layer=n_layer, n_tile=n_tile,
# write out the tile as a npz
print("saving", filename + ".npz")
np.savez_compressed(filename + ".npz", **tile)
# write out the tile as a csv
print("saving", filename + ".csv")
df = pd.DataFrame(tile)
df.to_csv(filename + ".csv", index=False)
|
python
|
def write_grid_local(tiles, params):
"""
Write a file for each tile
"""
# TODO: this isn't being used right now, will need to be
# ported to gfile if we want to keep it
for ti,tj,tile in enumerate_tiles(tiles):
filename = "{directory}/{name}/tile_{n_layer}_{n_tile}_{ti}_{tj}".format(ti=ti, tj=tj, **params) #directory=directory, name=name, n_layer=n_layer, n_tile=n_tile,
# write out the tile as a npz
print("saving", filename + ".npz")
np.savez_compressed(filename + ".npz", **tile)
# write out the tile as a csv
print("saving", filename + ".csv")
df = pd.DataFrame(tile)
df.to_csv(filename + ".csv", index=False)
|
[
"def",
"write_grid_local",
"(",
"tiles",
",",
"params",
")",
":",
"# TODO: this isn't being used right now, will need to be",
"# ported to gfile if we want to keep it",
"for",
"ti",
",",
"tj",
",",
"tile",
"in",
"enumerate_tiles",
"(",
"tiles",
")",
":",
"filename",
"=",
"\"{directory}/{name}/tile_{n_layer}_{n_tile}_{ti}_{tj}\"",
".",
"format",
"(",
"ti",
"=",
"ti",
",",
"tj",
"=",
"tj",
",",
"*",
"*",
"params",
")",
"#directory=directory, name=name, n_layer=n_layer, n_tile=n_tile, ",
"# write out the tile as a npz",
"print",
"(",
"\"saving\"",
",",
"filename",
"+",
"\".npz\"",
")",
"np",
".",
"savez_compressed",
"(",
"filename",
"+",
"\".npz\"",
",",
"*",
"*",
"tile",
")",
"# write out the tile as a csv",
"print",
"(",
"\"saving\"",
",",
"filename",
"+",
"\".csv\"",
")",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"tile",
")",
"df",
".",
"to_csv",
"(",
"filename",
"+",
"\".csv\"",
",",
"index",
"=",
"False",
")"
] |
Write a file for each tile
|
[
"Write",
"a",
"file",
"for",
"each",
"tile"
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/scratch/atlas_pipeline/grid.py#L70-L84
|
train
|
tensorflow/lucid
|
lucid/scratch/atlas_pipeline/grid.py
|
enumerate_tiles
|
def enumerate_tiles(tiles):
"""
Convenience
"""
enumerated = []
for key in tiles.keys():
enumerated.append((key[0], key[1], tiles[key]))
return enumerated
|
python
|
def enumerate_tiles(tiles):
"""
Convenience
"""
enumerated = []
for key in tiles.keys():
enumerated.append((key[0], key[1], tiles[key]))
return enumerated
|
[
"def",
"enumerate_tiles",
"(",
"tiles",
")",
":",
"enumerated",
"=",
"[",
"]",
"for",
"key",
"in",
"tiles",
".",
"keys",
"(",
")",
":",
"enumerated",
".",
"append",
"(",
"(",
"key",
"[",
"0",
"]",
",",
"key",
"[",
"1",
"]",
",",
"tiles",
"[",
"key",
"]",
")",
")",
"return",
"enumerated"
] |
Convenience
|
[
"Convenience"
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/scratch/atlas_pipeline/grid.py#L86-L93
|
train
|
tensorflow/lucid
|
lucid/misc/io/loading.py
|
_load_img
|
def _load_img(handle, target_dtype=np.float32, size=None, **kwargs):
"""Load image file as numpy array."""
image_pil = PIL.Image.open(handle, **kwargs)
# resize the image to the requested size, if one was specified
if size is not None:
if len(size) > 2:
size = size[:2]
log.warning("`_load_img()` received size: {}, trimming to first two dims!".format(size))
image_pil = image_pil.resize(size, resample=PIL.Image.LANCZOS)
image_array = np.asarray(image_pil)
# remove alpha channel if it contains no information
# if image_array.shape[-1] > 3 and 'A' not in image_pil.mode:
# image_array = image_array[..., :-1]
image_dtype = image_array.dtype
image_max_value = np.iinfo(image_dtype).max # ...for uint8 that's 255, etc.
# using np.divide should avoid an extra copy compared to doing division first
ndimage = np.divide(image_array, image_max_value, dtype=target_dtype)
rank = len(ndimage.shape)
if rank == 3:
return ndimage
elif rank == 2:
return np.repeat(np.expand_dims(ndimage, axis=2), 3, axis=2)
else:
message = "Loaded image has more dimensions than expected: {}".format(rank)
raise NotImplementedError(message)
|
python
|
def _load_img(handle, target_dtype=np.float32, size=None, **kwargs):
"""Load image file as numpy array."""
image_pil = PIL.Image.open(handle, **kwargs)
# resize the image to the requested size, if one was specified
if size is not None:
if len(size) > 2:
size = size[:2]
log.warning("`_load_img()` received size: {}, trimming to first two dims!".format(size))
image_pil = image_pil.resize(size, resample=PIL.Image.LANCZOS)
image_array = np.asarray(image_pil)
# remove alpha channel if it contains no information
# if image_array.shape[-1] > 3 and 'A' not in image_pil.mode:
# image_array = image_array[..., :-1]
image_dtype = image_array.dtype
image_max_value = np.iinfo(image_dtype).max # ...for uint8 that's 255, etc.
# using np.divide should avoid an extra copy compared to doing division first
ndimage = np.divide(image_array, image_max_value, dtype=target_dtype)
rank = len(ndimage.shape)
if rank == 3:
return ndimage
elif rank == 2:
return np.repeat(np.expand_dims(ndimage, axis=2), 3, axis=2)
else:
message = "Loaded image has more dimensions than expected: {}".format(rank)
raise NotImplementedError(message)
|
[
"def",
"_load_img",
"(",
"handle",
",",
"target_dtype",
"=",
"np",
".",
"float32",
",",
"size",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"image_pil",
"=",
"PIL",
".",
"Image",
".",
"open",
"(",
"handle",
",",
"*",
"*",
"kwargs",
")",
"# resize the image to the requested size, if one was specified",
"if",
"size",
"is",
"not",
"None",
":",
"if",
"len",
"(",
"size",
")",
">",
"2",
":",
"size",
"=",
"size",
"[",
":",
"2",
"]",
"log",
".",
"warning",
"(",
"\"`_load_img()` received size: {}, trimming to first two dims!\"",
".",
"format",
"(",
"size",
")",
")",
"image_pil",
"=",
"image_pil",
".",
"resize",
"(",
"size",
",",
"resample",
"=",
"PIL",
".",
"Image",
".",
"LANCZOS",
")",
"image_array",
"=",
"np",
".",
"asarray",
"(",
"image_pil",
")",
"# remove alpha channel if it contains no information",
"# if image_array.shape[-1] > 3 and 'A' not in image_pil.mode:",
"# image_array = image_array[..., :-1]",
"image_dtype",
"=",
"image_array",
".",
"dtype",
"image_max_value",
"=",
"np",
".",
"iinfo",
"(",
"image_dtype",
")",
".",
"max",
"# ...for uint8 that's 255, etc.",
"# using np.divide should avoid an extra copy compared to doing division first",
"ndimage",
"=",
"np",
".",
"divide",
"(",
"image_array",
",",
"image_max_value",
",",
"dtype",
"=",
"target_dtype",
")",
"rank",
"=",
"len",
"(",
"ndimage",
".",
"shape",
")",
"if",
"rank",
"==",
"3",
":",
"return",
"ndimage",
"elif",
"rank",
"==",
"2",
":",
"return",
"np",
".",
"repeat",
"(",
"np",
".",
"expand_dims",
"(",
"ndimage",
",",
"axis",
"=",
"2",
")",
",",
"3",
",",
"axis",
"=",
"2",
")",
"else",
":",
"message",
"=",
"\"Loaded image has more dimensions than expected: {}\"",
".",
"format",
"(",
"rank",
")",
"raise",
"NotImplementedError",
"(",
"message",
")"
] |
Load image file as numpy array.
|
[
"Load",
"image",
"file",
"as",
"numpy",
"array",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/loading.py#L47-L78
|
train
|
tensorflow/lucid
|
lucid/misc/io/loading.py
|
_load_text
|
def _load_text(handle, split=False, encoding="utf-8"):
"""Load and decode a string."""
string = handle.read().decode(encoding)
return string.splitlines() if split else string
|
python
|
def _load_text(handle, split=False, encoding="utf-8"):
"""Load and decode a string."""
string = handle.read().decode(encoding)
return string.splitlines() if split else string
|
[
"def",
"_load_text",
"(",
"handle",
",",
"split",
"=",
"False",
",",
"encoding",
"=",
"\"utf-8\"",
")",
":",
"string",
"=",
"handle",
".",
"read",
"(",
")",
".",
"decode",
"(",
"encoding",
")",
"return",
"string",
".",
"splitlines",
"(",
")",
"if",
"split",
"else",
"string"
] |
Load and decode a string.
|
[
"Load",
"and",
"decode",
"a",
"string",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/loading.py#L86-L89
|
train
|
tensorflow/lucid
|
lucid/misc/io/loading.py
|
_load_graphdef_protobuf
|
def _load_graphdef_protobuf(handle, **kwargs):
"""Load GraphDef from a binary proto file."""
# as_graph_def
graph_def = tf.GraphDef.FromString(handle.read())
# check if this is a lucid-saved model
# metadata = modelzoo.util.extract_metadata(graph_def)
# if metadata is not None:
# url = handle.name
# return modelzoo.vision_base.Model.load_from_metadata(url, metadata)
# else return a normal graph_def
return graph_def
|
python
|
def _load_graphdef_protobuf(handle, **kwargs):
"""Load GraphDef from a binary proto file."""
# as_graph_def
graph_def = tf.GraphDef.FromString(handle.read())
# check if this is a lucid-saved model
# metadata = modelzoo.util.extract_metadata(graph_def)
# if metadata is not None:
# url = handle.name
# return modelzoo.vision_base.Model.load_from_metadata(url, metadata)
# else return a normal graph_def
return graph_def
|
[
"def",
"_load_graphdef_protobuf",
"(",
"handle",
",",
"*",
"*",
"kwargs",
")",
":",
"# as_graph_def",
"graph_def",
"=",
"tf",
".",
"GraphDef",
".",
"FromString",
"(",
"handle",
".",
"read",
"(",
")",
")",
"# check if this is a lucid-saved model",
"# metadata = modelzoo.util.extract_metadata(graph_def)",
"# if metadata is not None:",
"# url = handle.name",
"# return modelzoo.vision_base.Model.load_from_metadata(url, metadata)",
"# else return a normal graph_def",
"return",
"graph_def"
] |
Load GraphDef from a binary proto file.
|
[
"Load",
"GraphDef",
"from",
"a",
"binary",
"proto",
"file",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/loading.py#L92-L104
|
train
|
tensorflow/lucid
|
lucid/misc/io/loading.py
|
load
|
def load(url_or_handle, cache=None, **kwargs):
"""Load a file.
File format is inferred from url. File retrieval strategy is inferred from
URL. Returned object type is inferred from url extension.
Args:
url_or_handle: a (reachable) URL, or an already open file handle
Raises:
RuntimeError: If file extension or URL is not supported.
"""
ext = get_extension(url_or_handle)
try:
loader = loaders[ext.lower()]
message = "Using inferred loader '%s' due to passed file extension '%s'."
log.debug(message, loader.__name__[6:], ext)
return load_using_loader(url_or_handle, loader, cache, **kwargs)
except KeyError:
log.warning("Unknown extension '%s', attempting to load as image.", ext)
try:
with read_handle(url_or_handle, cache=cache) as handle:
result = _load_img(handle)
except Exception as e:
message = "Could not load resource %s as image. Supported extensions: %s"
log.error(message, url_or_handle, list(loaders))
raise RuntimeError(message.format(url_or_handle, list(loaders)))
else:
log.info("Unknown extension '%s' successfully loaded as image.", ext)
return result
|
python
|
def load(url_or_handle, cache=None, **kwargs):
"""Load a file.
File format is inferred from url. File retrieval strategy is inferred from
URL. Returned object type is inferred from url extension.
Args:
url_or_handle: a (reachable) URL, or an already open file handle
Raises:
RuntimeError: If file extension or URL is not supported.
"""
ext = get_extension(url_or_handle)
try:
loader = loaders[ext.lower()]
message = "Using inferred loader '%s' due to passed file extension '%s'."
log.debug(message, loader.__name__[6:], ext)
return load_using_loader(url_or_handle, loader, cache, **kwargs)
except KeyError:
log.warning("Unknown extension '%s', attempting to load as image.", ext)
try:
with read_handle(url_or_handle, cache=cache) as handle:
result = _load_img(handle)
except Exception as e:
message = "Could not load resource %s as image. Supported extensions: %s"
log.error(message, url_or_handle, list(loaders))
raise RuntimeError(message.format(url_or_handle, list(loaders)))
else:
log.info("Unknown extension '%s' successfully loaded as image.", ext)
return result
|
[
"def",
"load",
"(",
"url_or_handle",
",",
"cache",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ext",
"=",
"get_extension",
"(",
"url_or_handle",
")",
"try",
":",
"loader",
"=",
"loaders",
"[",
"ext",
".",
"lower",
"(",
")",
"]",
"message",
"=",
"\"Using inferred loader '%s' due to passed file extension '%s'.\"",
"log",
".",
"debug",
"(",
"message",
",",
"loader",
".",
"__name__",
"[",
"6",
":",
"]",
",",
"ext",
")",
"return",
"load_using_loader",
"(",
"url_or_handle",
",",
"loader",
",",
"cache",
",",
"*",
"*",
"kwargs",
")",
"except",
"KeyError",
":",
"log",
".",
"warning",
"(",
"\"Unknown extension '%s', attempting to load as image.\"",
",",
"ext",
")",
"try",
":",
"with",
"read_handle",
"(",
"url_or_handle",
",",
"cache",
"=",
"cache",
")",
"as",
"handle",
":",
"result",
"=",
"_load_img",
"(",
"handle",
")",
"except",
"Exception",
"as",
"e",
":",
"message",
"=",
"\"Could not load resource %s as image. Supported extensions: %s\"",
"log",
".",
"error",
"(",
"message",
",",
"url_or_handle",
",",
"list",
"(",
"loaders",
")",
")",
"raise",
"RuntimeError",
"(",
"message",
".",
"format",
"(",
"url_or_handle",
",",
"list",
"(",
"loaders",
")",
")",
")",
"else",
":",
"log",
".",
"info",
"(",
"\"Unknown extension '%s' successfully loaded as image.\"",
",",
"ext",
")",
"return",
"result"
] |
Load a file.
File format is inferred from url. File retrieval strategy is inferred from
URL. Returned object type is inferred from url extension.
Args:
url_or_handle: a (reachable) URL, or an already open file handle
Raises:
RuntimeError: If file extension or URL is not supported.
|
[
"Load",
"a",
"file",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/loading.py#L120-L152
|
train
|
tensorflow/lucid
|
lucid/optvis/transform.py
|
crop_or_pad_to
|
def crop_or_pad_to(height, width):
"""Ensures the specified spatial shape by either padding or cropping.
Meant to be used as a last transform for architectures insisting on a specific
spatial shape of their inputs.
"""
def inner(t_image):
return tf.image.resize_image_with_crop_or_pad(t_image, height, width)
return inner
|
python
|
def crop_or_pad_to(height, width):
"""Ensures the specified spatial shape by either padding or cropping.
Meant to be used as a last transform for architectures insisting on a specific
spatial shape of their inputs.
"""
def inner(t_image):
return tf.image.resize_image_with_crop_or_pad(t_image, height, width)
return inner
|
[
"def",
"crop_or_pad_to",
"(",
"height",
",",
"width",
")",
":",
"def",
"inner",
"(",
"t_image",
")",
":",
"return",
"tf",
".",
"image",
".",
"resize_image_with_crop_or_pad",
"(",
"t_image",
",",
"height",
",",
"width",
")",
"return",
"inner"
] |
Ensures the specified spatial shape by either padding or cropping.
Meant to be used as a last transform for architectures insisting on a specific
spatial shape of their inputs.
|
[
"Ensures",
"the",
"specified",
"spatial",
"shape",
"by",
"either",
"padding",
"or",
"cropping",
".",
"Meant",
"to",
"be",
"used",
"as",
"a",
"last",
"transform",
"for",
"architectures",
"insisting",
"on",
"a",
"specific",
"spatial",
"shape",
"of",
"their",
"inputs",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/transform.py#L154-L161
|
train
|
tensorflow/lucid
|
lucid/misc/io/serialize_array.py
|
_normalize_array
|
def _normalize_array(array, domain=(0, 1)):
"""Given an arbitrary rank-3 NumPy array, produce one representing an image.
This ensures the resulting array has a dtype of uint8 and a domain of 0-255.
Args:
array: NumPy array representing the image
domain: expected range of values in array,
defaults to (0, 1), if explicitly set to None will use the array's
own range of values and normalize them.
Returns:
normalized PIL.Image
"""
# first copy the input so we're never mutating the user's data
array = np.array(array)
# squeeze helps both with batch=1 and B/W and PIL's mode inference
array = np.squeeze(array)
assert len(array.shape) <= 3
assert np.issubdtype(array.dtype, np.number)
assert not np.isnan(array).any()
low, high = np.min(array), np.max(array)
if domain is None:
message = "No domain specified, normalizing from measured (~%.2f, ~%.2f)"
log.debug(message, low, high)
domain = (low, high)
# clip values if domain was specified and array contains values outside of it
if low < domain[0] or high > domain[1]:
message = "Clipping domain from (~{:.2f}, ~{:.2f}) to (~{:.2f}, ~{:.2f})."
log.info(message.format(low, high, domain[0], domain[1]))
array = array.clip(*domain)
min_value, max_value = np.iinfo(np.uint8).min, np.iinfo(np.uint8).max # 0, 255
# convert signed to unsigned if needed
if np.issubdtype(array.dtype, np.inexact):
offset = domain[0]
if offset != 0:
array -= offset
log.debug("Converting inexact array by subtracting -%.2f.", offset)
scalar = max_value / (domain[1] - domain[0])
if scalar != 1:
array *= scalar
log.debug("Converting inexact array by scaling by %.2f.", scalar)
return array.clip(min_value, max_value).astype(np.uint8)
|
python
|
def _normalize_array(array, domain=(0, 1)):
"""Given an arbitrary rank-3 NumPy array, produce one representing an image.
This ensures the resulting array has a dtype of uint8 and a domain of 0-255.
Args:
array: NumPy array representing the image
domain: expected range of values in array,
defaults to (0, 1), if explicitly set to None will use the array's
own range of values and normalize them.
Returns:
normalized PIL.Image
"""
# first copy the input so we're never mutating the user's data
array = np.array(array)
# squeeze helps both with batch=1 and B/W and PIL's mode inference
array = np.squeeze(array)
assert len(array.shape) <= 3
assert np.issubdtype(array.dtype, np.number)
assert not np.isnan(array).any()
low, high = np.min(array), np.max(array)
if domain is None:
message = "No domain specified, normalizing from measured (~%.2f, ~%.2f)"
log.debug(message, low, high)
domain = (low, high)
# clip values if domain was specified and array contains values outside of it
if low < domain[0] or high > domain[1]:
message = "Clipping domain from (~{:.2f}, ~{:.2f}) to (~{:.2f}, ~{:.2f})."
log.info(message.format(low, high, domain[0], domain[1]))
array = array.clip(*domain)
min_value, max_value = np.iinfo(np.uint8).min, np.iinfo(np.uint8).max # 0, 255
# convert signed to unsigned if needed
if np.issubdtype(array.dtype, np.inexact):
offset = domain[0]
if offset != 0:
array -= offset
log.debug("Converting inexact array by subtracting -%.2f.", offset)
scalar = max_value / (domain[1] - domain[0])
if scalar != 1:
array *= scalar
log.debug("Converting inexact array by scaling by %.2f.", scalar)
return array.clip(min_value, max_value).astype(np.uint8)
|
[
"def",
"_normalize_array",
"(",
"array",
",",
"domain",
"=",
"(",
"0",
",",
"1",
")",
")",
":",
"# first copy the input so we're never mutating the user's data",
"array",
"=",
"np",
".",
"array",
"(",
"array",
")",
"# squeeze helps both with batch=1 and B/W and PIL's mode inference",
"array",
"=",
"np",
".",
"squeeze",
"(",
"array",
")",
"assert",
"len",
"(",
"array",
".",
"shape",
")",
"<=",
"3",
"assert",
"np",
".",
"issubdtype",
"(",
"array",
".",
"dtype",
",",
"np",
".",
"number",
")",
"assert",
"not",
"np",
".",
"isnan",
"(",
"array",
")",
".",
"any",
"(",
")",
"low",
",",
"high",
"=",
"np",
".",
"min",
"(",
"array",
")",
",",
"np",
".",
"max",
"(",
"array",
")",
"if",
"domain",
"is",
"None",
":",
"message",
"=",
"\"No domain specified, normalizing from measured (~%.2f, ~%.2f)\"",
"log",
".",
"debug",
"(",
"message",
",",
"low",
",",
"high",
")",
"domain",
"=",
"(",
"low",
",",
"high",
")",
"# clip values if domain was specified and array contains values outside of it",
"if",
"low",
"<",
"domain",
"[",
"0",
"]",
"or",
"high",
">",
"domain",
"[",
"1",
"]",
":",
"message",
"=",
"\"Clipping domain from (~{:.2f}, ~{:.2f}) to (~{:.2f}, ~{:.2f}).\"",
"log",
".",
"info",
"(",
"message",
".",
"format",
"(",
"low",
",",
"high",
",",
"domain",
"[",
"0",
"]",
",",
"domain",
"[",
"1",
"]",
")",
")",
"array",
"=",
"array",
".",
"clip",
"(",
"*",
"domain",
")",
"min_value",
",",
"max_value",
"=",
"np",
".",
"iinfo",
"(",
"np",
".",
"uint8",
")",
".",
"min",
",",
"np",
".",
"iinfo",
"(",
"np",
".",
"uint8",
")",
".",
"max",
"# 0, 255",
"# convert signed to unsigned if needed",
"if",
"np",
".",
"issubdtype",
"(",
"array",
".",
"dtype",
",",
"np",
".",
"inexact",
")",
":",
"offset",
"=",
"domain",
"[",
"0",
"]",
"if",
"offset",
"!=",
"0",
":",
"array",
"-=",
"offset",
"log",
".",
"debug",
"(",
"\"Converting inexact array by subtracting -%.2f.\"",
",",
"offset",
")",
"scalar",
"=",
"max_value",
"/",
"(",
"domain",
"[",
"1",
"]",
"-",
"domain",
"[",
"0",
"]",
")",
"if",
"scalar",
"!=",
"1",
":",
"array",
"*=",
"scalar",
"log",
".",
"debug",
"(",
"\"Converting inexact array by scaling by %.2f.\"",
",",
"scalar",
")",
"return",
"array",
".",
"clip",
"(",
"min_value",
",",
"max_value",
")",
".",
"astype",
"(",
"np",
".",
"uint8",
")"
] |
Given an arbitrary rank-3 NumPy array, produce one representing an image.
This ensures the resulting array has a dtype of uint8 and a domain of 0-255.
Args:
array: NumPy array representing the image
domain: expected range of values in array,
defaults to (0, 1), if explicitly set to None will use the array's
own range of values and normalize them.
Returns:
normalized PIL.Image
|
[
"Given",
"an",
"arbitrary",
"rank",
"-",
"3",
"NumPy",
"array",
"produce",
"one",
"representing",
"an",
"image",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/serialize_array.py#L31-L77
|
train
|
tensorflow/lucid
|
lucid/misc/io/serialize_array.py
|
_serialize_normalized_array
|
def _serialize_normalized_array(array, fmt='png', quality=70):
"""Given a normalized array, returns byte representation of image encoding.
Args:
array: NumPy array of dtype uint8 and range 0 to 255
fmt: string describing desired file format, defaults to 'png'
quality: specifies compression quality from 0 to 100 for lossy formats
Returns:
image data as BytesIO buffer
"""
dtype = array.dtype
assert np.issubdtype(dtype, np.unsignedinteger)
assert np.max(array) <= np.iinfo(dtype).max
assert array.shape[-1] > 1 # array dims must have been squeezed
image = PIL.Image.fromarray(array)
image_bytes = BytesIO()
image.save(image_bytes, fmt, quality=quality)
# TODO: Python 3 could save a copy here by using `getbuffer()` instead.
image_data = image_bytes.getvalue()
return image_data
|
python
|
def _serialize_normalized_array(array, fmt='png', quality=70):
"""Given a normalized array, returns byte representation of image encoding.
Args:
array: NumPy array of dtype uint8 and range 0 to 255
fmt: string describing desired file format, defaults to 'png'
quality: specifies compression quality from 0 to 100 for lossy formats
Returns:
image data as BytesIO buffer
"""
dtype = array.dtype
assert np.issubdtype(dtype, np.unsignedinteger)
assert np.max(array) <= np.iinfo(dtype).max
assert array.shape[-1] > 1 # array dims must have been squeezed
image = PIL.Image.fromarray(array)
image_bytes = BytesIO()
image.save(image_bytes, fmt, quality=quality)
# TODO: Python 3 could save a copy here by using `getbuffer()` instead.
image_data = image_bytes.getvalue()
return image_data
|
[
"def",
"_serialize_normalized_array",
"(",
"array",
",",
"fmt",
"=",
"'png'",
",",
"quality",
"=",
"70",
")",
":",
"dtype",
"=",
"array",
".",
"dtype",
"assert",
"np",
".",
"issubdtype",
"(",
"dtype",
",",
"np",
".",
"unsignedinteger",
")",
"assert",
"np",
".",
"max",
"(",
"array",
")",
"<=",
"np",
".",
"iinfo",
"(",
"dtype",
")",
".",
"max",
"assert",
"array",
".",
"shape",
"[",
"-",
"1",
"]",
">",
"1",
"# array dims must have been squeezed",
"image",
"=",
"PIL",
".",
"Image",
".",
"fromarray",
"(",
"array",
")",
"image_bytes",
"=",
"BytesIO",
"(",
")",
"image",
".",
"save",
"(",
"image_bytes",
",",
"fmt",
",",
"quality",
"=",
"quality",
")",
"# TODO: Python 3 could save a copy here by using `getbuffer()` instead.",
"image_data",
"=",
"image_bytes",
".",
"getvalue",
"(",
")",
"return",
"image_data"
] |
Given a normalized array, returns byte representation of image encoding.
Args:
array: NumPy array of dtype uint8 and range 0 to 255
fmt: string describing desired file format, defaults to 'png'
quality: specifies compression quality from 0 to 100 for lossy formats
Returns:
image data as BytesIO buffer
|
[
"Given",
"a",
"normalized",
"array",
"returns",
"byte",
"representation",
"of",
"image",
"encoding",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/serialize_array.py#L80-L101
|
train
|
tensorflow/lucid
|
lucid/misc/io/serialize_array.py
|
serialize_array
|
def serialize_array(array, domain=(0, 1), fmt='png', quality=70):
"""Given an arbitrary rank-3 NumPy array,
returns the byte representation of the encoded image.
Args:
array: NumPy array of dtype uint8 and range 0 to 255
domain: expected range of values in array, see `_normalize_array()`
fmt: string describing desired file format, defaults to 'png'
quality: specifies compression quality from 0 to 100 for lossy formats
Returns:
image data as BytesIO buffer
"""
normalized = _normalize_array(array, domain=domain)
return _serialize_normalized_array(normalized, fmt=fmt, quality=quality)
|
python
|
def serialize_array(array, domain=(0, 1), fmt='png', quality=70):
"""Given an arbitrary rank-3 NumPy array,
returns the byte representation of the encoded image.
Args:
array: NumPy array of dtype uint8 and range 0 to 255
domain: expected range of values in array, see `_normalize_array()`
fmt: string describing desired file format, defaults to 'png'
quality: specifies compression quality from 0 to 100 for lossy formats
Returns:
image data as BytesIO buffer
"""
normalized = _normalize_array(array, domain=domain)
return _serialize_normalized_array(normalized, fmt=fmt, quality=quality)
|
[
"def",
"serialize_array",
"(",
"array",
",",
"domain",
"=",
"(",
"0",
",",
"1",
")",
",",
"fmt",
"=",
"'png'",
",",
"quality",
"=",
"70",
")",
":",
"normalized",
"=",
"_normalize_array",
"(",
"array",
",",
"domain",
"=",
"domain",
")",
"return",
"_serialize_normalized_array",
"(",
"normalized",
",",
"fmt",
"=",
"fmt",
",",
"quality",
"=",
"quality",
")"
] |
Given an arbitrary rank-3 NumPy array,
returns the byte representation of the encoded image.
Args:
array: NumPy array of dtype uint8 and range 0 to 255
domain: expected range of values in array, see `_normalize_array()`
fmt: string describing desired file format, defaults to 'png'
quality: specifies compression quality from 0 to 100 for lossy formats
Returns:
image data as BytesIO buffer
|
[
"Given",
"an",
"arbitrary",
"rank",
"-",
"3",
"NumPy",
"array",
"returns",
"the",
"byte",
"representation",
"of",
"the",
"encoded",
"image",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/serialize_array.py#L104-L118
|
train
|
tensorflow/lucid
|
lucid/misc/io/serialize_array.py
|
array_to_jsbuffer
|
def array_to_jsbuffer(array):
"""Serialize 1d NumPy array to JS TypedArray.
Data is serialized to base64-encoded string, which is much faster
and memory-efficient than json list serialization.
Args:
array: 1d NumPy array, dtype must be one of JS_ARRAY_TYPES.
Returns:
JS code that evaluates to a TypedArray as string.
Raises:
TypeError: if array dtype or shape not supported.
"""
if array.ndim != 1:
raise TypeError('Only 1d arrays can be converted JS TypedArray.')
if array.dtype.name not in JS_ARRAY_TYPES:
raise TypeError('Array dtype not supported by JS TypedArray.')
js_type_name = array.dtype.name.capitalize() + 'Array'
data_base64 = base64.b64encode(array.tobytes()).decode('ascii')
code = """
(function() {
const data = atob("%s");
const buf = new Uint8Array(data.length);
for (var i=0; i<data.length; ++i) {
buf[i] = data.charCodeAt(i);
}
var array_type = %s;
if (array_type == Uint8Array) {
return buf;
}
return new array_type(buf.buffer);
})()
""" % (data_base64, js_type_name)
return code
|
python
|
def array_to_jsbuffer(array):
"""Serialize 1d NumPy array to JS TypedArray.
Data is serialized to base64-encoded string, which is much faster
and memory-efficient than json list serialization.
Args:
array: 1d NumPy array, dtype must be one of JS_ARRAY_TYPES.
Returns:
JS code that evaluates to a TypedArray as string.
Raises:
TypeError: if array dtype or shape not supported.
"""
if array.ndim != 1:
raise TypeError('Only 1d arrays can be converted JS TypedArray.')
if array.dtype.name not in JS_ARRAY_TYPES:
raise TypeError('Array dtype not supported by JS TypedArray.')
js_type_name = array.dtype.name.capitalize() + 'Array'
data_base64 = base64.b64encode(array.tobytes()).decode('ascii')
code = """
(function() {
const data = atob("%s");
const buf = new Uint8Array(data.length);
for (var i=0; i<data.length; ++i) {
buf[i] = data.charCodeAt(i);
}
var array_type = %s;
if (array_type == Uint8Array) {
return buf;
}
return new array_type(buf.buffer);
})()
""" % (data_base64, js_type_name)
return code
|
[
"def",
"array_to_jsbuffer",
"(",
"array",
")",
":",
"if",
"array",
".",
"ndim",
"!=",
"1",
":",
"raise",
"TypeError",
"(",
"'Only 1d arrays can be converted JS TypedArray.'",
")",
"if",
"array",
".",
"dtype",
".",
"name",
"not",
"in",
"JS_ARRAY_TYPES",
":",
"raise",
"TypeError",
"(",
"'Array dtype not supported by JS TypedArray.'",
")",
"js_type_name",
"=",
"array",
".",
"dtype",
".",
"name",
".",
"capitalize",
"(",
")",
"+",
"'Array'",
"data_base64",
"=",
"base64",
".",
"b64encode",
"(",
"array",
".",
"tobytes",
"(",
")",
")",
".",
"decode",
"(",
"'ascii'",
")",
"code",
"=",
"\"\"\"\n (function() {\n const data = atob(\"%s\");\n const buf = new Uint8Array(data.length);\n for (var i=0; i<data.length; ++i) {\n buf[i] = data.charCodeAt(i);\n }\n var array_type = %s;\n if (array_type == Uint8Array) {\n return buf;\n }\n return new array_type(buf.buffer);\n })()\n \"\"\"",
"%",
"(",
"data_base64",
",",
"js_type_name",
")",
"return",
"code"
] |
Serialize 1d NumPy array to JS TypedArray.
Data is serialized to base64-encoded string, which is much faster
and memory-efficient than json list serialization.
Args:
array: 1d NumPy array, dtype must be one of JS_ARRAY_TYPES.
Returns:
JS code that evaluates to a TypedArray as string.
Raises:
TypeError: if array dtype or shape not supported.
|
[
"Serialize",
"1d",
"NumPy",
"array",
"to",
"JS",
"TypedArray",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/serialize_array.py#L126-L161
|
train
|
tensorflow/lucid
|
lucid/misc/channel_reducer.py
|
ChannelReducer._apply_flat
|
def _apply_flat(cls, f, acts):
"""Utility for applying f to inner dimension of acts.
Flattens acts into a 2D tensor, applies f, then unflattens so that all
dimesnions except innermost are unchanged.
"""
orig_shape = acts.shape
acts_flat = acts.reshape([-1, acts.shape[-1]])
new_flat = f(acts_flat)
if not isinstance(new_flat, np.ndarray):
return new_flat
shape = list(orig_shape[:-1]) + [-1]
return new_flat.reshape(shape)
|
python
|
def _apply_flat(cls, f, acts):
"""Utility for applying f to inner dimension of acts.
Flattens acts into a 2D tensor, applies f, then unflattens so that all
dimesnions except innermost are unchanged.
"""
orig_shape = acts.shape
acts_flat = acts.reshape([-1, acts.shape[-1]])
new_flat = f(acts_flat)
if not isinstance(new_flat, np.ndarray):
return new_flat
shape = list(orig_shape[:-1]) + [-1]
return new_flat.reshape(shape)
|
[
"def",
"_apply_flat",
"(",
"cls",
",",
"f",
",",
"acts",
")",
":",
"orig_shape",
"=",
"acts",
".",
"shape",
"acts_flat",
"=",
"acts",
".",
"reshape",
"(",
"[",
"-",
"1",
",",
"acts",
".",
"shape",
"[",
"-",
"1",
"]",
"]",
")",
"new_flat",
"=",
"f",
"(",
"acts_flat",
")",
"if",
"not",
"isinstance",
"(",
"new_flat",
",",
"np",
".",
"ndarray",
")",
":",
"return",
"new_flat",
"shape",
"=",
"list",
"(",
"orig_shape",
"[",
":",
"-",
"1",
"]",
")",
"+",
"[",
"-",
"1",
"]",
"return",
"new_flat",
".",
"reshape",
"(",
"shape",
")"
] |
Utility for applying f to inner dimension of acts.
Flattens acts into a 2D tensor, applies f, then unflattens so that all
dimesnions except innermost are unchanged.
|
[
"Utility",
"for",
"applying",
"f",
"to",
"inner",
"dimension",
"of",
"acts",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/channel_reducer.py#L52-L64
|
train
|
tensorflow/lucid
|
lucid/optvis/style.py
|
StyleLoss.set_style
|
def set_style(self, input_feeds):
"""Set target style variables.
Expected usage:
style_loss = StyleLoss(style_layers)
...
init_op = tf.global_variables_initializer()
init_op.run()
feeds = {... session.run() 'feeds' argument that will make 'style_layers'
tensors evaluate to activation values of style image...}
style_loss.set_style(feeds) # this must be called after 'init_op.run()'
"""
sess = tf.get_default_session()
computed = sess.run(self.input_grams, input_feeds)
for v, g in zip(self.target_vars, computed):
v.load(g)
|
python
|
def set_style(self, input_feeds):
"""Set target style variables.
Expected usage:
style_loss = StyleLoss(style_layers)
...
init_op = tf.global_variables_initializer()
init_op.run()
feeds = {... session.run() 'feeds' argument that will make 'style_layers'
tensors evaluate to activation values of style image...}
style_loss.set_style(feeds) # this must be called after 'init_op.run()'
"""
sess = tf.get_default_session()
computed = sess.run(self.input_grams, input_feeds)
for v, g in zip(self.target_vars, computed):
v.load(g)
|
[
"def",
"set_style",
"(",
"self",
",",
"input_feeds",
")",
":",
"sess",
"=",
"tf",
".",
"get_default_session",
"(",
")",
"computed",
"=",
"sess",
".",
"run",
"(",
"self",
".",
"input_grams",
",",
"input_feeds",
")",
"for",
"v",
",",
"g",
"in",
"zip",
"(",
"self",
".",
"target_vars",
",",
"computed",
")",
":",
"v",
".",
"load",
"(",
"g",
")"
] |
Set target style variables.
Expected usage:
style_loss = StyleLoss(style_layers)
...
init_op = tf.global_variables_initializer()
init_op.run()
feeds = {... session.run() 'feeds' argument that will make 'style_layers'
tensors evaluate to activation values of style image...}
style_loss.set_style(feeds) # this must be called after 'init_op.run()'
|
[
"Set",
"target",
"style",
"variables",
".",
"Expected",
"usage",
":",
"style_loss",
"=",
"StyleLoss",
"(",
"style_layers",
")",
"...",
"init_op",
"=",
"tf",
".",
"global_variables_initializer",
"()",
"init_op",
".",
"run",
"()",
"feeds",
"=",
"{",
"...",
"session",
".",
"run",
"()",
"feeds",
"argument",
"that",
"will",
"make",
"style_layers",
"tensors",
"evaluate",
"to",
"activation",
"values",
"of",
"style",
"image",
"...",
"}",
"style_loss",
".",
"set_style",
"(",
"feeds",
")",
"#",
"this",
"must",
"be",
"called",
"after",
"init_op",
".",
"run",
"()"
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/style.py#L74-L90
|
train
|
tensorflow/lucid
|
lucid/misc/io/showing.py
|
_image_url
|
def _image_url(array, fmt='png', mode="data", quality=90, domain=None):
"""Create a data URL representing an image from a PIL.Image.
Args:
image: a numpy
mode: presently only supports "data" for data URL
Returns:
URL representing image
"""
supported_modes = ("data")
if mode not in supported_modes:
message = "Unsupported mode '%s', should be one of '%s'."
raise ValueError(message, mode, supported_modes)
image_data = serialize_array(array, fmt=fmt, quality=quality)
base64_byte_string = base64.b64encode(image_data).decode('ascii')
return "data:image/" + fmt.upper() + ";base64," + base64_byte_string
|
python
|
def _image_url(array, fmt='png', mode="data", quality=90, domain=None):
"""Create a data URL representing an image from a PIL.Image.
Args:
image: a numpy
mode: presently only supports "data" for data URL
Returns:
URL representing image
"""
supported_modes = ("data")
if mode not in supported_modes:
message = "Unsupported mode '%s', should be one of '%s'."
raise ValueError(message, mode, supported_modes)
image_data = serialize_array(array, fmt=fmt, quality=quality)
base64_byte_string = base64.b64encode(image_data).decode('ascii')
return "data:image/" + fmt.upper() + ";base64," + base64_byte_string
|
[
"def",
"_image_url",
"(",
"array",
",",
"fmt",
"=",
"'png'",
",",
"mode",
"=",
"\"data\"",
",",
"quality",
"=",
"90",
",",
"domain",
"=",
"None",
")",
":",
"supported_modes",
"=",
"(",
"\"data\"",
")",
"if",
"mode",
"not",
"in",
"supported_modes",
":",
"message",
"=",
"\"Unsupported mode '%s', should be one of '%s'.\"",
"raise",
"ValueError",
"(",
"message",
",",
"mode",
",",
"supported_modes",
")",
"image_data",
"=",
"serialize_array",
"(",
"array",
",",
"fmt",
"=",
"fmt",
",",
"quality",
"=",
"quality",
")",
"base64_byte_string",
"=",
"base64",
".",
"b64encode",
"(",
"image_data",
")",
".",
"decode",
"(",
"'ascii'",
")",
"return",
"\"data:image/\"",
"+",
"fmt",
".",
"upper",
"(",
")",
"+",
"\";base64,\"",
"+",
"base64_byte_string"
] |
Create a data URL representing an image from a PIL.Image.
Args:
image: a numpy
mode: presently only supports "data" for data URL
Returns:
URL representing image
|
[
"Create",
"a",
"data",
"URL",
"representing",
"an",
"image",
"from",
"a",
"PIL",
".",
"Image",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/showing.py#L39-L56
|
train
|
tensorflow/lucid
|
lucid/misc/io/showing.py
|
image
|
def image(array, domain=None, width=None, format='png', **kwargs):
"""Display an image.
Args:
array: NumPy array representing the image
fmt: Image format e.g. png, jpeg
domain: Domain of pixel values, inferred from min & max values if None
w: width of output image, scaled using nearest neighbor interpolation.
size unchanged if None
"""
image_data = serialize_array(array, fmt=format, domain=domain)
image = IPython.display.Image(data=image_data, format=format, width=width)
IPython.display.display(image)
|
python
|
def image(array, domain=None, width=None, format='png', **kwargs):
"""Display an image.
Args:
array: NumPy array representing the image
fmt: Image format e.g. png, jpeg
domain: Domain of pixel values, inferred from min & max values if None
w: width of output image, scaled using nearest neighbor interpolation.
size unchanged if None
"""
image_data = serialize_array(array, fmt=format, domain=domain)
image = IPython.display.Image(data=image_data, format=format, width=width)
IPython.display.display(image)
|
[
"def",
"image",
"(",
"array",
",",
"domain",
"=",
"None",
",",
"width",
"=",
"None",
",",
"format",
"=",
"'png'",
",",
"*",
"*",
"kwargs",
")",
":",
"image_data",
"=",
"serialize_array",
"(",
"array",
",",
"fmt",
"=",
"format",
",",
"domain",
"=",
"domain",
")",
"image",
"=",
"IPython",
".",
"display",
".",
"Image",
"(",
"data",
"=",
"image_data",
",",
"format",
"=",
"format",
",",
"width",
"=",
"width",
")",
"IPython",
".",
"display",
".",
"display",
"(",
"image",
")"
] |
Display an image.
Args:
array: NumPy array representing the image
fmt: Image format e.g. png, jpeg
domain: Domain of pixel values, inferred from min & max values if None
w: width of output image, scaled using nearest neighbor interpolation.
size unchanged if None
|
[
"Display",
"an",
"image",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/showing.py#L62-L75
|
train
|
tensorflow/lucid
|
lucid/misc/io/showing.py
|
images
|
def images(arrays, labels=None, domain=None, w=None):
"""Display a list of images with optional labels.
Args:
arrays: A list of NumPy arrays representing images
labels: A list of strings to label each image.
Defaults to show index if None
domain: Domain of pixel values, inferred from min & max values if None
w: width of output image, scaled using nearest neighbor interpolation.
size unchanged if None
"""
s = '<div style="display: flex; flex-direction: row;">'
for i, array in enumerate(arrays):
url = _image_url(array)
label = labels[i] if labels is not None else i
s += """<div style="margin-right:10px;">
{label}<br/>
<img src="{url}" style="margin-top:4px;">
</div>""".format(label=label, url=url)
s += "</div>"
_display_html(s)
|
python
|
def images(arrays, labels=None, domain=None, w=None):
"""Display a list of images with optional labels.
Args:
arrays: A list of NumPy arrays representing images
labels: A list of strings to label each image.
Defaults to show index if None
domain: Domain of pixel values, inferred from min & max values if None
w: width of output image, scaled using nearest neighbor interpolation.
size unchanged if None
"""
s = '<div style="display: flex; flex-direction: row;">'
for i, array in enumerate(arrays):
url = _image_url(array)
label = labels[i] if labels is not None else i
s += """<div style="margin-right:10px;">
{label}<br/>
<img src="{url}" style="margin-top:4px;">
</div>""".format(label=label, url=url)
s += "</div>"
_display_html(s)
|
[
"def",
"images",
"(",
"arrays",
",",
"labels",
"=",
"None",
",",
"domain",
"=",
"None",
",",
"w",
"=",
"None",
")",
":",
"s",
"=",
"'<div style=\"display: flex; flex-direction: row;\">'",
"for",
"i",
",",
"array",
"in",
"enumerate",
"(",
"arrays",
")",
":",
"url",
"=",
"_image_url",
"(",
"array",
")",
"label",
"=",
"labels",
"[",
"i",
"]",
"if",
"labels",
"is",
"not",
"None",
"else",
"i",
"s",
"+=",
"\"\"\"<div style=\"margin-right:10px;\">\n {label}<br/>\n <img src=\"{url}\" style=\"margin-top:4px;\">\n </div>\"\"\"",
".",
"format",
"(",
"label",
"=",
"label",
",",
"url",
"=",
"url",
")",
"s",
"+=",
"\"</div>\"",
"_display_html",
"(",
"s",
")"
] |
Display a list of images with optional labels.
Args:
arrays: A list of NumPy arrays representing images
labels: A list of strings to label each image.
Defaults to show index if None
domain: Domain of pixel values, inferred from min & max values if None
w: width of output image, scaled using nearest neighbor interpolation.
size unchanged if None
|
[
"Display",
"a",
"list",
"of",
"images",
"with",
"optional",
"labels",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/showing.py#L78-L99
|
train
|
tensorflow/lucid
|
lucid/misc/io/showing.py
|
show
|
def show(thing, domain=(0, 1), **kwargs):
"""Display a nupmy array without having to specify what it represents.
This module will attempt to infer how to display your tensor based on its
rank, shape and dtype. rank 4 tensors will be displayed as image grids, rank
2 and 3 tensors as images.
"""
if isinstance(thing, np.ndarray):
rank = len(thing.shape)
if rank == 4:
log.debug("Show is assuming rank 4 tensor to be a list of images.")
images(thing, domain=domain, **kwargs)
elif rank in (2, 3):
log.debug("Show is assuming rank 2 or 3 tensor to be an image.")
image(thing, domain=domain, **kwargs)
else:
log.warning("Show only supports numpy arrays of rank 2-4. Using repr().")
print(repr(thing))
elif isinstance(thing, (list, tuple)):
log.debug("Show is assuming list or tuple to be a collection of images.")
images(thing, domain=domain, **kwargs)
else:
log.warning("Show only supports numpy arrays so far. Using repr().")
print(repr(thing))
|
python
|
def show(thing, domain=(0, 1), **kwargs):
"""Display a nupmy array without having to specify what it represents.
This module will attempt to infer how to display your tensor based on its
rank, shape and dtype. rank 4 tensors will be displayed as image grids, rank
2 and 3 tensors as images.
"""
if isinstance(thing, np.ndarray):
rank = len(thing.shape)
if rank == 4:
log.debug("Show is assuming rank 4 tensor to be a list of images.")
images(thing, domain=domain, **kwargs)
elif rank in (2, 3):
log.debug("Show is assuming rank 2 or 3 tensor to be an image.")
image(thing, domain=domain, **kwargs)
else:
log.warning("Show only supports numpy arrays of rank 2-4. Using repr().")
print(repr(thing))
elif isinstance(thing, (list, tuple)):
log.debug("Show is assuming list or tuple to be a collection of images.")
images(thing, domain=domain, **kwargs)
else:
log.warning("Show only supports numpy arrays so far. Using repr().")
print(repr(thing))
|
[
"def",
"show",
"(",
"thing",
",",
"domain",
"=",
"(",
"0",
",",
"1",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"thing",
",",
"np",
".",
"ndarray",
")",
":",
"rank",
"=",
"len",
"(",
"thing",
".",
"shape",
")",
"if",
"rank",
"==",
"4",
":",
"log",
".",
"debug",
"(",
"\"Show is assuming rank 4 tensor to be a list of images.\"",
")",
"images",
"(",
"thing",
",",
"domain",
"=",
"domain",
",",
"*",
"*",
"kwargs",
")",
"elif",
"rank",
"in",
"(",
"2",
",",
"3",
")",
":",
"log",
".",
"debug",
"(",
"\"Show is assuming rank 2 or 3 tensor to be an image.\"",
")",
"image",
"(",
"thing",
",",
"domain",
"=",
"domain",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"log",
".",
"warning",
"(",
"\"Show only supports numpy arrays of rank 2-4. Using repr().\"",
")",
"print",
"(",
"repr",
"(",
"thing",
")",
")",
"elif",
"isinstance",
"(",
"thing",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"log",
".",
"debug",
"(",
"\"Show is assuming list or tuple to be a collection of images.\"",
")",
"images",
"(",
"thing",
",",
"domain",
"=",
"domain",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"log",
".",
"warning",
"(",
"\"Show only supports numpy arrays so far. Using repr().\"",
")",
"print",
"(",
"repr",
"(",
"thing",
")",
")"
] |
Display a nupmy array without having to specify what it represents.
This module will attempt to infer how to display your tensor based on its
rank, shape and dtype. rank 4 tensors will be displayed as image grids, rank
2 and 3 tensors as images.
|
[
"Display",
"a",
"nupmy",
"array",
"without",
"having",
"to",
"specify",
"what",
"it",
"represents",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/showing.py#L102-L125
|
train
|
tensorflow/lucid
|
lucid/misc/io/showing.py
|
_strip_consts
|
def _strip_consts(graph_def, max_const_size=32):
"""Strip large constant values from graph_def.
This is mostly a utility function for graph(), and also originates here:
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/deepdream/deepdream.ipynb
"""
strip_def = tf.GraphDef()
for n0 in graph_def.node:
n = strip_def.node.add()
n.MergeFrom(n0)
if n.op == 'Const':
tensor = n.attr['value'].tensor
size = len(tensor.tensor_content)
if size > max_const_size:
tensor.tensor_content = tf.compat.as_bytes("<stripped %d bytes>"%size)
return strip_def
|
python
|
def _strip_consts(graph_def, max_const_size=32):
"""Strip large constant values from graph_def.
This is mostly a utility function for graph(), and also originates here:
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/deepdream/deepdream.ipynb
"""
strip_def = tf.GraphDef()
for n0 in graph_def.node:
n = strip_def.node.add()
n.MergeFrom(n0)
if n.op == 'Const':
tensor = n.attr['value'].tensor
size = len(tensor.tensor_content)
if size > max_const_size:
tensor.tensor_content = tf.compat.as_bytes("<stripped %d bytes>"%size)
return strip_def
|
[
"def",
"_strip_consts",
"(",
"graph_def",
",",
"max_const_size",
"=",
"32",
")",
":",
"strip_def",
"=",
"tf",
".",
"GraphDef",
"(",
")",
"for",
"n0",
"in",
"graph_def",
".",
"node",
":",
"n",
"=",
"strip_def",
".",
"node",
".",
"add",
"(",
")",
"n",
".",
"MergeFrom",
"(",
"n0",
")",
"if",
"n",
".",
"op",
"==",
"'Const'",
":",
"tensor",
"=",
"n",
".",
"attr",
"[",
"'value'",
"]",
".",
"tensor",
"size",
"=",
"len",
"(",
"tensor",
".",
"tensor_content",
")",
"if",
"size",
">",
"max_const_size",
":",
"tensor",
".",
"tensor_content",
"=",
"tf",
".",
"compat",
".",
"as_bytes",
"(",
"\"<stripped %d bytes>\"",
"%",
"size",
")",
"return",
"strip_def"
] |
Strip large constant values from graph_def.
This is mostly a utility function for graph(), and also originates here:
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/deepdream/deepdream.ipynb
|
[
"Strip",
"large",
"constant",
"values",
"from",
"graph_def",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/showing.py#L272-L287
|
train
|
tensorflow/lucid
|
lucid/misc/io/showing.py
|
graph
|
def graph(graph_def, max_const_size=32):
"""Visualize a TensorFlow graph.
This function was originally found in this notebook (also Apache licensed):
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/deepdream/deepdream.ipynb
"""
if hasattr(graph_def, 'as_graph_def'):
graph_def = graph_def.as_graph_def()
strip_def = _strip_consts(graph_def, max_const_size=max_const_size)
code = """
<script>
function load() {{
document.getElementById("{id}").pbtxt = {data};
}}
</script>
<link rel="import" href="https://tensorboard.appspot.com/tf-graph-basic.build.html" onload=load()>
<div style="height:600px">
<tf-graph-basic id="{id}"></tf-graph-basic>
</div>
""".format(data=repr(str(strip_def)), id='graph'+str(np.random.rand()))
iframe = """
<iframe seamless style="width:100%; height:620px; border: none;" srcdoc="{}"></iframe>
""".format(code.replace('"', '"'))
_display_html(iframe)
|
python
|
def graph(graph_def, max_const_size=32):
"""Visualize a TensorFlow graph.
This function was originally found in this notebook (also Apache licensed):
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/deepdream/deepdream.ipynb
"""
if hasattr(graph_def, 'as_graph_def'):
graph_def = graph_def.as_graph_def()
strip_def = _strip_consts(graph_def, max_const_size=max_const_size)
code = """
<script>
function load() {{
document.getElementById("{id}").pbtxt = {data};
}}
</script>
<link rel="import" href="https://tensorboard.appspot.com/tf-graph-basic.build.html" onload=load()>
<div style="height:600px">
<tf-graph-basic id="{id}"></tf-graph-basic>
</div>
""".format(data=repr(str(strip_def)), id='graph'+str(np.random.rand()))
iframe = """
<iframe seamless style="width:100%; height:620px; border: none;" srcdoc="{}"></iframe>
""".format(code.replace('"', '"'))
_display_html(iframe)
|
[
"def",
"graph",
"(",
"graph_def",
",",
"max_const_size",
"=",
"32",
")",
":",
"if",
"hasattr",
"(",
"graph_def",
",",
"'as_graph_def'",
")",
":",
"graph_def",
"=",
"graph_def",
".",
"as_graph_def",
"(",
")",
"strip_def",
"=",
"_strip_consts",
"(",
"graph_def",
",",
"max_const_size",
"=",
"max_const_size",
")",
"code",
"=",
"\"\"\"\n <script>\n function load() {{\n document.getElementById(\"{id}\").pbtxt = {data};\n }}\n </script>\n <link rel=\"import\" href=\"https://tensorboard.appspot.com/tf-graph-basic.build.html\" onload=load()>\n <div style=\"height:600px\">\n <tf-graph-basic id=\"{id}\"></tf-graph-basic>\n </div>\n \"\"\"",
".",
"format",
"(",
"data",
"=",
"repr",
"(",
"str",
"(",
"strip_def",
")",
")",
",",
"id",
"=",
"'graph'",
"+",
"str",
"(",
"np",
".",
"random",
".",
"rand",
"(",
")",
")",
")",
"iframe",
"=",
"\"\"\"\n <iframe seamless style=\"width:100%; height:620px; border: none;\" srcdoc=\"{}\"></iframe>\n \"\"\"",
".",
"format",
"(",
"code",
".",
"replace",
"(",
"'\"'",
",",
"'"'",
")",
")",
"_display_html",
"(",
"iframe",
")"
] |
Visualize a TensorFlow graph.
This function was originally found in this notebook (also Apache licensed):
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/deepdream/deepdream.ipynb
|
[
"Visualize",
"a",
"TensorFlow",
"graph",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/showing.py#L290-L314
|
train
|
tensorflow/lucid
|
lucid/misc/ndimage_utils.py
|
resize
|
def resize(image, target_size, **kwargs):
"""Resize an ndarray image of rank 3 or 4.
target_size can be a tuple `(width, height)` or scalar `width`."""
if isinstance(target_size, int):
target_size = (target_size, target_size)
if not isinstance(target_size, (list, tuple, np.ndarray)):
message = (
"`target_size` should be a single number (width) or a list"
"/tuple/ndarray (width, height), not {}.".format(type(target_size))
)
raise ValueError(message)
rank = len(image.shape)
assert 3 <= rank <= 4
original_size = image.shape[-3:-1]
if original_size == target_size:
return image # noop return because ndimage.zoom doesn't check itself
# TODO: maybe allow -1 in target_size to signify aspect-ratio preserving resize?
ratios = [t / o for t, o in zip(target_size, original_size)]
zoom = [1] * rank
zoom[-3:-1] = ratios
roughly_resized = ndimage.zoom(image, zoom, **kwargs)
return roughly_resized[..., : target_size[0], : target_size[1], :]
|
python
|
def resize(image, target_size, **kwargs):
"""Resize an ndarray image of rank 3 or 4.
target_size can be a tuple `(width, height)` or scalar `width`."""
if isinstance(target_size, int):
target_size = (target_size, target_size)
if not isinstance(target_size, (list, tuple, np.ndarray)):
message = (
"`target_size` should be a single number (width) or a list"
"/tuple/ndarray (width, height), not {}.".format(type(target_size))
)
raise ValueError(message)
rank = len(image.shape)
assert 3 <= rank <= 4
original_size = image.shape[-3:-1]
if original_size == target_size:
return image # noop return because ndimage.zoom doesn't check itself
# TODO: maybe allow -1 in target_size to signify aspect-ratio preserving resize?
ratios = [t / o for t, o in zip(target_size, original_size)]
zoom = [1] * rank
zoom[-3:-1] = ratios
roughly_resized = ndimage.zoom(image, zoom, **kwargs)
return roughly_resized[..., : target_size[0], : target_size[1], :]
|
[
"def",
"resize",
"(",
"image",
",",
"target_size",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"target_size",
",",
"int",
")",
":",
"target_size",
"=",
"(",
"target_size",
",",
"target_size",
")",
"if",
"not",
"isinstance",
"(",
"target_size",
",",
"(",
"list",
",",
"tuple",
",",
"np",
".",
"ndarray",
")",
")",
":",
"message",
"=",
"(",
"\"`target_size` should be a single number (width) or a list\"",
"\"/tuple/ndarray (width, height), not {}.\"",
".",
"format",
"(",
"type",
"(",
"target_size",
")",
")",
")",
"raise",
"ValueError",
"(",
"message",
")",
"rank",
"=",
"len",
"(",
"image",
".",
"shape",
")",
"assert",
"3",
"<=",
"rank",
"<=",
"4",
"original_size",
"=",
"image",
".",
"shape",
"[",
"-",
"3",
":",
"-",
"1",
"]",
"if",
"original_size",
"==",
"target_size",
":",
"return",
"image",
"# noop return because ndimage.zoom doesn't check itself",
"# TODO: maybe allow -1 in target_size to signify aspect-ratio preserving resize?",
"ratios",
"=",
"[",
"t",
"/",
"o",
"for",
"t",
",",
"o",
"in",
"zip",
"(",
"target_size",
",",
"original_size",
")",
"]",
"zoom",
"=",
"[",
"1",
"]",
"*",
"rank",
"zoom",
"[",
"-",
"3",
":",
"-",
"1",
"]",
"=",
"ratios",
"roughly_resized",
"=",
"ndimage",
".",
"zoom",
"(",
"image",
",",
"zoom",
",",
"*",
"*",
"kwargs",
")",
"return",
"roughly_resized",
"[",
"...",
",",
":",
"target_size",
"[",
"0",
"]",
",",
":",
"target_size",
"[",
"1",
"]",
",",
":",
"]"
] |
Resize an ndarray image of rank 3 or 4.
target_size can be a tuple `(width, height)` or scalar `width`.
|
[
"Resize",
"an",
"ndarray",
"image",
"of",
"rank",
"3",
"or",
"4",
".",
"target_size",
"can",
"be",
"a",
"tuple",
"(",
"width",
"height",
")",
"or",
"scalar",
"width",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/ndimage_utils.py#L20-L48
|
train
|
tensorflow/lucid
|
lucid/misc/ndimage_utils.py
|
composite
|
def composite(
background_image,
foreground_image,
foreground_width_ratio=0.25,
foreground_position=(0.0, 0.0),
):
"""Takes two images and composites them."""
if foreground_width_ratio <= 0:
return background_image
composite = background_image.copy()
width = int(foreground_width_ratio * background_image.shape[1])
foreground_resized = resize(foreground_image, width)
size = foreground_resized.shape
x = int(foreground_position[1] * (background_image.shape[1] - size[1]))
y = int(foreground_position[0] * (background_image.shape[0] - size[0]))
# TODO: warn if resulting coordinates are out of bounds?
composite[y : y + size[0], x : x + size[1]] = foreground_resized
return composite
|
python
|
def composite(
background_image,
foreground_image,
foreground_width_ratio=0.25,
foreground_position=(0.0, 0.0),
):
"""Takes two images and composites them."""
if foreground_width_ratio <= 0:
return background_image
composite = background_image.copy()
width = int(foreground_width_ratio * background_image.shape[1])
foreground_resized = resize(foreground_image, width)
size = foreground_resized.shape
x = int(foreground_position[1] * (background_image.shape[1] - size[1]))
y = int(foreground_position[0] * (background_image.shape[0] - size[0]))
# TODO: warn if resulting coordinates are out of bounds?
composite[y : y + size[0], x : x + size[1]] = foreground_resized
return composite
|
[
"def",
"composite",
"(",
"background_image",
",",
"foreground_image",
",",
"foreground_width_ratio",
"=",
"0.25",
",",
"foreground_position",
"=",
"(",
"0.0",
",",
"0.0",
")",
",",
")",
":",
"if",
"foreground_width_ratio",
"<=",
"0",
":",
"return",
"background_image",
"composite",
"=",
"background_image",
".",
"copy",
"(",
")",
"width",
"=",
"int",
"(",
"foreground_width_ratio",
"*",
"background_image",
".",
"shape",
"[",
"1",
"]",
")",
"foreground_resized",
"=",
"resize",
"(",
"foreground_image",
",",
"width",
")",
"size",
"=",
"foreground_resized",
".",
"shape",
"x",
"=",
"int",
"(",
"foreground_position",
"[",
"1",
"]",
"*",
"(",
"background_image",
".",
"shape",
"[",
"1",
"]",
"-",
"size",
"[",
"1",
"]",
")",
")",
"y",
"=",
"int",
"(",
"foreground_position",
"[",
"0",
"]",
"*",
"(",
"background_image",
".",
"shape",
"[",
"0",
"]",
"-",
"size",
"[",
"0",
"]",
")",
")",
"# TODO: warn if resulting coordinates are out of bounds?",
"composite",
"[",
"y",
":",
"y",
"+",
"size",
"[",
"0",
"]",
",",
"x",
":",
"x",
"+",
"size",
"[",
"1",
"]",
"]",
"=",
"foreground_resized",
"return",
"composite"
] |
Takes two images and composites them.
|
[
"Takes",
"two",
"images",
"and",
"composites",
"them",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/ndimage_utils.py#L51-L73
|
train
|
tensorflow/lucid
|
lucid/optvis/param/lowres.py
|
lowres_tensor
|
def lowres_tensor(shape, underlying_shape, offset=None, sd=None):
"""Produces a tensor paramaterized by a interpolated lower resolution tensor.
This is like what is done in a laplacian pyramid, but a bit more general. It
can be a powerful way to describe images.
Args:
shape: desired shape of resulting tensor
underlying_shape: shape of the tensor being resized into final tensor
offset: Describes how to offset the interpolated vector (like phase in a
Fourier transform). If None, apply no offset. If a scalar, apply the same
offset to each dimension; if a list use each entry for each dimension.
If a int, offset by that much. If False, do not offset. If True, offset by
half the ratio between shape and underlying shape (analagous to 90
degrees).
sd: Standard deviation of initial tensor variable.
Returns:
A tensor paramaterized by a lower resolution tensorflow variable.
"""
sd = sd or 0.01
init_val = sd * np.random.randn(*underlying_shape).astype("float32")
underlying_t = tf.Variable(init_val)
t = resize_bilinear_nd(underlying_t, shape)
if offset is not None:
# Deal with non-list offset
if not isinstance(offset, list):
offset = len(shape) * [offset]
# Deal with the non-int offset entries
for n in range(len(offset)):
if offset[n] is True:
offset[n] = shape[n] / underlying_shape[n] / 2
if offset[n] is False:
offset[n] = 0
offset[n] = int(offset[n])
# Actually apply offset by padding and then croping off the excess.
padding = [(pad, 0) for pad in offset]
t = tf.pad(t, padding, "SYMMETRIC")
begin = len(shape) * [0]
t = tf.slice(t, begin, shape)
return t
|
python
|
def lowres_tensor(shape, underlying_shape, offset=None, sd=None):
"""Produces a tensor paramaterized by a interpolated lower resolution tensor.
This is like what is done in a laplacian pyramid, but a bit more general. It
can be a powerful way to describe images.
Args:
shape: desired shape of resulting tensor
underlying_shape: shape of the tensor being resized into final tensor
offset: Describes how to offset the interpolated vector (like phase in a
Fourier transform). If None, apply no offset. If a scalar, apply the same
offset to each dimension; if a list use each entry for each dimension.
If a int, offset by that much. If False, do not offset. If True, offset by
half the ratio between shape and underlying shape (analagous to 90
degrees).
sd: Standard deviation of initial tensor variable.
Returns:
A tensor paramaterized by a lower resolution tensorflow variable.
"""
sd = sd or 0.01
init_val = sd * np.random.randn(*underlying_shape).astype("float32")
underlying_t = tf.Variable(init_val)
t = resize_bilinear_nd(underlying_t, shape)
if offset is not None:
# Deal with non-list offset
if not isinstance(offset, list):
offset = len(shape) * [offset]
# Deal with the non-int offset entries
for n in range(len(offset)):
if offset[n] is True:
offset[n] = shape[n] / underlying_shape[n] / 2
if offset[n] is False:
offset[n] = 0
offset[n] = int(offset[n])
# Actually apply offset by padding and then croping off the excess.
padding = [(pad, 0) for pad in offset]
t = tf.pad(t, padding, "SYMMETRIC")
begin = len(shape) * [0]
t = tf.slice(t, begin, shape)
return t
|
[
"def",
"lowres_tensor",
"(",
"shape",
",",
"underlying_shape",
",",
"offset",
"=",
"None",
",",
"sd",
"=",
"None",
")",
":",
"sd",
"=",
"sd",
"or",
"0.01",
"init_val",
"=",
"sd",
"*",
"np",
".",
"random",
".",
"randn",
"(",
"*",
"underlying_shape",
")",
".",
"astype",
"(",
"\"float32\"",
")",
"underlying_t",
"=",
"tf",
".",
"Variable",
"(",
"init_val",
")",
"t",
"=",
"resize_bilinear_nd",
"(",
"underlying_t",
",",
"shape",
")",
"if",
"offset",
"is",
"not",
"None",
":",
"# Deal with non-list offset",
"if",
"not",
"isinstance",
"(",
"offset",
",",
"list",
")",
":",
"offset",
"=",
"len",
"(",
"shape",
")",
"*",
"[",
"offset",
"]",
"# Deal with the non-int offset entries",
"for",
"n",
"in",
"range",
"(",
"len",
"(",
"offset",
")",
")",
":",
"if",
"offset",
"[",
"n",
"]",
"is",
"True",
":",
"offset",
"[",
"n",
"]",
"=",
"shape",
"[",
"n",
"]",
"/",
"underlying_shape",
"[",
"n",
"]",
"/",
"2",
"if",
"offset",
"[",
"n",
"]",
"is",
"False",
":",
"offset",
"[",
"n",
"]",
"=",
"0",
"offset",
"[",
"n",
"]",
"=",
"int",
"(",
"offset",
"[",
"n",
"]",
")",
"# Actually apply offset by padding and then croping off the excess.",
"padding",
"=",
"[",
"(",
"pad",
",",
"0",
")",
"for",
"pad",
"in",
"offset",
"]",
"t",
"=",
"tf",
".",
"pad",
"(",
"t",
",",
"padding",
",",
"\"SYMMETRIC\"",
")",
"begin",
"=",
"len",
"(",
"shape",
")",
"*",
"[",
"0",
"]",
"t",
"=",
"tf",
".",
"slice",
"(",
"t",
",",
"begin",
",",
"shape",
")",
"return",
"t"
] |
Produces a tensor paramaterized by a interpolated lower resolution tensor.
This is like what is done in a laplacian pyramid, but a bit more general. It
can be a powerful way to describe images.
Args:
shape: desired shape of resulting tensor
underlying_shape: shape of the tensor being resized into final tensor
offset: Describes how to offset the interpolated vector (like phase in a
Fourier transform). If None, apply no offset. If a scalar, apply the same
offset to each dimension; if a list use each entry for each dimension.
If a int, offset by that much. If False, do not offset. If True, offset by
half the ratio between shape and underlying shape (analagous to 90
degrees).
sd: Standard deviation of initial tensor variable.
Returns:
A tensor paramaterized by a lower resolution tensorflow variable.
|
[
"Produces",
"a",
"tensor",
"paramaterized",
"by",
"a",
"interpolated",
"lower",
"resolution",
"tensor",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/param/lowres.py#L24-L66
|
train
|
tensorflow/lucid
|
lucid/misc/tfutil.py
|
create_session
|
def create_session(target='', timeout_sec=10):
'''Create an intractive TensorFlow session.
Helper function that creates TF session that uses growing GPU memory
allocation and opration timeout. 'allow_growth' flag prevents TF
from allocating the whole GPU memory an once, which is useful
when having multiple python sessions sharing the same GPU.
'''
graph = tf.Graph()
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
config.operation_timeout_in_ms = int(timeout_sec*1000)
return tf.InteractiveSession(target=target, graph=graph, config=config)
|
python
|
def create_session(target='', timeout_sec=10):
'''Create an intractive TensorFlow session.
Helper function that creates TF session that uses growing GPU memory
allocation and opration timeout. 'allow_growth' flag prevents TF
from allocating the whole GPU memory an once, which is useful
when having multiple python sessions sharing the same GPU.
'''
graph = tf.Graph()
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
config.operation_timeout_in_ms = int(timeout_sec*1000)
return tf.InteractiveSession(target=target, graph=graph, config=config)
|
[
"def",
"create_session",
"(",
"target",
"=",
"''",
",",
"timeout_sec",
"=",
"10",
")",
":",
"graph",
"=",
"tf",
".",
"Graph",
"(",
")",
"config",
"=",
"tf",
".",
"ConfigProto",
"(",
")",
"config",
".",
"gpu_options",
".",
"allow_growth",
"=",
"True",
"config",
".",
"operation_timeout_in_ms",
"=",
"int",
"(",
"timeout_sec",
"*",
"1000",
")",
"return",
"tf",
".",
"InteractiveSession",
"(",
"target",
"=",
"target",
",",
"graph",
"=",
"graph",
",",
"config",
"=",
"config",
")"
] |
Create an intractive TensorFlow session.
Helper function that creates TF session that uses growing GPU memory
allocation and opration timeout. 'allow_growth' flag prevents TF
from allocating the whole GPU memory an once, which is useful
when having multiple python sessions sharing the same GPU.
|
[
"Create",
"an",
"intractive",
"TensorFlow",
"session",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/tfutil.py#L19-L31
|
train
|
tensorflow/lucid
|
lucid/misc/io/reading.py
|
read
|
def read(url, encoding=None, cache=None, mode="rb"):
"""Read from any URL.
Internally differentiates between URLs supported by tf.gfile, such as URLs
with the Google Cloud Storage scheme ('gs://...') or local paths, and HTTP
URLs. This way users don't need to know about the underlying fetch mechanism.
Args:
url: a URL including scheme or a local path
mode: mode in which to open the file. defaults to binary ('rb')
encoding: if specified, encoding that should be used to decode read data
if mode is specified to be text ('r'), this defaults to 'utf-8'.
cache: whether to attempt caching the resource. Defaults to True only if
the given URL specifies a remote resource.
Returns:
All bytes form the specified resource, or a decoded string of those.
"""
with read_handle(url, cache, mode=mode) as handle:
data = handle.read()
if encoding:
data = data.decode(encoding)
return data
|
python
|
def read(url, encoding=None, cache=None, mode="rb"):
"""Read from any URL.
Internally differentiates between URLs supported by tf.gfile, such as URLs
with the Google Cloud Storage scheme ('gs://...') or local paths, and HTTP
URLs. This way users don't need to know about the underlying fetch mechanism.
Args:
url: a URL including scheme or a local path
mode: mode in which to open the file. defaults to binary ('rb')
encoding: if specified, encoding that should be used to decode read data
if mode is specified to be text ('r'), this defaults to 'utf-8'.
cache: whether to attempt caching the resource. Defaults to True only if
the given URL specifies a remote resource.
Returns:
All bytes form the specified resource, or a decoded string of those.
"""
with read_handle(url, cache, mode=mode) as handle:
data = handle.read()
if encoding:
data = data.decode(encoding)
return data
|
[
"def",
"read",
"(",
"url",
",",
"encoding",
"=",
"None",
",",
"cache",
"=",
"None",
",",
"mode",
"=",
"\"rb\"",
")",
":",
"with",
"read_handle",
"(",
"url",
",",
"cache",
",",
"mode",
"=",
"mode",
")",
"as",
"handle",
":",
"data",
"=",
"handle",
".",
"read",
"(",
")",
"if",
"encoding",
":",
"data",
"=",
"data",
".",
"decode",
"(",
"encoding",
")",
"return",
"data"
] |
Read from any URL.
Internally differentiates between URLs supported by tf.gfile, such as URLs
with the Google Cloud Storage scheme ('gs://...') or local paths, and HTTP
URLs. This way users don't need to know about the underlying fetch mechanism.
Args:
url: a URL including scheme or a local path
mode: mode in which to open the file. defaults to binary ('rb')
encoding: if specified, encoding that should be used to decode read data
if mode is specified to be text ('r'), this defaults to 'utf-8'.
cache: whether to attempt caching the resource. Defaults to True only if
the given URL specifies a remote resource.
Returns:
All bytes form the specified resource, or a decoded string of those.
|
[
"Read",
"from",
"any",
"URL",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/reading.py#L48-L71
|
train
|
tensorflow/lucid
|
lucid/misc/io/reading.py
|
read_handle
|
def read_handle(url, cache=None, mode="rb"):
"""Read from any URL with a file handle.
Use this to get a handle to a file rather than eagerly load the data:
```
with read_handle(url) as handle:
result = something.load(handle)
result.do_something()
```
When program execution leaves this `with` block, the handle will be closed
automatically.
Args:
url: a URL including scheme or a local path
Returns:
A file handle to the specified resource if it could be reached.
The handle will be closed automatically once execution leaves this context.
"""
scheme = urlparse(url).scheme
if cache == 'purge':
_purge_cached(url)
cache = None
if _is_remote(scheme) and cache is None:
cache = True
log.debug("Cache not specified, enabling because resource is remote.")
if cache:
handle = _read_and_cache(url, mode=mode)
else:
if scheme in ("http", "https"):
handle = _handle_web_url(url, mode=mode)
elif scheme in ("gs"):
handle = _handle_gfile(url, mode=mode)
else:
handle = open(url, mode=mode)
yield handle
handle.close()
|
python
|
def read_handle(url, cache=None, mode="rb"):
"""Read from any URL with a file handle.
Use this to get a handle to a file rather than eagerly load the data:
```
with read_handle(url) as handle:
result = something.load(handle)
result.do_something()
```
When program execution leaves this `with` block, the handle will be closed
automatically.
Args:
url: a URL including scheme or a local path
Returns:
A file handle to the specified resource if it could be reached.
The handle will be closed automatically once execution leaves this context.
"""
scheme = urlparse(url).scheme
if cache == 'purge':
_purge_cached(url)
cache = None
if _is_remote(scheme) and cache is None:
cache = True
log.debug("Cache not specified, enabling because resource is remote.")
if cache:
handle = _read_and_cache(url, mode=mode)
else:
if scheme in ("http", "https"):
handle = _handle_web_url(url, mode=mode)
elif scheme in ("gs"):
handle = _handle_gfile(url, mode=mode)
else:
handle = open(url, mode=mode)
yield handle
handle.close()
|
[
"def",
"read_handle",
"(",
"url",
",",
"cache",
"=",
"None",
",",
"mode",
"=",
"\"rb\"",
")",
":",
"scheme",
"=",
"urlparse",
"(",
"url",
")",
".",
"scheme",
"if",
"cache",
"==",
"'purge'",
":",
"_purge_cached",
"(",
"url",
")",
"cache",
"=",
"None",
"if",
"_is_remote",
"(",
"scheme",
")",
"and",
"cache",
"is",
"None",
":",
"cache",
"=",
"True",
"log",
".",
"debug",
"(",
"\"Cache not specified, enabling because resource is remote.\"",
")",
"if",
"cache",
":",
"handle",
"=",
"_read_and_cache",
"(",
"url",
",",
"mode",
"=",
"mode",
")",
"else",
":",
"if",
"scheme",
"in",
"(",
"\"http\"",
",",
"\"https\"",
")",
":",
"handle",
"=",
"_handle_web_url",
"(",
"url",
",",
"mode",
"=",
"mode",
")",
"elif",
"scheme",
"in",
"(",
"\"gs\"",
")",
":",
"handle",
"=",
"_handle_gfile",
"(",
"url",
",",
"mode",
"=",
"mode",
")",
"else",
":",
"handle",
"=",
"open",
"(",
"url",
",",
"mode",
"=",
"mode",
")",
"yield",
"handle",
"handle",
".",
"close",
"(",
")"
] |
Read from any URL with a file handle.
Use this to get a handle to a file rather than eagerly load the data:
```
with read_handle(url) as handle:
result = something.load(handle)
result.do_something()
```
When program execution leaves this `with` block, the handle will be closed
automatically.
Args:
url: a URL including scheme or a local path
Returns:
A file handle to the specified resource if it could be reached.
The handle will be closed automatically once execution leaves this context.
|
[
"Read",
"from",
"any",
"URL",
"with",
"a",
"file",
"handle",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/reading.py#L75-L118
|
train
|
tensorflow/lucid
|
lucid/misc/io/reading.py
|
local_cache_path
|
def local_cache_path(remote_url):
"""Returns the path that remote_url would be cached at locally."""
local_name = RESERVED_PATH_CHARS.sub("_", remote_url)
return os.path.join(gettempdir(), local_name)
|
python
|
def local_cache_path(remote_url):
"""Returns the path that remote_url would be cached at locally."""
local_name = RESERVED_PATH_CHARS.sub("_", remote_url)
return os.path.join(gettempdir(), local_name)
|
[
"def",
"local_cache_path",
"(",
"remote_url",
")",
":",
"local_name",
"=",
"RESERVED_PATH_CHARS",
".",
"sub",
"(",
"\"_\"",
",",
"remote_url",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"gettempdir",
"(",
")",
",",
"local_name",
")"
] |
Returns the path that remote_url would be cached at locally.
|
[
"Returns",
"the",
"path",
"that",
"remote_url",
"would",
"be",
"cached",
"at",
"locally",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/reading.py#L142-L145
|
train
|
tensorflow/lucid
|
lucid/optvis/param/cppn.py
|
cppn
|
def cppn(
width,
batch=1,
num_output_channels=3,
num_hidden_channels=24,
num_layers=8,
activation_func=_composite_activation,
normalize=False,
):
"""Compositional Pattern Producing Network
Args:
width: width of resulting image, equals height
batch: batch dimension of output, note that all params share the same weights!
num_output_channels:
num_hidden_channels:
num_layers:
activation_func:
normalize:
Returns:
The collapsed shape, represented as a list.
"""
r = 3.0 ** 0.5 # std(coord_range) == 1.0
coord_range = tf.linspace(-r, r, width)
y, x = tf.meshgrid(coord_range, coord_range, indexing="ij")
net = tf.stack([tf.stack([x, y], -1)] * batch, 0)
with slim.arg_scope(
[slim.conv2d],
kernel_size=[1, 1],
activation_fn=None,
weights_initializer=tf.initializers.variance_scaling(),
biases_initializer=tf.initializers.random_normal(0.0, 0.1),
):
for i in range(num_layers):
x = slim.conv2d(net, num_hidden_channels)
if normalize:
x = slim.instance_norm(x)
net = activation_func(x)
rgb = slim.conv2d(
net,
num_output_channels,
activation_fn=tf.nn.sigmoid,
weights_initializer=tf.zeros_initializer(),
)
return rgb
|
python
|
def cppn(
width,
batch=1,
num_output_channels=3,
num_hidden_channels=24,
num_layers=8,
activation_func=_composite_activation,
normalize=False,
):
"""Compositional Pattern Producing Network
Args:
width: width of resulting image, equals height
batch: batch dimension of output, note that all params share the same weights!
num_output_channels:
num_hidden_channels:
num_layers:
activation_func:
normalize:
Returns:
The collapsed shape, represented as a list.
"""
r = 3.0 ** 0.5 # std(coord_range) == 1.0
coord_range = tf.linspace(-r, r, width)
y, x = tf.meshgrid(coord_range, coord_range, indexing="ij")
net = tf.stack([tf.stack([x, y], -1)] * batch, 0)
with slim.arg_scope(
[slim.conv2d],
kernel_size=[1, 1],
activation_fn=None,
weights_initializer=tf.initializers.variance_scaling(),
biases_initializer=tf.initializers.random_normal(0.0, 0.1),
):
for i in range(num_layers):
x = slim.conv2d(net, num_hidden_channels)
if normalize:
x = slim.instance_norm(x)
net = activation_func(x)
rgb = slim.conv2d(
net,
num_output_channels,
activation_fn=tf.nn.sigmoid,
weights_initializer=tf.zeros_initializer(),
)
return rgb
|
[
"def",
"cppn",
"(",
"width",
",",
"batch",
"=",
"1",
",",
"num_output_channels",
"=",
"3",
",",
"num_hidden_channels",
"=",
"24",
",",
"num_layers",
"=",
"8",
",",
"activation_func",
"=",
"_composite_activation",
",",
"normalize",
"=",
"False",
",",
")",
":",
"r",
"=",
"3.0",
"**",
"0.5",
"# std(coord_range) == 1.0",
"coord_range",
"=",
"tf",
".",
"linspace",
"(",
"-",
"r",
",",
"r",
",",
"width",
")",
"y",
",",
"x",
"=",
"tf",
".",
"meshgrid",
"(",
"coord_range",
",",
"coord_range",
",",
"indexing",
"=",
"\"ij\"",
")",
"net",
"=",
"tf",
".",
"stack",
"(",
"[",
"tf",
".",
"stack",
"(",
"[",
"x",
",",
"y",
"]",
",",
"-",
"1",
")",
"]",
"*",
"batch",
",",
"0",
")",
"with",
"slim",
".",
"arg_scope",
"(",
"[",
"slim",
".",
"conv2d",
"]",
",",
"kernel_size",
"=",
"[",
"1",
",",
"1",
"]",
",",
"activation_fn",
"=",
"None",
",",
"weights_initializer",
"=",
"tf",
".",
"initializers",
".",
"variance_scaling",
"(",
")",
",",
"biases_initializer",
"=",
"tf",
".",
"initializers",
".",
"random_normal",
"(",
"0.0",
",",
"0.1",
")",
",",
")",
":",
"for",
"i",
"in",
"range",
"(",
"num_layers",
")",
":",
"x",
"=",
"slim",
".",
"conv2d",
"(",
"net",
",",
"num_hidden_channels",
")",
"if",
"normalize",
":",
"x",
"=",
"slim",
".",
"instance_norm",
"(",
"x",
")",
"net",
"=",
"activation_func",
"(",
"x",
")",
"rgb",
"=",
"slim",
".",
"conv2d",
"(",
"net",
",",
"num_output_channels",
",",
"activation_fn",
"=",
"tf",
".",
"nn",
".",
"sigmoid",
",",
"weights_initializer",
"=",
"tf",
".",
"zeros_initializer",
"(",
")",
",",
")",
"return",
"rgb"
] |
Compositional Pattern Producing Network
Args:
width: width of resulting image, equals height
batch: batch dimension of output, note that all params share the same weights!
num_output_channels:
num_hidden_channels:
num_layers:
activation_func:
normalize:
Returns:
The collapsed shape, represented as a list.
|
[
"Compositional",
"Pattern",
"Producing",
"Network"
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/param/cppn.py#L54-L100
|
train
|
tensorflow/lucid
|
lucid/modelzoo/nets_factory.py
|
get_model
|
def get_model(name):
"""Returns a model instance such as `model = vision_models.InceptionV1()`.
In the future may be expanded to filter by additional criteria, such as
architecture, dataset, and task the model was trained on.
Args:
name: The name of the model, as given by the class name in vision_models.
Returns:
An instantiated Model class with the requested model. Users still need to
manually `load_graphdef` on the return value, and manually import this
model's graph into their current graph.
Raises:
ValueError: If network `name` is not recognized.
"""
if name not in models_map:
candidates = filter(lambda key: name in key, models_map.keys())
candidates_string = ", ".join(candidates)
raise ValueError(
"No network named {}. Did you mean one of {}?".format(
name, candidates_string
)
)
model_class = models_map[name]
model = model_class()
return model
|
python
|
def get_model(name):
"""Returns a model instance such as `model = vision_models.InceptionV1()`.
In the future may be expanded to filter by additional criteria, such as
architecture, dataset, and task the model was trained on.
Args:
name: The name of the model, as given by the class name in vision_models.
Returns:
An instantiated Model class with the requested model. Users still need to
manually `load_graphdef` on the return value, and manually import this
model's graph into their current graph.
Raises:
ValueError: If network `name` is not recognized.
"""
if name not in models_map:
candidates = filter(lambda key: name in key, models_map.keys())
candidates_string = ", ".join(candidates)
raise ValueError(
"No network named {}. Did you mean one of {}?".format(
name, candidates_string
)
)
model_class = models_map[name]
model = model_class()
return model
|
[
"def",
"get_model",
"(",
"name",
")",
":",
"if",
"name",
"not",
"in",
"models_map",
":",
"candidates",
"=",
"filter",
"(",
"lambda",
"key",
":",
"name",
"in",
"key",
",",
"models_map",
".",
"keys",
"(",
")",
")",
"candidates_string",
"=",
"\", \"",
".",
"join",
"(",
"candidates",
")",
"raise",
"ValueError",
"(",
"\"No network named {}. Did you mean one of {}?\"",
".",
"format",
"(",
"name",
",",
"candidates_string",
")",
")",
"model_class",
"=",
"models_map",
"[",
"name",
"]",
"model",
"=",
"model_class",
"(",
")",
"return",
"model"
] |
Returns a model instance such as `model = vision_models.InceptionV1()`.
In the future may be expanded to filter by additional criteria, such as
architecture, dataset, and task the model was trained on.
Args:
name: The name of the model, as given by the class name in vision_models.
Returns:
An instantiated Model class with the requested model. Users still need to
manually `load_graphdef` on the return value, and manually import this
model's graph into their current graph.
Raises:
ValueError: If network `name` is not recognized.
|
[
"Returns",
"a",
"model",
"instance",
"such",
"as",
"model",
"=",
"vision_models",
".",
"InceptionV1",
"()",
".",
"In",
"the",
"future",
"may",
"be",
"expanded",
"to",
"filter",
"by",
"additional",
"criteria",
"such",
"as",
"architecture",
"dataset",
"and",
"task",
"the",
"model",
"was",
"trained",
"on",
".",
"Args",
":",
"name",
":",
"The",
"name",
"of",
"the",
"model",
"as",
"given",
"by",
"the",
"class",
"name",
"in",
"vision_models",
".",
"Returns",
":",
"An",
"instantiated",
"Model",
"class",
"with",
"the",
"requested",
"model",
".",
"Users",
"still",
"need",
"to",
"manually",
"load_graphdef",
"on",
"the",
"return",
"value",
"and",
"manually",
"import",
"this",
"model",
"s",
"graph",
"into",
"their",
"current",
"graph",
".",
"Raises",
":",
"ValueError",
":",
"If",
"network",
"name",
"is",
"not",
"recognized",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/modelzoo/nets_factory.py#L44-L68
|
train
|
tensorflow/lucid
|
lucid/recipes/activation_atlas/main.py
|
activation_atlas
|
def activation_atlas(
model,
layer,
grid_size=10,
icon_size=96,
number_activations=NUMBER_OF_AVAILABLE_SAMPLES,
icon_batch_size=32,
verbose=False,
):
"""Renders an Activation Atlas of the given model's layer."""
activations = layer.activations[:number_activations, ...]
layout, = aligned_umap(activations, verbose=verbose)
directions, coordinates, _ = bin_laid_out_activations(
layout, activations, grid_size
)
icons = []
for directions_batch in chunked(directions, icon_batch_size):
icon_batch, losses = render_icons(
directions_batch, model, layer=layer.name, size=icon_size, num_attempts=1
)
icons += icon_batch
canvas = make_canvas(icons, coordinates, grid_size)
return canvas
|
python
|
def activation_atlas(
model,
layer,
grid_size=10,
icon_size=96,
number_activations=NUMBER_OF_AVAILABLE_SAMPLES,
icon_batch_size=32,
verbose=False,
):
"""Renders an Activation Atlas of the given model's layer."""
activations = layer.activations[:number_activations, ...]
layout, = aligned_umap(activations, verbose=verbose)
directions, coordinates, _ = bin_laid_out_activations(
layout, activations, grid_size
)
icons = []
for directions_batch in chunked(directions, icon_batch_size):
icon_batch, losses = render_icons(
directions_batch, model, layer=layer.name, size=icon_size, num_attempts=1
)
icons += icon_batch
canvas = make_canvas(icons, coordinates, grid_size)
return canvas
|
[
"def",
"activation_atlas",
"(",
"model",
",",
"layer",
",",
"grid_size",
"=",
"10",
",",
"icon_size",
"=",
"96",
",",
"number_activations",
"=",
"NUMBER_OF_AVAILABLE_SAMPLES",
",",
"icon_batch_size",
"=",
"32",
",",
"verbose",
"=",
"False",
",",
")",
":",
"activations",
"=",
"layer",
".",
"activations",
"[",
":",
"number_activations",
",",
"...",
"]",
"layout",
",",
"=",
"aligned_umap",
"(",
"activations",
",",
"verbose",
"=",
"verbose",
")",
"directions",
",",
"coordinates",
",",
"_",
"=",
"bin_laid_out_activations",
"(",
"layout",
",",
"activations",
",",
"grid_size",
")",
"icons",
"=",
"[",
"]",
"for",
"directions_batch",
"in",
"chunked",
"(",
"directions",
",",
"icon_batch_size",
")",
":",
"icon_batch",
",",
"losses",
"=",
"render_icons",
"(",
"directions_batch",
",",
"model",
",",
"layer",
"=",
"layer",
".",
"name",
",",
"size",
"=",
"icon_size",
",",
"num_attempts",
"=",
"1",
")",
"icons",
"+=",
"icon_batch",
"canvas",
"=",
"make_canvas",
"(",
"icons",
",",
"coordinates",
",",
"grid_size",
")",
"return",
"canvas"
] |
Renders an Activation Atlas of the given model's layer.
|
[
"Renders",
"an",
"Activation",
"Atlas",
"of",
"the",
"given",
"model",
"s",
"layer",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/recipes/activation_atlas/main.py#L30-L54
|
train
|
tensorflow/lucid
|
lucid/recipes/activation_atlas/main.py
|
aligned_activation_atlas
|
def aligned_activation_atlas(
model1,
layer1,
model2,
layer2,
grid_size=10,
icon_size=80,
num_steps=1024,
whiten_layers=True,
number_activations=NUMBER_OF_AVAILABLE_SAMPLES,
icon_batch_size=32,
verbose=False,
):
"""Renders two aligned Activation Atlases of the given models' layers.
Returns a generator of the two atlasses, and a nested generator for intermediate
atlasses while they're being rendered.
"""
combined_activations = _combine_activations(
layer1, layer2, number_activations=number_activations
)
layouts = aligned_umap(combined_activations, verbose=verbose)
for model, layer, layout in zip((model1, model2), (layer1, layer2), layouts):
directions, coordinates, densities = bin_laid_out_activations(
layout, layer.activations[:number_activations, ...], grid_size, threshold=10
)
def _progressive_canvas_iterator():
icons = []
for directions_batch in chunked(directions, icon_batch_size):
icon_batch, losses = render_icons(
directions_batch,
model,
alpha=False,
layer=layer.name,
size=icon_size,
n_steps=num_steps,
S=layer_inverse_covariance(layer) if whiten_layers else None,
)
icons += icon_batch
yield make_canvas(icons, coordinates, grid_size)
yield _progressive_canvas_iterator()
|
python
|
def aligned_activation_atlas(
model1,
layer1,
model2,
layer2,
grid_size=10,
icon_size=80,
num_steps=1024,
whiten_layers=True,
number_activations=NUMBER_OF_AVAILABLE_SAMPLES,
icon_batch_size=32,
verbose=False,
):
"""Renders two aligned Activation Atlases of the given models' layers.
Returns a generator of the two atlasses, and a nested generator for intermediate
atlasses while they're being rendered.
"""
combined_activations = _combine_activations(
layer1, layer2, number_activations=number_activations
)
layouts = aligned_umap(combined_activations, verbose=verbose)
for model, layer, layout in zip((model1, model2), (layer1, layer2), layouts):
directions, coordinates, densities = bin_laid_out_activations(
layout, layer.activations[:number_activations, ...], grid_size, threshold=10
)
def _progressive_canvas_iterator():
icons = []
for directions_batch in chunked(directions, icon_batch_size):
icon_batch, losses = render_icons(
directions_batch,
model,
alpha=False,
layer=layer.name,
size=icon_size,
n_steps=num_steps,
S=layer_inverse_covariance(layer) if whiten_layers else None,
)
icons += icon_batch
yield make_canvas(icons, coordinates, grid_size)
yield _progressive_canvas_iterator()
|
[
"def",
"aligned_activation_atlas",
"(",
"model1",
",",
"layer1",
",",
"model2",
",",
"layer2",
",",
"grid_size",
"=",
"10",
",",
"icon_size",
"=",
"80",
",",
"num_steps",
"=",
"1024",
",",
"whiten_layers",
"=",
"True",
",",
"number_activations",
"=",
"NUMBER_OF_AVAILABLE_SAMPLES",
",",
"icon_batch_size",
"=",
"32",
",",
"verbose",
"=",
"False",
",",
")",
":",
"combined_activations",
"=",
"_combine_activations",
"(",
"layer1",
",",
"layer2",
",",
"number_activations",
"=",
"number_activations",
")",
"layouts",
"=",
"aligned_umap",
"(",
"combined_activations",
",",
"verbose",
"=",
"verbose",
")",
"for",
"model",
",",
"layer",
",",
"layout",
"in",
"zip",
"(",
"(",
"model1",
",",
"model2",
")",
",",
"(",
"layer1",
",",
"layer2",
")",
",",
"layouts",
")",
":",
"directions",
",",
"coordinates",
",",
"densities",
"=",
"bin_laid_out_activations",
"(",
"layout",
",",
"layer",
".",
"activations",
"[",
":",
"number_activations",
",",
"...",
"]",
",",
"grid_size",
",",
"threshold",
"=",
"10",
")",
"def",
"_progressive_canvas_iterator",
"(",
")",
":",
"icons",
"=",
"[",
"]",
"for",
"directions_batch",
"in",
"chunked",
"(",
"directions",
",",
"icon_batch_size",
")",
":",
"icon_batch",
",",
"losses",
"=",
"render_icons",
"(",
"directions_batch",
",",
"model",
",",
"alpha",
"=",
"False",
",",
"layer",
"=",
"layer",
".",
"name",
",",
"size",
"=",
"icon_size",
",",
"n_steps",
"=",
"num_steps",
",",
"S",
"=",
"layer_inverse_covariance",
"(",
"layer",
")",
"if",
"whiten_layers",
"else",
"None",
",",
")",
"icons",
"+=",
"icon_batch",
"yield",
"make_canvas",
"(",
"icons",
",",
"coordinates",
",",
"grid_size",
")",
"yield",
"_progressive_canvas_iterator",
"(",
")"
] |
Renders two aligned Activation Atlases of the given models' layers.
Returns a generator of the two atlasses, and a nested generator for intermediate
atlasses while they're being rendered.
|
[
"Renders",
"two",
"aligned",
"Activation",
"Atlases",
"of",
"the",
"given",
"models",
"layers",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/recipes/activation_atlas/main.py#L57-L100
|
train
|
tensorflow/lucid
|
lucid/recipes/activation_atlas/main.py
|
_combine_activations
|
def _combine_activations(
layer1,
layer2,
activations1=None,
activations2=None,
mode=ActivationTranslation.BIDIRECTIONAL,
number_activations=NUMBER_OF_AVAILABLE_SAMPLES,
):
"""Given two layers, combines their activations according to mode.
ActivationTranslation.ONE_TO_TWO:
Translate activations of layer1 into the space of layer2, and return a tuple of
the translated activations and the original layer2 activations.
ActivationTranslation.BIDIRECTIONAL:
Translate activations of layer1 into the space of layer2, activations of layer2
into the space of layer 1, concatenate them along their channels, and returns a
tuple of the concatenated activations for each layer.
"""
activations1 = activations1 or layer1.activations[:number_activations, ...]
activations2 = activations2 or layer2.activations[:number_activations, ...]
if mode is ActivationTranslation.ONE_TO_TWO:
acts_1_to_2 = push_activations(activations1, layer1, layer2)
return acts_1_to_2, activations2
elif mode is ActivationTranslation.BIDIRECTIONAL:
acts_1_to_2 = push_activations(activations1, layer1, layer2)
acts_2_to_1 = push_activations(activations2, layer2, layer1)
activations_model1 = np.concatenate((activations1, acts_1_to_2), axis=1)
activations_model2 = np.concatenate((acts_2_to_1, activations2), axis=1)
return activations_model1, activations_model2
|
python
|
def _combine_activations(
layer1,
layer2,
activations1=None,
activations2=None,
mode=ActivationTranslation.BIDIRECTIONAL,
number_activations=NUMBER_OF_AVAILABLE_SAMPLES,
):
"""Given two layers, combines their activations according to mode.
ActivationTranslation.ONE_TO_TWO:
Translate activations of layer1 into the space of layer2, and return a tuple of
the translated activations and the original layer2 activations.
ActivationTranslation.BIDIRECTIONAL:
Translate activations of layer1 into the space of layer2, activations of layer2
into the space of layer 1, concatenate them along their channels, and returns a
tuple of the concatenated activations for each layer.
"""
activations1 = activations1 or layer1.activations[:number_activations, ...]
activations2 = activations2 or layer2.activations[:number_activations, ...]
if mode is ActivationTranslation.ONE_TO_TWO:
acts_1_to_2 = push_activations(activations1, layer1, layer2)
return acts_1_to_2, activations2
elif mode is ActivationTranslation.BIDIRECTIONAL:
acts_1_to_2 = push_activations(activations1, layer1, layer2)
acts_2_to_1 = push_activations(activations2, layer2, layer1)
activations_model1 = np.concatenate((activations1, acts_1_to_2), axis=1)
activations_model2 = np.concatenate((acts_2_to_1, activations2), axis=1)
return activations_model1, activations_model2
|
[
"def",
"_combine_activations",
"(",
"layer1",
",",
"layer2",
",",
"activations1",
"=",
"None",
",",
"activations2",
"=",
"None",
",",
"mode",
"=",
"ActivationTranslation",
".",
"BIDIRECTIONAL",
",",
"number_activations",
"=",
"NUMBER_OF_AVAILABLE_SAMPLES",
",",
")",
":",
"activations1",
"=",
"activations1",
"or",
"layer1",
".",
"activations",
"[",
":",
"number_activations",
",",
"...",
"]",
"activations2",
"=",
"activations2",
"or",
"layer2",
".",
"activations",
"[",
":",
"number_activations",
",",
"...",
"]",
"if",
"mode",
"is",
"ActivationTranslation",
".",
"ONE_TO_TWO",
":",
"acts_1_to_2",
"=",
"push_activations",
"(",
"activations1",
",",
"layer1",
",",
"layer2",
")",
"return",
"acts_1_to_2",
",",
"activations2",
"elif",
"mode",
"is",
"ActivationTranslation",
".",
"BIDIRECTIONAL",
":",
"acts_1_to_2",
"=",
"push_activations",
"(",
"activations1",
",",
"layer1",
",",
"layer2",
")",
"acts_2_to_1",
"=",
"push_activations",
"(",
"activations2",
",",
"layer2",
",",
"layer1",
")",
"activations_model1",
"=",
"np",
".",
"concatenate",
"(",
"(",
"activations1",
",",
"acts_1_to_2",
")",
",",
"axis",
"=",
"1",
")",
"activations_model2",
"=",
"np",
".",
"concatenate",
"(",
"(",
"acts_2_to_1",
",",
"activations2",
")",
",",
"axis",
"=",
"1",
")",
"return",
"activations_model1",
",",
"activations_model2"
] |
Given two layers, combines their activations according to mode.
ActivationTranslation.ONE_TO_TWO:
Translate activations of layer1 into the space of layer2, and return a tuple of
the translated activations and the original layer2 activations.
ActivationTranslation.BIDIRECTIONAL:
Translate activations of layer1 into the space of layer2, activations of layer2
into the space of layer 1, concatenate them along their channels, and returns a
tuple of the concatenated activations for each layer.
|
[
"Given",
"two",
"layers",
"combines",
"their",
"activations",
"according",
"to",
"mode",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/recipes/activation_atlas/main.py#L111-L146
|
train
|
tensorflow/lucid
|
lucid/recipes/activation_atlas/main.py
|
bin_laid_out_activations
|
def bin_laid_out_activations(layout, activations, grid_size, threshold=5):
"""Given a layout and activations, overlays a grid on the layout and returns
averaged activations for each grid cell. If a cell contains less than `threshold`
activations it will be discarded, so the number of returned data is variable."""
assert layout.shape[0] == activations.shape[0]
# calculate which grid cells each activation's layout position falls into
# first bin stays empty because nothing should be < 0, so we add an extra bin
bins = np.linspace(0, 1, num=grid_size + 1)
bins[-1] = np.inf # last bin should include all higher values
indices = np.digitize(layout, bins) - 1 # subtract 1 to account for empty first bin
# because of thresholding we may need to return a variable number of means
means, coordinates, counts = [], [], []
# iterate over all grid cell coordinates to compute their average directions
grid_coordinates = np.indices((grid_size, grid_size)).transpose().reshape(-1, 2)
for xy_coordinates in grid_coordinates:
mask = np.equal(xy_coordinates, indices).all(axis=1)
count = np.count_nonzero(mask)
if count > threshold:
counts.append(count)
coordinates.append(xy_coordinates)
mean = np.average(activations[mask], axis=0)
means.append(mean)
assert len(means) == len(coordinates) == len(counts)
if len(coordinates) == 0:
raise RuntimeError("Binning activations led to 0 cells containing activations!")
return means, coordinates, counts
|
python
|
def bin_laid_out_activations(layout, activations, grid_size, threshold=5):
"""Given a layout and activations, overlays a grid on the layout and returns
averaged activations for each grid cell. If a cell contains less than `threshold`
activations it will be discarded, so the number of returned data is variable."""
assert layout.shape[0] == activations.shape[0]
# calculate which grid cells each activation's layout position falls into
# first bin stays empty because nothing should be < 0, so we add an extra bin
bins = np.linspace(0, 1, num=grid_size + 1)
bins[-1] = np.inf # last bin should include all higher values
indices = np.digitize(layout, bins) - 1 # subtract 1 to account for empty first bin
# because of thresholding we may need to return a variable number of means
means, coordinates, counts = [], [], []
# iterate over all grid cell coordinates to compute their average directions
grid_coordinates = np.indices((grid_size, grid_size)).transpose().reshape(-1, 2)
for xy_coordinates in grid_coordinates:
mask = np.equal(xy_coordinates, indices).all(axis=1)
count = np.count_nonzero(mask)
if count > threshold:
counts.append(count)
coordinates.append(xy_coordinates)
mean = np.average(activations[mask], axis=0)
means.append(mean)
assert len(means) == len(coordinates) == len(counts)
if len(coordinates) == 0:
raise RuntimeError("Binning activations led to 0 cells containing activations!")
return means, coordinates, counts
|
[
"def",
"bin_laid_out_activations",
"(",
"layout",
",",
"activations",
",",
"grid_size",
",",
"threshold",
"=",
"5",
")",
":",
"assert",
"layout",
".",
"shape",
"[",
"0",
"]",
"==",
"activations",
".",
"shape",
"[",
"0",
"]",
"# calculate which grid cells each activation's layout position falls into",
"# first bin stays empty because nothing should be < 0, so we add an extra bin",
"bins",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"1",
",",
"num",
"=",
"grid_size",
"+",
"1",
")",
"bins",
"[",
"-",
"1",
"]",
"=",
"np",
".",
"inf",
"# last bin should include all higher values",
"indices",
"=",
"np",
".",
"digitize",
"(",
"layout",
",",
"bins",
")",
"-",
"1",
"# subtract 1 to account for empty first bin",
"# because of thresholding we may need to return a variable number of means",
"means",
",",
"coordinates",
",",
"counts",
"=",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"# iterate over all grid cell coordinates to compute their average directions",
"grid_coordinates",
"=",
"np",
".",
"indices",
"(",
"(",
"grid_size",
",",
"grid_size",
")",
")",
".",
"transpose",
"(",
")",
".",
"reshape",
"(",
"-",
"1",
",",
"2",
")",
"for",
"xy_coordinates",
"in",
"grid_coordinates",
":",
"mask",
"=",
"np",
".",
"equal",
"(",
"xy_coordinates",
",",
"indices",
")",
".",
"all",
"(",
"axis",
"=",
"1",
")",
"count",
"=",
"np",
".",
"count_nonzero",
"(",
"mask",
")",
"if",
"count",
">",
"threshold",
":",
"counts",
".",
"append",
"(",
"count",
")",
"coordinates",
".",
"append",
"(",
"xy_coordinates",
")",
"mean",
"=",
"np",
".",
"average",
"(",
"activations",
"[",
"mask",
"]",
",",
"axis",
"=",
"0",
")",
"means",
".",
"append",
"(",
"mean",
")",
"assert",
"len",
"(",
"means",
")",
"==",
"len",
"(",
"coordinates",
")",
"==",
"len",
"(",
"counts",
")",
"if",
"len",
"(",
"coordinates",
")",
"==",
"0",
":",
"raise",
"RuntimeError",
"(",
"\"Binning activations led to 0 cells containing activations!\"",
")",
"return",
"means",
",",
"coordinates",
",",
"counts"
] |
Given a layout and activations, overlays a grid on the layout and returns
averaged activations for each grid cell. If a cell contains less than `threshold`
activations it will be discarded, so the number of returned data is variable.
|
[
"Given",
"a",
"layout",
"and",
"activations",
"overlays",
"a",
"grid",
"on",
"the",
"layout",
"and",
"returns",
"averaged",
"activations",
"for",
"each",
"grid",
"cell",
".",
"If",
"a",
"cell",
"contains",
"less",
"than",
"threshold",
"activations",
"it",
"will",
"be",
"discarded",
"so",
"the",
"number",
"of",
"returned",
"data",
"is",
"variable",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/recipes/activation_atlas/main.py#L149-L180
|
train
|
tensorflow/lucid
|
lucid/modelzoo/util.py
|
load_graphdef
|
def load_graphdef(model_url, reset_device=True):
"""Load GraphDef from a binary proto file."""
graph_def = load(model_url)
if reset_device:
for n in graph_def.node:
n.device = ""
return graph_def
|
python
|
def load_graphdef(model_url, reset_device=True):
"""Load GraphDef from a binary proto file."""
graph_def = load(model_url)
if reset_device:
for n in graph_def.node:
n.device = ""
return graph_def
|
[
"def",
"load_graphdef",
"(",
"model_url",
",",
"reset_device",
"=",
"True",
")",
":",
"graph_def",
"=",
"load",
"(",
"model_url",
")",
"if",
"reset_device",
":",
"for",
"n",
"in",
"graph_def",
".",
"node",
":",
"n",
".",
"device",
"=",
"\"\"",
"return",
"graph_def"
] |
Load GraphDef from a binary proto file.
|
[
"Load",
"GraphDef",
"from",
"a",
"binary",
"proto",
"file",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/modelzoo/util.py#L39-L47
|
train
|
tensorflow/lucid
|
lucid/modelzoo/util.py
|
forget_xy
|
def forget_xy(t):
"""Ignore sizes of dimensions (1, 2) of a 4d tensor in shape inference.
This allows using smaller input sizes, which create an invalid graph at higher
layers (for example because a spatial dimension becomes smaller than a conv
filter) when we only use early parts of it.
"""
shape = (t.shape[0], None, None, t.shape[3])
return tf.placeholder_with_default(t, shape)
|
python
|
def forget_xy(t):
"""Ignore sizes of dimensions (1, 2) of a 4d tensor in shape inference.
This allows using smaller input sizes, which create an invalid graph at higher
layers (for example because a spatial dimension becomes smaller than a conv
filter) when we only use early parts of it.
"""
shape = (t.shape[0], None, None, t.shape[3])
return tf.placeholder_with_default(t, shape)
|
[
"def",
"forget_xy",
"(",
"t",
")",
":",
"shape",
"=",
"(",
"t",
".",
"shape",
"[",
"0",
"]",
",",
"None",
",",
"None",
",",
"t",
".",
"shape",
"[",
"3",
"]",
")",
"return",
"tf",
".",
"placeholder_with_default",
"(",
"t",
",",
"shape",
")"
] |
Ignore sizes of dimensions (1, 2) of a 4d tensor in shape inference.
This allows using smaller input sizes, which create an invalid graph at higher
layers (for example because a spatial dimension becomes smaller than a conv
filter) when we only use early parts of it.
|
[
"Ignore",
"sizes",
"of",
"dimensions",
"(",
"1",
"2",
")",
"of",
"a",
"4d",
"tensor",
"in",
"shape",
"inference",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/modelzoo/util.py#L50-L58
|
train
|
tensorflow/lucid
|
lucid/modelzoo/util.py
|
frozen_default_graph_def
|
def frozen_default_graph_def(input_node_names, output_node_names):
"""Return frozen and simplified graph_def of default graph."""
sess = tf.get_default_session()
input_graph_def = tf.get_default_graph().as_graph_def()
pruned_graph = tf.graph_util.remove_training_nodes(
input_graph_def, protected_nodes=(output_node_names + input_node_names)
)
pruned_graph = tf.graph_util.extract_sub_graph(pruned_graph, output_node_names)
# remove explicit device assignments
for node in pruned_graph.node:
node.device = ""
all_variable_names = [v.op.name for v in tf.global_variables()]
output_graph_def = tf.graph_util.convert_variables_to_constants(
sess=sess,
input_graph_def=pruned_graph,
output_node_names=output_node_names,
variable_names_whitelist=all_variable_names,
)
return output_graph_def
|
python
|
def frozen_default_graph_def(input_node_names, output_node_names):
"""Return frozen and simplified graph_def of default graph."""
sess = tf.get_default_session()
input_graph_def = tf.get_default_graph().as_graph_def()
pruned_graph = tf.graph_util.remove_training_nodes(
input_graph_def, protected_nodes=(output_node_names + input_node_names)
)
pruned_graph = tf.graph_util.extract_sub_graph(pruned_graph, output_node_names)
# remove explicit device assignments
for node in pruned_graph.node:
node.device = ""
all_variable_names = [v.op.name for v in tf.global_variables()]
output_graph_def = tf.graph_util.convert_variables_to_constants(
sess=sess,
input_graph_def=pruned_graph,
output_node_names=output_node_names,
variable_names_whitelist=all_variable_names,
)
return output_graph_def
|
[
"def",
"frozen_default_graph_def",
"(",
"input_node_names",
",",
"output_node_names",
")",
":",
"sess",
"=",
"tf",
".",
"get_default_session",
"(",
")",
"input_graph_def",
"=",
"tf",
".",
"get_default_graph",
"(",
")",
".",
"as_graph_def",
"(",
")",
"pruned_graph",
"=",
"tf",
".",
"graph_util",
".",
"remove_training_nodes",
"(",
"input_graph_def",
",",
"protected_nodes",
"=",
"(",
"output_node_names",
"+",
"input_node_names",
")",
")",
"pruned_graph",
"=",
"tf",
".",
"graph_util",
".",
"extract_sub_graph",
"(",
"pruned_graph",
",",
"output_node_names",
")",
"# remove explicit device assignments",
"for",
"node",
"in",
"pruned_graph",
".",
"node",
":",
"node",
".",
"device",
"=",
"\"\"",
"all_variable_names",
"=",
"[",
"v",
".",
"op",
".",
"name",
"for",
"v",
"in",
"tf",
".",
"global_variables",
"(",
")",
"]",
"output_graph_def",
"=",
"tf",
".",
"graph_util",
".",
"convert_variables_to_constants",
"(",
"sess",
"=",
"sess",
",",
"input_graph_def",
"=",
"pruned_graph",
",",
"output_node_names",
"=",
"output_node_names",
",",
"variable_names_whitelist",
"=",
"all_variable_names",
",",
")",
"return",
"output_graph_def"
] |
Return frozen and simplified graph_def of default graph.
|
[
"Return",
"frozen",
"and",
"simplified",
"graph_def",
"of",
"default",
"graph",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/modelzoo/util.py#L61-L84
|
train
|
tensorflow/lucid
|
lucid/modelzoo/util.py
|
infuse_metadata
|
def infuse_metadata(graph_def, info):
"""Embed meta data as a string constant in a TF graph.
This function takes info, converts it into json, and embeds
it in graph_def as a constant op called `__lucid_metadata_json`.
"""
temp_graph = tf.Graph()
with temp_graph.as_default():
tf.constant(json.dumps(info, cls=NumpyJSONEncoder), name=metadata_node_name)
meta_node = temp_graph.as_graph_def().node[0]
graph_def.node.extend([meta_node])
|
python
|
def infuse_metadata(graph_def, info):
"""Embed meta data as a string constant in a TF graph.
This function takes info, converts it into json, and embeds
it in graph_def as a constant op called `__lucid_metadata_json`.
"""
temp_graph = tf.Graph()
with temp_graph.as_default():
tf.constant(json.dumps(info, cls=NumpyJSONEncoder), name=metadata_node_name)
meta_node = temp_graph.as_graph_def().node[0]
graph_def.node.extend([meta_node])
|
[
"def",
"infuse_metadata",
"(",
"graph_def",
",",
"info",
")",
":",
"temp_graph",
"=",
"tf",
".",
"Graph",
"(",
")",
"with",
"temp_graph",
".",
"as_default",
"(",
")",
":",
"tf",
".",
"constant",
"(",
"json",
".",
"dumps",
"(",
"info",
",",
"cls",
"=",
"NumpyJSONEncoder",
")",
",",
"name",
"=",
"metadata_node_name",
")",
"meta_node",
"=",
"temp_graph",
".",
"as_graph_def",
"(",
")",
".",
"node",
"[",
"0",
"]",
"graph_def",
".",
"node",
".",
"extend",
"(",
"[",
"meta_node",
"]",
")"
] |
Embed meta data as a string constant in a TF graph.
This function takes info, converts it into json, and embeds
it in graph_def as a constant op called `__lucid_metadata_json`.
|
[
"Embed",
"meta",
"data",
"as",
"a",
"string",
"constant",
"in",
"a",
"TF",
"graph",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/modelzoo/util.py#L89-L99
|
train
|
tensorflow/lucid
|
lucid/modelzoo/util.py
|
extract_metadata
|
def extract_metadata(graph_def):
"""Attempt to extract meta data hidden in graph_def.
Looks for a `__lucid_metadata_json` constant string op.
If present, extract it's content and convert it from json to python.
If not, returns None.
"""
meta_matches = [n for n in graph_def.node if n.name==metadata_node_name]
if meta_matches:
assert len(meta_matches) == 1, "found more than 1 lucid metadata node!"
meta_tensor = meta_matches[0].attr['value'].tensor
return json.loads(meta_tensor.string_val[0])
else:
return None
|
python
|
def extract_metadata(graph_def):
"""Attempt to extract meta data hidden in graph_def.
Looks for a `__lucid_metadata_json` constant string op.
If present, extract it's content and convert it from json to python.
If not, returns None.
"""
meta_matches = [n for n in graph_def.node if n.name==metadata_node_name]
if meta_matches:
assert len(meta_matches) == 1, "found more than 1 lucid metadata node!"
meta_tensor = meta_matches[0].attr['value'].tensor
return json.loads(meta_tensor.string_val[0])
else:
return None
|
[
"def",
"extract_metadata",
"(",
"graph_def",
")",
":",
"meta_matches",
"=",
"[",
"n",
"for",
"n",
"in",
"graph_def",
".",
"node",
"if",
"n",
".",
"name",
"==",
"metadata_node_name",
"]",
"if",
"meta_matches",
":",
"assert",
"len",
"(",
"meta_matches",
")",
"==",
"1",
",",
"\"found more than 1 lucid metadata node!\"",
"meta_tensor",
"=",
"meta_matches",
"[",
"0",
"]",
".",
"attr",
"[",
"'value'",
"]",
".",
"tensor",
"return",
"json",
".",
"loads",
"(",
"meta_tensor",
".",
"string_val",
"[",
"0",
"]",
")",
"else",
":",
"return",
"None"
] |
Attempt to extract meta data hidden in graph_def.
Looks for a `__lucid_metadata_json` constant string op.
If present, extract it's content and convert it from json to python.
If not, returns None.
|
[
"Attempt",
"to",
"extract",
"meta",
"data",
"hidden",
"in",
"graph_def",
"."
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/modelzoo/util.py#L102-L115
|
train
|
tensorflow/lucid
|
lucid/modelzoo/util.py
|
GraphDefHelper.neighborhood
|
def neighborhood(self, node, degree=4):
"""Am I really handcoding graph traversal please no"""
assert self.by_name[node.name] == node
already_visited = frontier = set([node.name])
for _ in range(degree):
neighbor_names = set()
for node_name in frontier:
outgoing = set(n.name for n in self.by_input[node_name])
incoming = set(self.by_name[node_name].input)
neighbor_names |= incoming | outgoing
frontier = neighbor_names - already_visited
already_visited |= neighbor_names
return [self.by_name[name] for name in already_visited]
|
python
|
def neighborhood(self, node, degree=4):
"""Am I really handcoding graph traversal please no"""
assert self.by_name[node.name] == node
already_visited = frontier = set([node.name])
for _ in range(degree):
neighbor_names = set()
for node_name in frontier:
outgoing = set(n.name for n in self.by_input[node_name])
incoming = set(self.by_name[node_name].input)
neighbor_names |= incoming | outgoing
frontier = neighbor_names - already_visited
already_visited |= neighbor_names
return [self.by_name[name] for name in already_visited]
|
[
"def",
"neighborhood",
"(",
"self",
",",
"node",
",",
"degree",
"=",
"4",
")",
":",
"assert",
"self",
".",
"by_name",
"[",
"node",
".",
"name",
"]",
"==",
"node",
"already_visited",
"=",
"frontier",
"=",
"set",
"(",
"[",
"node",
".",
"name",
"]",
")",
"for",
"_",
"in",
"range",
"(",
"degree",
")",
":",
"neighbor_names",
"=",
"set",
"(",
")",
"for",
"node_name",
"in",
"frontier",
":",
"outgoing",
"=",
"set",
"(",
"n",
".",
"name",
"for",
"n",
"in",
"self",
".",
"by_input",
"[",
"node_name",
"]",
")",
"incoming",
"=",
"set",
"(",
"self",
".",
"by_name",
"[",
"node_name",
"]",
".",
"input",
")",
"neighbor_names",
"|=",
"incoming",
"|",
"outgoing",
"frontier",
"=",
"neighbor_names",
"-",
"already_visited",
"already_visited",
"|=",
"neighbor_names",
"return",
"[",
"self",
".",
"by_name",
"[",
"name",
"]",
"for",
"name",
"in",
"already_visited",
"]"
] |
Am I really handcoding graph traversal please no
|
[
"Am",
"I",
"really",
"handcoding",
"graph",
"traversal",
"please",
"no"
] |
d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e
|
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/modelzoo/util.py#L135-L147
|
train
|
Rapptz/discord.py
|
discord/iterators.py
|
HistoryIterator._retrieve_messages_before_strategy
|
async def _retrieve_messages_before_strategy(self, retrieve):
"""Retrieve messages using before parameter."""
before = self.before.id if self.before else None
data = await self.logs_from(self.channel.id, retrieve, before=before)
if len(data):
if self.limit is not None:
self.limit -= retrieve
self.before = Object(id=int(data[-1]['id']))
return data
|
python
|
async def _retrieve_messages_before_strategy(self, retrieve):
"""Retrieve messages using before parameter."""
before = self.before.id if self.before else None
data = await self.logs_from(self.channel.id, retrieve, before=before)
if len(data):
if self.limit is not None:
self.limit -= retrieve
self.before = Object(id=int(data[-1]['id']))
return data
|
[
"async",
"def",
"_retrieve_messages_before_strategy",
"(",
"self",
",",
"retrieve",
")",
":",
"before",
"=",
"self",
".",
"before",
".",
"id",
"if",
"self",
".",
"before",
"else",
"None",
"data",
"=",
"await",
"self",
".",
"logs_from",
"(",
"self",
".",
"channel",
".",
"id",
",",
"retrieve",
",",
"before",
"=",
"before",
")",
"if",
"len",
"(",
"data",
")",
":",
"if",
"self",
".",
"limit",
"is",
"not",
"None",
":",
"self",
".",
"limit",
"-=",
"retrieve",
"self",
".",
"before",
"=",
"Object",
"(",
"id",
"=",
"int",
"(",
"data",
"[",
"-",
"1",
"]",
"[",
"'id'",
"]",
")",
")",
"return",
"data"
] |
Retrieve messages using before parameter.
|
[
"Retrieve",
"messages",
"using",
"before",
"parameter",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/iterators.py#L325-L333
|
train
|
Rapptz/discord.py
|
discord/iterators.py
|
HistoryIterator._retrieve_messages_after_strategy
|
async def _retrieve_messages_after_strategy(self, retrieve):
"""Retrieve messages using after parameter."""
after = self.after.id if self.after else None
data = await self.logs_from(self.channel.id, retrieve, after=after)
if len(data):
if self.limit is not None:
self.limit -= retrieve
self.after = Object(id=int(data[0]['id']))
return data
|
python
|
async def _retrieve_messages_after_strategy(self, retrieve):
"""Retrieve messages using after parameter."""
after = self.after.id if self.after else None
data = await self.logs_from(self.channel.id, retrieve, after=after)
if len(data):
if self.limit is not None:
self.limit -= retrieve
self.after = Object(id=int(data[0]['id']))
return data
|
[
"async",
"def",
"_retrieve_messages_after_strategy",
"(",
"self",
",",
"retrieve",
")",
":",
"after",
"=",
"self",
".",
"after",
".",
"id",
"if",
"self",
".",
"after",
"else",
"None",
"data",
"=",
"await",
"self",
".",
"logs_from",
"(",
"self",
".",
"channel",
".",
"id",
",",
"retrieve",
",",
"after",
"=",
"after",
")",
"if",
"len",
"(",
"data",
")",
":",
"if",
"self",
".",
"limit",
"is",
"not",
"None",
":",
"self",
".",
"limit",
"-=",
"retrieve",
"self",
".",
"after",
"=",
"Object",
"(",
"id",
"=",
"int",
"(",
"data",
"[",
"0",
"]",
"[",
"'id'",
"]",
")",
")",
"return",
"data"
] |
Retrieve messages using after parameter.
|
[
"Retrieve",
"messages",
"using",
"after",
"parameter",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/iterators.py#L335-L343
|
train
|
Rapptz/discord.py
|
discord/iterators.py
|
HistoryIterator._retrieve_messages_around_strategy
|
async def _retrieve_messages_around_strategy(self, retrieve):
"""Retrieve messages using around parameter."""
if self.around:
around = self.around.id if self.around else None
data = await self.logs_from(self.channel.id, retrieve, around=around)
self.around = None
return data
return []
|
python
|
async def _retrieve_messages_around_strategy(self, retrieve):
"""Retrieve messages using around parameter."""
if self.around:
around = self.around.id if self.around else None
data = await self.logs_from(self.channel.id, retrieve, around=around)
self.around = None
return data
return []
|
[
"async",
"def",
"_retrieve_messages_around_strategy",
"(",
"self",
",",
"retrieve",
")",
":",
"if",
"self",
".",
"around",
":",
"around",
"=",
"self",
".",
"around",
".",
"id",
"if",
"self",
".",
"around",
"else",
"None",
"data",
"=",
"await",
"self",
".",
"logs_from",
"(",
"self",
".",
"channel",
".",
"id",
",",
"retrieve",
",",
"around",
"=",
"around",
")",
"self",
".",
"around",
"=",
"None",
"return",
"data",
"return",
"[",
"]"
] |
Retrieve messages using around parameter.
|
[
"Retrieve",
"messages",
"using",
"around",
"parameter",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/iterators.py#L345-L352
|
train
|
Rapptz/discord.py
|
discord/iterators.py
|
GuildIterator._retrieve_guilds_before_strategy
|
async def _retrieve_guilds_before_strategy(self, retrieve):
"""Retrieve guilds using before parameter."""
before = self.before.id if self.before else None
data = await self.get_guilds(retrieve, before=before)
if len(data):
if self.limit is not None:
self.limit -= retrieve
self.before = Object(id=int(data[-1]['id']))
return data
|
python
|
async def _retrieve_guilds_before_strategy(self, retrieve):
"""Retrieve guilds using before parameter."""
before = self.before.id if self.before else None
data = await self.get_guilds(retrieve, before=before)
if len(data):
if self.limit is not None:
self.limit -= retrieve
self.before = Object(id=int(data[-1]['id']))
return data
|
[
"async",
"def",
"_retrieve_guilds_before_strategy",
"(",
"self",
",",
"retrieve",
")",
":",
"before",
"=",
"self",
".",
"before",
".",
"id",
"if",
"self",
".",
"before",
"else",
"None",
"data",
"=",
"await",
"self",
".",
"get_guilds",
"(",
"retrieve",
",",
"before",
"=",
"before",
")",
"if",
"len",
"(",
"data",
")",
":",
"if",
"self",
".",
"limit",
"is",
"not",
"None",
":",
"self",
".",
"limit",
"-=",
"retrieve",
"self",
".",
"before",
"=",
"Object",
"(",
"id",
"=",
"int",
"(",
"data",
"[",
"-",
"1",
"]",
"[",
"'id'",
"]",
")",
")",
"return",
"data"
] |
Retrieve guilds using before parameter.
|
[
"Retrieve",
"guilds",
"using",
"before",
"parameter",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/iterators.py#L571-L579
|
train
|
Rapptz/discord.py
|
discord/iterators.py
|
GuildIterator._retrieve_guilds_after_strategy
|
async def _retrieve_guilds_after_strategy(self, retrieve):
"""Retrieve guilds using after parameter."""
after = self.after.id if self.after else None
data = await self.get_guilds(retrieve, after=after)
if len(data):
if self.limit is not None:
self.limit -= retrieve
self.after = Object(id=int(data[0]['id']))
return data
|
python
|
async def _retrieve_guilds_after_strategy(self, retrieve):
"""Retrieve guilds using after parameter."""
after = self.after.id if self.after else None
data = await self.get_guilds(retrieve, after=after)
if len(data):
if self.limit is not None:
self.limit -= retrieve
self.after = Object(id=int(data[0]['id']))
return data
|
[
"async",
"def",
"_retrieve_guilds_after_strategy",
"(",
"self",
",",
"retrieve",
")",
":",
"after",
"=",
"self",
".",
"after",
".",
"id",
"if",
"self",
".",
"after",
"else",
"None",
"data",
"=",
"await",
"self",
".",
"get_guilds",
"(",
"retrieve",
",",
"after",
"=",
"after",
")",
"if",
"len",
"(",
"data",
")",
":",
"if",
"self",
".",
"limit",
"is",
"not",
"None",
":",
"self",
".",
"limit",
"-=",
"retrieve",
"self",
".",
"after",
"=",
"Object",
"(",
"id",
"=",
"int",
"(",
"data",
"[",
"0",
"]",
"[",
"'id'",
"]",
")",
")",
"return",
"data"
] |
Retrieve guilds using after parameter.
|
[
"Retrieve",
"guilds",
"using",
"after",
"parameter",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/iterators.py#L581-L589
|
train
|
Rapptz/discord.py
|
discord/widget.py
|
Widget.fetch_invite
|
async def fetch_invite(self, *, with_counts=True):
"""|coro|
Retrieves an :class:`Invite` from a invite URL or ID.
This is the same as :meth:`Client.get_invite`; the invite
code is abstracted away.
Parameters
-----------
with_counts: :class:`bool`
Whether to include count information in the invite. This fills the
:attr:`Invite.approximate_member_count` and :attr:`Invite.approximate_presence_count`
fields.
Returns
--------
:class:`Invite`
The invite from the URL/ID.
"""
if self._invite:
invite_id = resolve_invite(self._invite)
data = await self._state.http.get_invite(invite_id, with_counts=with_counts)
return Invite.from_incomplete(state=self._state, data=data)
|
python
|
async def fetch_invite(self, *, with_counts=True):
"""|coro|
Retrieves an :class:`Invite` from a invite URL or ID.
This is the same as :meth:`Client.get_invite`; the invite
code is abstracted away.
Parameters
-----------
with_counts: :class:`bool`
Whether to include count information in the invite. This fills the
:attr:`Invite.approximate_member_count` and :attr:`Invite.approximate_presence_count`
fields.
Returns
--------
:class:`Invite`
The invite from the URL/ID.
"""
if self._invite:
invite_id = resolve_invite(self._invite)
data = await self._state.http.get_invite(invite_id, with_counts=with_counts)
return Invite.from_incomplete(state=self._state, data=data)
|
[
"async",
"def",
"fetch_invite",
"(",
"self",
",",
"*",
",",
"with_counts",
"=",
"True",
")",
":",
"if",
"self",
".",
"_invite",
":",
"invite_id",
"=",
"resolve_invite",
"(",
"self",
".",
"_invite",
")",
"data",
"=",
"await",
"self",
".",
"_state",
".",
"http",
".",
"get_invite",
"(",
"invite_id",
",",
"with_counts",
"=",
"with_counts",
")",
"return",
"Invite",
".",
"from_incomplete",
"(",
"state",
"=",
"self",
".",
"_state",
",",
"data",
"=",
"data",
")"
] |
|coro|
Retrieves an :class:`Invite` from a invite URL or ID.
This is the same as :meth:`Client.get_invite`; the invite
code is abstracted away.
Parameters
-----------
with_counts: :class:`bool`
Whether to include count information in the invite. This fills the
:attr:`Invite.approximate_member_count` and :attr:`Invite.approximate_presence_count`
fields.
Returns
--------
:class:`Invite`
The invite from the URL/ID.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/widget.py#L228-L250
|
train
|
Rapptz/discord.py
|
discord/colour.py
|
Colour.from_hsv
|
def from_hsv(cls, h, s, v):
"""Constructs a :class:`Colour` from an HSV tuple."""
rgb = colorsys.hsv_to_rgb(h, s, v)
return cls.from_rgb(*(int(x * 255) for x in rgb))
|
python
|
def from_hsv(cls, h, s, v):
"""Constructs a :class:`Colour` from an HSV tuple."""
rgb = colorsys.hsv_to_rgb(h, s, v)
return cls.from_rgb(*(int(x * 255) for x in rgb))
|
[
"def",
"from_hsv",
"(",
"cls",
",",
"h",
",",
"s",
",",
"v",
")",
":",
"rgb",
"=",
"colorsys",
".",
"hsv_to_rgb",
"(",
"h",
",",
"s",
",",
"v",
")",
"return",
"cls",
".",
"from_rgb",
"(",
"*",
"(",
"int",
"(",
"x",
"*",
"255",
")",
"for",
"x",
"in",
"rgb",
")",
")"
] |
Constructs a :class:`Colour` from an HSV tuple.
|
[
"Constructs",
"a",
":",
"class",
":",
"Colour",
"from",
"an",
"HSV",
"tuple",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/colour.py#L110-L113
|
train
|
Rapptz/discord.py
|
discord/ext/commands/cog.py
|
Cog.description
|
def description(self):
""":class:`str`: Returns the cog's description, typically the cleaned docstring."""
try:
return self.__cog_cleaned_doc__
except AttributeError:
self.__cog_cleaned_doc__ = cleaned = inspect.getdoc(self)
return cleaned
|
python
|
def description(self):
""":class:`str`: Returns the cog's description, typically the cleaned docstring."""
try:
return self.__cog_cleaned_doc__
except AttributeError:
self.__cog_cleaned_doc__ = cleaned = inspect.getdoc(self)
return cleaned
|
[
"def",
"description",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"__cog_cleaned_doc__",
"except",
"AttributeError",
":",
"self",
".",
"__cog_cleaned_doc__",
"=",
"cleaned",
"=",
"inspect",
".",
"getdoc",
"(",
"self",
")",
"return",
"cleaned"
] |
:class:`str`: Returns the cog's description, typically the cleaned docstring.
|
[
":",
"class",
":",
"str",
":",
"Returns",
"the",
"cog",
"s",
"description",
"typically",
"the",
"cleaned",
"docstring",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/cog.py#L206-L212
|
train
|
Rapptz/discord.py
|
discord/ext/commands/cog.py
|
Cog.walk_commands
|
def walk_commands(self):
"""An iterator that recursively walks through this cog's commands and subcommands."""
from .core import GroupMixin
for command in self.__cog_commands__:
if command.parent is None:
yield command
if isinstance(command, GroupMixin):
yield from command.walk_commands()
|
python
|
def walk_commands(self):
"""An iterator that recursively walks through this cog's commands and subcommands."""
from .core import GroupMixin
for command in self.__cog_commands__:
if command.parent is None:
yield command
if isinstance(command, GroupMixin):
yield from command.walk_commands()
|
[
"def",
"walk_commands",
"(",
"self",
")",
":",
"from",
".",
"core",
"import",
"GroupMixin",
"for",
"command",
"in",
"self",
".",
"__cog_commands__",
":",
"if",
"command",
".",
"parent",
"is",
"None",
":",
"yield",
"command",
"if",
"isinstance",
"(",
"command",
",",
"GroupMixin",
")",
":",
"yield",
"from",
"command",
".",
"walk_commands",
"(",
")"
] |
An iterator that recursively walks through this cog's commands and subcommands.
|
[
"An",
"iterator",
"that",
"recursively",
"walks",
"through",
"this",
"cog",
"s",
"commands",
"and",
"subcommands",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/cog.py#L214-L221
|
train
|
Rapptz/discord.py
|
discord/ext/commands/cog.py
|
Cog.get_listeners
|
def get_listeners(self):
"""Returns a :class:`list` of (name, function) listener pairs that are defined in this cog."""
return [(name, getattr(self, method_name)) for name, method_name in self.__cog_listeners__]
|
python
|
def get_listeners(self):
"""Returns a :class:`list` of (name, function) listener pairs that are defined in this cog."""
return [(name, getattr(self, method_name)) for name, method_name in self.__cog_listeners__]
|
[
"def",
"get_listeners",
"(",
"self",
")",
":",
"return",
"[",
"(",
"name",
",",
"getattr",
"(",
"self",
",",
"method_name",
")",
")",
"for",
"name",
",",
"method_name",
"in",
"self",
".",
"__cog_listeners__",
"]"
] |
Returns a :class:`list` of (name, function) listener pairs that are defined in this cog.
|
[
"Returns",
"a",
":",
"class",
":",
"list",
"of",
"(",
"name",
"function",
")",
"listener",
"pairs",
"that",
"are",
"defined",
"in",
"this",
"cog",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/cog.py#L223-L225
|
train
|
Rapptz/discord.py
|
discord/ext/commands/cog.py
|
Cog.listener
|
def listener(cls, name=None):
"""A decorator that marks a function as a listener.
This is the cog equivalent of :meth:`.Bot.listen`.
Parameters
------------
name: :class:`str`
The name of the event being listened to. If not provided, it
defaults to the function's name.
Raises
--------
TypeError
The function is not a coroutine function or a string was not passed as
the name.
"""
if name is not None and not isinstance(name, str):
raise TypeError('Cog.listener expected str but received {0.__class__.__name__!r} instead.'.format(name))
def decorator(func):
actual = func
if isinstance(actual, staticmethod):
actual = actual.__func__
if not inspect.iscoroutinefunction(actual):
raise TypeError('Listener function must be a coroutine function.')
actual.__cog_listener__ = True
to_assign = name or actual.__name__
try:
actual.__cog_listener_names__.append(to_assign)
except AttributeError:
actual.__cog_listener_names__ = [to_assign]
# we have to return `func` instead of `actual` because
# we need the type to be `staticmethod` for the metaclass
# to pick it up but the metaclass unfurls the function and
# thus the assignments need to be on the actual function
return func
return decorator
|
python
|
def listener(cls, name=None):
"""A decorator that marks a function as a listener.
This is the cog equivalent of :meth:`.Bot.listen`.
Parameters
------------
name: :class:`str`
The name of the event being listened to. If not provided, it
defaults to the function's name.
Raises
--------
TypeError
The function is not a coroutine function or a string was not passed as
the name.
"""
if name is not None and not isinstance(name, str):
raise TypeError('Cog.listener expected str but received {0.__class__.__name__!r} instead.'.format(name))
def decorator(func):
actual = func
if isinstance(actual, staticmethod):
actual = actual.__func__
if not inspect.iscoroutinefunction(actual):
raise TypeError('Listener function must be a coroutine function.')
actual.__cog_listener__ = True
to_assign = name or actual.__name__
try:
actual.__cog_listener_names__.append(to_assign)
except AttributeError:
actual.__cog_listener_names__ = [to_assign]
# we have to return `func` instead of `actual` because
# we need the type to be `staticmethod` for the metaclass
# to pick it up but the metaclass unfurls the function and
# thus the assignments need to be on the actual function
return func
return decorator
|
[
"def",
"listener",
"(",
"cls",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"name",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"'Cog.listener expected str but received {0.__class__.__name__!r} instead.'",
".",
"format",
"(",
"name",
")",
")",
"def",
"decorator",
"(",
"func",
")",
":",
"actual",
"=",
"func",
"if",
"isinstance",
"(",
"actual",
",",
"staticmethod",
")",
":",
"actual",
"=",
"actual",
".",
"__func__",
"if",
"not",
"inspect",
".",
"iscoroutinefunction",
"(",
"actual",
")",
":",
"raise",
"TypeError",
"(",
"'Listener function must be a coroutine function.'",
")",
"actual",
".",
"__cog_listener__",
"=",
"True",
"to_assign",
"=",
"name",
"or",
"actual",
".",
"__name__",
"try",
":",
"actual",
".",
"__cog_listener_names__",
".",
"append",
"(",
"to_assign",
")",
"except",
"AttributeError",
":",
"actual",
".",
"__cog_listener_names__",
"=",
"[",
"to_assign",
"]",
"# we have to return `func` instead of `actual` because",
"# we need the type to be `staticmethod` for the metaclass",
"# to pick it up but the metaclass unfurls the function and",
"# thus the assignments need to be on the actual function",
"return",
"func",
"return",
"decorator"
] |
A decorator that marks a function as a listener.
This is the cog equivalent of :meth:`.Bot.listen`.
Parameters
------------
name: :class:`str`
The name of the event being listened to. If not provided, it
defaults to the function's name.
Raises
--------
TypeError
The function is not a coroutine function or a string was not passed as
the name.
|
[
"A",
"decorator",
"that",
"marks",
"a",
"function",
"as",
"a",
"listener",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/cog.py#L233-L271
|
train
|
Rapptz/discord.py
|
discord/embeds.py
|
Embed.set_footer
|
def set_footer(self, *, text=EmptyEmbed, icon_url=EmptyEmbed):
"""Sets the footer for the embed content.
This function returns the class instance to allow for fluent-style
chaining.
Parameters
-----------
text: :class:`str`
The footer text.
icon_url: :class:`str`
The URL of the footer icon. Only HTTP(S) is supported.
"""
self._footer = {}
if text is not EmptyEmbed:
self._footer['text'] = str(text)
if icon_url is not EmptyEmbed:
self._footer['icon_url'] = str(icon_url)
return self
|
python
|
def set_footer(self, *, text=EmptyEmbed, icon_url=EmptyEmbed):
"""Sets the footer for the embed content.
This function returns the class instance to allow for fluent-style
chaining.
Parameters
-----------
text: :class:`str`
The footer text.
icon_url: :class:`str`
The URL of the footer icon. Only HTTP(S) is supported.
"""
self._footer = {}
if text is not EmptyEmbed:
self._footer['text'] = str(text)
if icon_url is not EmptyEmbed:
self._footer['icon_url'] = str(icon_url)
return self
|
[
"def",
"set_footer",
"(",
"self",
",",
"*",
",",
"text",
"=",
"EmptyEmbed",
",",
"icon_url",
"=",
"EmptyEmbed",
")",
":",
"self",
".",
"_footer",
"=",
"{",
"}",
"if",
"text",
"is",
"not",
"EmptyEmbed",
":",
"self",
".",
"_footer",
"[",
"'text'",
"]",
"=",
"str",
"(",
"text",
")",
"if",
"icon_url",
"is",
"not",
"EmptyEmbed",
":",
"self",
".",
"_footer",
"[",
"'icon_url'",
"]",
"=",
"str",
"(",
"icon_url",
")",
"return",
"self"
] |
Sets the footer for the embed content.
This function returns the class instance to allow for fluent-style
chaining.
Parameters
-----------
text: :class:`str`
The footer text.
icon_url: :class:`str`
The URL of the footer icon. Only HTTP(S) is supported.
|
[
"Sets",
"the",
"footer",
"for",
"the",
"embed",
"content",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/embeds.py#L233-L254
|
train
|
Rapptz/discord.py
|
discord/embeds.py
|
Embed.set_author
|
def set_author(self, *, name, url=EmptyEmbed, icon_url=EmptyEmbed):
"""Sets the author for the embed content.
This function returns the class instance to allow for fluent-style
chaining.
Parameters
-----------
name: :class:`str`
The name of the author.
url: :class:`str`
The URL for the author.
icon_url: :class:`str`
The URL of the author icon. Only HTTP(S) is supported.
"""
self._author = {
'name': str(name)
}
if url is not EmptyEmbed:
self._author['url'] = str(url)
if icon_url is not EmptyEmbed:
self._author['icon_url'] = str(icon_url)
return self
|
python
|
def set_author(self, *, name, url=EmptyEmbed, icon_url=EmptyEmbed):
"""Sets the author for the embed content.
This function returns the class instance to allow for fluent-style
chaining.
Parameters
-----------
name: :class:`str`
The name of the author.
url: :class:`str`
The URL for the author.
icon_url: :class:`str`
The URL of the author icon. Only HTTP(S) is supported.
"""
self._author = {
'name': str(name)
}
if url is not EmptyEmbed:
self._author['url'] = str(url)
if icon_url is not EmptyEmbed:
self._author['icon_url'] = str(icon_url)
return self
|
[
"def",
"set_author",
"(",
"self",
",",
"*",
",",
"name",
",",
"url",
"=",
"EmptyEmbed",
",",
"icon_url",
"=",
"EmptyEmbed",
")",
":",
"self",
".",
"_author",
"=",
"{",
"'name'",
":",
"str",
"(",
"name",
")",
"}",
"if",
"url",
"is",
"not",
"EmptyEmbed",
":",
"self",
".",
"_author",
"[",
"'url'",
"]",
"=",
"str",
"(",
"url",
")",
"if",
"icon_url",
"is",
"not",
"EmptyEmbed",
":",
"self",
".",
"_author",
"[",
"'icon_url'",
"]",
"=",
"str",
"(",
"icon_url",
")",
"return",
"self"
] |
Sets the author for the embed content.
This function returns the class instance to allow for fluent-style
chaining.
Parameters
-----------
name: :class:`str`
The name of the author.
url: :class:`str`
The URL for the author.
icon_url: :class:`str`
The URL of the author icon. Only HTTP(S) is supported.
|
[
"Sets",
"the",
"author",
"for",
"the",
"embed",
"content",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/embeds.py#L356-L382
|
train
|
Rapptz/discord.py
|
discord/embeds.py
|
Embed.add_field
|
def add_field(self, *, name, value, inline=True):
"""Adds a field to the embed object.
This function returns the class instance to allow for fluent-style
chaining.
Parameters
-----------
name: :class:`str`
The name of the field.
value: :class:`str`
The value of the field.
inline: :class:`bool`
Whether the field should be displayed inline.
"""
field = {
'inline': inline,
'name': str(name),
'value': str(value)
}
try:
self._fields.append(field)
except AttributeError:
self._fields = [field]
return self
|
python
|
def add_field(self, *, name, value, inline=True):
"""Adds a field to the embed object.
This function returns the class instance to allow for fluent-style
chaining.
Parameters
-----------
name: :class:`str`
The name of the field.
value: :class:`str`
The value of the field.
inline: :class:`bool`
Whether the field should be displayed inline.
"""
field = {
'inline': inline,
'name': str(name),
'value': str(value)
}
try:
self._fields.append(field)
except AttributeError:
self._fields = [field]
return self
|
[
"def",
"add_field",
"(",
"self",
",",
"*",
",",
"name",
",",
"value",
",",
"inline",
"=",
"True",
")",
":",
"field",
"=",
"{",
"'inline'",
":",
"inline",
",",
"'name'",
":",
"str",
"(",
"name",
")",
",",
"'value'",
":",
"str",
"(",
"value",
")",
"}",
"try",
":",
"self",
".",
"_fields",
".",
"append",
"(",
"field",
")",
"except",
"AttributeError",
":",
"self",
".",
"_fields",
"=",
"[",
"field",
"]",
"return",
"self"
] |
Adds a field to the embed object.
This function returns the class instance to allow for fluent-style
chaining.
Parameters
-----------
name: :class:`str`
The name of the field.
value: :class:`str`
The value of the field.
inline: :class:`bool`
Whether the field should be displayed inline.
|
[
"Adds",
"a",
"field",
"to",
"the",
"embed",
"object",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/embeds.py#L394-L421
|
train
|
Rapptz/discord.py
|
discord/embeds.py
|
Embed.set_field_at
|
def set_field_at(self, index, *, name, value, inline=True):
"""Modifies a field to the embed object.
The index must point to a valid pre-existing field.
This function returns the class instance to allow for fluent-style
chaining.
Parameters
-----------
index: :class:`int`
The index of the field to modify.
name: :class:`str`
The name of the field.
value: :class:`str`
The value of the field.
inline: :class:`bool`
Whether the field should be displayed inline.
Raises
-------
IndexError
An invalid index was provided.
"""
try:
field = self._fields[index]
except (TypeError, IndexError, AttributeError):
raise IndexError('field index out of range')
field['name'] = str(name)
field['value'] = str(value)
field['inline'] = inline
return self
|
python
|
def set_field_at(self, index, *, name, value, inline=True):
"""Modifies a field to the embed object.
The index must point to a valid pre-existing field.
This function returns the class instance to allow for fluent-style
chaining.
Parameters
-----------
index: :class:`int`
The index of the field to modify.
name: :class:`str`
The name of the field.
value: :class:`str`
The value of the field.
inline: :class:`bool`
Whether the field should be displayed inline.
Raises
-------
IndexError
An invalid index was provided.
"""
try:
field = self._fields[index]
except (TypeError, IndexError, AttributeError):
raise IndexError('field index out of range')
field['name'] = str(name)
field['value'] = str(value)
field['inline'] = inline
return self
|
[
"def",
"set_field_at",
"(",
"self",
",",
"index",
",",
"*",
",",
"name",
",",
"value",
",",
"inline",
"=",
"True",
")",
":",
"try",
":",
"field",
"=",
"self",
".",
"_fields",
"[",
"index",
"]",
"except",
"(",
"TypeError",
",",
"IndexError",
",",
"AttributeError",
")",
":",
"raise",
"IndexError",
"(",
"'field index out of range'",
")",
"field",
"[",
"'name'",
"]",
"=",
"str",
"(",
"name",
")",
"field",
"[",
"'value'",
"]",
"=",
"str",
"(",
"value",
")",
"field",
"[",
"'inline'",
"]",
"=",
"inline",
"return",
"self"
] |
Modifies a field to the embed object.
The index must point to a valid pre-existing field.
This function returns the class instance to allow for fluent-style
chaining.
Parameters
-----------
index: :class:`int`
The index of the field to modify.
name: :class:`str`
The name of the field.
value: :class:`str`
The value of the field.
inline: :class:`bool`
Whether the field should be displayed inline.
Raises
-------
IndexError
An invalid index was provided.
|
[
"Modifies",
"a",
"field",
"to",
"the",
"embed",
"object",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/embeds.py#L451-L484
|
train
|
Rapptz/discord.py
|
discord/embeds.py
|
Embed.to_dict
|
def to_dict(self):
"""Converts this embed object into a dict."""
# add in the raw data into the dict
result = {
key[1:]: getattr(self, key)
for key in self.__slots__
if key[0] == '_' and hasattr(self, key)
}
# deal with basic convenience wrappers
try:
colour = result.pop('colour')
except KeyError:
pass
else:
if colour:
result['color'] = colour.value
try:
timestamp = result.pop('timestamp')
except KeyError:
pass
else:
if timestamp:
if timestamp.tzinfo:
result['timestamp'] = timestamp.astimezone(tz=datetime.timezone.utc).isoformat()
else:
result['timestamp'] = timestamp.replace(tzinfo=datetime.timezone.utc).isoformat()
# add in the non raw attribute ones
if self.type:
result['type'] = self.type
if self.description:
result['description'] = self.description
if self.url:
result['url'] = self.url
if self.title:
result['title'] = self.title
return result
|
python
|
def to_dict(self):
"""Converts this embed object into a dict."""
# add in the raw data into the dict
result = {
key[1:]: getattr(self, key)
for key in self.__slots__
if key[0] == '_' and hasattr(self, key)
}
# deal with basic convenience wrappers
try:
colour = result.pop('colour')
except KeyError:
pass
else:
if colour:
result['color'] = colour.value
try:
timestamp = result.pop('timestamp')
except KeyError:
pass
else:
if timestamp:
if timestamp.tzinfo:
result['timestamp'] = timestamp.astimezone(tz=datetime.timezone.utc).isoformat()
else:
result['timestamp'] = timestamp.replace(tzinfo=datetime.timezone.utc).isoformat()
# add in the non raw attribute ones
if self.type:
result['type'] = self.type
if self.description:
result['description'] = self.description
if self.url:
result['url'] = self.url
if self.title:
result['title'] = self.title
return result
|
[
"def",
"to_dict",
"(",
"self",
")",
":",
"# add in the raw data into the dict",
"result",
"=",
"{",
"key",
"[",
"1",
":",
"]",
":",
"getattr",
"(",
"self",
",",
"key",
")",
"for",
"key",
"in",
"self",
".",
"__slots__",
"if",
"key",
"[",
"0",
"]",
"==",
"'_'",
"and",
"hasattr",
"(",
"self",
",",
"key",
")",
"}",
"# deal with basic convenience wrappers",
"try",
":",
"colour",
"=",
"result",
".",
"pop",
"(",
"'colour'",
")",
"except",
"KeyError",
":",
"pass",
"else",
":",
"if",
"colour",
":",
"result",
"[",
"'color'",
"]",
"=",
"colour",
".",
"value",
"try",
":",
"timestamp",
"=",
"result",
".",
"pop",
"(",
"'timestamp'",
")",
"except",
"KeyError",
":",
"pass",
"else",
":",
"if",
"timestamp",
":",
"if",
"timestamp",
".",
"tzinfo",
":",
"result",
"[",
"'timestamp'",
"]",
"=",
"timestamp",
".",
"astimezone",
"(",
"tz",
"=",
"datetime",
".",
"timezone",
".",
"utc",
")",
".",
"isoformat",
"(",
")",
"else",
":",
"result",
"[",
"'timestamp'",
"]",
"=",
"timestamp",
".",
"replace",
"(",
"tzinfo",
"=",
"datetime",
".",
"timezone",
".",
"utc",
")",
".",
"isoformat",
"(",
")",
"# add in the non raw attribute ones",
"if",
"self",
".",
"type",
":",
"result",
"[",
"'type'",
"]",
"=",
"self",
".",
"type",
"if",
"self",
".",
"description",
":",
"result",
"[",
"'description'",
"]",
"=",
"self",
".",
"description",
"if",
"self",
".",
"url",
":",
"result",
"[",
"'url'",
"]",
"=",
"self",
".",
"url",
"if",
"self",
".",
"title",
":",
"result",
"[",
"'title'",
"]",
"=",
"self",
".",
"title",
"return",
"result"
] |
Converts this embed object into a dict.
|
[
"Converts",
"this",
"embed",
"object",
"into",
"a",
"dict",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/embeds.py#L486-L530
|
train
|
Rapptz/discord.py
|
discord/user.py
|
BaseUser.avatar_url_as
|
def avatar_url_as(self, *, format=None, static_format='webp', size=1024):
"""Returns a friendly URL version of the avatar the user has.
If the user does not have a traditional avatar, their default
avatar URL is returned instead.
The format must be one of 'webp', 'jpeg', 'jpg', 'png' or 'gif', and
'gif' is only valid for animated avatars. The size must be a power of 2
between 16 and 1024.
Parameters
-----------
format: Optional[:class:`str`]
The format to attempt to convert the avatar to.
If the format is ``None``, then it is automatically
detected into either 'gif' or static_format depending on the
avatar being animated or not.
static_format: Optional[:class:`str`]
Format to attempt to convert only non-animated avatars to.
Defaults to 'webp'
size: :class:`int`
The size of the image to display.
Raises
------
InvalidArgument
Bad image format passed to ``format`` or ``static_format``, or
invalid ``size``.
Returns
--------
:class:`Asset`
The resulting CDN asset.
"""
return Asset._from_avatar(self._state, self, format=format, static_format=static_format, size=size)
|
python
|
def avatar_url_as(self, *, format=None, static_format='webp', size=1024):
"""Returns a friendly URL version of the avatar the user has.
If the user does not have a traditional avatar, their default
avatar URL is returned instead.
The format must be one of 'webp', 'jpeg', 'jpg', 'png' or 'gif', and
'gif' is only valid for animated avatars. The size must be a power of 2
between 16 and 1024.
Parameters
-----------
format: Optional[:class:`str`]
The format to attempt to convert the avatar to.
If the format is ``None``, then it is automatically
detected into either 'gif' or static_format depending on the
avatar being animated or not.
static_format: Optional[:class:`str`]
Format to attempt to convert only non-animated avatars to.
Defaults to 'webp'
size: :class:`int`
The size of the image to display.
Raises
------
InvalidArgument
Bad image format passed to ``format`` or ``static_format``, or
invalid ``size``.
Returns
--------
:class:`Asset`
The resulting CDN asset.
"""
return Asset._from_avatar(self._state, self, format=format, static_format=static_format, size=size)
|
[
"def",
"avatar_url_as",
"(",
"self",
",",
"*",
",",
"format",
"=",
"None",
",",
"static_format",
"=",
"'webp'",
",",
"size",
"=",
"1024",
")",
":",
"return",
"Asset",
".",
"_from_avatar",
"(",
"self",
".",
"_state",
",",
"self",
",",
"format",
"=",
"format",
",",
"static_format",
"=",
"static_format",
",",
"size",
"=",
"size",
")"
] |
Returns a friendly URL version of the avatar the user has.
If the user does not have a traditional avatar, their default
avatar URL is returned instead.
The format must be one of 'webp', 'jpeg', 'jpg', 'png' or 'gif', and
'gif' is only valid for animated avatars. The size must be a power of 2
between 16 and 1024.
Parameters
-----------
format: Optional[:class:`str`]
The format to attempt to convert the avatar to.
If the format is ``None``, then it is automatically
detected into either 'gif' or static_format depending on the
avatar being animated or not.
static_format: Optional[:class:`str`]
Format to attempt to convert only non-animated avatars to.
Defaults to 'webp'
size: :class:`int`
The size of the image to display.
Raises
------
InvalidArgument
Bad image format passed to ``format`` or ``static_format``, or
invalid ``size``.
Returns
--------
:class:`Asset`
The resulting CDN asset.
|
[
"Returns",
"a",
"friendly",
"URL",
"version",
"of",
"the",
"avatar",
"the",
"user",
"has",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/user.py#L131-L165
|
train
|
Rapptz/discord.py
|
discord/user.py
|
BaseUser.mentioned_in
|
def mentioned_in(self, message):
"""Checks if the user is mentioned in the specified message.
Parameters
-----------
message: :class:`Message`
The message to check if you're mentioned in.
"""
if message.mention_everyone:
return True
for user in message.mentions:
if user.id == self.id:
return True
return False
|
python
|
def mentioned_in(self, message):
"""Checks if the user is mentioned in the specified message.
Parameters
-----------
message: :class:`Message`
The message to check if you're mentioned in.
"""
if message.mention_everyone:
return True
for user in message.mentions:
if user.id == self.id:
return True
return False
|
[
"def",
"mentioned_in",
"(",
"self",
",",
"message",
")",
":",
"if",
"message",
".",
"mention_everyone",
":",
"return",
"True",
"for",
"user",
"in",
"message",
".",
"mentions",
":",
"if",
"user",
".",
"id",
"==",
"self",
".",
"id",
":",
"return",
"True",
"return",
"False"
] |
Checks if the user is mentioned in the specified message.
Parameters
-----------
message: :class:`Message`
The message to check if you're mentioned in.
|
[
"Checks",
"if",
"the",
"user",
"is",
"mentioned",
"in",
"the",
"specified",
"message",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/user.py#L226-L242
|
train
|
Rapptz/discord.py
|
discord/user.py
|
ClientUser.friends
|
def friends(self):
r"""Returns a :class:`list` of :class:`User`\s that the user is friends with.
.. note::
This only applies to non-bot accounts.
"""
return [r.user for r in self._relationships.values() if r.type is RelationshipType.friend]
|
python
|
def friends(self):
r"""Returns a :class:`list` of :class:`User`\s that the user is friends with.
.. note::
This only applies to non-bot accounts.
"""
return [r.user for r in self._relationships.values() if r.type is RelationshipType.friend]
|
[
"def",
"friends",
"(",
"self",
")",
":",
"return",
"[",
"r",
".",
"user",
"for",
"r",
"in",
"self",
".",
"_relationships",
".",
"values",
"(",
")",
"if",
"r",
".",
"type",
"is",
"RelationshipType",
".",
"friend",
"]"
] |
r"""Returns a :class:`list` of :class:`User`\s that the user is friends with.
.. note::
This only applies to non-bot accounts.
|
[
"r",
"Returns",
"a",
":",
"class",
":",
"list",
"of",
":",
"class",
":",
"User",
"\\",
"s",
"that",
"the",
"user",
"is",
"friends",
"with",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/user.py#L342-L349
|
train
|
Rapptz/discord.py
|
discord/user.py
|
ClientUser.blocked
|
def blocked(self):
r"""Returns a :class:`list` of :class:`User`\s that the user has blocked.
.. note::
This only applies to non-bot accounts.
"""
return [r.user for r in self._relationships.values() if r.type is RelationshipType.blocked]
|
python
|
def blocked(self):
r"""Returns a :class:`list` of :class:`User`\s that the user has blocked.
.. note::
This only applies to non-bot accounts.
"""
return [r.user for r in self._relationships.values() if r.type is RelationshipType.blocked]
|
[
"def",
"blocked",
"(",
"self",
")",
":",
"return",
"[",
"r",
".",
"user",
"for",
"r",
"in",
"self",
".",
"_relationships",
".",
"values",
"(",
")",
"if",
"r",
".",
"type",
"is",
"RelationshipType",
".",
"blocked",
"]"
] |
r"""Returns a :class:`list` of :class:`User`\s that the user has blocked.
.. note::
This only applies to non-bot accounts.
|
[
"r",
"Returns",
"a",
":",
"class",
":",
"list",
"of",
":",
"class",
":",
"User",
"\\",
"s",
"that",
"the",
"user",
"has",
"blocked",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/user.py#L352-L359
|
train
|
Rapptz/discord.py
|
discord/user.py
|
ClientUser.edit
|
async def edit(self, **fields):
"""|coro|
Edits the current profile of the client.
If a bot account is used then a password field is optional,
otherwise it is required.
Note
-----
To upload an avatar, a :term:`py:bytes-like object` must be passed in that
represents the image being uploaded. If this is done through a file
then the file must be opened via ``open('some_filename', 'rb')`` and
the :term:`py:bytes-like object` is given through the use of ``fp.read()``.
The only image formats supported for uploading is JPEG and PNG.
Parameters
-----------
password: :class:`str`
The current password for the client's account.
Only applicable to user accounts.
new_password: :class:`str`
The new password you wish to change to.
Only applicable to user accounts.
email: :class:`str`
The new email you wish to change to.
Only applicable to user accounts.
house: Optional[:class:`HypeSquadHouse`]
The hypesquad house you wish to change to.
Could be ``None`` to leave the current house.
Only applicable to user accounts.
username: :class:`str`
The new username you wish to change to.
avatar: :class:`bytes`
A :term:`py:bytes-like object` representing the image to upload.
Could be ``None`` to denote no avatar.
Raises
------
HTTPException
Editing your profile failed.
InvalidArgument
Wrong image format passed for ``avatar``.
ClientException
Password is required for non-bot accounts.
House field was not a HypeSquadHouse.
"""
try:
avatar_bytes = fields['avatar']
except KeyError:
avatar = self.avatar
else:
if avatar_bytes is not None:
avatar = _bytes_to_base64_data(avatar_bytes)
else:
avatar = None
not_bot_account = not self.bot
password = fields.get('password')
if not_bot_account and password is None:
raise ClientException('Password is required for non-bot accounts.')
args = {
'password': password,
'username': fields.get('username', self.name),
'avatar': avatar
}
if not_bot_account:
args['email'] = fields.get('email', self.email)
if 'new_password' in fields:
args['new_password'] = fields['new_password']
http = self._state.http
if 'house' in fields:
house = fields['house']
if house is None:
await http.leave_hypesquad_house()
elif not isinstance(house, HypeSquadHouse):
raise ClientException('`house` parameter was not a HypeSquadHouse')
else:
value = house.value
await http.change_hypesquad_house(value)
data = await http.edit_profile(**args)
if not_bot_account:
self.email = data['email']
try:
http._token(data['token'], bot=False)
except KeyError:
pass
self._update(data)
|
python
|
async def edit(self, **fields):
"""|coro|
Edits the current profile of the client.
If a bot account is used then a password field is optional,
otherwise it is required.
Note
-----
To upload an avatar, a :term:`py:bytes-like object` must be passed in that
represents the image being uploaded. If this is done through a file
then the file must be opened via ``open('some_filename', 'rb')`` and
the :term:`py:bytes-like object` is given through the use of ``fp.read()``.
The only image formats supported for uploading is JPEG and PNG.
Parameters
-----------
password: :class:`str`
The current password for the client's account.
Only applicable to user accounts.
new_password: :class:`str`
The new password you wish to change to.
Only applicable to user accounts.
email: :class:`str`
The new email you wish to change to.
Only applicable to user accounts.
house: Optional[:class:`HypeSquadHouse`]
The hypesquad house you wish to change to.
Could be ``None`` to leave the current house.
Only applicable to user accounts.
username: :class:`str`
The new username you wish to change to.
avatar: :class:`bytes`
A :term:`py:bytes-like object` representing the image to upload.
Could be ``None`` to denote no avatar.
Raises
------
HTTPException
Editing your profile failed.
InvalidArgument
Wrong image format passed for ``avatar``.
ClientException
Password is required for non-bot accounts.
House field was not a HypeSquadHouse.
"""
try:
avatar_bytes = fields['avatar']
except KeyError:
avatar = self.avatar
else:
if avatar_bytes is not None:
avatar = _bytes_to_base64_data(avatar_bytes)
else:
avatar = None
not_bot_account = not self.bot
password = fields.get('password')
if not_bot_account and password is None:
raise ClientException('Password is required for non-bot accounts.')
args = {
'password': password,
'username': fields.get('username', self.name),
'avatar': avatar
}
if not_bot_account:
args['email'] = fields.get('email', self.email)
if 'new_password' in fields:
args['new_password'] = fields['new_password']
http = self._state.http
if 'house' in fields:
house = fields['house']
if house is None:
await http.leave_hypesquad_house()
elif not isinstance(house, HypeSquadHouse):
raise ClientException('`house` parameter was not a HypeSquadHouse')
else:
value = house.value
await http.change_hypesquad_house(value)
data = await http.edit_profile(**args)
if not_bot_account:
self.email = data['email']
try:
http._token(data['token'], bot=False)
except KeyError:
pass
self._update(data)
|
[
"async",
"def",
"edit",
"(",
"self",
",",
"*",
"*",
"fields",
")",
":",
"try",
":",
"avatar_bytes",
"=",
"fields",
"[",
"'avatar'",
"]",
"except",
"KeyError",
":",
"avatar",
"=",
"self",
".",
"avatar",
"else",
":",
"if",
"avatar_bytes",
"is",
"not",
"None",
":",
"avatar",
"=",
"_bytes_to_base64_data",
"(",
"avatar_bytes",
")",
"else",
":",
"avatar",
"=",
"None",
"not_bot_account",
"=",
"not",
"self",
".",
"bot",
"password",
"=",
"fields",
".",
"get",
"(",
"'password'",
")",
"if",
"not_bot_account",
"and",
"password",
"is",
"None",
":",
"raise",
"ClientException",
"(",
"'Password is required for non-bot accounts.'",
")",
"args",
"=",
"{",
"'password'",
":",
"password",
",",
"'username'",
":",
"fields",
".",
"get",
"(",
"'username'",
",",
"self",
".",
"name",
")",
",",
"'avatar'",
":",
"avatar",
"}",
"if",
"not_bot_account",
":",
"args",
"[",
"'email'",
"]",
"=",
"fields",
".",
"get",
"(",
"'email'",
",",
"self",
".",
"email",
")",
"if",
"'new_password'",
"in",
"fields",
":",
"args",
"[",
"'new_password'",
"]",
"=",
"fields",
"[",
"'new_password'",
"]",
"http",
"=",
"self",
".",
"_state",
".",
"http",
"if",
"'house'",
"in",
"fields",
":",
"house",
"=",
"fields",
"[",
"'house'",
"]",
"if",
"house",
"is",
"None",
":",
"await",
"http",
".",
"leave_hypesquad_house",
"(",
")",
"elif",
"not",
"isinstance",
"(",
"house",
",",
"HypeSquadHouse",
")",
":",
"raise",
"ClientException",
"(",
"'`house` parameter was not a HypeSquadHouse'",
")",
"else",
":",
"value",
"=",
"house",
".",
"value",
"await",
"http",
".",
"change_hypesquad_house",
"(",
"value",
")",
"data",
"=",
"await",
"http",
".",
"edit_profile",
"(",
"*",
"*",
"args",
")",
"if",
"not_bot_account",
":",
"self",
".",
"email",
"=",
"data",
"[",
"'email'",
"]",
"try",
":",
"http",
".",
"_token",
"(",
"data",
"[",
"'token'",
"]",
",",
"bot",
"=",
"False",
")",
"except",
"KeyError",
":",
"pass",
"self",
".",
"_update",
"(",
"data",
")"
] |
|coro|
Edits the current profile of the client.
If a bot account is used then a password field is optional,
otherwise it is required.
Note
-----
To upload an avatar, a :term:`py:bytes-like object` must be passed in that
represents the image being uploaded. If this is done through a file
then the file must be opened via ``open('some_filename', 'rb')`` and
the :term:`py:bytes-like object` is given through the use of ``fp.read()``.
The only image formats supported for uploading is JPEG and PNG.
Parameters
-----------
password: :class:`str`
The current password for the client's account.
Only applicable to user accounts.
new_password: :class:`str`
The new password you wish to change to.
Only applicable to user accounts.
email: :class:`str`
The new email you wish to change to.
Only applicable to user accounts.
house: Optional[:class:`HypeSquadHouse`]
The hypesquad house you wish to change to.
Could be ``None`` to leave the current house.
Only applicable to user accounts.
username: :class:`str`
The new username you wish to change to.
avatar: :class:`bytes`
A :term:`py:bytes-like object` representing the image to upload.
Could be ``None`` to denote no avatar.
Raises
------
HTTPException
Editing your profile failed.
InvalidArgument
Wrong image format passed for ``avatar``.
ClientException
Password is required for non-bot accounts.
House field was not a HypeSquadHouse.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/user.py#L361-L458
|
train
|
Rapptz/discord.py
|
discord/user.py
|
ClientUser.create_group
|
async def create_group(self, *recipients):
r"""|coro|
Creates a group direct message with the recipients
provided. These recipients must be have a relationship
of type :attr:`RelationshipType.friend`.
.. note::
This only applies to non-bot accounts.
Parameters
-----------
\*recipients: :class:`User`
An argument :class:`list` of :class:`User` to have in
your group.
Raises
-------
HTTPException
Failed to create the group direct message.
ClientException
Attempted to create a group with only one recipient.
This does not include yourself.
Returns
-------
:class:`GroupChannel`
The new group channel.
"""
from .channel import GroupChannel
if len(recipients) < 2:
raise ClientException('You must have two or more recipients to create a group.')
users = [str(u.id) for u in recipients]
data = await self._state.http.start_group(self.id, users)
return GroupChannel(me=self, data=data, state=self._state)
|
python
|
async def create_group(self, *recipients):
r"""|coro|
Creates a group direct message with the recipients
provided. These recipients must be have a relationship
of type :attr:`RelationshipType.friend`.
.. note::
This only applies to non-bot accounts.
Parameters
-----------
\*recipients: :class:`User`
An argument :class:`list` of :class:`User` to have in
your group.
Raises
-------
HTTPException
Failed to create the group direct message.
ClientException
Attempted to create a group with only one recipient.
This does not include yourself.
Returns
-------
:class:`GroupChannel`
The new group channel.
"""
from .channel import GroupChannel
if len(recipients) < 2:
raise ClientException('You must have two or more recipients to create a group.')
users = [str(u.id) for u in recipients]
data = await self._state.http.start_group(self.id, users)
return GroupChannel(me=self, data=data, state=self._state)
|
[
"async",
"def",
"create_group",
"(",
"self",
",",
"*",
"recipients",
")",
":",
"from",
".",
"channel",
"import",
"GroupChannel",
"if",
"len",
"(",
"recipients",
")",
"<",
"2",
":",
"raise",
"ClientException",
"(",
"'You must have two or more recipients to create a group.'",
")",
"users",
"=",
"[",
"str",
"(",
"u",
".",
"id",
")",
"for",
"u",
"in",
"recipients",
"]",
"data",
"=",
"await",
"self",
".",
"_state",
".",
"http",
".",
"start_group",
"(",
"self",
".",
"id",
",",
"users",
")",
"return",
"GroupChannel",
"(",
"me",
"=",
"self",
",",
"data",
"=",
"data",
",",
"state",
"=",
"self",
".",
"_state",
")"
] |
r"""|coro|
Creates a group direct message with the recipients
provided. These recipients must be have a relationship
of type :attr:`RelationshipType.friend`.
.. note::
This only applies to non-bot accounts.
Parameters
-----------
\*recipients: :class:`User`
An argument :class:`list` of :class:`User` to have in
your group.
Raises
-------
HTTPException
Failed to create the group direct message.
ClientException
Attempted to create a group with only one recipient.
This does not include yourself.
Returns
-------
:class:`GroupChannel`
The new group channel.
|
[
"r",
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/user.py#L460-L498
|
train
|
Rapptz/discord.py
|
discord/user.py
|
ClientUser.edit_settings
|
async def edit_settings(self, **kwargs):
"""|coro|
Edits the client user's settings.
.. note::
This only applies to non-bot accounts.
Parameters
-------
afk_timeout: :class:`int`
How long (in seconds) the user needs to be AFK until Discord
sends push notifications to your mobile device.
animate_emojis: :class:`bool`
Whether or not to animate emojis in the chat.
convert_emoticons: :class:`bool`
Whether or not to automatically convert emoticons into emojis.
e.g. :-) -> 😃
default_guilds_restricted: :class:`bool`
Whether or not to automatically disable DMs between you and
members of new guilds you join.
detect_platform_accounts: :class:`bool`
Whether or not to automatically detect accounts from services
like Steam and Blizzard when you open the Discord client.
developer_mode: :class:`bool`
Whether or not to enable developer mode.
disable_games_tab: :class:`bool`
Whether or not to disable the showing of the Games tab.
enable_tts_command: :class:`bool`
Whether or not to allow tts messages to be played/sent.
explicit_content_filter: :class:`UserContentFilter`
The filter for explicit content in all messages.
friend_source_flags: :class:`FriendFlags`
Who can add you as a friend.
gif_auto_play: :class:`bool`
Whether or not to automatically play gifs that are in the chat.
guild_positions: List[:class:`abc.Snowflake`]
A list of guilds in order of the guild/guild icons that are on
the left hand side of the UI.
inline_attachment_media: :class:`bool`
Whether or not to display attachments when they are uploaded in chat.
inline_embed_media: :class:`bool`
Whether or not to display videos and images from links posted in chat.
locale: :class:`str`
The RFC 3066 language identifier of the locale to use for the language
of the Discord client.
message_display_compact: :class:`bool`
Whether or not to use the compact Discord display mode.
render_embeds: :class:`bool`
Whether or not to render embeds that are sent in the chat.
render_reactions: :class:`bool`
Whether or not to render reactions that are added to messages.
restricted_guilds: List[:class:`abc.Snowflake`]
A list of guilds that you will not receive DMs from.
show_current_game: :class:`bool`
Whether or not to display the game that you are currently playing.
status: :class:`Status`
The clients status that is shown to others.
theme: :class:`Theme`
The theme of the Discord UI.
timezone_offset: :class:`int`
The timezone offset to use.
Raises
-------
HTTPException
Editing the settings failed.
Forbidden
The client is a bot user and not a user account.
Returns
-------
:class:`dict`
The client user's updated settings.
"""
payload = {}
content_filter = kwargs.pop('explicit_content_filter', None)
if content_filter:
payload.update({'explicit_content_filter': content_filter.value})
friend_flags = kwargs.pop('friend_source_flags', None)
if friend_flags:
dicts = [{}, {'mutual_guilds': True}, {'mutual_friends': True},
{'mutual_guilds': True, 'mutual_friends': True}, {'all': True}]
payload.update({'friend_source_flags': dicts[friend_flags.value]})
guild_positions = kwargs.pop('guild_positions', None)
if guild_positions:
guild_positions = [str(x.id) for x in guild_positions]
payload.update({'guild_positions': guild_positions})
restricted_guilds = kwargs.pop('restricted_guilds', None)
if restricted_guilds:
restricted_guilds = [str(x.id) for x in restricted_guilds]
payload.update({'restricted_guilds': restricted_guilds})
status = kwargs.pop('status', None)
if status:
payload.update({'status': status.value})
theme = kwargs.pop('theme', None)
if theme:
payload.update({'theme': theme.value})
payload.update(kwargs)
data = await self._state.http.edit_settings(**payload)
return data
|
python
|
async def edit_settings(self, **kwargs):
"""|coro|
Edits the client user's settings.
.. note::
This only applies to non-bot accounts.
Parameters
-------
afk_timeout: :class:`int`
How long (in seconds) the user needs to be AFK until Discord
sends push notifications to your mobile device.
animate_emojis: :class:`bool`
Whether or not to animate emojis in the chat.
convert_emoticons: :class:`bool`
Whether or not to automatically convert emoticons into emojis.
e.g. :-) -> 😃
default_guilds_restricted: :class:`bool`
Whether or not to automatically disable DMs between you and
members of new guilds you join.
detect_platform_accounts: :class:`bool`
Whether or not to automatically detect accounts from services
like Steam and Blizzard when you open the Discord client.
developer_mode: :class:`bool`
Whether or not to enable developer mode.
disable_games_tab: :class:`bool`
Whether or not to disable the showing of the Games tab.
enable_tts_command: :class:`bool`
Whether or not to allow tts messages to be played/sent.
explicit_content_filter: :class:`UserContentFilter`
The filter for explicit content in all messages.
friend_source_flags: :class:`FriendFlags`
Who can add you as a friend.
gif_auto_play: :class:`bool`
Whether or not to automatically play gifs that are in the chat.
guild_positions: List[:class:`abc.Snowflake`]
A list of guilds in order of the guild/guild icons that are on
the left hand side of the UI.
inline_attachment_media: :class:`bool`
Whether or not to display attachments when they are uploaded in chat.
inline_embed_media: :class:`bool`
Whether or not to display videos and images from links posted in chat.
locale: :class:`str`
The RFC 3066 language identifier of the locale to use for the language
of the Discord client.
message_display_compact: :class:`bool`
Whether or not to use the compact Discord display mode.
render_embeds: :class:`bool`
Whether or not to render embeds that are sent in the chat.
render_reactions: :class:`bool`
Whether or not to render reactions that are added to messages.
restricted_guilds: List[:class:`abc.Snowflake`]
A list of guilds that you will not receive DMs from.
show_current_game: :class:`bool`
Whether or not to display the game that you are currently playing.
status: :class:`Status`
The clients status that is shown to others.
theme: :class:`Theme`
The theme of the Discord UI.
timezone_offset: :class:`int`
The timezone offset to use.
Raises
-------
HTTPException
Editing the settings failed.
Forbidden
The client is a bot user and not a user account.
Returns
-------
:class:`dict`
The client user's updated settings.
"""
payload = {}
content_filter = kwargs.pop('explicit_content_filter', None)
if content_filter:
payload.update({'explicit_content_filter': content_filter.value})
friend_flags = kwargs.pop('friend_source_flags', None)
if friend_flags:
dicts = [{}, {'mutual_guilds': True}, {'mutual_friends': True},
{'mutual_guilds': True, 'mutual_friends': True}, {'all': True}]
payload.update({'friend_source_flags': dicts[friend_flags.value]})
guild_positions = kwargs.pop('guild_positions', None)
if guild_positions:
guild_positions = [str(x.id) for x in guild_positions]
payload.update({'guild_positions': guild_positions})
restricted_guilds = kwargs.pop('restricted_guilds', None)
if restricted_guilds:
restricted_guilds = [str(x.id) for x in restricted_guilds]
payload.update({'restricted_guilds': restricted_guilds})
status = kwargs.pop('status', None)
if status:
payload.update({'status': status.value})
theme = kwargs.pop('theme', None)
if theme:
payload.update({'theme': theme.value})
payload.update(kwargs)
data = await self._state.http.edit_settings(**payload)
return data
|
[
"async",
"def",
"edit_settings",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"payload",
"=",
"{",
"}",
"content_filter",
"=",
"kwargs",
".",
"pop",
"(",
"'explicit_content_filter'",
",",
"None",
")",
"if",
"content_filter",
":",
"payload",
".",
"update",
"(",
"{",
"'explicit_content_filter'",
":",
"content_filter",
".",
"value",
"}",
")",
"friend_flags",
"=",
"kwargs",
".",
"pop",
"(",
"'friend_source_flags'",
",",
"None",
")",
"if",
"friend_flags",
":",
"dicts",
"=",
"[",
"{",
"}",
",",
"{",
"'mutual_guilds'",
":",
"True",
"}",
",",
"{",
"'mutual_friends'",
":",
"True",
"}",
",",
"{",
"'mutual_guilds'",
":",
"True",
",",
"'mutual_friends'",
":",
"True",
"}",
",",
"{",
"'all'",
":",
"True",
"}",
"]",
"payload",
".",
"update",
"(",
"{",
"'friend_source_flags'",
":",
"dicts",
"[",
"friend_flags",
".",
"value",
"]",
"}",
")",
"guild_positions",
"=",
"kwargs",
".",
"pop",
"(",
"'guild_positions'",
",",
"None",
")",
"if",
"guild_positions",
":",
"guild_positions",
"=",
"[",
"str",
"(",
"x",
".",
"id",
")",
"for",
"x",
"in",
"guild_positions",
"]",
"payload",
".",
"update",
"(",
"{",
"'guild_positions'",
":",
"guild_positions",
"}",
")",
"restricted_guilds",
"=",
"kwargs",
".",
"pop",
"(",
"'restricted_guilds'",
",",
"None",
")",
"if",
"restricted_guilds",
":",
"restricted_guilds",
"=",
"[",
"str",
"(",
"x",
".",
"id",
")",
"for",
"x",
"in",
"restricted_guilds",
"]",
"payload",
".",
"update",
"(",
"{",
"'restricted_guilds'",
":",
"restricted_guilds",
"}",
")",
"status",
"=",
"kwargs",
".",
"pop",
"(",
"'status'",
",",
"None",
")",
"if",
"status",
":",
"payload",
".",
"update",
"(",
"{",
"'status'",
":",
"status",
".",
"value",
"}",
")",
"theme",
"=",
"kwargs",
".",
"pop",
"(",
"'theme'",
",",
"None",
")",
"if",
"theme",
":",
"payload",
".",
"update",
"(",
"{",
"'theme'",
":",
"theme",
".",
"value",
"}",
")",
"payload",
".",
"update",
"(",
"kwargs",
")",
"data",
"=",
"await",
"self",
".",
"_state",
".",
"http",
".",
"edit_settings",
"(",
"*",
"*",
"payload",
")",
"return",
"data"
] |
|coro|
Edits the client user's settings.
.. note::
This only applies to non-bot accounts.
Parameters
-------
afk_timeout: :class:`int`
How long (in seconds) the user needs to be AFK until Discord
sends push notifications to your mobile device.
animate_emojis: :class:`bool`
Whether or not to animate emojis in the chat.
convert_emoticons: :class:`bool`
Whether or not to automatically convert emoticons into emojis.
e.g. :-) -> 😃
default_guilds_restricted: :class:`bool`
Whether or not to automatically disable DMs between you and
members of new guilds you join.
detect_platform_accounts: :class:`bool`
Whether or not to automatically detect accounts from services
like Steam and Blizzard when you open the Discord client.
developer_mode: :class:`bool`
Whether or not to enable developer mode.
disable_games_tab: :class:`bool`
Whether or not to disable the showing of the Games tab.
enable_tts_command: :class:`bool`
Whether or not to allow tts messages to be played/sent.
explicit_content_filter: :class:`UserContentFilter`
The filter for explicit content in all messages.
friend_source_flags: :class:`FriendFlags`
Who can add you as a friend.
gif_auto_play: :class:`bool`
Whether or not to automatically play gifs that are in the chat.
guild_positions: List[:class:`abc.Snowflake`]
A list of guilds in order of the guild/guild icons that are on
the left hand side of the UI.
inline_attachment_media: :class:`bool`
Whether or not to display attachments when they are uploaded in chat.
inline_embed_media: :class:`bool`
Whether or not to display videos and images from links posted in chat.
locale: :class:`str`
The RFC 3066 language identifier of the locale to use for the language
of the Discord client.
message_display_compact: :class:`bool`
Whether or not to use the compact Discord display mode.
render_embeds: :class:`bool`
Whether or not to render embeds that are sent in the chat.
render_reactions: :class:`bool`
Whether or not to render reactions that are added to messages.
restricted_guilds: List[:class:`abc.Snowflake`]
A list of guilds that you will not receive DMs from.
show_current_game: :class:`bool`
Whether or not to display the game that you are currently playing.
status: :class:`Status`
The clients status that is shown to others.
theme: :class:`Theme`
The theme of the Discord UI.
timezone_offset: :class:`int`
The timezone offset to use.
Raises
-------
HTTPException
Editing the settings failed.
Forbidden
The client is a bot user and not a user account.
Returns
-------
:class:`dict`
The client user's updated settings.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/user.py#L500-L609
|
train
|
Rapptz/discord.py
|
discord/user.py
|
User.create_dm
|
async def create_dm(self):
"""Creates a :class:`DMChannel` with this user.
This should be rarely called, as this is done transparently for most
people.
"""
found = self.dm_channel
if found is not None:
return found
state = self._state
data = await state.http.start_private_message(self.id)
return state.add_dm_channel(data)
|
python
|
async def create_dm(self):
"""Creates a :class:`DMChannel` with this user.
This should be rarely called, as this is done transparently for most
people.
"""
found = self.dm_channel
if found is not None:
return found
state = self._state
data = await state.http.start_private_message(self.id)
return state.add_dm_channel(data)
|
[
"async",
"def",
"create_dm",
"(",
"self",
")",
":",
"found",
"=",
"self",
".",
"dm_channel",
"if",
"found",
"is",
"not",
"None",
":",
"return",
"found",
"state",
"=",
"self",
".",
"_state",
"data",
"=",
"await",
"state",
".",
"http",
".",
"start_private_message",
"(",
"self",
".",
"id",
")",
"return",
"state",
".",
"add_dm_channel",
"(",
"data",
")"
] |
Creates a :class:`DMChannel` with this user.
This should be rarely called, as this is done transparently for most
people.
|
[
"Creates",
"a",
":",
"class",
":",
"DMChannel",
"with",
"this",
"user",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/user.py#L664-L676
|
train
|
Rapptz/discord.py
|
discord/user.py
|
User.mutual_friends
|
async def mutual_friends(self):
"""|coro|
Gets all mutual friends of this user.
.. note::
This only applies to non-bot accounts.
Raises
-------
Forbidden
Not allowed to get mutual friends of this user.
HTTPException
Getting mutual friends failed.
Returns
-------
List[:class:`User`]
The users that are mutual friends.
"""
state = self._state
mutuals = await state.http.get_mutual_friends(self.id)
return [User(state=state, data=friend) for friend in mutuals]
|
python
|
async def mutual_friends(self):
"""|coro|
Gets all mutual friends of this user.
.. note::
This only applies to non-bot accounts.
Raises
-------
Forbidden
Not allowed to get mutual friends of this user.
HTTPException
Getting mutual friends failed.
Returns
-------
List[:class:`User`]
The users that are mutual friends.
"""
state = self._state
mutuals = await state.http.get_mutual_friends(self.id)
return [User(state=state, data=friend) for friend in mutuals]
|
[
"async",
"def",
"mutual_friends",
"(",
"self",
")",
":",
"state",
"=",
"self",
".",
"_state",
"mutuals",
"=",
"await",
"state",
".",
"http",
".",
"get_mutual_friends",
"(",
"self",
".",
"id",
")",
"return",
"[",
"User",
"(",
"state",
"=",
"state",
",",
"data",
"=",
"friend",
")",
"for",
"friend",
"in",
"mutuals",
"]"
] |
|coro|
Gets all mutual friends of this user.
.. note::
This only applies to non-bot accounts.
Raises
-------
Forbidden
Not allowed to get mutual friends of this user.
HTTPException
Getting mutual friends failed.
Returns
-------
List[:class:`User`]
The users that are mutual friends.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/user.py#L688-L711
|
train
|
Rapptz/discord.py
|
discord/user.py
|
User.is_friend
|
def is_friend(self):
""":class:`bool`: Checks if the user is your friend.
.. note::
This only applies to non-bot accounts.
"""
r = self.relationship
if r is None:
return False
return r.type is RelationshipType.friend
|
python
|
def is_friend(self):
""":class:`bool`: Checks if the user is your friend.
.. note::
This only applies to non-bot accounts.
"""
r = self.relationship
if r is None:
return False
return r.type is RelationshipType.friend
|
[
"def",
"is_friend",
"(",
"self",
")",
":",
"r",
"=",
"self",
".",
"relationship",
"if",
"r",
"is",
"None",
":",
"return",
"False",
"return",
"r",
".",
"type",
"is",
"RelationshipType",
".",
"friend"
] |
:class:`bool`: Checks if the user is your friend.
.. note::
This only applies to non-bot accounts.
|
[
":",
"class",
":",
"bool",
":",
"Checks",
"if",
"the",
"user",
"is",
"your",
"friend",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/user.py#L713-L723
|
train
|
Rapptz/discord.py
|
discord/user.py
|
User.is_blocked
|
def is_blocked(self):
""":class:`bool`: Checks if the user is blocked.
.. note::
This only applies to non-bot accounts.
"""
r = self.relationship
if r is None:
return False
return r.type is RelationshipType.blocked
|
python
|
def is_blocked(self):
""":class:`bool`: Checks if the user is blocked.
.. note::
This only applies to non-bot accounts.
"""
r = self.relationship
if r is None:
return False
return r.type is RelationshipType.blocked
|
[
"def",
"is_blocked",
"(",
"self",
")",
":",
"r",
"=",
"self",
".",
"relationship",
"if",
"r",
"is",
"None",
":",
"return",
"False",
"return",
"r",
".",
"type",
"is",
"RelationshipType",
".",
"blocked"
] |
:class:`bool`: Checks if the user is blocked.
.. note::
This only applies to non-bot accounts.
|
[
":",
"class",
":",
"bool",
":",
"Checks",
"if",
"the",
"user",
"is",
"blocked",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/user.py#L725-L735
|
train
|
Rapptz/discord.py
|
discord/user.py
|
User.block
|
async def block(self):
"""|coro|
Blocks the user.
.. note::
This only applies to non-bot accounts.
Raises
-------
Forbidden
Not allowed to block this user.
HTTPException
Blocking the user failed.
"""
await self._state.http.add_relationship(self.id, type=RelationshipType.blocked.value)
|
python
|
async def block(self):
"""|coro|
Blocks the user.
.. note::
This only applies to non-bot accounts.
Raises
-------
Forbidden
Not allowed to block this user.
HTTPException
Blocking the user failed.
"""
await self._state.http.add_relationship(self.id, type=RelationshipType.blocked.value)
|
[
"async",
"def",
"block",
"(",
"self",
")",
":",
"await",
"self",
".",
"_state",
".",
"http",
".",
"add_relationship",
"(",
"self",
".",
"id",
",",
"type",
"=",
"RelationshipType",
".",
"blocked",
".",
"value",
")"
] |
|coro|
Blocks the user.
.. note::
This only applies to non-bot accounts.
Raises
-------
Forbidden
Not allowed to block this user.
HTTPException
Blocking the user failed.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/user.py#L737-L754
|
train
|
Rapptz/discord.py
|
discord/user.py
|
User.send_friend_request
|
async def send_friend_request(self):
"""|coro|
Sends the user a friend request.
.. note::
This only applies to non-bot accounts.
Raises
-------
Forbidden
Not allowed to send a friend request to the user.
HTTPException
Sending the friend request failed.
"""
await self._state.http.send_friend_request(username=self.name, discriminator=self.discriminator)
|
python
|
async def send_friend_request(self):
"""|coro|
Sends the user a friend request.
.. note::
This only applies to non-bot accounts.
Raises
-------
Forbidden
Not allowed to send a friend request to the user.
HTTPException
Sending the friend request failed.
"""
await self._state.http.send_friend_request(username=self.name, discriminator=self.discriminator)
|
[
"async",
"def",
"send_friend_request",
"(",
"self",
")",
":",
"await",
"self",
".",
"_state",
".",
"http",
".",
"send_friend_request",
"(",
"username",
"=",
"self",
".",
"name",
",",
"discriminator",
"=",
"self",
".",
"discriminator",
")"
] |
|coro|
Sends the user a friend request.
.. note::
This only applies to non-bot accounts.
Raises
-------
Forbidden
Not allowed to send a friend request to the user.
HTTPException
Sending the friend request failed.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/user.py#L792-L808
|
train
|
Rapptz/discord.py
|
discord/user.py
|
User.profile
|
async def profile(self):
"""|coro|
Gets the user's profile.
.. note::
This only applies to non-bot accounts.
Raises
-------
Forbidden
Not allowed to fetch profiles.
HTTPException
Fetching the profile failed.
Returns
--------
:class:`Profile`
The profile of the user.
"""
state = self._state
data = await state.http.get_user_profile(self.id)
def transform(d):
return state._get_guild(int(d['id']))
since = data.get('premium_since')
mutual_guilds = list(filter(None, map(transform, data.get('mutual_guilds', []))))
return Profile(flags=data['user'].get('flags', 0),
premium_since=parse_time(since),
mutual_guilds=mutual_guilds,
user=self,
connected_accounts=data['connected_accounts'])
|
python
|
async def profile(self):
"""|coro|
Gets the user's profile.
.. note::
This only applies to non-bot accounts.
Raises
-------
Forbidden
Not allowed to fetch profiles.
HTTPException
Fetching the profile failed.
Returns
--------
:class:`Profile`
The profile of the user.
"""
state = self._state
data = await state.http.get_user_profile(self.id)
def transform(d):
return state._get_guild(int(d['id']))
since = data.get('premium_since')
mutual_guilds = list(filter(None, map(transform, data.get('mutual_guilds', []))))
return Profile(flags=data['user'].get('flags', 0),
premium_since=parse_time(since),
mutual_guilds=mutual_guilds,
user=self,
connected_accounts=data['connected_accounts'])
|
[
"async",
"def",
"profile",
"(",
"self",
")",
":",
"state",
"=",
"self",
".",
"_state",
"data",
"=",
"await",
"state",
".",
"http",
".",
"get_user_profile",
"(",
"self",
".",
"id",
")",
"def",
"transform",
"(",
"d",
")",
":",
"return",
"state",
".",
"_get_guild",
"(",
"int",
"(",
"d",
"[",
"'id'",
"]",
")",
")",
"since",
"=",
"data",
".",
"get",
"(",
"'premium_since'",
")",
"mutual_guilds",
"=",
"list",
"(",
"filter",
"(",
"None",
",",
"map",
"(",
"transform",
",",
"data",
".",
"get",
"(",
"'mutual_guilds'",
",",
"[",
"]",
")",
")",
")",
")",
"return",
"Profile",
"(",
"flags",
"=",
"data",
"[",
"'user'",
"]",
".",
"get",
"(",
"'flags'",
",",
"0",
")",
",",
"premium_since",
"=",
"parse_time",
"(",
"since",
")",
",",
"mutual_guilds",
"=",
"mutual_guilds",
",",
"user",
"=",
"self",
",",
"connected_accounts",
"=",
"data",
"[",
"'connected_accounts'",
"]",
")"
] |
|coro|
Gets the user's profile.
.. note::
This only applies to non-bot accounts.
Raises
-------
Forbidden
Not allowed to fetch profiles.
HTTPException
Fetching the profile failed.
Returns
--------
:class:`Profile`
The profile of the user.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/user.py#L810-L844
|
train
|
Rapptz/discord.py
|
discord/utils.py
|
time_snowflake
|
def time_snowflake(datetime_obj, high=False):
"""Returns a numeric snowflake pretending to be created at the given date.
When using as the lower end of a range, use time_snowflake(high=False) - 1 to be inclusive, high=True to be exclusive
When using as the higher end of a range, use time_snowflake(high=True) + 1 to be inclusive, high=False to be exclusive
Parameters
-----------
datetime_obj
A timezone-naive datetime object representing UTC time.
high: :class:`bool`
Whether or not to set the lower 22 bit to high or low.
"""
unix_seconds = (datetime_obj - type(datetime_obj)(1970, 1, 1)).total_seconds()
discord_millis = int(unix_seconds * 1000 - DISCORD_EPOCH)
return (discord_millis << 22) + (2**22-1 if high else 0)
|
python
|
def time_snowflake(datetime_obj, high=False):
"""Returns a numeric snowflake pretending to be created at the given date.
When using as the lower end of a range, use time_snowflake(high=False) - 1 to be inclusive, high=True to be exclusive
When using as the higher end of a range, use time_snowflake(high=True) + 1 to be inclusive, high=False to be exclusive
Parameters
-----------
datetime_obj
A timezone-naive datetime object representing UTC time.
high: :class:`bool`
Whether or not to set the lower 22 bit to high or low.
"""
unix_seconds = (datetime_obj - type(datetime_obj)(1970, 1, 1)).total_seconds()
discord_millis = int(unix_seconds * 1000 - DISCORD_EPOCH)
return (discord_millis << 22) + (2**22-1 if high else 0)
|
[
"def",
"time_snowflake",
"(",
"datetime_obj",
",",
"high",
"=",
"False",
")",
":",
"unix_seconds",
"=",
"(",
"datetime_obj",
"-",
"type",
"(",
"datetime_obj",
")",
"(",
"1970",
",",
"1",
",",
"1",
")",
")",
".",
"total_seconds",
"(",
")",
"discord_millis",
"=",
"int",
"(",
"unix_seconds",
"*",
"1000",
"-",
"DISCORD_EPOCH",
")",
"return",
"(",
"discord_millis",
"<<",
"22",
")",
"+",
"(",
"2",
"**",
"22",
"-",
"1",
"if",
"high",
"else",
"0",
")"
] |
Returns a numeric snowflake pretending to be created at the given date.
When using as the lower end of a range, use time_snowflake(high=False) - 1 to be inclusive, high=True to be exclusive
When using as the higher end of a range, use time_snowflake(high=True) + 1 to be inclusive, high=False to be exclusive
Parameters
-----------
datetime_obj
A timezone-naive datetime object representing UTC time.
high: :class:`bool`
Whether or not to set the lower 22 bit to high or low.
|
[
"Returns",
"a",
"numeric",
"snowflake",
"pretending",
"to",
"be",
"created",
"at",
"the",
"given",
"date",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/utils.py#L160-L176
|
train
|
Rapptz/discord.py
|
discord/utils.py
|
get
|
def get(iterable, **attrs):
r"""A helper that returns the first element in the iterable that meets
all the traits passed in ``attrs``. This is an alternative for
:func:`discord.utils.find`.
When multiple attributes are specified, they are checked using
logical AND, not logical OR. Meaning they have to meet every
attribute passed in and not one of them.
To have a nested attribute search (i.e. search by ``x.y``) then
pass in ``x__y`` as the keyword argument.
If nothing is found that matches the attributes passed, then
``None`` is returned.
Examples
---------
Basic usage:
.. code-block:: python3
member = discord.utils.get(message.guild.members, name='Foo')
Multiple attribute matching:
.. code-block:: python3
channel = discord.utils.get(guild.voice_channels, name='Foo', bitrate=64000)
Nested attribute matching:
.. code-block:: python3
channel = discord.utils.get(client.get_all_channels(), guild__name='Cool', name='general')
Parameters
-----------
iterable
An iterable to search through.
\*\*attrs
Keyword arguments that denote attributes to search with.
"""
def predicate(elem):
for attr, val in attrs.items():
nested = attr.split('__')
obj = elem
for attribute in nested:
obj = getattr(obj, attribute)
if obj != val:
return False
return True
return find(predicate, iterable)
|
python
|
def get(iterable, **attrs):
r"""A helper that returns the first element in the iterable that meets
all the traits passed in ``attrs``. This is an alternative for
:func:`discord.utils.find`.
When multiple attributes are specified, they are checked using
logical AND, not logical OR. Meaning they have to meet every
attribute passed in and not one of them.
To have a nested attribute search (i.e. search by ``x.y``) then
pass in ``x__y`` as the keyword argument.
If nothing is found that matches the attributes passed, then
``None`` is returned.
Examples
---------
Basic usage:
.. code-block:: python3
member = discord.utils.get(message.guild.members, name='Foo')
Multiple attribute matching:
.. code-block:: python3
channel = discord.utils.get(guild.voice_channels, name='Foo', bitrate=64000)
Nested attribute matching:
.. code-block:: python3
channel = discord.utils.get(client.get_all_channels(), guild__name='Cool', name='general')
Parameters
-----------
iterable
An iterable to search through.
\*\*attrs
Keyword arguments that denote attributes to search with.
"""
def predicate(elem):
for attr, val in attrs.items():
nested = attr.split('__')
obj = elem
for attribute in nested:
obj = getattr(obj, attribute)
if obj != val:
return False
return True
return find(predicate, iterable)
|
[
"def",
"get",
"(",
"iterable",
",",
"*",
"*",
"attrs",
")",
":",
"def",
"predicate",
"(",
"elem",
")",
":",
"for",
"attr",
",",
"val",
"in",
"attrs",
".",
"items",
"(",
")",
":",
"nested",
"=",
"attr",
".",
"split",
"(",
"'__'",
")",
"obj",
"=",
"elem",
"for",
"attribute",
"in",
"nested",
":",
"obj",
"=",
"getattr",
"(",
"obj",
",",
"attribute",
")",
"if",
"obj",
"!=",
"val",
":",
"return",
"False",
"return",
"True",
"return",
"find",
"(",
"predicate",
",",
"iterable",
")"
] |
r"""A helper that returns the first element in the iterable that meets
all the traits passed in ``attrs``. This is an alternative for
:func:`discord.utils.find`.
When multiple attributes are specified, they are checked using
logical AND, not logical OR. Meaning they have to meet every
attribute passed in and not one of them.
To have a nested attribute search (i.e. search by ``x.y``) then
pass in ``x__y`` as the keyword argument.
If nothing is found that matches the attributes passed, then
``None`` is returned.
Examples
---------
Basic usage:
.. code-block:: python3
member = discord.utils.get(message.guild.members, name='Foo')
Multiple attribute matching:
.. code-block:: python3
channel = discord.utils.get(guild.voice_channels, name='Foo', bitrate=64000)
Nested attribute matching:
.. code-block:: python3
channel = discord.utils.get(client.get_all_channels(), guild__name='Cool', name='general')
Parameters
-----------
iterable
An iterable to search through.
\*\*attrs
Keyword arguments that denote attributes to search with.
|
[
"r",
"A",
"helper",
"that",
"returns",
"the",
"first",
"element",
"in",
"the",
"iterable",
"that",
"meets",
"all",
"the",
"traits",
"passed",
"in",
"attrs",
".",
"This",
"is",
"an",
"alternative",
"for",
":",
"func",
":",
"discord",
".",
"utils",
".",
"find",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/utils.py#L206-L261
|
train
|
Rapptz/discord.py
|
discord/utils.py
|
_string_width
|
def _string_width(string, *, _IS_ASCII=_IS_ASCII):
"""Returns string's width."""
match = _IS_ASCII.match(string)
if match:
return match.endpos
UNICODE_WIDE_CHAR_TYPE = 'WFA'
width = 0
func = unicodedata.east_asian_width
for char in string:
width += 2 if func(char) in UNICODE_WIDE_CHAR_TYPE else 1
return width
|
python
|
def _string_width(string, *, _IS_ASCII=_IS_ASCII):
"""Returns string's width."""
match = _IS_ASCII.match(string)
if match:
return match.endpos
UNICODE_WIDE_CHAR_TYPE = 'WFA'
width = 0
func = unicodedata.east_asian_width
for char in string:
width += 2 if func(char) in UNICODE_WIDE_CHAR_TYPE else 1
return width
|
[
"def",
"_string_width",
"(",
"string",
",",
"*",
",",
"_IS_ASCII",
"=",
"_IS_ASCII",
")",
":",
"match",
"=",
"_IS_ASCII",
".",
"match",
"(",
"string",
")",
"if",
"match",
":",
"return",
"match",
".",
"endpos",
"UNICODE_WIDE_CHAR_TYPE",
"=",
"'WFA'",
"width",
"=",
"0",
"func",
"=",
"unicodedata",
".",
"east_asian_width",
"for",
"char",
"in",
"string",
":",
"width",
"+=",
"2",
"if",
"func",
"(",
"char",
")",
"in",
"UNICODE_WIDE_CHAR_TYPE",
"else",
"1",
"return",
"width"
] |
Returns string's width.
|
[
"Returns",
"string",
"s",
"width",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/utils.py#L359-L370
|
train
|
Rapptz/discord.py
|
discord/utils.py
|
resolve_invite
|
def resolve_invite(invite):
"""
Resolves an invite from a :class:`Invite`, URL or ID
Parameters
-----------
invite: Union[:class:`Invite`, :class:`Object`, :class:`str`]
The invite.
Returns
--------
:class:`str`
The invite code.
"""
from .invite import Invite # circular import
if isinstance(invite, Invite) or isinstance(invite, Object):
return invite.id
else:
rx = r'(?:https?\:\/\/)?discord(?:\.gg|app\.com\/invite)\/(.+)'
m = re.match(rx, invite)
if m:
return m.group(1)
return invite
|
python
|
def resolve_invite(invite):
"""
Resolves an invite from a :class:`Invite`, URL or ID
Parameters
-----------
invite: Union[:class:`Invite`, :class:`Object`, :class:`str`]
The invite.
Returns
--------
:class:`str`
The invite code.
"""
from .invite import Invite # circular import
if isinstance(invite, Invite) or isinstance(invite, Object):
return invite.id
else:
rx = r'(?:https?\:\/\/)?discord(?:\.gg|app\.com\/invite)\/(.+)'
m = re.match(rx, invite)
if m:
return m.group(1)
return invite
|
[
"def",
"resolve_invite",
"(",
"invite",
")",
":",
"from",
".",
"invite",
"import",
"Invite",
"# circular import",
"if",
"isinstance",
"(",
"invite",
",",
"Invite",
")",
"or",
"isinstance",
"(",
"invite",
",",
"Object",
")",
":",
"return",
"invite",
".",
"id",
"else",
":",
"rx",
"=",
"r'(?:https?\\:\\/\\/)?discord(?:\\.gg|app\\.com\\/invite)\\/(.+)'",
"m",
"=",
"re",
".",
"match",
"(",
"rx",
",",
"invite",
")",
"if",
"m",
":",
"return",
"m",
".",
"group",
"(",
"1",
")",
"return",
"invite"
] |
Resolves an invite from a :class:`Invite`, URL or ID
Parameters
-----------
invite: Union[:class:`Invite`, :class:`Object`, :class:`str`]
The invite.
Returns
--------
:class:`str`
The invite code.
|
[
"Resolves",
"an",
"invite",
"from",
"a",
":",
"class",
":",
"Invite",
"URL",
"or",
"ID"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/utils.py#L372-L394
|
train
|
Rapptz/discord.py
|
discord/utils.py
|
escape_markdown
|
def escape_markdown(text, *, as_needed=False, ignore_links=True):
r"""A helper function that escapes Discord's markdown.
Parameters
-----------
text: :class:`str`
The text to escape markdown from.
as_needed: :class:`bool`
Whether to escape the markdown characters as needed. This
means that it does not escape extraneous characters if it's
not necessary, e.g. ``**hello**`` is escaped into ``\*\*hello**``
instead of ``\*\*hello\*\*``. Note however that this can open
you up to some clever syntax abuse. Defaults to ``False``.
ignore_links: :class:`bool`
Whether to leave links alone when escaping markdown. For example,
if a URL in the text contains characters such as ``_`` then it will
be left alone. This option is not supported with ``as_needed``.
Defaults to ``True``.
Returns
--------
:class:`str`
The text with the markdown special characters escaped with a slash.
"""
if not as_needed:
url_regex = r'(?P<url>(?:https?|steam)://(?:-\.)?(?:[^\s/?\.#-]+\.?)+(?:/[^\s]*)?)'
def replacement(match):
groupdict = match.groupdict()
is_url = groupdict.get('url')
if is_url:
return is_url
return '\\' + groupdict['markdown']
regex = r'(?P<markdown>[_\\~|\*`])'
if ignore_links:
regex = '(?:%s|%s)' % (url_regex, regex)
return re.sub(regex, replacement, text)
else:
text = re.sub(r'\\', r'\\\\', text)
return _MARKDOWN_ESCAPE_REGEX.sub(r'\\\1', text)
|
python
|
def escape_markdown(text, *, as_needed=False, ignore_links=True):
r"""A helper function that escapes Discord's markdown.
Parameters
-----------
text: :class:`str`
The text to escape markdown from.
as_needed: :class:`bool`
Whether to escape the markdown characters as needed. This
means that it does not escape extraneous characters if it's
not necessary, e.g. ``**hello**`` is escaped into ``\*\*hello**``
instead of ``\*\*hello\*\*``. Note however that this can open
you up to some clever syntax abuse. Defaults to ``False``.
ignore_links: :class:`bool`
Whether to leave links alone when escaping markdown. For example,
if a URL in the text contains characters such as ``_`` then it will
be left alone. This option is not supported with ``as_needed``.
Defaults to ``True``.
Returns
--------
:class:`str`
The text with the markdown special characters escaped with a slash.
"""
if not as_needed:
url_regex = r'(?P<url>(?:https?|steam)://(?:-\.)?(?:[^\s/?\.#-]+\.?)+(?:/[^\s]*)?)'
def replacement(match):
groupdict = match.groupdict()
is_url = groupdict.get('url')
if is_url:
return is_url
return '\\' + groupdict['markdown']
regex = r'(?P<markdown>[_\\~|\*`])'
if ignore_links:
regex = '(?:%s|%s)' % (url_regex, regex)
return re.sub(regex, replacement, text)
else:
text = re.sub(r'\\', r'\\\\', text)
return _MARKDOWN_ESCAPE_REGEX.sub(r'\\\1', text)
|
[
"def",
"escape_markdown",
"(",
"text",
",",
"*",
",",
"as_needed",
"=",
"False",
",",
"ignore_links",
"=",
"True",
")",
":",
"if",
"not",
"as_needed",
":",
"url_regex",
"=",
"r'(?P<url>(?:https?|steam)://(?:-\\.)?(?:[^\\s/?\\.#-]+\\.?)+(?:/[^\\s]*)?)'",
"def",
"replacement",
"(",
"match",
")",
":",
"groupdict",
"=",
"match",
".",
"groupdict",
"(",
")",
"is_url",
"=",
"groupdict",
".",
"get",
"(",
"'url'",
")",
"if",
"is_url",
":",
"return",
"is_url",
"return",
"'\\\\'",
"+",
"groupdict",
"[",
"'markdown'",
"]",
"regex",
"=",
"r'(?P<markdown>[_\\\\~|\\*`])'",
"if",
"ignore_links",
":",
"regex",
"=",
"'(?:%s|%s)'",
"%",
"(",
"url_regex",
",",
"regex",
")",
"return",
"re",
".",
"sub",
"(",
"regex",
",",
"replacement",
",",
"text",
")",
"else",
":",
"text",
"=",
"re",
".",
"sub",
"(",
"r'\\\\'",
",",
"r'\\\\\\\\'",
",",
"text",
")",
"return",
"_MARKDOWN_ESCAPE_REGEX",
".",
"sub",
"(",
"r'\\\\\\1'",
",",
"text",
")"
] |
r"""A helper function that escapes Discord's markdown.
Parameters
-----------
text: :class:`str`
The text to escape markdown from.
as_needed: :class:`bool`
Whether to escape the markdown characters as needed. This
means that it does not escape extraneous characters if it's
not necessary, e.g. ``**hello**`` is escaped into ``\*\*hello**``
instead of ``\*\*hello\*\*``. Note however that this can open
you up to some clever syntax abuse. Defaults to ``False``.
ignore_links: :class:`bool`
Whether to leave links alone when escaping markdown. For example,
if a URL in the text contains characters such as ``_`` then it will
be left alone. This option is not supported with ``as_needed``.
Defaults to ``True``.
Returns
--------
:class:`str`
The text with the markdown special characters escaped with a slash.
|
[
"r",
"A",
"helper",
"function",
"that",
"escapes",
"Discord",
"s",
"markdown",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/utils.py#L401-L441
|
train
|
Rapptz/discord.py
|
examples/basic_bot.py
|
add
|
async def add(ctx, left: int, right: int):
"""Adds two numbers together."""
await ctx.send(left + right)
|
python
|
async def add(ctx, left: int, right: int):
"""Adds two numbers together."""
await ctx.send(left + right)
|
[
"async",
"def",
"add",
"(",
"ctx",
",",
"left",
":",
"int",
",",
"right",
":",
"int",
")",
":",
"await",
"ctx",
".",
"send",
"(",
"left",
"+",
"right",
")"
] |
Adds two numbers together.
|
[
"Adds",
"two",
"numbers",
"together",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/examples/basic_bot.py#L19-L21
|
train
|
Rapptz/discord.py
|
examples/basic_bot.py
|
roll
|
async def roll(ctx, dice: str):
"""Rolls a dice in NdN format."""
try:
rolls, limit = map(int, dice.split('d'))
except Exception:
await ctx.send('Format has to be in NdN!')
return
result = ', '.join(str(random.randint(1, limit)) for r in range(rolls))
await ctx.send(result)
|
python
|
async def roll(ctx, dice: str):
"""Rolls a dice in NdN format."""
try:
rolls, limit = map(int, dice.split('d'))
except Exception:
await ctx.send('Format has to be in NdN!')
return
result = ', '.join(str(random.randint(1, limit)) for r in range(rolls))
await ctx.send(result)
|
[
"async",
"def",
"roll",
"(",
"ctx",
",",
"dice",
":",
"str",
")",
":",
"try",
":",
"rolls",
",",
"limit",
"=",
"map",
"(",
"int",
",",
"dice",
".",
"split",
"(",
"'d'",
")",
")",
"except",
"Exception",
":",
"await",
"ctx",
".",
"send",
"(",
"'Format has to be in NdN!'",
")",
"return",
"result",
"=",
"', '",
".",
"join",
"(",
"str",
"(",
"random",
".",
"randint",
"(",
"1",
",",
"limit",
")",
")",
"for",
"r",
"in",
"range",
"(",
"rolls",
")",
")",
"await",
"ctx",
".",
"send",
"(",
"result",
")"
] |
Rolls a dice in NdN format.
|
[
"Rolls",
"a",
"dice",
"in",
"NdN",
"format",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/examples/basic_bot.py#L24-L33
|
train
|
Rapptz/discord.py
|
examples/basic_bot.py
|
repeat
|
async def repeat(ctx, times: int, content='repeating...'):
"""Repeats a message multiple times."""
for i in range(times):
await ctx.send(content)
|
python
|
async def repeat(ctx, times: int, content='repeating...'):
"""Repeats a message multiple times."""
for i in range(times):
await ctx.send(content)
|
[
"async",
"def",
"repeat",
"(",
"ctx",
",",
"times",
":",
"int",
",",
"content",
"=",
"'repeating...'",
")",
":",
"for",
"i",
"in",
"range",
"(",
"times",
")",
":",
"await",
"ctx",
".",
"send",
"(",
"content",
")"
] |
Repeats a message multiple times.
|
[
"Repeats",
"a",
"message",
"multiple",
"times",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/examples/basic_bot.py#L41-L44
|
train
|
Rapptz/discord.py
|
examples/basic_voice.py
|
Music.join
|
async def join(self, ctx, *, channel: discord.VoiceChannel):
"""Joins a voice channel"""
if ctx.voice_client is not None:
return await ctx.voice_client.move_to(channel)
await channel.connect()
|
python
|
async def join(self, ctx, *, channel: discord.VoiceChannel):
"""Joins a voice channel"""
if ctx.voice_client is not None:
return await ctx.voice_client.move_to(channel)
await channel.connect()
|
[
"async",
"def",
"join",
"(",
"self",
",",
"ctx",
",",
"*",
",",
"channel",
":",
"discord",
".",
"VoiceChannel",
")",
":",
"if",
"ctx",
".",
"voice_client",
"is",
"not",
"None",
":",
"return",
"await",
"ctx",
".",
"voice_client",
".",
"move_to",
"(",
"channel",
")",
"await",
"channel",
".",
"connect",
"(",
")"
] |
Joins a voice channel
|
[
"Joins",
"a",
"voice",
"channel"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/examples/basic_voice.py#L60-L66
|
train
|
Rapptz/discord.py
|
examples/basic_voice.py
|
Music.play
|
async def play(self, ctx, *, query):
"""Plays a file from the local filesystem"""
source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(query))
ctx.voice_client.play(source, after=lambda e: print('Player error: %s' % e) if e else None)
await ctx.send('Now playing: {}'.format(query))
|
python
|
async def play(self, ctx, *, query):
"""Plays a file from the local filesystem"""
source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(query))
ctx.voice_client.play(source, after=lambda e: print('Player error: %s' % e) if e else None)
await ctx.send('Now playing: {}'.format(query))
|
[
"async",
"def",
"play",
"(",
"self",
",",
"ctx",
",",
"*",
",",
"query",
")",
":",
"source",
"=",
"discord",
".",
"PCMVolumeTransformer",
"(",
"discord",
".",
"FFmpegPCMAudio",
"(",
"query",
")",
")",
"ctx",
".",
"voice_client",
".",
"play",
"(",
"source",
",",
"after",
"=",
"lambda",
"e",
":",
"print",
"(",
"'Player error: %s'",
"%",
"e",
")",
"if",
"e",
"else",
"None",
")",
"await",
"ctx",
".",
"send",
"(",
"'Now playing: {}'",
".",
"format",
"(",
"query",
")",
")"
] |
Plays a file from the local filesystem
|
[
"Plays",
"a",
"file",
"from",
"the",
"local",
"filesystem"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/examples/basic_voice.py#L69-L75
|
train
|
Rapptz/discord.py
|
examples/basic_voice.py
|
Music.stream
|
async def stream(self, ctx, *, url):
"""Streams from a url (same as yt, but doesn't predownload)"""
async with ctx.typing():
player = await YTDLSource.from_url(url, loop=self.bot.loop, stream=True)
ctx.voice_client.play(player, after=lambda e: print('Player error: %s' % e) if e else None)
await ctx.send('Now playing: {}'.format(player.title))
|
python
|
async def stream(self, ctx, *, url):
"""Streams from a url (same as yt, but doesn't predownload)"""
async with ctx.typing():
player = await YTDLSource.from_url(url, loop=self.bot.loop, stream=True)
ctx.voice_client.play(player, after=lambda e: print('Player error: %s' % e) if e else None)
await ctx.send('Now playing: {}'.format(player.title))
|
[
"async",
"def",
"stream",
"(",
"self",
",",
"ctx",
",",
"*",
",",
"url",
")",
":",
"async",
"with",
"ctx",
".",
"typing",
"(",
")",
":",
"player",
"=",
"await",
"YTDLSource",
".",
"from_url",
"(",
"url",
",",
"loop",
"=",
"self",
".",
"bot",
".",
"loop",
",",
"stream",
"=",
"True",
")",
"ctx",
".",
"voice_client",
".",
"play",
"(",
"player",
",",
"after",
"=",
"lambda",
"e",
":",
"print",
"(",
"'Player error: %s'",
"%",
"e",
")",
"if",
"e",
"else",
"None",
")",
"await",
"ctx",
".",
"send",
"(",
"'Now playing: {}'",
".",
"format",
"(",
"player",
".",
"title",
")",
")"
] |
Streams from a url (same as yt, but doesn't predownload)
|
[
"Streams",
"from",
"a",
"url",
"(",
"same",
"as",
"yt",
"but",
"doesn",
"t",
"predownload",
")"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/examples/basic_voice.py#L88-L95
|
train
|
Rapptz/discord.py
|
examples/basic_voice.py
|
Music.volume
|
async def volume(self, ctx, volume: int):
"""Changes the player's volume"""
if ctx.voice_client is None:
return await ctx.send("Not connected to a voice channel.")
ctx.voice_client.source.volume = volume / 100
await ctx.send("Changed volume to {}%".format(volume))
|
python
|
async def volume(self, ctx, volume: int):
"""Changes the player's volume"""
if ctx.voice_client is None:
return await ctx.send("Not connected to a voice channel.")
ctx.voice_client.source.volume = volume / 100
await ctx.send("Changed volume to {}%".format(volume))
|
[
"async",
"def",
"volume",
"(",
"self",
",",
"ctx",
",",
"volume",
":",
"int",
")",
":",
"if",
"ctx",
".",
"voice_client",
"is",
"None",
":",
"return",
"await",
"ctx",
".",
"send",
"(",
"\"Not connected to a voice channel.\"",
")",
"ctx",
".",
"voice_client",
".",
"source",
".",
"volume",
"=",
"volume",
"/",
"100",
"await",
"ctx",
".",
"send",
"(",
"\"Changed volume to {}%\"",
".",
"format",
"(",
"volume",
")",
")"
] |
Changes the player's volume
|
[
"Changes",
"the",
"player",
"s",
"volume"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/examples/basic_voice.py#L98-L105
|
train
|
Rapptz/discord.py
|
discord/calls.py
|
CallMessage.duration
|
def duration(self):
"""Queries the duration of the call.
If the call has not ended then the current duration will
be returned.
Returns
---------
datetime.timedelta
The timedelta object representing the duration.
"""
if self.ended_timestamp is None:
return datetime.datetime.utcnow() - self.message.created_at
else:
return self.ended_timestamp - self.message.created_at
|
python
|
def duration(self):
"""Queries the duration of the call.
If the call has not ended then the current duration will
be returned.
Returns
---------
datetime.timedelta
The timedelta object representing the duration.
"""
if self.ended_timestamp is None:
return datetime.datetime.utcnow() - self.message.created_at
else:
return self.ended_timestamp - self.message.created_at
|
[
"def",
"duration",
"(",
"self",
")",
":",
"if",
"self",
".",
"ended_timestamp",
"is",
"None",
":",
"return",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"-",
"self",
".",
"message",
".",
"created_at",
"else",
":",
"return",
"self",
".",
"ended_timestamp",
"-",
"self",
".",
"message",
".",
"created_at"
] |
Queries the duration of the call.
If the call has not ended then the current duration will
be returned.
Returns
---------
datetime.timedelta
The timedelta object representing the duration.
|
[
"Queries",
"the",
"duration",
"of",
"the",
"call",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/calls.py#L65-L79
|
train
|
Rapptz/discord.py
|
discord/calls.py
|
GroupCall.connected
|
def connected(self):
"""A property that returns the :class:`list` of :class:`User` that are currently in this call."""
ret = [u for u in self.channel.recipients if self.voice_state_for(u) is not None]
me = self.channel.me
if self.voice_state_for(me) is not None:
ret.append(me)
return ret
|
python
|
def connected(self):
"""A property that returns the :class:`list` of :class:`User` that are currently in this call."""
ret = [u for u in self.channel.recipients if self.voice_state_for(u) is not None]
me = self.channel.me
if self.voice_state_for(me) is not None:
ret.append(me)
return ret
|
[
"def",
"connected",
"(",
"self",
")",
":",
"ret",
"=",
"[",
"u",
"for",
"u",
"in",
"self",
".",
"channel",
".",
"recipients",
"if",
"self",
".",
"voice_state_for",
"(",
"u",
")",
"is",
"not",
"None",
"]",
"me",
"=",
"self",
".",
"channel",
".",
"me",
"if",
"self",
".",
"voice_state_for",
"(",
"me",
")",
"is",
"not",
"None",
":",
"ret",
".",
"append",
"(",
"me",
")",
"return",
"ret"
] |
A property that returns the :class:`list` of :class:`User` that are currently in this call.
|
[
"A",
"property",
"that",
"returns",
"the",
":",
"class",
":",
"list",
"of",
":",
"class",
":",
"User",
"that",
"are",
"currently",
"in",
"this",
"call",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/calls.py#L124-L131
|
train
|
Rapptz/discord.py
|
discord/webhook.py
|
Webhook.partial
|
def partial(cls, id, token, *, adapter):
"""Creates a partial :class:`Webhook`.
A partial webhook is just a webhook object with an ID and a token.
Parameters
-----------
id: :class:`int`
The ID of the webhook.
token: :class:`str`
The authentication token of the webhook.
adapter: :class:`WebhookAdapter`
The webhook adapter to use when sending requests. This is
typically :class:`AsyncWebhookAdapter` for ``aiohttp`` or
:class:`RequestsWebhookAdapter` for ``requests``.
"""
if not isinstance(adapter, WebhookAdapter):
raise TypeError('adapter must be a subclass of WebhookAdapter')
data = {
'id': id,
'token': token
}
return cls(data, adapter=adapter)
|
python
|
def partial(cls, id, token, *, adapter):
"""Creates a partial :class:`Webhook`.
A partial webhook is just a webhook object with an ID and a token.
Parameters
-----------
id: :class:`int`
The ID of the webhook.
token: :class:`str`
The authentication token of the webhook.
adapter: :class:`WebhookAdapter`
The webhook adapter to use when sending requests. This is
typically :class:`AsyncWebhookAdapter` for ``aiohttp`` or
:class:`RequestsWebhookAdapter` for ``requests``.
"""
if not isinstance(adapter, WebhookAdapter):
raise TypeError('adapter must be a subclass of WebhookAdapter')
data = {
'id': id,
'token': token
}
return cls(data, adapter=adapter)
|
[
"def",
"partial",
"(",
"cls",
",",
"id",
",",
"token",
",",
"*",
",",
"adapter",
")",
":",
"if",
"not",
"isinstance",
"(",
"adapter",
",",
"WebhookAdapter",
")",
":",
"raise",
"TypeError",
"(",
"'adapter must be a subclass of WebhookAdapter'",
")",
"data",
"=",
"{",
"'id'",
":",
"id",
",",
"'token'",
":",
"token",
"}",
"return",
"cls",
"(",
"data",
",",
"adapter",
"=",
"adapter",
")"
] |
Creates a partial :class:`Webhook`.
A partial webhook is just a webhook object with an ID and a token.
Parameters
-----------
id: :class:`int`
The ID of the webhook.
token: :class:`str`
The authentication token of the webhook.
adapter: :class:`WebhookAdapter`
The webhook adapter to use when sending requests. This is
typically :class:`AsyncWebhookAdapter` for ``aiohttp`` or
:class:`RequestsWebhookAdapter` for ``requests``.
|
[
"Creates",
"a",
"partial",
":",
"class",
":",
"Webhook",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/webhook.py#L446-L471
|
train
|
Rapptz/discord.py
|
discord/webhook.py
|
Webhook.from_url
|
def from_url(cls, url, *, adapter):
"""Creates a partial :class:`Webhook` from a webhook URL.
Parameters
------------
url: :class:`str`
The URL of the webhook.
adapter: :class:`WebhookAdapter`
The webhook adapter to use when sending requests. This is
typically :class:`AsyncWebhookAdapter` for ``aiohttp`` or
:class:`RequestsWebhookAdapter` for ``requests``.
Raises
-------
InvalidArgument
The URL is invalid.
"""
m = re.search(r'discordapp.com/api/webhooks/(?P<id>[0-9]{17,21})/(?P<token>[A-Za-z0-9\.\-\_]{60,68})', url)
if m is None:
raise InvalidArgument('Invalid webhook URL given.')
return cls(m.groupdict(), adapter=adapter)
|
python
|
def from_url(cls, url, *, adapter):
"""Creates a partial :class:`Webhook` from a webhook URL.
Parameters
------------
url: :class:`str`
The URL of the webhook.
adapter: :class:`WebhookAdapter`
The webhook adapter to use when sending requests. This is
typically :class:`AsyncWebhookAdapter` for ``aiohttp`` or
:class:`RequestsWebhookAdapter` for ``requests``.
Raises
-------
InvalidArgument
The URL is invalid.
"""
m = re.search(r'discordapp.com/api/webhooks/(?P<id>[0-9]{17,21})/(?P<token>[A-Za-z0-9\.\-\_]{60,68})', url)
if m is None:
raise InvalidArgument('Invalid webhook URL given.')
return cls(m.groupdict(), adapter=adapter)
|
[
"def",
"from_url",
"(",
"cls",
",",
"url",
",",
"*",
",",
"adapter",
")",
":",
"m",
"=",
"re",
".",
"search",
"(",
"r'discordapp.com/api/webhooks/(?P<id>[0-9]{17,21})/(?P<token>[A-Za-z0-9\\.\\-\\_]{60,68})'",
",",
"url",
")",
"if",
"m",
"is",
"None",
":",
"raise",
"InvalidArgument",
"(",
"'Invalid webhook URL given.'",
")",
"return",
"cls",
"(",
"m",
".",
"groupdict",
"(",
")",
",",
"adapter",
"=",
"adapter",
")"
] |
Creates a partial :class:`Webhook` from a webhook URL.
Parameters
------------
url: :class:`str`
The URL of the webhook.
adapter: :class:`WebhookAdapter`
The webhook adapter to use when sending requests. This is
typically :class:`AsyncWebhookAdapter` for ``aiohttp`` or
:class:`RequestsWebhookAdapter` for ``requests``.
Raises
-------
InvalidArgument
The URL is invalid.
|
[
"Creates",
"a",
"partial",
":",
"class",
":",
"Webhook",
"from",
"a",
"webhook",
"URL",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/webhook.py#L474-L495
|
train
|
Rapptz/discord.py
|
discord/webhook.py
|
Webhook.channel
|
def channel(self):
"""Optional[:class:`TextChannel`]: The text channel this webhook belongs to.
If this is a partial webhook, then this will always return ``None``.
"""
guild = self.guild
return guild and guild.get_channel(self.channel_id)
|
python
|
def channel(self):
"""Optional[:class:`TextChannel`]: The text channel this webhook belongs to.
If this is a partial webhook, then this will always return ``None``.
"""
guild = self.guild
return guild and guild.get_channel(self.channel_id)
|
[
"def",
"channel",
"(",
"self",
")",
":",
"guild",
"=",
"self",
".",
"guild",
"return",
"guild",
"and",
"guild",
".",
"get_channel",
"(",
"self",
".",
"channel_id",
")"
] |
Optional[:class:`TextChannel`]: The text channel this webhook belongs to.
If this is a partial webhook, then this will always return ``None``.
|
[
"Optional",
"[",
":",
"class",
":",
"TextChannel",
"]",
":",
"The",
"text",
"channel",
"this",
"webhook",
"belongs",
"to",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/webhook.py#L511-L517
|
train
|
Rapptz/discord.py
|
discord/webhook.py
|
Webhook.avatar_url_as
|
def avatar_url_as(self, *, format=None, size=1024):
"""Returns a friendly URL version of the avatar the webhook has.
If the webhook does not have a traditional avatar, their default
avatar URL is returned instead.
The format must be one of 'jpeg', 'jpg', or 'png'.
The size must be a power of 2 between 16 and 1024.
Parameters
-----------
format: Optional[:class:`str`]
The format to attempt to convert the avatar to.
If the format is ``None``, then it is equivalent to png.
size: :class:`int`
The size of the image to display.
Raises
------
InvalidArgument
Bad image format passed to ``format`` or invalid ``size``.
Returns
--------
:class:`Asset`
The resulting CDN asset.
"""
if self.avatar is None:
# Default is always blurple apparently
return Asset(self._state, 'https://cdn.discordapp.com/embed/avatars/0.png')
if not utils.valid_icon_size(size):
raise InvalidArgument("size must be a power of 2 between 16 and 1024")
format = format or 'png'
if format not in ('png', 'jpg', 'jpeg'):
raise InvalidArgument("format must be one of 'png', 'jpg', or 'jpeg'.")
url = 'https://cdn.discordapp.com/avatars/{0.id}/{0.avatar}.{1}?size={2}'.format(self, format, size)
return Asset(self._state, url)
|
python
|
def avatar_url_as(self, *, format=None, size=1024):
"""Returns a friendly URL version of the avatar the webhook has.
If the webhook does not have a traditional avatar, their default
avatar URL is returned instead.
The format must be one of 'jpeg', 'jpg', or 'png'.
The size must be a power of 2 between 16 and 1024.
Parameters
-----------
format: Optional[:class:`str`]
The format to attempt to convert the avatar to.
If the format is ``None``, then it is equivalent to png.
size: :class:`int`
The size of the image to display.
Raises
------
InvalidArgument
Bad image format passed to ``format`` or invalid ``size``.
Returns
--------
:class:`Asset`
The resulting CDN asset.
"""
if self.avatar is None:
# Default is always blurple apparently
return Asset(self._state, 'https://cdn.discordapp.com/embed/avatars/0.png')
if not utils.valid_icon_size(size):
raise InvalidArgument("size must be a power of 2 between 16 and 1024")
format = format or 'png'
if format not in ('png', 'jpg', 'jpeg'):
raise InvalidArgument("format must be one of 'png', 'jpg', or 'jpeg'.")
url = 'https://cdn.discordapp.com/avatars/{0.id}/{0.avatar}.{1}?size={2}'.format(self, format, size)
return Asset(self._state, url)
|
[
"def",
"avatar_url_as",
"(",
"self",
",",
"*",
",",
"format",
"=",
"None",
",",
"size",
"=",
"1024",
")",
":",
"if",
"self",
".",
"avatar",
"is",
"None",
":",
"# Default is always blurple apparently",
"return",
"Asset",
"(",
"self",
".",
"_state",
",",
"'https://cdn.discordapp.com/embed/avatars/0.png'",
")",
"if",
"not",
"utils",
".",
"valid_icon_size",
"(",
"size",
")",
":",
"raise",
"InvalidArgument",
"(",
"\"size must be a power of 2 between 16 and 1024\"",
")",
"format",
"=",
"format",
"or",
"'png'",
"if",
"format",
"not",
"in",
"(",
"'png'",
",",
"'jpg'",
",",
"'jpeg'",
")",
":",
"raise",
"InvalidArgument",
"(",
"\"format must be one of 'png', 'jpg', or 'jpeg'.\"",
")",
"url",
"=",
"'https://cdn.discordapp.com/avatars/{0.id}/{0.avatar}.{1}?size={2}'",
".",
"format",
"(",
"self",
",",
"format",
",",
"size",
")",
"return",
"Asset",
"(",
"self",
".",
"_state",
",",
"url",
")"
] |
Returns a friendly URL version of the avatar the webhook has.
If the webhook does not have a traditional avatar, their default
avatar URL is returned instead.
The format must be one of 'jpeg', 'jpg', or 'png'.
The size must be a power of 2 between 16 and 1024.
Parameters
-----------
format: Optional[:class:`str`]
The format to attempt to convert the avatar to.
If the format is ``None``, then it is equivalent to png.
size: :class:`int`
The size of the image to display.
Raises
------
InvalidArgument
Bad image format passed to ``format`` or invalid ``size``.
Returns
--------
:class:`Asset`
The resulting CDN asset.
|
[
"Returns",
"a",
"friendly",
"URL",
"version",
"of",
"the",
"avatar",
"the",
"webhook",
"has",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/webhook.py#L536-L576
|
train
|
Rapptz/discord.py
|
discord/webhook.py
|
Webhook.edit
|
def edit(self, **kwargs):
"""|maybecoro|
Edits this Webhook.
If the webhook is constructed with a :class:`RequestsWebhookAdapter` then this is
not a coroutine.
Parameters
-------------
name: Optional[:class:`str`]
The webhook's new default name.
avatar: Optional[:class:`bytes`]
A :term:`py:bytes-like object` representing the webhook's new default avatar.
Raises
-------
HTTPException
Editing the webhook failed.
NotFound
This webhook does not exist.
Forbidden
You do not have permissions to edit this webhook.
"""
payload = {}
try:
name = kwargs['name']
except KeyError:
pass
else:
if name is not None:
payload['name'] = str(name)
else:
payload['name'] = None
try:
avatar = kwargs['avatar']
except KeyError:
pass
else:
if avatar is not None:
payload['avatar'] = utils._bytes_to_base64_data(avatar)
else:
payload['avatar'] = None
return self._adapter.edit_webhook(**payload)
|
python
|
def edit(self, **kwargs):
"""|maybecoro|
Edits this Webhook.
If the webhook is constructed with a :class:`RequestsWebhookAdapter` then this is
not a coroutine.
Parameters
-------------
name: Optional[:class:`str`]
The webhook's new default name.
avatar: Optional[:class:`bytes`]
A :term:`py:bytes-like object` representing the webhook's new default avatar.
Raises
-------
HTTPException
Editing the webhook failed.
NotFound
This webhook does not exist.
Forbidden
You do not have permissions to edit this webhook.
"""
payload = {}
try:
name = kwargs['name']
except KeyError:
pass
else:
if name is not None:
payload['name'] = str(name)
else:
payload['name'] = None
try:
avatar = kwargs['avatar']
except KeyError:
pass
else:
if avatar is not None:
payload['avatar'] = utils._bytes_to_base64_data(avatar)
else:
payload['avatar'] = None
return self._adapter.edit_webhook(**payload)
|
[
"def",
"edit",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"payload",
"=",
"{",
"}",
"try",
":",
"name",
"=",
"kwargs",
"[",
"'name'",
"]",
"except",
"KeyError",
":",
"pass",
"else",
":",
"if",
"name",
"is",
"not",
"None",
":",
"payload",
"[",
"'name'",
"]",
"=",
"str",
"(",
"name",
")",
"else",
":",
"payload",
"[",
"'name'",
"]",
"=",
"None",
"try",
":",
"avatar",
"=",
"kwargs",
"[",
"'avatar'",
"]",
"except",
"KeyError",
":",
"pass",
"else",
":",
"if",
"avatar",
"is",
"not",
"None",
":",
"payload",
"[",
"'avatar'",
"]",
"=",
"utils",
".",
"_bytes_to_base64_data",
"(",
"avatar",
")",
"else",
":",
"payload",
"[",
"'avatar'",
"]",
"=",
"None",
"return",
"self",
".",
"_adapter",
".",
"edit_webhook",
"(",
"*",
"*",
"payload",
")"
] |
|maybecoro|
Edits this Webhook.
If the webhook is constructed with a :class:`RequestsWebhookAdapter` then this is
not a coroutine.
Parameters
-------------
name: Optional[:class:`str`]
The webhook's new default name.
avatar: Optional[:class:`bytes`]
A :term:`py:bytes-like object` representing the webhook's new default avatar.
Raises
-------
HTTPException
Editing the webhook failed.
NotFound
This webhook does not exist.
Forbidden
You do not have permissions to edit this webhook.
|
[
"|maybecoro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/webhook.py#L597-L643
|
train
|
Rapptz/discord.py
|
discord/webhook.py
|
Webhook.send
|
def send(self, content=None, *, wait=False, username=None, avatar_url=None, tts=False,
file=None, files=None, embed=None, embeds=None):
"""|maybecoro|
Sends a message using the webhook.
If the webhook is constructed with a :class:`RequestsWebhookAdapter` then this is
not a coroutine.
The content must be a type that can convert to a string through ``str(content)``.
To upload a single file, the ``file`` parameter should be used with a
single :class:`File` object.
If the ``embed`` parameter is provided, it must be of type :class:`Embed` and
it must be a rich embed type. You cannot mix the ``embed`` parameter with the
``embeds`` parameter, which must be a :class:`list` of :class:`Embed` objects to send.
Parameters
------------
content: :class:`str`
The content of the message to send.
wait: :class:`bool`
Whether the server should wait before sending a response. This essentially
means that the return type of this function changes from ``None`` to
a :class:`Message` if set to ``True``.
username: :class:`str`
The username to send with this message. If no username is provided
then the default username for the webhook is used.
avatar_url: Union[:class:`str`, :class:`Asset`]
The avatar URL to send with this message. If no avatar URL is provided
then the default avatar for the webhook is used.
tts: :class:`bool`
Indicates if the message should be sent using text-to-speech.
file: :class:`File`
The file to upload. This cannot be mixed with ``files`` parameter.
files: List[:class:`File`]
A list of files to send with the content. This cannot be mixed with the
``file`` parameter.
embed: :class:`Embed`
The rich embed for the content to send. This cannot be mixed with
``embeds`` parameter.
embeds: List[:class:`Embed`]
A list of embeds to send with the content. Maximum of 10. This cannot
be mixed with the ``embed`` parameter.
Raises
--------
HTTPException
Sending the message failed.
NotFound
This webhook was not found.
Forbidden
The authorization token for the webhook is incorrect.
InvalidArgument
You specified both ``embed`` and ``embeds`` or the length of
``embeds`` was invalid.
Returns
---------
Optional[:class:`Message`]
The message that was sent.
"""
payload = {}
if files is not None and file is not None:
raise InvalidArgument('Cannot mix file and files keyword arguments.')
if embeds is not None and embed is not None:
raise InvalidArgument('Cannot mix embed and embeds keyword arguments.')
if embeds is not None:
if len(embeds) > 10:
raise InvalidArgument('embeds has a maximum of 10 elements.')
payload['embeds'] = [e.to_dict() for e in embeds]
if embed is not None:
payload['embeds'] = [embed.to_dict()]
if content is not None:
payload['content'] = str(content)
payload['tts'] = tts
if avatar_url:
payload['avatar_url'] = str(avatar_url)
if username:
payload['username'] = username
return self._adapter.execute_webhook(wait=wait, file=file, files=files, payload=payload)
|
python
|
def send(self, content=None, *, wait=False, username=None, avatar_url=None, tts=False,
file=None, files=None, embed=None, embeds=None):
"""|maybecoro|
Sends a message using the webhook.
If the webhook is constructed with a :class:`RequestsWebhookAdapter` then this is
not a coroutine.
The content must be a type that can convert to a string through ``str(content)``.
To upload a single file, the ``file`` parameter should be used with a
single :class:`File` object.
If the ``embed`` parameter is provided, it must be of type :class:`Embed` and
it must be a rich embed type. You cannot mix the ``embed`` parameter with the
``embeds`` parameter, which must be a :class:`list` of :class:`Embed` objects to send.
Parameters
------------
content: :class:`str`
The content of the message to send.
wait: :class:`bool`
Whether the server should wait before sending a response. This essentially
means that the return type of this function changes from ``None`` to
a :class:`Message` if set to ``True``.
username: :class:`str`
The username to send with this message. If no username is provided
then the default username for the webhook is used.
avatar_url: Union[:class:`str`, :class:`Asset`]
The avatar URL to send with this message. If no avatar URL is provided
then the default avatar for the webhook is used.
tts: :class:`bool`
Indicates if the message should be sent using text-to-speech.
file: :class:`File`
The file to upload. This cannot be mixed with ``files`` parameter.
files: List[:class:`File`]
A list of files to send with the content. This cannot be mixed with the
``file`` parameter.
embed: :class:`Embed`
The rich embed for the content to send. This cannot be mixed with
``embeds`` parameter.
embeds: List[:class:`Embed`]
A list of embeds to send with the content. Maximum of 10. This cannot
be mixed with the ``embed`` parameter.
Raises
--------
HTTPException
Sending the message failed.
NotFound
This webhook was not found.
Forbidden
The authorization token for the webhook is incorrect.
InvalidArgument
You specified both ``embed`` and ``embeds`` or the length of
``embeds`` was invalid.
Returns
---------
Optional[:class:`Message`]
The message that was sent.
"""
payload = {}
if files is not None and file is not None:
raise InvalidArgument('Cannot mix file and files keyword arguments.')
if embeds is not None and embed is not None:
raise InvalidArgument('Cannot mix embed and embeds keyword arguments.')
if embeds is not None:
if len(embeds) > 10:
raise InvalidArgument('embeds has a maximum of 10 elements.')
payload['embeds'] = [e.to_dict() for e in embeds]
if embed is not None:
payload['embeds'] = [embed.to_dict()]
if content is not None:
payload['content'] = str(content)
payload['tts'] = tts
if avatar_url:
payload['avatar_url'] = str(avatar_url)
if username:
payload['username'] = username
return self._adapter.execute_webhook(wait=wait, file=file, files=files, payload=payload)
|
[
"def",
"send",
"(",
"self",
",",
"content",
"=",
"None",
",",
"*",
",",
"wait",
"=",
"False",
",",
"username",
"=",
"None",
",",
"avatar_url",
"=",
"None",
",",
"tts",
"=",
"False",
",",
"file",
"=",
"None",
",",
"files",
"=",
"None",
",",
"embed",
"=",
"None",
",",
"embeds",
"=",
"None",
")",
":",
"payload",
"=",
"{",
"}",
"if",
"files",
"is",
"not",
"None",
"and",
"file",
"is",
"not",
"None",
":",
"raise",
"InvalidArgument",
"(",
"'Cannot mix file and files keyword arguments.'",
")",
"if",
"embeds",
"is",
"not",
"None",
"and",
"embed",
"is",
"not",
"None",
":",
"raise",
"InvalidArgument",
"(",
"'Cannot mix embed and embeds keyword arguments.'",
")",
"if",
"embeds",
"is",
"not",
"None",
":",
"if",
"len",
"(",
"embeds",
")",
">",
"10",
":",
"raise",
"InvalidArgument",
"(",
"'embeds has a maximum of 10 elements.'",
")",
"payload",
"[",
"'embeds'",
"]",
"=",
"[",
"e",
".",
"to_dict",
"(",
")",
"for",
"e",
"in",
"embeds",
"]",
"if",
"embed",
"is",
"not",
"None",
":",
"payload",
"[",
"'embeds'",
"]",
"=",
"[",
"embed",
".",
"to_dict",
"(",
")",
"]",
"if",
"content",
"is",
"not",
"None",
":",
"payload",
"[",
"'content'",
"]",
"=",
"str",
"(",
"content",
")",
"payload",
"[",
"'tts'",
"]",
"=",
"tts",
"if",
"avatar_url",
":",
"payload",
"[",
"'avatar_url'",
"]",
"=",
"str",
"(",
"avatar_url",
")",
"if",
"username",
":",
"payload",
"[",
"'username'",
"]",
"=",
"username",
"return",
"self",
".",
"_adapter",
".",
"execute_webhook",
"(",
"wait",
"=",
"wait",
",",
"file",
"=",
"file",
",",
"files",
"=",
"files",
",",
"payload",
"=",
"payload",
")"
] |
|maybecoro|
Sends a message using the webhook.
If the webhook is constructed with a :class:`RequestsWebhookAdapter` then this is
not a coroutine.
The content must be a type that can convert to a string through ``str(content)``.
To upload a single file, the ``file`` parameter should be used with a
single :class:`File` object.
If the ``embed`` parameter is provided, it must be of type :class:`Embed` and
it must be a rich embed type. You cannot mix the ``embed`` parameter with the
``embeds`` parameter, which must be a :class:`list` of :class:`Embed` objects to send.
Parameters
------------
content: :class:`str`
The content of the message to send.
wait: :class:`bool`
Whether the server should wait before sending a response. This essentially
means that the return type of this function changes from ``None`` to
a :class:`Message` if set to ``True``.
username: :class:`str`
The username to send with this message. If no username is provided
then the default username for the webhook is used.
avatar_url: Union[:class:`str`, :class:`Asset`]
The avatar URL to send with this message. If no avatar URL is provided
then the default avatar for the webhook is used.
tts: :class:`bool`
Indicates if the message should be sent using text-to-speech.
file: :class:`File`
The file to upload. This cannot be mixed with ``files`` parameter.
files: List[:class:`File`]
A list of files to send with the content. This cannot be mixed with the
``file`` parameter.
embed: :class:`Embed`
The rich embed for the content to send. This cannot be mixed with
``embeds`` parameter.
embeds: List[:class:`Embed`]
A list of embeds to send with the content. Maximum of 10. This cannot
be mixed with the ``embed`` parameter.
Raises
--------
HTTPException
Sending the message failed.
NotFound
This webhook was not found.
Forbidden
The authorization token for the webhook is incorrect.
InvalidArgument
You specified both ``embed`` and ``embeds`` or the length of
``embeds`` was invalid.
Returns
---------
Optional[:class:`Message`]
The message that was sent.
|
[
"|maybecoro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/webhook.py#L645-L733
|
train
|
Rapptz/discord.py
|
discord/reaction.py
|
Reaction.users
|
def users(self, limit=None, after=None):
"""Returns an :class:`AsyncIterator` representing the users that have reacted to the message.
The ``after`` parameter must represent a member
and meet the :class:`abc.Snowflake` abc.
Examples
---------
Usage ::
# I do not actually recommend doing this.
async for user in reaction.users():
await channel.send('{0} has reacted with {1.emoji}!'.format(user, reaction))
Flattening into a list: ::
users = await reaction.users().flatten()
# users is now a list...
winner = random.choice(users)
await channel.send('{} has won the raffle.'.format(winner))
Parameters
------------
limit: :class:`int`
The maximum number of results to return.
If not provided, returns all the users who
reacted to the message.
after: :class:`abc.Snowflake`
For pagination, reactions are sorted by member.
Raises
--------
HTTPException
Getting the users for the reaction failed.
Yields
--------
Union[:class:`User`, :class:`Member`]
The member (if retrievable) or the user that has reacted
to this message. The case where it can be a :class:`Member` is
in a guild message context. Sometimes it can be a :class:`User`
if the member has left the guild.
"""
if self.custom_emoji:
emoji = '{0.name}:{0.id}'.format(self.emoji)
else:
emoji = self.emoji
if limit is None:
limit = self.count
return ReactionIterator(self.message, emoji, limit, after)
|
python
|
def users(self, limit=None, after=None):
"""Returns an :class:`AsyncIterator` representing the users that have reacted to the message.
The ``after`` parameter must represent a member
and meet the :class:`abc.Snowflake` abc.
Examples
---------
Usage ::
# I do not actually recommend doing this.
async for user in reaction.users():
await channel.send('{0} has reacted with {1.emoji}!'.format(user, reaction))
Flattening into a list: ::
users = await reaction.users().flatten()
# users is now a list...
winner = random.choice(users)
await channel.send('{} has won the raffle.'.format(winner))
Parameters
------------
limit: :class:`int`
The maximum number of results to return.
If not provided, returns all the users who
reacted to the message.
after: :class:`abc.Snowflake`
For pagination, reactions are sorted by member.
Raises
--------
HTTPException
Getting the users for the reaction failed.
Yields
--------
Union[:class:`User`, :class:`Member`]
The member (if retrievable) or the user that has reacted
to this message. The case where it can be a :class:`Member` is
in a guild message context. Sometimes it can be a :class:`User`
if the member has left the guild.
"""
if self.custom_emoji:
emoji = '{0.name}:{0.id}'.format(self.emoji)
else:
emoji = self.emoji
if limit is None:
limit = self.count
return ReactionIterator(self.message, emoji, limit, after)
|
[
"def",
"users",
"(",
"self",
",",
"limit",
"=",
"None",
",",
"after",
"=",
"None",
")",
":",
"if",
"self",
".",
"custom_emoji",
":",
"emoji",
"=",
"'{0.name}:{0.id}'",
".",
"format",
"(",
"self",
".",
"emoji",
")",
"else",
":",
"emoji",
"=",
"self",
".",
"emoji",
"if",
"limit",
"is",
"None",
":",
"limit",
"=",
"self",
".",
"count",
"return",
"ReactionIterator",
"(",
"self",
".",
"message",
",",
"emoji",
",",
"limit",
",",
"after",
")"
] |
Returns an :class:`AsyncIterator` representing the users that have reacted to the message.
The ``after`` parameter must represent a member
and meet the :class:`abc.Snowflake` abc.
Examples
---------
Usage ::
# I do not actually recommend doing this.
async for user in reaction.users():
await channel.send('{0} has reacted with {1.emoji}!'.format(user, reaction))
Flattening into a list: ::
users = await reaction.users().flatten()
# users is now a list...
winner = random.choice(users)
await channel.send('{} has won the raffle.'.format(winner))
Parameters
------------
limit: :class:`int`
The maximum number of results to return.
If not provided, returns all the users who
reacted to the message.
after: :class:`abc.Snowflake`
For pagination, reactions are sorted by member.
Raises
--------
HTTPException
Getting the users for the reaction failed.
Yields
--------
Union[:class:`User`, :class:`Member`]
The member (if retrievable) or the user that has reacted
to this message. The case where it can be a :class:`Member` is
in a guild message context. Sometimes it can be a :class:`User`
if the member has left the guild.
|
[
"Returns",
"an",
":",
"class",
":",
"AsyncIterator",
"representing",
"the",
"users",
"that",
"have",
"reacted",
"to",
"the",
"message",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/reaction.py#L124-L177
|
train
|
Rapptz/discord.py
|
discord/channel.py
|
TextChannel.members
|
def members(self):
"""Returns a :class:`list` of :class:`Member` that can see this channel."""
return [m for m in self.guild.members if self.permissions_for(m).read_messages]
|
python
|
def members(self):
"""Returns a :class:`list` of :class:`Member` that can see this channel."""
return [m for m in self.guild.members if self.permissions_for(m).read_messages]
|
[
"def",
"members",
"(",
"self",
")",
":",
"return",
"[",
"m",
"for",
"m",
"in",
"self",
".",
"guild",
".",
"members",
"if",
"self",
".",
"permissions_for",
"(",
"m",
")",
".",
"read_messages",
"]"
] |
Returns a :class:`list` of :class:`Member` that can see this channel.
|
[
"Returns",
"a",
":",
"class",
":",
"list",
"of",
":",
"class",
":",
"Member",
"that",
"can",
"see",
"this",
"channel",
"."
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/channel.py#L143-L145
|
train
|
Rapptz/discord.py
|
discord/channel.py
|
TextChannel.delete_messages
|
async def delete_messages(self, messages):
"""|coro|
Deletes a list of messages. This is similar to :meth:`Message.delete`
except it bulk deletes multiple messages.
As a special case, if the number of messages is 0, then nothing
is done. If the number of messages is 1 then single message
delete is done. If it's more than two, then bulk delete is used.
You cannot bulk delete more than 100 messages or messages that
are older than 14 days old.
You must have the :attr:`~Permissions.manage_messages` permission to
use this.
Usable only by bot accounts.
Parameters
-----------
messages: Iterable[:class:`abc.Snowflake`]
An iterable of messages denoting which ones to bulk delete.
Raises
------
ClientException
The number of messages to delete was more than 100.
Forbidden
You do not have proper permissions to delete the messages or
you're not using a bot account.
HTTPException
Deleting the messages failed.
"""
if not isinstance(messages, (list, tuple)):
messages = list(messages)
if len(messages) == 0:
return # do nothing
if len(messages) == 1:
message_id = messages[0].id
await self._state.http.delete_message(self.id, message_id)
return
if len(messages) > 100:
raise ClientException('Can only bulk delete messages up to 100 messages')
message_ids = [m.id for m in messages]
await self._state.http.delete_messages(self.id, message_ids)
|
python
|
async def delete_messages(self, messages):
"""|coro|
Deletes a list of messages. This is similar to :meth:`Message.delete`
except it bulk deletes multiple messages.
As a special case, if the number of messages is 0, then nothing
is done. If the number of messages is 1 then single message
delete is done. If it's more than two, then bulk delete is used.
You cannot bulk delete more than 100 messages or messages that
are older than 14 days old.
You must have the :attr:`~Permissions.manage_messages` permission to
use this.
Usable only by bot accounts.
Parameters
-----------
messages: Iterable[:class:`abc.Snowflake`]
An iterable of messages denoting which ones to bulk delete.
Raises
------
ClientException
The number of messages to delete was more than 100.
Forbidden
You do not have proper permissions to delete the messages or
you're not using a bot account.
HTTPException
Deleting the messages failed.
"""
if not isinstance(messages, (list, tuple)):
messages = list(messages)
if len(messages) == 0:
return # do nothing
if len(messages) == 1:
message_id = messages[0].id
await self._state.http.delete_message(self.id, message_id)
return
if len(messages) > 100:
raise ClientException('Can only bulk delete messages up to 100 messages')
message_ids = [m.id for m in messages]
await self._state.http.delete_messages(self.id, message_ids)
|
[
"async",
"def",
"delete_messages",
"(",
"self",
",",
"messages",
")",
":",
"if",
"not",
"isinstance",
"(",
"messages",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"messages",
"=",
"list",
"(",
"messages",
")",
"if",
"len",
"(",
"messages",
")",
"==",
"0",
":",
"return",
"# do nothing",
"if",
"len",
"(",
"messages",
")",
"==",
"1",
":",
"message_id",
"=",
"messages",
"[",
"0",
"]",
".",
"id",
"await",
"self",
".",
"_state",
".",
"http",
".",
"delete_message",
"(",
"self",
".",
"id",
",",
"message_id",
")",
"return",
"if",
"len",
"(",
"messages",
")",
">",
"100",
":",
"raise",
"ClientException",
"(",
"'Can only bulk delete messages up to 100 messages'",
")",
"message_ids",
"=",
"[",
"m",
".",
"id",
"for",
"m",
"in",
"messages",
"]",
"await",
"self",
".",
"_state",
".",
"http",
".",
"delete_messages",
"(",
"self",
".",
"id",
",",
"message_ids",
")"
] |
|coro|
Deletes a list of messages. This is similar to :meth:`Message.delete`
except it bulk deletes multiple messages.
As a special case, if the number of messages is 0, then nothing
is done. If the number of messages is 1 then single message
delete is done. If it's more than two, then bulk delete is used.
You cannot bulk delete more than 100 messages or messages that
are older than 14 days old.
You must have the :attr:`~Permissions.manage_messages` permission to
use this.
Usable only by bot accounts.
Parameters
-----------
messages: Iterable[:class:`abc.Snowflake`]
An iterable of messages denoting which ones to bulk delete.
Raises
------
ClientException
The number of messages to delete was more than 100.
Forbidden
You do not have proper permissions to delete the messages or
you're not using a bot account.
HTTPException
Deleting the messages failed.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/channel.py#L226-L274
|
train
|
Rapptz/discord.py
|
discord/channel.py
|
TextChannel.purge
|
async def purge(self, *, limit=100, check=None, before=None, after=None, around=None, oldest_first=False, bulk=True):
"""|coro|
Purges a list of messages that meet the criteria given by the predicate
``check``. If a ``check`` is not provided then all messages are deleted
without discrimination.
You must have the :attr:`~Permissions.manage_messages` permission to
delete messages even if they are your own (unless you are a user
account). The :attr:`~Permissions.read_message_history` permission is
also needed to retrieve message history.
Internally, this employs a different number of strategies depending
on the conditions met such as if a bulk delete is possible or if
the account is a user bot or not.
Examples
---------
Deleting bot's messages ::
def is_me(m):
return m.author == client.user
deleted = await channel.purge(limit=100, check=is_me)
await channel.send('Deleted {} message(s)'.format(len(deleted)))
Parameters
-----------
limit: Optional[:class:`int`]
The number of messages to search through. This is not the number
of messages that will be deleted, though it can be.
check: predicate
The function used to check if a message should be deleted.
It must take a :class:`Message` as its sole parameter.
before
Same as ``before`` in :meth:`history`.
after
Same as ``after`` in :meth:`history`.
around
Same as ``around`` in :meth:`history`.
oldest_first
Same as ``oldest_first`` in :meth:`history`.
bulk: :class:`bool`
If True, use bulk delete. bulk=False is useful for mass-deleting
a bot's own messages without manage_messages. When True, will fall
back to single delete if current account is a user bot, or if
messages are older than two weeks.
Raises
-------
Forbidden
You do not have proper permissions to do the actions required.
HTTPException
Purging the messages failed.
Returns
--------
List[:class:`.Message`]
The list of messages that were deleted.
"""
if check is None:
check = lambda m: True
iterator = self.history(limit=limit, before=before, after=after, oldest_first=oldest_first, around=around)
ret = []
count = 0
minimum_time = int((time.time() - 14 * 24 * 60 * 60) * 1000.0 - 1420070400000) << 22
strategy = self.delete_messages if self._state.is_bot and bulk else _single_delete_strategy
while True:
try:
msg = await iterator.next()
except NoMoreItems:
# no more messages to poll
if count >= 2:
# more than 2 messages -> bulk delete
to_delete = ret[-count:]
await strategy(to_delete)
elif count == 1:
# delete a single message
await ret[-1].delete()
return ret
else:
if count == 100:
# we've reached a full 'queue'
to_delete = ret[-100:]
await strategy(to_delete)
count = 0
await asyncio.sleep(1)
if check(msg):
if msg.id < minimum_time:
# older than 14 days old
if count == 1:
await ret[-1].delete()
elif count >= 2:
to_delete = ret[-count:]
await strategy(to_delete)
count = 0
strategy = _single_delete_strategy
count += 1
ret.append(msg)
|
python
|
async def purge(self, *, limit=100, check=None, before=None, after=None, around=None, oldest_first=False, bulk=True):
"""|coro|
Purges a list of messages that meet the criteria given by the predicate
``check``. If a ``check`` is not provided then all messages are deleted
without discrimination.
You must have the :attr:`~Permissions.manage_messages` permission to
delete messages even if they are your own (unless you are a user
account). The :attr:`~Permissions.read_message_history` permission is
also needed to retrieve message history.
Internally, this employs a different number of strategies depending
on the conditions met such as if a bulk delete is possible or if
the account is a user bot or not.
Examples
---------
Deleting bot's messages ::
def is_me(m):
return m.author == client.user
deleted = await channel.purge(limit=100, check=is_me)
await channel.send('Deleted {} message(s)'.format(len(deleted)))
Parameters
-----------
limit: Optional[:class:`int`]
The number of messages to search through. This is not the number
of messages that will be deleted, though it can be.
check: predicate
The function used to check if a message should be deleted.
It must take a :class:`Message` as its sole parameter.
before
Same as ``before`` in :meth:`history`.
after
Same as ``after`` in :meth:`history`.
around
Same as ``around`` in :meth:`history`.
oldest_first
Same as ``oldest_first`` in :meth:`history`.
bulk: :class:`bool`
If True, use bulk delete. bulk=False is useful for mass-deleting
a bot's own messages without manage_messages. When True, will fall
back to single delete if current account is a user bot, or if
messages are older than two weeks.
Raises
-------
Forbidden
You do not have proper permissions to do the actions required.
HTTPException
Purging the messages failed.
Returns
--------
List[:class:`.Message`]
The list of messages that were deleted.
"""
if check is None:
check = lambda m: True
iterator = self.history(limit=limit, before=before, after=after, oldest_first=oldest_first, around=around)
ret = []
count = 0
minimum_time = int((time.time() - 14 * 24 * 60 * 60) * 1000.0 - 1420070400000) << 22
strategy = self.delete_messages if self._state.is_bot and bulk else _single_delete_strategy
while True:
try:
msg = await iterator.next()
except NoMoreItems:
# no more messages to poll
if count >= 2:
# more than 2 messages -> bulk delete
to_delete = ret[-count:]
await strategy(to_delete)
elif count == 1:
# delete a single message
await ret[-1].delete()
return ret
else:
if count == 100:
# we've reached a full 'queue'
to_delete = ret[-100:]
await strategy(to_delete)
count = 0
await asyncio.sleep(1)
if check(msg):
if msg.id < minimum_time:
# older than 14 days old
if count == 1:
await ret[-1].delete()
elif count >= 2:
to_delete = ret[-count:]
await strategy(to_delete)
count = 0
strategy = _single_delete_strategy
count += 1
ret.append(msg)
|
[
"async",
"def",
"purge",
"(",
"self",
",",
"*",
",",
"limit",
"=",
"100",
",",
"check",
"=",
"None",
",",
"before",
"=",
"None",
",",
"after",
"=",
"None",
",",
"around",
"=",
"None",
",",
"oldest_first",
"=",
"False",
",",
"bulk",
"=",
"True",
")",
":",
"if",
"check",
"is",
"None",
":",
"check",
"=",
"lambda",
"m",
":",
"True",
"iterator",
"=",
"self",
".",
"history",
"(",
"limit",
"=",
"limit",
",",
"before",
"=",
"before",
",",
"after",
"=",
"after",
",",
"oldest_first",
"=",
"oldest_first",
",",
"around",
"=",
"around",
")",
"ret",
"=",
"[",
"]",
"count",
"=",
"0",
"minimum_time",
"=",
"int",
"(",
"(",
"time",
".",
"time",
"(",
")",
"-",
"14",
"*",
"24",
"*",
"60",
"*",
"60",
")",
"*",
"1000.0",
"-",
"1420070400000",
")",
"<<",
"22",
"strategy",
"=",
"self",
".",
"delete_messages",
"if",
"self",
".",
"_state",
".",
"is_bot",
"and",
"bulk",
"else",
"_single_delete_strategy",
"while",
"True",
":",
"try",
":",
"msg",
"=",
"await",
"iterator",
".",
"next",
"(",
")",
"except",
"NoMoreItems",
":",
"# no more messages to poll",
"if",
"count",
">=",
"2",
":",
"# more than 2 messages -> bulk delete",
"to_delete",
"=",
"ret",
"[",
"-",
"count",
":",
"]",
"await",
"strategy",
"(",
"to_delete",
")",
"elif",
"count",
"==",
"1",
":",
"# delete a single message",
"await",
"ret",
"[",
"-",
"1",
"]",
".",
"delete",
"(",
")",
"return",
"ret",
"else",
":",
"if",
"count",
"==",
"100",
":",
"# we've reached a full 'queue'",
"to_delete",
"=",
"ret",
"[",
"-",
"100",
":",
"]",
"await",
"strategy",
"(",
"to_delete",
")",
"count",
"=",
"0",
"await",
"asyncio",
".",
"sleep",
"(",
"1",
")",
"if",
"check",
"(",
"msg",
")",
":",
"if",
"msg",
".",
"id",
"<",
"minimum_time",
":",
"# older than 14 days old",
"if",
"count",
"==",
"1",
":",
"await",
"ret",
"[",
"-",
"1",
"]",
".",
"delete",
"(",
")",
"elif",
"count",
">=",
"2",
":",
"to_delete",
"=",
"ret",
"[",
"-",
"count",
":",
"]",
"await",
"strategy",
"(",
"to_delete",
")",
"count",
"=",
"0",
"strategy",
"=",
"_single_delete_strategy",
"count",
"+=",
"1",
"ret",
".",
"append",
"(",
"msg",
")"
] |
|coro|
Purges a list of messages that meet the criteria given by the predicate
``check``. If a ``check`` is not provided then all messages are deleted
without discrimination.
You must have the :attr:`~Permissions.manage_messages` permission to
delete messages even if they are your own (unless you are a user
account). The :attr:`~Permissions.read_message_history` permission is
also needed to retrieve message history.
Internally, this employs a different number of strategies depending
on the conditions met such as if a bulk delete is possible or if
the account is a user bot or not.
Examples
---------
Deleting bot's messages ::
def is_me(m):
return m.author == client.user
deleted = await channel.purge(limit=100, check=is_me)
await channel.send('Deleted {} message(s)'.format(len(deleted)))
Parameters
-----------
limit: Optional[:class:`int`]
The number of messages to search through. This is not the number
of messages that will be deleted, though it can be.
check: predicate
The function used to check if a message should be deleted.
It must take a :class:`Message` as its sole parameter.
before
Same as ``before`` in :meth:`history`.
after
Same as ``after`` in :meth:`history`.
around
Same as ``around`` in :meth:`history`.
oldest_first
Same as ``oldest_first`` in :meth:`history`.
bulk: :class:`bool`
If True, use bulk delete. bulk=False is useful for mass-deleting
a bot's own messages without manage_messages. When True, will fall
back to single delete if current account is a user bot, or if
messages are older than two weeks.
Raises
-------
Forbidden
You do not have proper permissions to do the actions required.
HTTPException
Purging the messages failed.
Returns
--------
List[:class:`.Message`]
The list of messages that were deleted.
|
[
"|coro|"
] |
05d4f7f9620ef33635d6ac965b26528e09cdaf5b
|
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/channel.py#L276-L383
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.