code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def tensor2im(input_image, imtype=np.uint8):
""""Converts a Tensor array into a numpy image array.
Parameters:
input_image (tensor) -- the input image tensor array, range(0, 1)
imtype (type) -- the desired type of the converted numpy array
"""
if not isinstance(input_image, np.... | "Converts a Tensor array into a numpy image array.
Parameters:
input_image (tensor) -- the input image tensor array, range(0, 1)
imtype (type) -- the desired type of the converted numpy array
| tensor2im | python | OpenTalker/video-retalking | third_part/face3d/util/util.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/util.py | Apache-2.0 |
def diagnose_network(net, name='network'):
"""Calculate and print the mean of average absolute(gradients)
Parameters:
net (torch network) -- Torch network
name (str) -- the name of the network
"""
mean = 0.0
count = 0
for param in net.parameters():
if param.grad is not N... | Calculate and print the mean of average absolute(gradients)
Parameters:
net (torch network) -- Torch network
name (str) -- the name of the network
| diagnose_network | python | OpenTalker/video-retalking | third_part/face3d/util/util.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/util.py | Apache-2.0 |
def save_image(image_numpy, image_path, aspect_ratio=1.0):
"""Save a numpy image to the disk
Parameters:
image_numpy (numpy array) -- input numpy array
image_path (str) -- the path of the image
"""
image_pil = Image.fromarray(image_numpy)
h, w, _ = image_numpy.shape
i... | Save a numpy image to the disk
Parameters:
image_numpy (numpy array) -- input numpy array
image_path (str) -- the path of the image
| save_image | python | OpenTalker/video-retalking | third_part/face3d/util/util.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/util.py | Apache-2.0 |
def print_numpy(x, val=True, shp=False):
"""Print the mean, min, max, median, std, and size of a numpy array
Parameters:
val (bool) -- if print the values of the numpy array
shp (bool) -- if print the shape of the numpy array
"""
x = x.astype(np.float64)
if shp:
print('shape... | Print the mean, min, max, median, std, and size of a numpy array
Parameters:
val (bool) -- if print the values of the numpy array
shp (bool) -- if print the shape of the numpy array
| print_numpy | python | OpenTalker/video-retalking | third_part/face3d/util/util.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/util.py | Apache-2.0 |
def mkdirs(paths):
"""create empty directories if they don't exist
Parameters:
paths (str list) -- a list of directory paths
"""
if isinstance(paths, list) and not isinstance(paths, str):
for path in paths:
mkdir(path)
else:
mkdir(paths) | create empty directories if they don't exist
Parameters:
paths (str list) -- a list of directory paths
| mkdirs | python | OpenTalker/video-retalking | third_part/face3d/util/util.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/util.py | Apache-2.0 |
def draw_landmarks(img, landmark, color='r', step=2):
"""
Return:
img -- numpy.array, (B, H, W, 3) img with landmark, RGB order, range (0, 255)
Parameters:
img -- numpy.array, (B, H, W, 3), RGB order, range (0, 255)
landmark -- numpy.array,... |
Return:
img -- numpy.array, (B, H, W, 3) img with landmark, RGB order, range (0, 255)
Parameters:
img -- numpy.array, (B, H, W, 3), RGB order, range (0, 255)
landmark -- numpy.array, (B, 68, 2), y direction is opposite to v direction
c... | draw_landmarks | python | OpenTalker/video-retalking | third_part/face3d/util/util.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/util.py | Apache-2.0 |
def save_images(webpage, visuals, image_path, aspect_ratio=1.0, width=256):
"""Save images to the disk.
Parameters:
webpage (the HTML class) -- the HTML webpage class that stores these imaegs (see html.py for more details)
visuals (OrderedDict) -- an ordered dictionary that stores (name, ima... | Save images to the disk.
Parameters:
webpage (the HTML class) -- the HTML webpage class that stores these imaegs (see html.py for more details)
visuals (OrderedDict) -- an ordered dictionary that stores (name, images (either tensor or numpy) ) pairs
image_path (str) -- the string... | save_images | python | OpenTalker/video-retalking | third_part/face3d/util/visualizer.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/visualizer.py | Apache-2.0 |
def __init__(self, opt):
"""Initialize the Visualizer class
Parameters:
opt -- stores all the experiment flags; needs to be a subclass of BaseOptions
Step 1: Cache the training/test options
Step 2: create a tensorboard writer
Step 3: create an HTML object for saving ... | Initialize the Visualizer class
Parameters:
opt -- stores all the experiment flags; needs to be a subclass of BaseOptions
Step 1: Cache the training/test options
Step 2: create a tensorboard writer
Step 3: create an HTML object for saving HTML filters
Step 4: create ... | __init__ | python | OpenTalker/video-retalking | third_part/face3d/util/visualizer.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/visualizer.py | Apache-2.0 |
def display_current_results(self, visuals, total_iters, epoch, save_result):
"""Display current results on tensorboad; save current results to an HTML file.
Parameters:
visuals (OrderedDict) - - dictionary of images to display or save
total_iters (int) -- total iterations
... | Display current results on tensorboad; save current results to an HTML file.
Parameters:
visuals (OrderedDict) - - dictionary of images to display or save
total_iters (int) -- total iterations
epoch (int) - - the current epoch
save_result (bool) - - if save the c... | display_current_results | python | OpenTalker/video-retalking | third_part/face3d/util/visualizer.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/visualizer.py | Apache-2.0 |
def print_current_losses(self, epoch, iters, losses, t_comp, t_data):
"""print current losses on console; also save the losses to the disk
Parameters:
epoch (int) -- current epoch
iters (int) -- current training iteration during this epoch (reset to 0 at the end of every epoch)
... | print current losses on console; also save the losses to the disk
Parameters:
epoch (int) -- current epoch
iters (int) -- current training iteration during this epoch (reset to 0 at the end of every epoch)
losses (OrderedDict) -- training losses stored in the format of (name... | print_current_losses | python | OpenTalker/video-retalking | third_part/face3d/util/visualizer.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/visualizer.py | Apache-2.0 |
def __init__(self, opt):
"""Initialize the Visualizer class
Parameters:
opt -- stores all the experiment flags; needs to be a subclass of BaseOptions
Step 1: Cache the training/test options
Step 2: create a tensorboard writer
Step 3: create an HTML object for saving ... | Initialize the Visualizer class
Parameters:
opt -- stores all the experiment flags; needs to be a subclass of BaseOptions
Step 1: Cache the training/test options
Step 2: create a tensorboard writer
Step 3: create an HTML object for saving HTML filters
Step 4: create ... | __init__ | python | OpenTalker/video-retalking | third_part/face3d/util/visualizer.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/visualizer.py | Apache-2.0 |
def display_current_results(self, visuals, total_iters, epoch, dataset='train', save_results=False, count=0, name=None,
add_image=True):
"""Display current results on tensorboad; save current results to an HTML file.
Parameters:
visuals (OrderedDict) - - dictionary of images to ... | Display current results on tensorboad; save current results to an HTML file.
Parameters:
visuals (OrderedDict) - - dictionary of images to display or save
total_iters (int) -- total iterations
epoch (int) - - the current epoch
dataset (str) - - 'train' or 'val' o... | display_current_results | python | OpenTalker/video-retalking | third_part/face3d/util/visualizer.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/visualizer.py | Apache-2.0 |
def print_current_losses(self, epoch, iters, losses, t_comp, t_data, dataset='train'):
"""print current losses on console; also save the losses to the disk
Parameters:
epoch (int) -- current epoch
iters (int) -- current training iteration during this epoch (reset to 0 at the end... | print current losses on console; also save the losses to the disk
Parameters:
epoch (int) -- current epoch
iters (int) -- current training iteration during this epoch (reset to 0 at the end of every epoch)
losses (OrderedDict) -- training losses stored in the format of (name... | print_current_losses | python | OpenTalker/video-retalking | third_part/face3d/util/visualizer.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/visualizer.py | Apache-2.0 |
def transform(point, center, scale, resolution, invert=False):
"""Generate and affine transformation matrix.
Given a set of points, a center, a scale and a targer resolution, the
function generates and affine transformation matrix. If invert is ``True``
it will produce the inverse transformation.
... | Generate and affine transformation matrix.
Given a set of points, a center, a scale and a targer resolution, the
function generates and affine transformation matrix. If invert is ``True``
it will produce the inverse transformation.
Arguments:
point {torch.tensor} -- the input 2D point
... | transform | python | OpenTalker/video-retalking | third_part/face_detection/utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face_detection/utils.py | Apache-2.0 |
def crop(image, center, scale, resolution=256.0):
"""Center crops an image or set of heatmaps
Arguments:
image {numpy.array} -- an rgb image
center {numpy.array} -- the center of the object, usually the same as of the bounding box
scale {float} -- scale of the face
Keyword Argument... | Center crops an image or set of heatmaps
Arguments:
image {numpy.array} -- an rgb image
center {numpy.array} -- the center of the object, usually the same as of the bounding box
scale {float} -- scale of the face
Keyword Arguments:
resolution {float} -- the size of the output c... | crop | python | OpenTalker/video-retalking | third_part/face_detection/utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face_detection/utils.py | Apache-2.0 |
def get_preds_fromhm(hm, center=None, scale=None):
"""Obtain (x,y) coordinates given a set of N heatmaps. If the center
and the scale is provided the function will return the points also in
the original coordinate frame.
Arguments:
hm {torch.tensor} -- the predicted heatmaps, of shape [B, N, W,... | Obtain (x,y) coordinates given a set of N heatmaps. If the center
and the scale is provided the function will return the points also in
the original coordinate frame.
Arguments:
hm {torch.tensor} -- the predicted heatmaps, of shape [B, N, W, H]
Keyword Arguments:
center {torch.tensor} ... | get_preds_fromhm | python | OpenTalker/video-retalking | third_part/face_detection/utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face_detection/utils.py | Apache-2.0 |
def get_preds_fromhm_batch(hm, centers=None, scales=None):
"""Obtain (x,y) coordinates given a set of N heatmaps. If the centers
and the scales is provided the function will return the points also in
the original coordinate frame.
Arguments:
hm {torch.tensor} -- the predicted heatmaps, of shape... | Obtain (x,y) coordinates given a set of N heatmaps. If the centers
and the scales is provided the function will return the points also in
the original coordinate frame.
Arguments:
hm {torch.tensor} -- the predicted heatmaps, of shape [B, N, W, H]
Keyword Arguments:
centers {torch.tenso... | get_preds_fromhm_batch | python | OpenTalker/video-retalking | third_part/face_detection/utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face_detection/utils.py | Apache-2.0 |
def shuffle_lr(parts, pairs=None):
"""Shuffle the points left-right according to the axis of symmetry
of the object.
Arguments:
parts {torch.tensor} -- a 3D or 4D object containing the
heatmaps.
Keyword Arguments:
pairs {list of integers} -- [order of the flipped points] (defau... | Shuffle the points left-right according to the axis of symmetry
of the object.
Arguments:
parts {torch.tensor} -- a 3D or 4D object containing the
heatmaps.
Keyword Arguments:
pairs {list of integers} -- [order of the flipped points] (default: {None})
| shuffle_lr | python | OpenTalker/video-retalking | third_part/face_detection/utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face_detection/utils.py | Apache-2.0 |
def flip(tensor, is_label=False):
"""Flip an image or a set of heatmaps left-right
Arguments:
tensor {numpy.array or torch.tensor} -- [the input image or heatmaps]
Keyword Arguments:
is_label {bool} -- [denote wherever the input is an image or a set of heatmaps ] (default: {False})
"""... | Flip an image or a set of heatmaps left-right
Arguments:
tensor {numpy.array or torch.tensor} -- [the input image or heatmaps]
Keyword Arguments:
is_label {bool} -- [denote wherever the input is an image or a set of heatmaps ] (default: {False})
| flip | python | OpenTalker/video-retalking | third_part/face_detection/utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face_detection/utils.py | Apache-2.0 |
def appdata_dir(appname=None, roaming=False):
""" appdata_dir(appname=None, roaming=False)
Get the path to the application directory, where applications are allowed
to write user specific files (e.g. configurations). For non-user specific
data, consider using common_appdata_dir().
If appname is giv... | appdata_dir(appname=None, roaming=False)
Get the path to the application directory, where applications are allowed
to write user specific files (e.g. configurations). For non-user specific
data, consider using common_appdata_dir().
If appname is given, a subdir is appended (and created if necessary).
... | appdata_dir | python | OpenTalker/video-retalking | third_part/face_detection/utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face_detection/utils.py | Apache-2.0 |
def detect_from_directory(self, path, extensions=['.jpg', '.png'], recursive=False, show_progress_bar=True):
"""Detects faces from all the images present in a given directory.
Arguments:
path {string} -- a string containing a path that points to the folder containing the images
Key... | Detects faces from all the images present in a given directory.
Arguments:
path {string} -- a string containing a path that points to the folder containing the images
Keyword Arguments:
extensions {list} -- list of string containing the extensions to be
consider in ... | detect_from_directory | python | OpenTalker/video-retalking | third_part/face_detection/detection/core.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face_detection/detection/core.py | Apache-2.0 |
def tensor_or_path_to_ndarray(tensor_or_path, rgb=True):
"""Convert path (represented as a string) or torch.tensor to a numpy.ndarray
Arguments:
tensor_or_path {numpy.ndarray, torch.tensor or string} -- path to the image, or the image itself
"""
if isinstance(tensor_or_path,... | Convert path (represented as a string) or torch.tensor to a numpy.ndarray
Arguments:
tensor_or_path {numpy.ndarray, torch.tensor or string} -- path to the image, or the image itself
| tensor_or_path_to_ndarray | python | OpenTalker/video-retalking | third_part/face_detection/detection/core.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face_detection/detection/core.py | Apache-2.0 |
def encode(matched, priors, variances):
"""Encode the variances from the priorbox layers into the ground truth boxes
we have matched (based on jaccard overlap) with the prior boxes.
Args:
matched: (tensor) Coords of ground truth for each prior in point-form
Shape: [num_priors, 4].
... | Encode the variances from the priorbox layers into the ground truth boxes
we have matched (based on jaccard overlap) with the prior boxes.
Args:
matched: (tensor) Coords of ground truth for each prior in point-form
Shape: [num_priors, 4].
priors: (tensor) Prior boxes in center-offset... | encode | python | OpenTalker/video-retalking | third_part/face_detection/detection/sfd/bbox.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face_detection/detection/sfd/bbox.py | Apache-2.0 |
def decode(loc, priors, variances):
"""Decode locations from predictions using priors to undo
the encoding we did for offset regression at train time.
Args:
loc (tensor): location predictions for loc layers,
Shape: [num_priors,4]
priors (tensor): Prior boxes in center-offset form... | Decode locations from predictions using priors to undo
the encoding we did for offset regression at train time.
Args:
loc (tensor): location predictions for loc layers,
Shape: [num_priors,4]
priors (tensor): Prior boxes in center-offset form.
Shape: [num_priors,4].
... | decode | python | OpenTalker/video-retalking | third_part/face_detection/detection/sfd/bbox.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face_detection/detection/sfd/bbox.py | Apache-2.0 |
def batch_decode(loc, priors, variances):
"""Decode locations from predictions using priors to undo
the encoding we did for offset regression at train time.
Args:
loc (tensor): location predictions for loc layers,
Shape: [num_priors,4]
priors (tensor): Prior boxes in center-offse... | Decode locations from predictions using priors to undo
the encoding we did for offset regression at train time.
Args:
loc (tensor): location predictions for loc layers,
Shape: [num_priors,4]
priors (tensor): Prior boxes in center-offset form.
Shape: [num_priors,4].
... | batch_decode | python | OpenTalker/video-retalking | third_part/face_detection/detection/sfd/bbox.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/face_detection/detection/sfd/bbox.py | Apache-2.0 |
def get_norm_layer(norm_type='instance'):
"""Return a normalization layer
Parameters:
norm_type (str) -- the name of the normalization layer: batch | instance | none
For BatchNorm, we use learnable affine parameters and track running statistics (mean/stddev).
For InstanceNorm, we do not use lear... | Return a normalization layer
Parameters:
norm_type (str) -- the name of the normalization layer: batch | instance | none
For BatchNorm, we use learnable affine parameters and track running statistics (mean/stddev).
For InstanceNorm, we do not use learnable affine parameters. We do not track running ... | get_norm_layer | python | OpenTalker/video-retalking | third_part/ganimation_replicate/model/model_utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/ganimation_replicate/model/model_utils.py | Apache-2.0 |
def forward(self,
styles,
conditions,
input_is_latent=False,
noise=None,
randomize_noise=True,
truncation=1,
truncation_latent=None,
inject_index=None,
return_latents=False):
... | Forward function for StyleGAN2GeneratorSFT.
Args:
styles (list[Tensor]): Sample codes of styles.
conditions (list[Tensor]): SFT conditions to generators.
input_is_latent (bool): Whether input is latent style. Default: False.
noise (Tensor | None): Input noise or ... | forward | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/archs/gfpganv1_arch.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/archs/gfpganv1_arch.py | Apache-2.0 |
def forward(self, x, return_latents=False, return_rgb=True, randomize_noise=True):
"""Forward function for GFPGANv1.
Args:
x (Tensor): Input images.
return_latents (bool): Whether to return style latents. Default: False.
return_rgb (bool): Whether return intermediate... | Forward function for GFPGANv1.
Args:
x (Tensor): Input images.
return_latents (bool): Whether to return style latents. Default: False.
return_rgb (bool): Whether return intermediate rgb images. Default: True.
randomize_noise (bool): Randomize noise, used when 'no... | forward | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/archs/gfpganv1_arch.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/archs/gfpganv1_arch.py | Apache-2.0 |
def forward(self, x, return_feats=False):
"""Forward function for FacialComponentDiscriminator.
Args:
x (Tensor): Input images.
return_feats (bool): Whether to return intermediate features. Default: False.
"""
feat = self.conv1(x)
feat = self.conv3(self.c... | Forward function for FacialComponentDiscriminator.
Args:
x (Tensor): Input images.
return_feats (bool): Whether to return intermediate features. Default: False.
| forward | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/archs/gfpganv1_arch.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/archs/gfpganv1_arch.py | Apache-2.0 |
def forward(self,
styles,
conditions,
input_is_latent=False,
noise=None,
randomize_noise=True,
truncation=1,
truncation_latent=None,
inject_index=None,
return_latents=False):
... | Forward function for StyleGAN2GeneratorCSFT.
Args:
styles (list[Tensor]): Sample codes of styles.
conditions (list[Tensor]): SFT conditions to generators.
input_is_latent (bool): Whether input is latent style. Default: False.
noise (Tensor | None): Input noise or... | forward | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/archs/gfpganv1_clean_arch.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/archs/gfpganv1_clean_arch.py | Apache-2.0 |
def forward(self, x, return_latents=False, return_rgb=True, randomize_noise=True):
"""Forward function for GFPGANv1Clean.
Args:
x (Tensor): Input images.
return_latents (bool): Whether to return style latents. Default: False.
return_rgb (bool): Whether return interme... | Forward function for GFPGANv1Clean.
Args:
x (Tensor): Input images.
return_latents (bool): Whether to return style latents. Default: False.
return_rgb (bool): Whether return intermediate rgb images. Default: True.
randomize_noise (bool): Randomize noise, used whe... | forward | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/archs/gfpganv1_clean_arch.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/archs/gfpganv1_clean_arch.py | Apache-2.0 |
def forward(self,
styles,
conditions,
input_is_latent=False,
noise=None,
randomize_noise=True,
truncation=1,
truncation_latent=None,
inject_index=None,
return_latents=False):
... | Forward function for StyleGAN2GeneratorBilinearSFT.
Args:
styles (list[Tensor]): Sample codes of styles.
conditions (list[Tensor]): SFT conditions to generators.
input_is_latent (bool): Whether input is latent style. Default: False.
noise (Tensor | None): Input n... | forward | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/archs/gfpgan_bilinear_arch.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/archs/gfpgan_bilinear_arch.py | Apache-2.0 |
def forward(self, x, return_latents=False, return_rgb=True, randomize_noise=True):
"""Forward function for GFPGANBilinear.
Args:
x (Tensor): Input images.
return_latents (bool): Whether to return style latents. Default: False.
return_rgb (bool): Whether return interm... | Forward function for GFPGANBilinear.
Args:
x (Tensor): Input images.
return_latents (bool): Whether to return style latents. Default: False.
return_rgb (bool): Whether return intermediate rgb images. Default: True.
randomize_noise (bool): Randomize noise, used wh... | forward | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/archs/gfpgan_bilinear_arch.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/archs/gfpgan_bilinear_arch.py | Apache-2.0 |
def forward(self, x, style):
"""Forward function.
Args:
x (Tensor): Tensor with shape (b, c, h, w).
style (Tensor): Tensor with shape (b, num_style_feat).
Returns:
Tensor: Modulated tensor after convolution.
"""
b, c, h, w = x.shape # c = c_... | Forward function.
Args:
x (Tensor): Tensor with shape (b, c, h, w).
style (Tensor): Tensor with shape (b, num_style_feat).
Returns:
Tensor: Modulated tensor after convolution.
| forward | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/archs/stylegan2_bilinear_arch.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/archs/stylegan2_bilinear_arch.py | Apache-2.0 |
def forward(self, x, style, skip=None):
"""Forward function.
Args:
x (Tensor): Feature tensor with shape (b, c, h, w).
style (Tensor): Tensor with shape (b, num_style_feat).
skip (Tensor): Base/skip tensor. Default: None.
Returns:
Tensor: RGB ima... | Forward function.
Args:
x (Tensor): Feature tensor with shape (b, c, h, w).
style (Tensor): Tensor with shape (b, num_style_feat).
skip (Tensor): Base/skip tensor. Default: None.
Returns:
Tensor: RGB images.
| forward | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/archs/stylegan2_bilinear_arch.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/archs/stylegan2_bilinear_arch.py | Apache-2.0 |
def forward(self,
styles,
input_is_latent=False,
noise=None,
randomize_noise=True,
truncation=1,
truncation_latent=None,
inject_index=None,
return_latents=False):
"""Forward function f... | Forward function for StyleGAN2Generator.
Args:
styles (list[Tensor]): Sample codes of styles.
input_is_latent (bool): Whether input is latent style.
Default: False.
noise (Tensor | None): Input noise or None. Default: None.
randomize_noise (bool):... | forward | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/archs/stylegan2_bilinear_arch.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/archs/stylegan2_bilinear_arch.py | Apache-2.0 |
def forward(self, x, style):
"""Forward function.
Args:
x (Tensor): Tensor with shape (b, c, h, w).
style (Tensor): Tensor with shape (b, num_style_feat).
Returns:
Tensor: Modulated tensor after convolution.
"""
b, c, h, w = x.shape # c = c_... | Forward function.
Args:
x (Tensor): Tensor with shape (b, c, h, w).
style (Tensor): Tensor with shape (b, num_style_feat).
Returns:
Tensor: Modulated tensor after convolution.
| forward | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/archs/stylegan2_clean_arch.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/archs/stylegan2_clean_arch.py | Apache-2.0 |
def forward(self, x, style, skip=None):
"""Forward function.
Args:
x (Tensor): Feature tensor with shape (b, c, h, w).
style (Tensor): Tensor with shape (b, num_style_feat).
skip (Tensor): Base/skip tensor. Default: None.
Returns:
Tensor: RGB ima... | Forward function.
Args:
x (Tensor): Feature tensor with shape (b, c, h, w).
style (Tensor): Tensor with shape (b, num_style_feat).
skip (Tensor): Base/skip tensor. Default: None.
Returns:
Tensor: RGB images.
| forward | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/archs/stylegan2_clean_arch.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/archs/stylegan2_clean_arch.py | Apache-2.0 |
def forward(self,
styles,
input_is_latent=False,
noise=None,
randomize_noise=True,
truncation=1,
truncation_latent=None,
inject_index=None,
return_latents=False):
"""Forward function f... | Forward function for StyleGAN2GeneratorClean.
Args:
styles (list[Tensor]): Sample codes of styles.
input_is_latent (bool): Whether input is latent style. Default: False.
noise (Tensor | None): Input noise or None. Default: None.
randomize_noise (bool): Randomize ... | forward | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/archs/stylegan2_clean_arch.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/archs/stylegan2_clean_arch.py | Apache-2.0 |
def color_jitter(img, shift):
"""jitter color: randomly jitter the RGB values, in numpy formats"""
jitter_val = np.random.uniform(-shift, shift, 3).astype(np.float32)
img = img + jitter_val
img = np.clip(img, 0, 1)
return img | jitter color: randomly jitter the RGB values, in numpy formats | color_jitter | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/data/ffhq_degradation_dataset.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/data/ffhq_degradation_dataset.py | Apache-2.0 |
def color_jitter_pt(img, brightness, contrast, saturation, hue):
"""jitter color: randomly jitter the brightness, contrast, saturation, and hue, in torch Tensor formats"""
fn_idx = torch.randperm(4)
for fn_id in fn_idx:
if fn_id == 0 and brightness is not None:
bright... | jitter color: randomly jitter the brightness, contrast, saturation, and hue, in torch Tensor formats | color_jitter_pt | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/data/ffhq_degradation_dataset.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/data/ffhq_degradation_dataset.py | Apache-2.0 |
def get_component_coordinates(self, index, status):
"""Get facial component (left_eye, right_eye, mouth) coordinates from a pre-loaded pth file"""
components_bbox = self.components_list[f'{index:08d}']
if status[0]: # hflip
# exchange right and left eye
tmp = components_... | Get facial component (left_eye, right_eye, mouth) coordinates from a pre-loaded pth file | get_component_coordinates | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/data/ffhq_degradation_dataset.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/data/ffhq_degradation_dataset.py | Apache-2.0 |
def construct_img_pyramid(self):
"""Construct image pyramid for intermediate restoration loss"""
pyramid_gt = [self.gt]
down_img = self.gt
for _ in range(0, self.log_size - 3):
down_img = F.interpolate(down_img, scale_factor=0.5, mode='bilinear', align_corners=False)
... | Construct image pyramid for intermediate restoration loss | construct_img_pyramid | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/models/gfpgan_model.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/models/gfpgan_model.py | Apache-2.0 |
def _gram_mat(self, x):
"""Calculate Gram matrix.
Args:
x (torch.Tensor): Tensor with shape of (n, c, h, w).
Returns:
torch.Tensor: Gram matrix.
"""
n, c, h, w = x.size()
features = x.view(n, c, w * h)
features_t = features.transpose(1, 2... | Calculate Gram matrix.
Args:
x (torch.Tensor): Tensor with shape of (n, c, h, w).
Returns:
torch.Tensor: Gram matrix.
| _gram_mat | python | OpenTalker/video-retalking | third_part/GFPGAN/gfpgan/models/gfpgan_model.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GFPGAN/gfpgan/models/gfpgan_model.py | Apache-2.0 |
def _umeyama(src, dst, estimate_scale=True, scale=1.0):
"""Estimate N-D similarity transformation with or without scaling.
Parameters
----------
src : (M, N) array
Source coordinates.
dst : (M, N) array
Destination coordinates.
estimate_scale : bool
Whether to estimate sc... | Estimate N-D similarity transformation with or without scaling.
Parameters
----------
src : (M, N) array
Source coordinates.
dst : (M, N) array
Destination coordinates.
estimate_scale : bool
Whether to estimate scaling factor.
Returns
-------
T : (N + 1, N + 1)
... | _umeyama | python | OpenTalker/video-retalking | third_part/GPEN/align_faces.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/align_faces.py | Apache-2.0 |
def remove_prefix(self, state_dict, prefix):
''' Old style model is stored with all names of parameters sharing common prefix 'module.' '''
f = lambda x: x.split(prefix, 1)[-1] if x.startswith(prefix) else x
return {f(key): value for key, value in state_dict.items()} | Old style model is stored with all names of parameters sharing common prefix 'module.' | remove_prefix | python | OpenTalker/video-retalking | third_part/GPEN/face_detect/retinaface_detection.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_detect/retinaface_detection.py | Apache-2.0 |
def detection_collate(batch):
"""Custom collate fn for dealing with batches of images that have a different
number of associated object annotations (bounding boxes).
Arguments:
batch: (tuple) A tuple of tensor images and lists of annotations
Return:
A tuple containing:
1) (... | Custom collate fn for dealing with batches of images that have a different
number of associated object annotations (bounding boxes).
Arguments:
batch: (tuple) A tuple of tensor images and lists of annotations
Return:
A tuple containing:
1) (tensor) batch of images stacked on th... | detection_collate | python | OpenTalker/video-retalking | third_part/GPEN/face_detect/data/wider_face.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_detect/data/wider_face.py | Apache-2.0 |
def __init__(self, cfg = None, phase = 'train'):
"""
:param cfg: Network related settings.
:param phase: train or test.
"""
super(RetinaFace,self).__init__()
self.phase = phase
backbone = None
if cfg['name'] == 'mobilenet0.25':
backbone = Mobi... |
:param cfg: Network related settings.
:param phase: train or test.
| __init__ | python | OpenTalker/video-retalking | third_part/GPEN/face_detect/facemodels/retinaface.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_detect/facemodels/retinaface.py | Apache-2.0 |
def point_form(boxes):
""" Convert prior_boxes to (xmin, ymin, xmax, ymax)
representation for comparison to point form ground truth data.
Args:
boxes: (tensor) center-size default boxes from priorbox layers.
Return:
boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes.
"""
... | Convert prior_boxes to (xmin, ymin, xmax, ymax)
representation for comparison to point form ground truth data.
Args:
boxes: (tensor) center-size default boxes from priorbox layers.
Return:
boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes.
| point_form | python | OpenTalker/video-retalking | third_part/GPEN/face_detect/utils/box_utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_detect/utils/box_utils.py | Apache-2.0 |
def center_size(boxes):
""" Convert prior_boxes to (cx, cy, w, h)
representation for comparison to center-size form ground truth data.
Args:
boxes: (tensor) point_form boxes
Return:
boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes.
"""
return torch.cat((boxes[:, 2:]... | Convert prior_boxes to (cx, cy, w, h)
representation for comparison to center-size form ground truth data.
Args:
boxes: (tensor) point_form boxes
Return:
boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes.
| center_size | python | OpenTalker/video-retalking | third_part/GPEN/face_detect/utils/box_utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_detect/utils/box_utils.py | Apache-2.0 |
def intersect(box_a, box_b):
""" We resize both tensors to [A,B,2] without new malloc:
[A,2] -> [A,1,2] -> [A,B,2]
[B,2] -> [1,B,2] -> [A,B,2]
Then we compute the area of intersect between box_a and box_b.
Args:
box_a: (tensor) bounding boxes, Shape: [A,4].
box_b: (tensor) bounding boxes... | We resize both tensors to [A,B,2] without new malloc:
[A,2] -> [A,1,2] -> [A,B,2]
[B,2] -> [1,B,2] -> [A,B,2]
Then we compute the area of intersect between box_a and box_b.
Args:
box_a: (tensor) bounding boxes, Shape: [A,4].
box_b: (tensor) bounding boxes, Shape: [B,4].
Return:
(t... | intersect | python | OpenTalker/video-retalking | third_part/GPEN/face_detect/utils/box_utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_detect/utils/box_utils.py | Apache-2.0 |
def matrix_iou(a, b):
"""
return iou of a and b, numpy version for data augenmentation
"""
lt = np.maximum(a[:, np.newaxis, :2], b[:, :2])
rb = np.minimum(a[:, np.newaxis, 2:], b[:, 2:])
area_i = np.prod(rb - lt, axis=2) * (lt < rb).all(axis=2)
area_a = np.prod(a[:, 2:] - a[:, :2], axis=1)
... |
return iou of a and b, numpy version for data augenmentation
| matrix_iou | python | OpenTalker/video-retalking | third_part/GPEN/face_detect/utils/box_utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_detect/utils/box_utils.py | Apache-2.0 |
def matrix_iof(a, b):
"""
return iof of a and b, numpy version for data augenmentation
"""
lt = np.maximum(a[:, np.newaxis, :2], b[:, :2])
rb = np.minimum(a[:, np.newaxis, 2:], b[:, 2:])
area_i = np.prod(rb - lt, axis=2) * (lt < rb).all(axis=2)
area_a = np.prod(a[:, 2:] - a[:, :2], axis=1)
... |
return iof of a and b, numpy version for data augenmentation
| matrix_iof | python | OpenTalker/video-retalking | third_part/GPEN/face_detect/utils/box_utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_detect/utils/box_utils.py | Apache-2.0 |
def encode(matched, priors, variances):
"""Encode the variances from the priorbox layers into the ground truth boxes
we have matched (based on jaccard overlap) with the prior boxes.
Args:
matched: (tensor) Coords of ground truth for each prior in point-form
Shape: [num_priors, 4].
... | Encode the variances from the priorbox layers into the ground truth boxes
we have matched (based on jaccard overlap) with the prior boxes.
Args:
matched: (tensor) Coords of ground truth for each prior in point-form
Shape: [num_priors, 4].
priors: (tensor) Prior boxes in center-offset... | encode | python | OpenTalker/video-retalking | third_part/GPEN/face_detect/utils/box_utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_detect/utils/box_utils.py | Apache-2.0 |
def encode_landm(matched, priors, variances):
"""Encode the variances from the priorbox layers into the ground truth boxes
we have matched (based on jaccard overlap) with the prior boxes.
Args:
matched: (tensor) Coords of ground truth for each prior in point-form
Shape: [num_priors, 10].... | Encode the variances from the priorbox layers into the ground truth boxes
we have matched (based on jaccard overlap) with the prior boxes.
Args:
matched: (tensor) Coords of ground truth for each prior in point-form
Shape: [num_priors, 10].
priors: (tensor) Prior boxes in center-offse... | encode_landm | python | OpenTalker/video-retalking | third_part/GPEN/face_detect/utils/box_utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_detect/utils/box_utils.py | Apache-2.0 |
def decode(loc, priors, variances):
"""Decode locations from predictions using priors to undo
the encoding we did for offset regression at train time.
Args:
loc (tensor): location predictions for loc layers,
Shape: [num_priors,4]
priors (tensor): Prior boxes in center-offset form... | Decode locations from predictions using priors to undo
the encoding we did for offset regression at train time.
Args:
loc (tensor): location predictions for loc layers,
Shape: [num_priors,4]
priors (tensor): Prior boxes in center-offset form.
Shape: [num_priors,4].
... | decode | python | OpenTalker/video-retalking | third_part/GPEN/face_detect/utils/box_utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_detect/utils/box_utils.py | Apache-2.0 |
def decode_landm(pre, priors, variances):
"""Decode landm from predictions using priors to undo
the encoding we did for offset regression at train time.
Args:
pre (tensor): landm predictions for loc layers,
Shape: [num_priors,10]
priors (tensor): Prior boxes in center-offset form... | Decode landm from predictions using priors to undo
the encoding we did for offset regression at train time.
Args:
pre (tensor): landm predictions for loc layers,
Shape: [num_priors,10]
priors (tensor): Prior boxes in center-offset form.
Shape: [num_priors,4].
vari... | decode_landm | python | OpenTalker/video-retalking | third_part/GPEN/face_detect/utils/box_utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_detect/utils/box_utils.py | Apache-2.0 |
def log_sum_exp(x):
"""Utility function for computing log_sum_exp while determining
This will be used to determine unaveraged confidence loss across
all examples in a batch.
Args:
x (Variable(tensor)): conf_preds from conf layers
"""
x_max = x.data.max()
return torch.log(torch.sum(to... | Utility function for computing log_sum_exp while determining
This will be used to determine unaveraged confidence loss across
all examples in a batch.
Args:
x (Variable(tensor)): conf_preds from conf layers
| log_sum_exp | python | OpenTalker/video-retalking | third_part/GPEN/face_detect/utils/box_utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_detect/utils/box_utils.py | Apache-2.0 |
def nms(boxes, scores, overlap=0.5, top_k=200):
"""Apply non-maximum suppression at test time to avoid detecting too many
overlapping bounding boxes for a given object.
Args:
boxes: (tensor) The location preds for the img, Shape: [num_priors,4].
scores: (tensor) The class predscores for the ... | Apply non-maximum suppression at test time to avoid detecting too many
overlapping bounding boxes for a given object.
Args:
boxes: (tensor) The location preds for the img, Shape: [num_priors,4].
scores: (tensor) The class predscores for the img, Shape:[num_priors].
overlap: (float) The o... | nms | python | OpenTalker/video-retalking | third_part/GPEN/face_detect/utils/box_utils.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_detect/utils/box_utils.py | Apache-2.0 |
def positive_cap(num):
""" Cap a number to ensure positivity
:param num: positive or negative number
:returns: (overflow, capped_number)
"""
if num < 0:
return 0, abs(num)
else:
return num, 0 | Cap a number to ensure positivity
:param num: positive or negative number
:returns: (overflow, capped_number)
| positive_cap | python | OpenTalker/video-retalking | third_part/GPEN/face_morpher/facemorpher/aligner.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_morpher/facemorpher/aligner.py | Apache-2.0 |
def roi_coordinates(rect, size, scale):
""" Align the rectangle into the center and return the top-left coordinates
within the new size. If rect is smaller, we add borders.
:param rect: (x, y, w, h) bounding rectangle of the face
:param size: (width, height) are the desired dimensions
:param scale: scaling f... | Align the rectangle into the center and return the top-left coordinates
within the new size. If rect is smaller, we add borders.
:param rect: (x, y, w, h) bounding rectangle of the face
:param size: (width, height) are the desired dimensions
:param scale: scaling factor of the rectangle to be resized
:retur... | roi_coordinates | python | OpenTalker/video-retalking | third_part/GPEN/face_morpher/facemorpher/aligner.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_morpher/facemorpher/aligner.py | Apache-2.0 |
def scaling_factor(rect, size):
""" Calculate the scaling factor for the current image to be
resized to the new dimensions
:param rect: (x, y, w, h) bounding rectangle of the face
:param size: (width, height) are the desired dimensions
:returns: floating point scaling factor
"""
new_height, new_width... | Calculate the scaling factor for the current image to be
resized to the new dimensions
:param rect: (x, y, w, h) bounding rectangle of the face
:param size: (width, height) are the desired dimensions
:returns: floating point scaling factor
| scaling_factor | python | OpenTalker/video-retalking | third_part/GPEN/face_morpher/facemorpher/aligner.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_morpher/facemorpher/aligner.py | Apache-2.0 |
def resize_image(img, scale):
""" Resize image with the provided scaling factor
:param img: image to be resized
:param scale: scaling factor for resizing the image
"""
cur_height, cur_width = img.shape[:2]
new_scaled_height = int(scale * cur_height)
new_scaled_width = int(scale * cur_width)
return cv2... | Resize image with the provided scaling factor
:param img: image to be resized
:param scale: scaling factor for resizing the image
| resize_image | python | OpenTalker/video-retalking | third_part/GPEN/face_morpher/facemorpher/aligner.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_morpher/facemorpher/aligner.py | Apache-2.0 |
def resize_align(img, points, size):
""" Resize image and associated points, align face to the center
and crop to the desired size
:param img: image to be resized
:param points: *m* x 2 array of points
:param size: (height, width) tuple of new desired size
"""
new_height, new_width = size
# Resize i... | Resize image and associated points, align face to the center
and crop to the desired size
:param img: image to be resized
:param points: *m* x 2 array of points
:param size: (height, width) tuple of new desired size
| resize_align | python | OpenTalker/video-retalking | third_part/GPEN/face_morpher/facemorpher/aligner.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_morpher/facemorpher/aligner.py | Apache-2.0 |
def mask_from_points(size, points):
""" Create a mask of supplied size from supplied points
:param size: tuple of output mask size
:param points: array of [x, y] points
:returns: mask of values 0 and 255 where
255 indicates the convex hull containing the points
"""
radius = 10 # kernel size
k... | Create a mask of supplied size from supplied points
:param size: tuple of output mask size
:param points: array of [x, y] points
:returns: mask of values 0 and 255 where
255 indicates the convex hull containing the points
| mask_from_points | python | OpenTalker/video-retalking | third_part/GPEN/face_morpher/facemorpher/blender.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_morpher/facemorpher/blender.py | Apache-2.0 |
def overlay_image(foreground_image, mask, background_image):
""" Overlay foreground image onto the background given a mask
:param foreground_image: foreground image points
:param mask: [0-255] values in mask
:param background_image: background image points
:returns: image with foreground where mask > 0 overla... | Overlay foreground image onto the background given a mask
:param foreground_image: foreground image points
:param mask: [0-255] values in mask
:param background_image: background image points
:returns: image with foreground where mask > 0 overlaid on background image
| overlay_image | python | OpenTalker/video-retalking | third_part/GPEN/face_morpher/facemorpher/blender.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_morpher/facemorpher/blender.py | Apache-2.0 |
def apply_mask(img, mask):
""" Apply mask to supplied image
:param img: max 3 channel image
:param mask: [0-255] values in mask
:returns: new image with mask applied
"""
masked_img = np.copy(img)
num_channels = 3
for c in range(num_channels):
masked_img[..., c] = img[..., c] * (mask / 255)
return... | Apply mask to supplied image
:param img: max 3 channel image
:param mask: [0-255] values in mask
:returns: new image with mask applied
| apply_mask | python | OpenTalker/video-retalking | third_part/GPEN/face_morpher/facemorpher/blender.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_morpher/facemorpher/blender.py | Apache-2.0 |
def boundary_points(points, width_percent=0.1, height_percent=0.1):
""" Produce additional boundary points
:param points: *m* x 2 array of x,y points
:param width_percent: [-1, 1] percentage of width to taper inwards. Negative for opposite direction
:param height_percent: [-1, 1] percentage of height to taper d... | Produce additional boundary points
:param points: *m* x 2 array of x,y points
:param width_percent: [-1, 1] percentage of width to taper inwards. Negative for opposite direction
:param height_percent: [-1, 1] percentage of height to taper downwards. Negative for opposite direction
:returns: 2 additional points... | boundary_points | python | OpenTalker/video-retalking | third_part/GPEN/face_morpher/facemorpher/locator.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_morpher/facemorpher/locator.py | Apache-2.0 |
def face_points_dlib(img, add_boundary_points=True):
""" Locates 68 face points using dlib (http://dlib.net)
Requires shape_predictor_68_face_landmarks.dat to be in face_morpher/data
Download at: http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2
:param img: an image array
:param add_boundary... | Locates 68 face points using dlib (http://dlib.net)
Requires shape_predictor_68_face_landmarks.dat to be in face_morpher/data
Download at: http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2
:param img: an image array
:param add_boundary_points: bool to add additional boundary points
:returns... | face_points_dlib | python | OpenTalker/video-retalking | third_part/GPEN/face_morpher/facemorpher/locator.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_morpher/facemorpher/locator.py | Apache-2.0 |
def weighted_average_points(start_points, end_points, percent=0.5):
""" Weighted average of two sets of supplied points
:param start_points: *m* x 2 array of start face points.
:param end_points: *m* x 2 array of end face points.
:param percent: [0, 1] percentage weight on start_points
:returns: *m* x 2 arra... | Weighted average of two sets of supplied points
:param start_points: *m* x 2 array of start face points.
:param end_points: *m* x 2 array of end face points.
:param percent: [0, 1] percentage weight on start_points
:returns: *m* x 2 array of weighted average points
| weighted_average_points | python | OpenTalker/video-retalking | third_part/GPEN/face_morpher/facemorpher/locator.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_morpher/facemorpher/locator.py | Apache-2.0 |
def morph(src_img, src_points, dest_img, dest_points,
video, width=500, height=600, num_frames=20, fps=10,
out_frames=None, out_video=None, plot=False, background='black'):
"""
Create a morph sequence from source to destination image
:param src_img: ndarray source image
:param src_points: s... |
Create a morph sequence from source to destination image
:param src_img: ndarray source image
:param src_points: source image array of x,y face points
:param dest_img: ndarray destination image
:param dest_points: destination image array of x,y face points
:param video: facemorpher.videoer.Video object
| morph | python | OpenTalker/video-retalking | third_part/GPEN/face_morpher/facemorpher/morpher.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_morpher/facemorpher/morpher.py | Apache-2.0 |
def morpher(imgpaths, width=500, height=600, num_frames=20, fps=10,
out_frames=None, out_video=None, plot=False, background='black'):
"""
Create a morph sequence from multiple images in imgpaths
:param imgpaths: array or generator of image paths
"""
video = videoer.Video(out_video, fps, width, he... |
Create a morph sequence from multiple images in imgpaths
:param imgpaths: array or generator of image paths
| morpher | python | OpenTalker/video-retalking | third_part/GPEN/face_morpher/facemorpher/morpher.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_morpher/facemorpher/morpher.py | Apache-2.0 |
def bilinear_interpolate(img, coords):
""" Interpolates over every image channel
http://en.wikipedia.org/wiki/Bilinear_interpolation
:param img: max 3 channel image
:param coords: 2 x _m_ array. 1st row = xcoords, 2nd row = ycoords
:returns: array of interpolated pixels with same shape as coords
"""
int_... | Interpolates over every image channel
http://en.wikipedia.org/wiki/Bilinear_interpolation
:param img: max 3 channel image
:param coords: 2 x _m_ array. 1st row = xcoords, 2nd row = ycoords
:returns: array of interpolated pixels with same shape as coords
| bilinear_interpolate | python | OpenTalker/video-retalking | third_part/GPEN/face_morpher/facemorpher/warper.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_morpher/facemorpher/warper.py | Apache-2.0 |
def grid_coordinates(points):
""" x,y grid coordinates within the ROI of supplied points
:param points: points to generate grid coordinates
:returns: array of (x, y) coordinates
"""
xmin = np.min(points[:, 0])
xmax = np.max(points[:, 0]) + 1
ymin = np.min(points[:, 1])
ymax = np.max(points[:, 1]) + 1
... | x,y grid coordinates within the ROI of supplied points
:param points: points to generate grid coordinates
:returns: array of (x, y) coordinates
| grid_coordinates | python | OpenTalker/video-retalking | third_part/GPEN/face_morpher/facemorpher/warper.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_morpher/facemorpher/warper.py | Apache-2.0 |
def process_warp(src_img, result_img, tri_affines, dst_points, delaunay):
"""
Warp each triangle from the src_image only within the
ROI of the destination image (points in dst_points).
"""
roi_coords = grid_coordinates(dst_points)
# indices to vertices. -1 if pixel is not in any triangle
roi_tri_indices =... |
Warp each triangle from the src_image only within the
ROI of the destination image (points in dst_points).
| process_warp | python | OpenTalker/video-retalking | third_part/GPEN/face_morpher/facemorpher/warper.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_morpher/facemorpher/warper.py | Apache-2.0 |
def triangular_affine_matrices(vertices, src_points, dest_points):
"""
Calculate the affine transformation matrix for each
triangle (x,y) vertex from dest_points to src_points
:param vertices: array of triplet indices to corners of triangle
:param src_points: array of [x, y] points to landmarks for source im... |
Calculate the affine transformation matrix for each
triangle (x,y) vertex from dest_points to src_points
:param vertices: array of triplet indices to corners of triangle
:param src_points: array of [x, y] points to landmarks for source image
:param dest_points: array of [x, y] points to landmarks for destin... | triangular_affine_matrices | python | OpenTalker/video-retalking | third_part/GPEN/face_morpher/facemorpher/warper.py | https://github.com/OpenTalker/video-retalking/blob/master/third_part/GPEN/face_morpher/facemorpher/warper.py | Apache-2.0 |
def get_landmark(filepath, predictor, detector=None, fa=None):
"""get landmark with dlib
:return: np.array shape=(68, 2)
"""
if fa is not None:
image = io.imread(filepath)
lms, _, bboxes = fa.get_landmarks(image, return_bboxes=True)
if len(lms) == 0:
return None
... | get landmark with dlib
:return: np.array shape=(68, 2)
| get_landmark | python | OpenTalker/video-retalking | utils/alignment_stit.py | https://github.com/OpenTalker/video-retalking/blob/master/utils/alignment_stit.py | Apache-2.0 |
def align_face(filepath_or_image, predictor, output_size, detector=None,
enable_padding=False, scale=1.0):
"""
:param filepath: str
:return: PIL Image
"""
c, x, y = compute_transform(filepath_or_image, predictor, detector=detector,
scale=scale)
qua... |
:param filepath: str
:return: PIL Image
| align_face | python | OpenTalker/video-retalking | utils/alignment_stit.py | https://github.com/OpenTalker/video-retalking/blob/master/utils/alignment_stit.py | Apache-2.0 |
def num_frames(length, fsize, fshift):
"""Compute number of time frames of spectrogram
"""
pad = (fsize - fshift)
if length % fshift == 0:
M = (length + pad * 2 - fsize) // fshift + 1
else:
M = (length + pad * 2 - fsize) // fshift + 2
return M | Compute number of time frames of spectrogram
| num_frames | python | OpenTalker/video-retalking | utils/audio.py | https://github.com/OpenTalker/video-retalking/blob/master/utils/audio.py | Apache-2.0 |
def get_landmark(self, img_np):
"""get landmark with dlib
:return: np.array shape=(68, 2)
"""
detector = dlib.get_frontal_face_detector()
dets = detector(img_np, 1)
if len(dets) == 0:
return None
d = dets[0]
# Get the landmarks/parts for the fa... | get landmark with dlib
:return: np.array shape=(68, 2)
| get_landmark | python | OpenTalker/video-retalking | utils/ffhq_preprocess.py | https://github.com/OpenTalker/video-retalking/blob/master/utils/ffhq_preprocess.py | Apache-2.0 |
def align_face(self, img, lm, output_size=1024):
"""
:param filepath: str
:return: PIL Image
"""
lm_chin = lm[0: 17] # left-right
lm_eyebrow_left = lm[17: 22] # left-right
lm_eyebrow_right = lm[22: 27] # left-right
lm_nose = lm[27: 31] # top-down
... |
:param filepath: str
:return: PIL Image
| align_face | python | OpenTalker/video-retalking | utils/ffhq_preprocess.py | https://github.com/OpenTalker/video-retalking/blob/master/utils/ffhq_preprocess.py | Apache-2.0 |
def convert_flow_to_deformation(flow):
r"""convert flow fields to deformations.
Args:
flow (tensor): Flow field obtained by the model
Returns:
deformation (tensor): The deformation used for warping
"""
b,c,h,w = flow.shape
flow_norm = 2 * torch.cat([flow[:,:1,...]/(w-1),flow[:,1... | convert flow fields to deformations.
Args:
flow (tensor): Flow field obtained by the model
Returns:
deformation (tensor): The deformation used for warping
| convert_flow_to_deformation | python | OpenTalker/video-retalking | utils/flow_util.py | https://github.com/OpenTalker/video-retalking/blob/master/utils/flow_util.py | Apache-2.0 |
def make_coordinate_grid(flow):
r"""obtain coordinate grid with the same size as the flow filed.
Args:
flow (tensor): Flow field obtained by the model
Returns:
grid (tensor): The grid with the same size as the input flow
"""
b,c,h,w = flow.shape
x = torch.arange(w).to(flow)... | obtain coordinate grid with the same size as the flow filed.
Args:
flow (tensor): Flow field obtained by the model
Returns:
grid (tensor): The grid with the same size as the input flow
| make_coordinate_grid | python | OpenTalker/video-retalking | utils/flow_util.py | https://github.com/OpenTalker/video-retalking/blob/master/utils/flow_util.py | Apache-2.0 |
def warp_image(source_image, deformation):
r"""warp the input image according to the deformation
Args:
source_image (tensor): source images to be warped
deformation (tensor): deformations used to warp the images; value in range (-1, 1)
Returns:
output (tensor): the warped images
... | warp the input image according to the deformation
Args:
source_image (tensor): source images to be warped
deformation (tensor): deformations used to warp the images; value in range (-1, 1)
Returns:
output (tensor): the warped images
| warp_image | python | OpenTalker/video-retalking | utils/flow_util.py | https://github.com/OpenTalker/video-retalking/blob/master/utils/flow_util.py | Apache-2.0 |
def split_coeff(coeffs):
"""
Return:
coeffs_dict -- a dict of torch.tensors
Parameters:
coeffs -- torch.tensor, size (B, 256)
"""
id_coeffs = coeffs[:, :80]
exp_coeffs = coeffs[:, 80: 144]
tex_coeffs = coeffs[:, 144: 224]
... |
Return:
coeffs_dict -- a dict of torch.tensors
Parameters:
coeffs -- torch.tensor, size (B, 256)
| split_coeff | python | OpenTalker/video-retalking | utils/inference_utils.py | https://github.com/OpenTalker/video-retalking/blob/master/utils/inference_utils.py | Apache-2.0 |
def compute_density_for_timestep_sampling(
weighting_scheme: str, batch_size: int, logit_mean: float = None, logit_std: float = None, mode_scale: float = None
):
"""Compute the density for sampling the timesteps when doing SD3 training.
Courtesy: This was contributed by Rafie Walker in https://github.com/h... | Compute the density for sampling the timesteps when doing SD3 training.
Courtesy: This was contributed by Rafie Walker in https://github.com/huggingface/diffusers/pull/8528.
SD3 paper reference: https://arxiv.org/abs/2403.03206v1.
| compute_density_for_timestep_sampling | python | memoavatar/memo | finetune.py | https://github.com/memoavatar/memo/blob/master/finetune.py | Apache-2.0 |
def compute_loss_weighting_for_sd3(weighting_scheme: str, sigmas=None):
"""Computes loss weighting scheme for SD3 training.
Courtesy: This was contributed by Rafie Walker in https://github.com/huggingface/diffusers/pull/8528.
SD3 paper reference: https://arxiv.org/abs/2403.03206v1.
"""
if weightin... | Computes loss weighting scheme for SD3 training.
Courtesy: This was contributed by Rafie Walker in https://github.com/huggingface/diffusers/pull/8528.
SD3 paper reference: https://arxiv.org/abs/2403.03206v1.
| compute_loss_weighting_for_sd3 | python | memoavatar/memo | finetune.py | https://github.com/memoavatar/memo/blob/master/finetune.py | Apache-2.0 |
def set_use_npu_flash_attention(self, use_npu_flash_attention: bool) -> None:
r"""
Set whether to use npu flash attention from `torch_npu` or not.
"""
if use_npu_flash_attention:
processor = AttnProcessorNPU()
else:
# set attention processor
#... |
Set whether to use npu flash attention from `torch_npu` or not.
| set_use_npu_flash_attention | python | memoavatar/memo | memo/models/attention_processor.py | https://github.com/memoavatar/memo/blob/master/memo/models/attention_processor.py | Apache-2.0 |
def set_use_memory_efficient_attention_xformers(
self,
use_memory_efficient_attention_xformers: bool,
attention_op: Optional[Callable] = None,
) -> None:
r"""
Set whether to use memory efficient attention from `xformers` or not.
Args:
use_memory_efficient... |
Set whether to use memory efficient attention from `xformers` or not.
Args:
use_memory_efficient_attention_xformers (`bool`):
Whether to use memory efficient attention from `xformers` or not.
attention_op (`Callable`, *optional*):
The attention o... | set_use_memory_efficient_attention_xformers | python | memoavatar/memo | memo/models/attention_processor.py | https://github.com/memoavatar/memo/blob/master/memo/models/attention_processor.py | Apache-2.0 |
def set_attention_slice(self, slice_size: int) -> None:
r"""
Set the slice size for attention computation.
Args:
slice_size (`int`):
The slice size for attention computation.
"""
if slice_size is not None and slice_size > self.sliceable_head_dim:
... |
Set the slice size for attention computation.
Args:
slice_size (`int`):
The slice size for attention computation.
| set_attention_slice | python | memoavatar/memo | memo/models/attention_processor.py | https://github.com/memoavatar/memo/blob/master/memo/models/attention_processor.py | Apache-2.0 |
def set_processor(self, processor: "AttnProcessor") -> None:
r"""
Set the attention processor to use.
Args:
processor (`AttnProcessor`):
The attention processor to use.
"""
# if current processor is in `self._modules` and if passed `processor` is not,... |
Set the attention processor to use.
Args:
processor (`AttnProcessor`):
The attention processor to use.
| set_processor | python | memoavatar/memo | memo/models/attention_processor.py | https://github.com/memoavatar/memo/blob/master/memo/models/attention_processor.py | Apache-2.0 |
def forward(
self,
hidden_states: torch.Tensor,
encoder_hidden_states: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
**cross_attention_kwargs,
) -> torch.Tensor:
r"""
The forward method of the `Attention` class.
Args:
... |
The forward method of the `Attention` class.
Args:
hidden_states (`torch.Tensor`):
The hidden states of the query.
encoder_hidden_states (`torch.Tensor`, *optional*):
The hidden states of the encoder.
attention_mask (`torch.Tensor`, *... | forward | python | memoavatar/memo | memo/models/attention_processor.py | https://github.com/memoavatar/memo/blob/master/memo/models/attention_processor.py | Apache-2.0 |
def batch_to_head_dim(self, tensor: torch.Tensor) -> torch.Tensor:
r"""
Reshape the tensor from `[batch_size, seq_len, dim]` to `[batch_size // heads, seq_len, dim * heads]`. `heads`
is the number of heads initialized while constructing the `Attention` class.
Args:
tensor (`... |
Reshape the tensor from `[batch_size, seq_len, dim]` to `[batch_size // heads, seq_len, dim * heads]`. `heads`
is the number of heads initialized while constructing the `Attention` class.
Args:
tensor (`torch.Tensor`): The tensor to reshape.
Returns:
`torch.Ten... | batch_to_head_dim | python | memoavatar/memo | memo/models/attention_processor.py | https://github.com/memoavatar/memo/blob/master/memo/models/attention_processor.py | Apache-2.0 |
def head_to_batch_dim(self, tensor: torch.Tensor, out_dim: int = 3) -> torch.Tensor:
r"""
Reshape the tensor from `[batch_size, seq_len, dim]` to `[batch_size, seq_len, heads, dim // heads]` `heads` is
the number of heads initialized while constructing the `Attention` class.
Args:
... |
Reshape the tensor from `[batch_size, seq_len, dim]` to `[batch_size, seq_len, heads, dim // heads]` `heads` is
the number of heads initialized while constructing the `Attention` class.
Args:
tensor (`torch.Tensor`): The tensor to reshape.
out_dim (`int`, *optional*, de... | head_to_batch_dim | python | memoavatar/memo | memo/models/attention_processor.py | https://github.com/memoavatar/memo/blob/master/memo/models/attention_processor.py | Apache-2.0 |
def get_attention_scores(
self,
query: torch.Tensor,
key: torch.Tensor,
attention_mask: torch.Tensor = None,
) -> torch.Tensor:
r"""
Compute the attention scores.
Args:
query (`torch.Tensor`): The query tensor.
key (`torch.Tensor`): Th... |
Compute the attention scores.
Args:
query (`torch.Tensor`): The query tensor.
key (`torch.Tensor`): The key tensor.
attention_mask (`torch.Tensor`, *optional*): The attention mask to use. If `None`, no mask is applied.
Returns:
`torch.Tensor`: T... | get_attention_scores | python | memoavatar/memo | memo/models/attention_processor.py | https://github.com/memoavatar/memo/blob/master/memo/models/attention_processor.py | Apache-2.0 |
def prepare_attention_mask(
self,
attention_mask: torch.Tensor,
target_length: int,
batch_size: int,
out_dim: int = 3,
) -> torch.Tensor:
r"""
Prepare the attention mask for the attention computation.
Args:
attention_mask (`torch.Tensor`):... |
Prepare the attention mask for the attention computation.
Args:
attention_mask (`torch.Tensor`):
The attention mask to prepare.
target_length (`int`):
The target length of the attention mask. This is the length of the attention mask after padding... | prepare_attention_mask | python | memoavatar/memo | memo/models/attention_processor.py | https://github.com/memoavatar/memo/blob/master/memo/models/attention_processor.py | Apache-2.0 |
def norm_encoder_hidden_states(self, encoder_hidden_states: torch.Tensor) -> torch.Tensor:
r"""
Normalize the encoder hidden states. Requires `self.norm_cross` to be specified when constructing the
`Attention` class.
Args:
encoder_hidden_states (`torch.Tensor`): Hidden state... |
Normalize the encoder hidden states. Requires `self.norm_cross` to be specified when constructing the
`Attention` class.
Args:
encoder_hidden_states (`torch.Tensor`): Hidden states of the encoder.
Returns:
`torch.Tensor`: The normalized encoder hidden states.
... | norm_encoder_hidden_states | python | memoavatar/memo | memo/models/attention_processor.py | https://github.com/memoavatar/memo/blob/master/memo/models/attention_processor.py | Apache-2.0 |
def attn_processors(self) -> Dict[str, AttentionProcessor]:
r"""
Returns:
`dict` of attention processors: A dictionary containing all attention processors used in the model with
indexed by its weight name.
"""
# set recursively
processors = {}
def... |
Returns:
`dict` of attention processors: A dictionary containing all attention processors used in the model with
indexed by its weight name.
| attn_processors | python | memoavatar/memo | memo/models/unet_2d_condition.py | https://github.com/memoavatar/memo/blob/master/memo/models/unet_2d_condition.py | Apache-2.0 |
def set_attn_processor(
self,
processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]],
_remove_lora=False,
):
r"""
Sets the attention processor to use to compute attention.
Parameters:
processor (`dict` of `AttentionProcessor` or only `Attenti... |
Sets the attention processor to use to compute attention.
Parameters:
processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
The instantiated processor class or a dictionary of processor classes that will be set as the processor
for **all**... | set_attn_processor | python | memoavatar/memo | memo/models/unet_2d_condition.py | https://github.com/memoavatar/memo/blob/master/memo/models/unet_2d_condition.py | Apache-2.0 |
def set_default_attn_processor(self):
"""
Disables custom attention processors and sets the default attention implementation.
"""
if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
processor = AttnAddedKVProcessor()
elif... |
Disables custom attention processors and sets the default attention implementation.
| set_default_attn_processor | python | memoavatar/memo | memo/models/unet_2d_condition.py | https://github.com/memoavatar/memo/blob/master/memo/models/unet_2d_condition.py | Apache-2.0 |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves Python code examples from Django repository that contain 'django' in the code, which helps identify Django-specific code snippets but provides limited analytical insights beyond basic filtering.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.