index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4,576 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/audio2pose_models/networks.py | 110,111 | 104,114 | forward | Upsample_ | 111,114 | 111,114 | class Upsample_(nn.Module):
def __init__(self, scale=2):
super(Upsample_, self).__init__()
self.upsample = nn.Upsample(mode="bilinear", scale_factor=scale)
def forward(self, x):
FILL_FUNC_BODY | class Upsample_(nn.Module):
def __init__(self, scale=2):
super(Upsample_, self).__init__()
self.upsample = nn.Upsample(mode="bilinear", scale_factor=scale)
def forward(self, x):
FILL_FUNC_BODY | return self.upsample(x)
| return self.upsample(x)
| 2 | 85 | 15 | 100 | import torch.nn as nn
import torch
class ResidualConv(nn.Module):
def __init__(self, input_dim, output_dim, stride, padding):
super(ResidualConv, self).__init__()
self.conv_block = nn.Sequential(
nn.BatchNorm2d(input_dim),
nn.ReLU(),
nn.Conv2d(
... | import torch.nn as nn
import torch
class ResidualConv(nn.Module):
def __init__(self, input_dim, output_dim, stride, padding):
super(ResidualConv, self).__init__()
self.conv_block = nn.Sequential(
nn.BatchNorm2d(input_dim),
nn.ReLU(),
nn.Conv2d(
... |
4,577 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/audio2pose_models/res_unet.py | 39,40 | 6,66 | forward | ResUnet | 40,66 | 40,66 | class ResUnet(nn.Module):
def __init__(self, channel=1, filters=[32, 64, 128, 256]):
super(ResUnet, self).__init__()
self.input_layer = nn.Sequential(
nn.Conv2d(channel, filters[0], kernel_size=3, padding=1),
nn.BatchNorm2d(filters[0]),
nn.ReLU(),
nn.... | class ResUnet(nn.Module):
def __init__(self, channel=1, filters=[32, 64, 128, 256]):
super(ResUnet, self).__init__()
self.input_layer = nn.Sequential(
nn.Conv2d(channel, filters[0], kernel_size=3, padding=1),
nn.BatchNorm2d(filters[0]),
nn.ReLU(),
nn.... | # Encode
x1 = self.input_layer(x) + self.input_skip(x)
x2 = self.residual_conv_1(x1)
x3 = self.residual_conv_2(x2)
# Bridge
x4 = self.bridge(x3)
# Decode
x4 = self.upsample_1(x4)
x5 = torch.cat([x4, x3], dim=1)
x6 = self.up_residual_conv1... | # Encode
x1 = self.input_layer(x) + self.input_skip(x)
x2 = self.residual_conv_1(x1)
x3 = self.residual_conv_2(x2)
# Bridge
x4 = self.bridge(x3)
# Decode
x4 = self.upsample_1(x4)
x5 = torch.cat([x4, x3], dim=1)
x6 = self.up_residual_conv1... | 58 | 614 | 293 | 907 | import torch
import torch.nn as nn
from src.audio2pose_models.networks import ResidualConv, Upsample
class ResUnet(nn.Module):
def __init__(self, channel=1, filters=[32, 64, 128, 256]):
super(ResUnet, self).__init__()
self.input_layer = nn.Sequential(
nn.Conv2d(channel, filters[0], ke... | import torch
import torch.nn as nn
from src.audio2pose_models.networks import ResidualConv, Upsample
class ResUnet(nn.Module):
def __init__(self, channel=1, filters=[32, 64, 128, 256]):
super(ResUnet, self).__init__()
self.input_layer = nn.Sequential(
nn.Conv2d(channel, filters[0], ke... |
4,578 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/face3d/data/image_folder.py | 24,25 | 1,67 | make_dataset | 25,36 | 25,36 | """A modified image folder class
We modify the official PyTorch image folder (https://github.com/pytorch/vision/blob/master/torchvision/datasets/folder.py)
so that this class can load images from both current directory and its subdirectories.
"""
import numpy as np
import torch.utils.data as data
from PIL import Imag... | """A modified image folder class
We modify the official PyTorch image folder (https://github.com/pytorch/vision/blob/master/torchvision/datasets/folder.py)
so that this class can load images from both current directory and its subdirectories.
"""
import numpy as np
import torch.utils.data as data
from PIL import Imag... | images = []
assert os.path.isdir(dir) or os.path.islink(dir), '%s is not a valid directory' % dir
for root, _, fnames in sorted(os.walk(dir, followlinks=True)):
for fname in fnames:
if is_image_file(fname):
path = os.path.join(root, fname)
images.append(p... | images = []
assert os.path.isdir(dir) or os.path.islink(dir), '%s is not a valid directory' % dir
for root, _, fnames in sorted(os.walk(dir, followlinks=True)):
for fname in fnames:
if is_image_file(fname):
path = os.path.join(root, fname)
images.append(p... | 36 | 505 | 136 | 641 | """A modified image folder class
We modify the official PyTorch image folder (https://github.com/pytorch/vision/blob/master/torchvision/datasets/folder.py)
so that this class can load images from both current directory and its subdirectories.
"""
import numpy as np
import torch.utils.data as data
from PIL import Imag... | """A modified image folder class
We modify the official PyTorch image folder (https://github.com/pytorch/vision/blob/master/torchvision/datasets/folder.py)
so that this class can load images from both current directory and its subdirectories.
"""
import numpy as np
import torch.utils.data as data
from PIL import Imag... | |
4,579 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/face3d/data/template_dataset.py | 21,23 | 19,76 | modify_commandline_options | TemplateDataset | 32,36 | 23,36 | class TemplateDataset(BaseDataset):
"""A template dataset class for you to implement custom datasets."""
@staticmethod
def modify_commandline_options(parser, is_train):
FILL_FUNC_BODY def __init__(self, opt):
"""Initialize this dataset class.
Parameters:
opt (Option class) --... | class TemplateDataset(BaseDataset):
"""A template dataset class for you to implement custom datasets."""
@staticmethod
def modify_commandline_options(parser, is_train):
"""Add new dataset-specific options, and rewrite default values for existing options.
Parameters:
parser ... | parser.add_argument('--new_dataset_option', type=float, default=1.0, help='new dataset option')
parser.set_defaults(max_dataset_size=10, new_dataset_option=2.0) # specify dataset-specific default values
return parser
| """Add new dataset-specific options, and rewrite default values for existing options.
Parameters:
parser -- original option parser
is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options.
... | 15 | 628 | 76 | 704 | """Dataset class template
This module provides a template for users to implement custom datasets.
You can specify '--dataset_mode template' to use this dataset.
The class name should be consistent with both the filename and its dataset_mode option.
The filename should be <dataset_mode>_dataset.py
The class name should... | """Dataset class template
This module provides a template for users to implement custom datasets.
You can specify '--dataset_mode template' to use this dataset.
The class name should be consistent with both the filename and its dataset_mode option.
The filename should be <dataset_mode>_dataset.py
The class name should... |
4,581 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/face3d/models/arcface_torch/backbones/iresnet.py | 46,47 | 28,60 | forward | IBasicBlock | 47,60 | 47,60 | class IBasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None,
groups=1, base_width=64, dilation=1):
super(IBasicBlock, self).__init__()
if groups != 1 or base_width != 64:
raise ValueError('BasicBlock only supports groups... | class IBasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None,
groups=1, base_width=64, dilation=1):
super(IBasicBlock, self).__init__()
if groups != 1 or base_width != 64:
raise ValueError('BasicBlock only supports groups... | identity = x
out = self.bn1(x)
out = self.conv1(out)
out = self.bn2(out)
out = self.prelu(out)
out = self.conv2(out)
out = self.bn3(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
return out
| identity = x
out = self.bn1(x)
out = self.conv1(out)
out = self.bn2(out)
out = self.prelu(out)
out = self.conv2(out)
out = self.bn3(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
return out
| 34 | 312 | 117 | 429 | import torch
from torch import nn
__all__ = ['iresnet18', 'iresnet34', 'iresnet50', 'iresnet100', 'iresnet200']
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes,
out_planes,
kernel_size=... | import torch
from torch import nn
__all__ = ['iresnet18', 'iresnet34', 'iresnet50', 'iresnet100', 'iresnet200']
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes,
out_planes,
kernel_size=... |
4,582 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/face3d/models/arcface_torch/backbones/iresnet.py | 114,115 | 60,157 | _make_layer | IResNet | 115,140 | 115,140 | class IResNet(nn.Module):
fc_scale = 7 * 7
def __init__(self,
block, layers, dropout=0, num_features=512, zero_init_residual=False,
groups=1, width_per_group=64, replace_stride_with_dilation=None, fp16=False):
super(IResNet, self).__init__()
self.fp16 = fp16
... | class IResNet(nn.Module):
fc_scale = 7 * 7
def __init__(self,
block, layers, dropout=0, num_features=512, zero_init_residual=False,
groups=1, width_per_group=64, replace_stride_with_dilation=None, fp16=False):
super(IResNet, self).__init__()
self.fp16 = fp16
... | downsample = None
previous_dilation = self.dilation
if dilate:
self.dilation *= stride
stride = 1
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
conv1x1(self.inplanes, planes * block.expansion, ... | downsample = None
previous_dilation = self.dilation
if dilate:
self.dilation *= stride
stride = 1
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
conv1x1(self.inplanes, planes * block.expansion, ... | 67 | 1,046 | 288 | 1,334 | import torch
from torch import nn
__all__ = ['iresnet18', 'iresnet34', 'iresnet50', 'iresnet100', 'iresnet200']
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes,
out_planes,
kernel_size=... | import torch
from torch import nn
__all__ = ['iresnet18', 'iresnet34', 'iresnet50', 'iresnet100', 'iresnet200']
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes,
out_planes,
kernel_size=... |
4,584 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/face3d/models/arcface_torch/backbones/iresnet2060.py | 50,51 | 31,64 | forward | IBasicBlock | 51,64 | 51,64 | class IBasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None,
groups=1, base_width=64, dilation=1):
super(IBasicBlock, self).__init__()
if groups != 1 or base_width != 64:
raise ValueError('BasicBlock only supports group... | class IBasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None,
groups=1, base_width=64, dilation=1):
super(IBasicBlock, self).__init__()
if groups != 1 or base_width != 64:
raise ValueError('BasicBlock only supports group... | identity = x
out = self.bn1(x)
out = self.conv1(out)
out = self.bn2(out)
out = self.prelu(out)
out = self.conv2(out)
out = self.bn3(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
return out
| identity = x
out = self.bn1(x)
out = self.conv1(out)
out = self.bn2(out)
out = self.prelu(out)
out = self.conv2(out)
out = self.bn3(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
return out
| 34 | 316 | 117 | 433 | import torch
from torch import nn
assert torch.__version__ >= "1.8.1"
from torch.utils.checkpoint import checkpoint_sequential
__all__ = ['iresnet2060']
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes,
out... | import torch
from torch import nn
assert torch.__version__ >= "1.8.1"
from torch.utils.checkpoint import checkpoint_sequential
__all__ = ['iresnet2060']
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes,
out... |
4,585 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/face3d/models/arcface_torch/backbones/iresnet2060.py | 151,152 | 64,168 | forward | IResNet | 152,168 | 152,168 | class IResNet(nn.Module):
fc_scale = 7 * 7
def __init__(self,
block, layers, dropout=0, num_features=512, zero_init_residual=False,
groups=1, width_per_group=64, replace_stride_with_dilation=None, fp16=False):
super(IResNet, self).__init__()
self.fp16 = fp16
... | class IResNet(nn.Module):
fc_scale = 7 * 7
def __init__(self,
block, layers, dropout=0, num_features=512, zero_init_residual=False,
groups=1, width_per_group=64, replace_stride_with_dilation=None, fp16=False):
super(IResNet, self).__init__()
self.fp16 = fp16
... | with torch.cuda.amp.autocast(self.fp16):
x = self.conv1(x)
x = self.bn1(x)
x = self.prelu(x)
x = self.layer1(x)
x = self.checkpoint(self.layer2, 20, x)
x = self.checkpoint(self.layer3, 100, x)
x = self.layer4(x)
x = ... | with torch.cuda.amp.autocast(self.fp16):
x = self.conv1(x)
x = self.bn1(x)
x = self.prelu(x)
x = self.layer1(x)
x = self.checkpoint(self.layer2, 20, x)
x = self.checkpoint(self.layer3, 100, x)
x = self.layer4(x)
x = ... | 49 | 1,191 | 207 | 1,398 | import torch
from torch import nn
assert torch.__version__ >= "1.8.1"
from torch.utils.checkpoint import checkpoint_sequential
__all__ = ['iresnet2060']
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes,
out... | import torch
from torch import nn
assert torch.__version__ >= "1.8.1"
from torch.utils.checkpoint import checkpoint_sequential
__all__ = ['iresnet2060']
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes,
out... |
4,586 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/face3d/models/arcface_torch/backbones/mobilefacenet.py | 129,130 | 1,131 | get_mbf | 130,131 | 130,131 | '''
Adapted from https://github.com/cavalleria/cavaface.pytorch/blob/master/backbone/mobilefacenet.py
Original author cavalleria
'''
import torch.nn as nn
from torch.nn import Linear, Conv2d, BatchNorm1d, BatchNorm2d, PReLU, Sequential, Module
import torch
class Flatten(Module):
def forward(self, x):
ret... | '''
Adapted from https://github.com/cavalleria/cavaface.pytorch/blob/master/backbone/mobilefacenet.py
Original author cavalleria
'''
import torch.nn as nn
from torch.nn import Linear, Conv2d, BatchNorm1d, BatchNorm2d, PReLU, Sequential, Module
import torch
class Flatten(Module):
def forward(self, x):
ret... | return MobileFaceNet(fp16, num_features) | return MobileFaceNet(fp16, num_features) | 3 | 1,844 | 15 | 1,859 | '''
Adapted from https://github.com/cavalleria/cavaface.pytorch/blob/master/backbone/mobilefacenet.py
Original author cavalleria
'''
import torch.nn as nn
from torch.nn import Linear, Conv2d, BatchNorm1d, BatchNorm2d, PReLU, Sequential, Module
import torch
class Flatten(Module):
def forward(self, x):
ret... | '''
Adapted from https://github.com/cavalleria/cavaface.pytorch/blob/master/backbone/mobilefacenet.py
Original author cavalleria
'''
import torch.nn as nn
from torch.nn import Linear, Conv2d, BatchNorm1d, BatchNorm2d, PReLU, Sequential, Module
import torch
class Flatten(Module):
def forward(self, x):
ret... | |
4,587 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/face3d/models/arcface_torch/backbones/mobilefacenet.py | 25,26 | 16,29 | forward | ConvBlock | 26,29 | 26,29 | class ConvBlock(Module):
def __init__(self, in_c, out_c, kernel=(1, 1), stride=(1, 1), padding=(0, 0), groups=1):
super(ConvBlock, self).__init__()
self.layers = nn.Sequential(
Conv2d(in_c, out_c, kernel, groups=groups, stride=stride, padding=padding, bias=False),
BatchNorm2d... | class ConvBlock(Module):
def __init__(self, in_c, out_c, kernel=(1, 1), stride=(1, 1), padding=(0, 0), groups=1):
super(ConvBlock, self).__init__()
self.layers = nn.Sequential(
Conv2d(in_c, out_c, kernel, groups=groups, stride=stride, padding=padding, bias=False),
BatchNorm2d... | return self.layers(x)
| return self.layers(x)
| 2 | 169 | 14 | 183 | '''
Adapted from https://github.com/cavalleria/cavaface.pytorch/blob/master/backbone/mobilefacenet.py
Original author cavalleria
'''
import torch.nn as nn
from torch.nn import Linear, Conv2d, BatchNorm1d, BatchNorm2d, PReLU, Sequential, Module
import torch
class Flatten(Module):
def forward(self, x):
ret... | '''
Adapted from https://github.com/cavalleria/cavaface.pytorch/blob/master/backbone/mobilefacenet.py
Original author cavalleria
'''
import torch.nn as nn
from torch.nn import Linear, Conv2d, BatchNorm1d, BatchNorm2d, PReLU, Sequential, Module
import torch
class Flatten(Module):
def forward(self, x):
ret... |
4,588 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/face3d/models/arcface_torch/backbones/mobilefacenet.py | 51,52 | 41,63 | forward | DepthWise | 52,63 | 52,63 | class DepthWise(Module):
def __init__(self, in_c, out_c, residual=False, kernel=(3, 3), stride=(2, 2), padding=(1, 1), groups=1):
super(DepthWise, self).__init__()
self.residual = residual
self.layers = nn.Sequential(
ConvBlock(in_c, out_c=groups, kernel=(1, 1), padding=(0, 0), s... | class DepthWise(Module):
def __init__(self, in_c, out_c, residual=False, kernel=(3, 3), stride=(2, 2), padding=(1, 1), groups=1):
super(DepthWise, self).__init__()
self.residual = residual
self.layers = nn.Sequential(
ConvBlock(in_c, out_c=groups, kernel=(1, 1), padding=(0, 0), s... | short_cut = None
if self.residual:
short_cut = x
x = self.layers(x)
if self.residual:
output = short_cut + x
else:
output = x
return output
| short_cut = None
if self.residual:
short_cut = x
x = self.layers(x)
if self.residual:
output = short_cut + x
else:
output = x
return output
| 24 | 222 | 75 | 297 | '''
Adapted from https://github.com/cavalleria/cavaface.pytorch/blob/master/backbone/mobilefacenet.py
Original author cavalleria
'''
import torch.nn as nn
from torch.nn import Linear, Conv2d, BatchNorm1d, BatchNorm2d, PReLU, Sequential, Module
import torch
class Flatten(Module):
def forward(self, x):
ret... | '''
Adapted from https://github.com/cavalleria/cavaface.pytorch/blob/master/backbone/mobilefacenet.py
Original author cavalleria
'''
import torch.nn as nn
from torch.nn import Linear, Conv2d, BatchNorm1d, BatchNorm2d, PReLU, Sequential, Module
import torch
class Flatten(Module):
def forward(self, x):
ret... |
4,589 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/face3d/models/arcface_torch/backbones/mobilefacenet.py | 12,13 | 11,16 | forward | Flatten | 13,16 | 13,16 | class Flatten(Module):
def forward(self, x):
FILL_FUNC_BODY | class Flatten(Module):
def forward(self, x):
FILL_FUNC_BODY | return x.view(x.size(0), -1)
| return x.view(x.size(0), -1)
| 3 | 26 | 21 | 47 | '''
Adapted from https://github.com/cavalleria/cavaface.pytorch/blob/master/backbone/mobilefacenet.py
Original author cavalleria
'''
import torch.nn as nn
from torch.nn import Linear, Conv2d, BatchNorm1d, BatchNorm2d, PReLU, Sequential, Module
import torch
class Flatten(Module):
def forward(self, x):
FILL_FUNC_B... | '''
Adapted from https://github.com/cavalleria/cavaface.pytorch/blob/master/backbone/mobilefacenet.py
Original author cavalleria
'''
import torch.nn as nn
from torch.nn import Linear, Conv2d, BatchNorm1d, BatchNorm2d, PReLU, Sequential, Module
import torch
class Flatten(Module):
def forward(self, x):
FILL_FUNC_B... |
4,590 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/face3d/models/arcface_torch/backbones/mobilefacenet.py | 84,85 | 75,88 | forward | GDC | 85,88 | 85,88 | class GDC(Module):
def __init__(self, embedding_size):
super(GDC, self).__init__()
self.layers = nn.Sequential(
LinearBlock(512, 512, groups=512, kernel=(7, 7), stride=(1, 1), padding=(0, 0)),
Flatten(),
Linear(512, embedding_size, bias=False),
BatchNo... | class GDC(Module):
def __init__(self, embedding_size):
super(GDC, self).__init__()
self.layers = nn.Sequential(
LinearBlock(512, 512, groups=512, kernel=(7, 7), stride=(1, 1), padding=(0, 0)),
Flatten(),
Linear(512, embedding_size, bias=False),
BatchNo... | return self.layers(x)
| return self.layers(x)
| 2 | 146 | 14 | 160 | '''
Adapted from https://github.com/cavalleria/cavaface.pytorch/blob/master/backbone/mobilefacenet.py
Original author cavalleria
'''
import torch.nn as nn
from torch.nn import Linear, Conv2d, BatchNorm1d, BatchNorm2d, PReLU, Sequential, Module
import torch
class Flatten(Module):
def forward(self, x):
ret... | '''
Adapted from https://github.com/cavalleria/cavaface.pytorch/blob/master/backbone/mobilefacenet.py
Original author cavalleria
'''
import torch.nn as nn
from torch.nn import Linear, Conv2d, BatchNorm1d, BatchNorm2d, PReLU, Sequential, Module
import torch
class Flatten(Module):
def forward(self, x):
ret... |
4,591 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/face3d/models/arcface_torch/backbones/mobilefacenet.py | 37,38 | 29,41 | forward | LinearBlock | 38,41 | 38,41 | class LinearBlock(Module):
def __init__(self, in_c, out_c, kernel=(1, 1), stride=(1, 1), padding=(0, 0), groups=1):
super(LinearBlock, self).__init__()
self.layers = nn.Sequential(
Conv2d(in_c, out_c, kernel, stride, padding, groups=groups, bias=False),
BatchNorm2d(num_featur... | class LinearBlock(Module):
def __init__(self, in_c, out_c, kernel=(1, 1), stride=(1, 1), padding=(0, 0), groups=1):
super(LinearBlock, self).__init__()
self.layers = nn.Sequential(
Conv2d(in_c, out_c, kernel, stride, padding, groups=groups, bias=False),
BatchNorm2d(num_featur... | return self.layers(x)
| return self.layers(x)
| 2 | 148 | 14 | 162 | '''
Adapted from https://github.com/cavalleria/cavaface.pytorch/blob/master/backbone/mobilefacenet.py
Original author cavalleria
'''
import torch.nn as nn
from torch.nn import Linear, Conv2d, BatchNorm1d, BatchNorm2d, PReLU, Sequential, Module
import torch
class Flatten(Module):
def forward(self, x):
ret... | '''
Adapted from https://github.com/cavalleria/cavaface.pytorch/blob/master/backbone/mobilefacenet.py
Original author cavalleria
'''
import torch.nn as nn
from torch.nn import Linear, Conv2d, BatchNorm1d, BatchNorm2d, PReLU, Sequential, Module
import torch
class Flatten(Module):
def forward(self, x):
ret... |
4,592 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/face3d/models/arcface_torch/backbones/mobilefacenet.py | 107,108 | 88,129 | _initialize_weights | MobileFaceNet | 108,121 | 108,121 | class MobileFaceNet(Module):
def __init__(self, fp16=False, num_features=512):
super(MobileFaceNet, self).__init__()
scale = 2
self.fp16 = fp16
self.layers = nn.Sequential(
ConvBlock(3, 64 * scale, kernel=(3, 3), stride=(2, 2), padding=(1, 1)),
ConvBlock(64 * ... | class MobileFaceNet(Module):
def __init__(self, fp16=False, num_features=512):
super(MobileFaceNet, self).__init__()
scale = 2
self.fp16 = fp16
self.layers = nn.Sequential(
ConvBlock(3, 64 * scale, kernel=(3, 3), stride=(2, 2), padding=(1, 1)),
ConvBlock(64 * ... | for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
if m.bias is not None:
m.bias.data.zero_()
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fi... | for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
if m.bias is not None:
m.bias.data.zero_()
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fi... | 33 | 630 | 200 | 830 | '''
Adapted from https://github.com/cavalleria/cavaface.pytorch/blob/master/backbone/mobilefacenet.py
Original author cavalleria
'''
import torch.nn as nn
from torch.nn import Linear, Conv2d, BatchNorm1d, BatchNorm2d, PReLU, Sequential, Module
import torch
class Flatten(Module):
def forward(self, x):
ret... | '''
Adapted from https://github.com/cavalleria/cavaface.pytorch/blob/master/backbone/mobilefacenet.py
Original author cavalleria
'''
import torch.nn as nn
from torch.nn import Linear, Conv2d, BatchNorm1d, BatchNorm2d, PReLU, Sequential, Module
import torch
class Flatten(Module):
def forward(self, x):
ret... |
4,593 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/face3d/models/arcface_torch/backbones/mobilefacenet.py | 71,72 | 63,75 | forward | Residual | 72,75 | 72,75 | class Residual(Module):
def __init__(self, c, num_block, groups, kernel=(3, 3), stride=(1, 1), padding=(1, 1)):
super(Residual, self).__init__()
modules = []
for _ in range(num_block):
modules.append(DepthWise(c, c, True, kernel, stride, padding, groups))
self.layers = Se... | class Residual(Module):
def __init__(self, c, num_block, groups, kernel=(3, 3), stride=(1, 1), padding=(1, 1)):
super(Residual, self).__init__()
modules = []
for _ in range(num_block):
modules.append(DepthWise(c, c, True, kernel, stride, padding, groups))
self.layers = Se... | return self.layers(x)
| return self.layers(x)
| 2 | 135 | 14 | 149 | '''
Adapted from https://github.com/cavalleria/cavaface.pytorch/blob/master/backbone/mobilefacenet.py
Original author cavalleria
'''
import torch.nn as nn
from torch.nn import Linear, Conv2d, BatchNorm1d, BatchNorm2d, PReLU, Sequential, Module
import torch
class Flatten(Module):
def forward(self, x):
ret... | '''
Adapted from https://github.com/cavalleria/cavaface.pytorch/blob/master/backbone/mobilefacenet.py
Original author cavalleria
'''
import torch.nn as nn
from torch.nn import Linear, Conv2d, BatchNorm1d, BatchNorm2d, PReLU, Sequential, Module
import torch
class Flatten(Module):
def forward(self, x):
ret... |
4,594 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/face3d/models/arcface_torch/inference.py | 10,12 | 1,36 | inference | 12,29 | 12,29 | import argparse
import cv2
import numpy as np
import torch
from backbones import get_model
@torch.no_grad()
def inference(weight, name, img):
FILL_FUNC_BODYif __name__ == "__main__":
parser = argparse.ArgumentParser(description='PyTorch ArcFace Training')
parser.add_argument('--network', type=str, default='... | import argparse
import cv2
import numpy as np
import torch
from backbones import get_model
@torch.no_grad()
def inference(weight, name, img):
FILL_FUNC_BODYif __name__ == "__main__":
parser = argparse.ArgumentParser(description='PyTorch ArcFace Training')
parser.add_argument('--network', type=str, default='... | if img is None:
img = np.random.randint(0, 255, size=(112, 112, 3), dtype=np.uint8)
else:
img = cv2.imread(img)
img = cv2.resize(img, (112, 112))
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = np.transpose(img, (2, 0, 1))
img = torch.from_numpy(img).unsqueeze(0).float()
... | if img is None:
img = np.random.randint(0, 255, size=(112, 112, 3), dtype=np.uint8)
else:
img = cv2.imread(img)
img = cv2.resize(img, (112, 112))
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = np.transpose(img, (2, 0, 1))
img = torch.from_numpy(img).unsqueeze(0).float()
... | 45 | 185 | 258 | 443 | import argparse
import cv2
import numpy as np
import torch
from backbones import get_model
@torch.no_grad()
def inference(weight, name, img):
FILL_FUNC_BODYif __name__ == "__main__":
parser = argparse.ArgumentParser(description='PyTorch ArcFace Training')
parser.add_argument('--network', type=str, default='... | import argparse
import cv2
import numpy as np
import torch
from backbones import get_model
@torch.no_grad()
def inference(weight, name, img):
FILL_FUNC_BODYif __name__ == "__main__":
parser = argparse.ArgumentParser(description='PyTorch ArcFace Training')
parser.add_argument('--network', type=str, default='... | |
4,595 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/face3d/models/arcface_torch/losses.py | 5,6 | 1,43 | get_loss | 6,14 | 6,14 | import torch
from torch import nn
def get_loss(name):
FILL_FUNC_BODYclass CosFace(nn.Module):
def __init__(self, s=64.0, m=0.40):
super(CosFace, self).__init__()
self.s = s
self.m = m
def forward(self, cosine, label):
index = torch.where(label != -1)[0]
m_hot = torch.z... | import torch
from torch import nn
def get_loss(name):
FILL_FUNC_BODYclass CosFace(nn.Module):
def __init__(self, s=64.0, m=0.40):
super(CosFace, self).__init__()
self.s = s
self.m = m
def forward(self, cosine, label):
index = torch.where(label != -1)[0]
m_hot = torch.z... | if name == "cosface":
return CosFace()
elif name == "arcface":
return ArcFace()
else:
raise ValueError()
| if name == "cosface":
return CosFace()
elif name == "arcface":
return ArcFace()
else:
raise ValueError()
| 15 | 391 | 50 | 441 | import torch
from torch import nn
def get_loss(name):
FILL_FUNC_BODYclass CosFace(nn.Module):
def __init__(self, s=64.0, m=0.40):
super(CosFace, self).__init__()
self.s = s
self.m = m
def forward(self, cosine, label):
index = torch.where(label != -1)[0]
m_hot = torch.z... | import torch
from torch import nn
def get_loss(name):
FILL_FUNC_BODYclass CosFace(nn.Module):
def __init__(self, s=64.0, m=0.40):
super(CosFace, self).__init__()
self.s = s
self.m = m
def forward(self, cosine, label):
index = torch.where(label != -1)[0]
m_hot = torch.z... | |
4,596 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/face3d/models/arcface_torch/losses.py | 35,36 | 29,43 | forward | ArcFace | 36,43 | 36,43 | class ArcFace(nn.Module):
def __init__(self, s=64.0, m=0.5):
super(ArcFace, self).__init__()
self.s = s
self.m = m
def forward(self, cosine: torch.Tensor, label):
FILL_FUNC_BODY | class ArcFace(nn.Module):
def __init__(self, s=64.0, m=0.5):
super(ArcFace, self).__init__()
self.s = s
self.m = m
def forward(self, cosine: torch.Tensor, label):
FILL_FUNC_BODY | index = torch.where(label != -1)[0]
m_hot = torch.zeros(index.size()[0], cosine.size()[1], device=cosine.device)
m_hot.scatter_(1, label[index, None], self.m)
cosine.acos_()
cosine[index] += m_hot
cosine.cos_().mul_(self.s)
return cosine
| index = torch.where(label != -1)[0]
m_hot = torch.zeros(index.size()[0], cosine.size()[1], device=cosine.device)
m_hot.scatter_(1, label[index, None], self.m)
cosine.acos_()
cosine[index] += m_hot
cosine.cos_().mul_(self.s)
return cosine
| 21 | 86 | 119 | 205 | import torch
from torch import nn
def get_loss(name):
if name == "cosface":
return CosFace()
elif name == "arcface":
return ArcFace()
else:
raise ValueError()
class CosFace(nn.Module):
def __init__(self, s=64.0, m=0.40):
super(CosFace, self).__init__()
self.s ... | import torch
from torch import nn
def get_loss(name):
if name == "cosface":
return CosFace()
elif name == "arcface":
return ArcFace()
else:
raise ValueError()
class CosFace(nn.Module):
def __init__(self, s=64.0, m=0.40):
super(CosFace, self).__init__()
self.s ... |
4,597 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/face3d/models/arcface_torch/losses.py | 20,21 | 14,29 | forward | CosFace | 21,29 | 21,29 | class CosFace(nn.Module):
def __init__(self, s=64.0, m=0.40):
super(CosFace, self).__init__()
self.s = s
self.m = m
def forward(self, cosine, label):
FILL_FUNC_BODY | class CosFace(nn.Module):
def __init__(self, s=64.0, m=0.40):
super(CosFace, self).__init__()
self.s = s
self.m = m
def forward(self, cosine, label):
FILL_FUNC_BODY | index = torch.where(label != -1)[0]
m_hot = torch.zeros(index.size()[0], cosine.size()[1], device=cosine.device)
m_hot.scatter_(1, label[index, None], self.m)
cosine[index] -= m_hot
ret = cosine * self.s
return ret
| index = torch.where(label != -1)[0]
m_hot = torch.zeros(index.size()[0], cosine.size()[1], device=cosine.device)
m_hot.scatter_(1, label[index, None], self.m)
cosine[index] -= m_hot
ret = cosine * self.s
return ret
| 24 | 82 | 108 | 190 | import torch
from torch import nn
def get_loss(name):
if name == "cosface":
return CosFace()
elif name == "arcface":
return ArcFace()
else:
raise ValueError()
class CosFace(nn.Module):
def __init__(self, s=64.0, m=0.40):
super(CosFace, self).__init__()
self.s ... | import torch
from torch import nn
def get_loss(name):
if name == "cosface":
return CosFace()
elif name == "arcface":
return ArcFace()
else:
raise ValueError()
class CosFace(nn.Module):
def __init__(self, s=64.0, m=0.40):
super(CosFace, self).__init__()
self.s ... |
4,598 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/face3d/models/arcface_torch/utils/utils_amp.py | 70,71 | 32,89 | apply_scale | MaxClipGradScaler | 71,88 | 71,88 | class MaxClipGradScaler(GradScaler):
def __init__(self, init_scale, max_scale: float, growth_interval=100):
GradScaler.__init__(self, init_scale=init_scale, growth_interval=growth_interval)
self.max_scale = max_scale
def scale_clip(self):
if self.get_scale() == self.max_scale:
... | class MaxClipGradScaler(GradScaler):
def __init__(self, init_scale, max_scale: float, growth_interval=100):
GradScaler.__init__(self, init_scale=init_scale, growth_interval=growth_interval)
self.max_scale = max_scale
def scale_clip(self):
if self.get_scale() == self.max_scale:
... | if isinstance(val, torch.Tensor):
assert val.is_cuda
if len(stash) == 0:
if self._scale is None:
self._lazy_init_scale_growth_tracker(val.device)
assert self._scale is not None
stash.append(_M... | if isinstance(val, torch.Tensor):
assert val.is_cuda
if len(stash) == 0:
if self._scale is None:
self._lazy_init_scale_growth_tracker(val.device)
assert self._scale is not None
stash.append(_M... | 54 | 483 | 211 | 694 | from typing import Dict, List
import torch
if torch.__version__ < '1.9':
Iterable = torch._six.container_abcs.Iterable
else:
import collections
Iterable = collections.abc.Iterable
from torch.cuda.amp import GradScaler
class _MultiDeviceReplicator(object):
"""
Lazily serves copies of a tensor to... | from typing import Dict, List
import torch
if torch.__version__ < '1.9':
Iterable = torch._six.container_abcs.Iterable
else:
import collections
Iterable = collections.abc.Iterable
from torch.cuda.amp import GradScaler
class _MultiDeviceReplicator(object):
"""
Lazily serves copies of a tensor to... |
4,599 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/face3d/models/arcface_torch/utils/utils_amp.py | 24,25 | 14,32 | get | _MultiDeviceReplicator | 25,32 | 25,32 | class _MultiDeviceReplicator(object):
"""
Lazily serves copies of a tensor to requested devices. Copies are cached per-device.
"""
def __init__(self, master_tensor: torch.Tensor) -> None:
assert master_tensor.is_cuda
self.master = master_tensor
self._per_device_tensors: Dict[to... | class _MultiDeviceReplicator(object):
"""
Lazily serves copies of a tensor to requested devices. Copies are cached per-device.
"""
def __init__(self, master_tensor: torch.Tensor) -> None:
assert master_tensor.is_cuda
self.master = master_tensor
self._per_device_tensors: Dict[to... | retval = self._per_device_tensors.get(device, None)
if retval is None:
retval = self.master.to(device=device, non_blocking=True, copy=True)
self._per_device_tensors[device] = retval
return retval
| retval = self._per_device_tensors.get(device, None)
if retval is None:
retval = self.master.to(device=device, non_blocking=True, copy=True)
self._per_device_tensors[device] = retval
return retval
| 18 | 139 | 86 | 225 | from typing import Dict, List
import torch
if torch.__version__ < '1.9':
Iterable = torch._six.container_abcs.Iterable
else:
import collections
Iterable = collections.abc.Iterable
from torch.cuda.amp import GradScaler
class _MultiDeviceReplicator(object):
"""
Lazily serves copies of a tensor to... | from typing import Dict, List
import torch
if torch.__version__ < '1.9':
Iterable = torch._six.container_abcs.Iterable
else:
import collections
Iterable = collections.abc.Iterable
from torch.cuda.amp import GradScaler
class _MultiDeviceReplicator(object):
"""
Lazily serves copies of a tensor to... |
4,600 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/face3d/models/arcface_torch/utils/utils_callbacks.py | 23,24 | 12,51 | ver_test | CallBackVerification | 24,36 | 24,36 | class CallBackVerification(object):
def __init__(self, frequent, rank, val_targets, rec_prefix, image_size=(112, 112)):
self.frequent: int = frequent
self.rank: int = rank
self.highest_acc: float = 0.0
self.highest_acc_list: List[float] = [0.0] * len(val_targets)
self.ver_lis... | class CallBackVerification(object):
def __init__(self, frequent, rank, val_targets, rec_prefix, image_size=(112, 112)):
self.frequent: int = frequent
self.rank: int = rank
self.highest_acc: float = 0.0
self.highest_acc_list: List[float] = [0.0] * len(val_targets)
self.ver_lis... | results = []
for i in range(len(self.ver_list)):
acc1, std1, acc2, std2, xnorm, embeddings_list = verification.test(
self.ver_list[i], backbone, 10, 10)
logging.info('[%s][%d]XNorm: %f' % (self.ver_name_list[i], global_step, xnorm))
logging.info('[%s][... | results = []
for i in range(len(self.ver_list)):
acc1, std1, acc2, std2, xnorm, embeddings_list = verification.test(
self.ver_list[i], backbone, 10, 10)
logging.info('[%s][%d]XNorm: %f' % (self.ver_name_list[i], global_step, xnorm))
logging.info('[%s][... | 47 | 408 | 273 | 681 | import logging
import os
import time
from typing import List
import torch
from eval import verification
from utils.utils_logging import AverageMeter
class CallBackVerification(object):
def __init__(self, frequent, rank, val_targets, rec_prefix, image_size=(112, 112)):
self.frequent: int = frequent
... | import logging
import os
import time
from typing import List
import torch
from eval import verification
from utils.utils_logging import AverageMeter
class CallBackVerification(object):
def __init__(self, frequent, rank, val_targets, rec_prefix, image_size=(112, 112)):
self.frequent: int = frequent
... |
4,601 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/face3d/models/arcface_torch/utils/utils_config.py | 5,6 | 1,17 | get_config | 6,17 | 6,17 | import importlib
import os.path as osp
def get_config(config_file):
FILL_FUNC_BODY | import importlib
import os.path as osp
def get_config(config_file):
FILL_FUNC_BODY | assert config_file.startswith('configs/'), 'config file setting must start with configs/'
temp_config_name = osp.basename(config_file)
temp_module_name = osp.splitext(temp_config_name)[0]
config = importlib.import_module("configs.base")
cfg = config.config
config = importlib.import_module("confi... | assert config_file.startswith('configs/'), 'config file setting must start with configs/'
temp_config_name = osp.basename(config_file)
temp_module_name = osp.splitext(temp_config_name)[0]
config = importlib.import_module("configs.base")
cfg = config.config
config = importlib.import_module("confi... | 40 | 34 | 183 | 217 | import importlib
import os.path as osp
def get_config(config_file):
FILL_FUNC_BODY | import importlib
import os.path as osp
def get_config(config_file):
FILL_FUNC_BODY | |
4,602 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/face3d/models/arcface_torch/utils/utils_logging.py | 30,31 | 1,42 | init_logging | 31,42 | 31,42 | import logging
import os
import sys
class AverageMeter(object):
"""Computes and stores the average and current value
"""
def __init__(self):
self.val = None
self.avg = None
self.sum = None
self.count = None
self.reset()
def reset(self):
self.val = 0
... | import logging
import os
import sys
class AverageMeter(object):
"""Computes and stores the average and current value
"""
def __init__(self):
self.val = None
self.avg = None
self.sum = None
self.count = None
self.reset()
def reset(self):
self.val = 0
... | if rank == 0:
log_root = logging.getLogger()
log_root.setLevel(logging.INFO)
formatter = logging.Formatter("Training: %(asctime)s-%(message)s")
handler_file = logging.FileHandler(os.path.join(models_root, "training.log"))
handler_stream = logging.StreamHandler(sys.stdout)
... | if rank == 0:
log_root = logging.getLogger()
log_root.setLevel(logging.INFO)
formatter = logging.Formatter("Training: %(asctime)s-%(message)s")
handler_file = logging.FileHandler(os.path.join(models_root, "training.log"))
handler_stream = logging.StreamHandler(sys.stdout)
... | 27 | 191 | 181 | 372 | import logging
import os
import sys
class AverageMeter(object):
"""Computes and stores the average and current value
"""
def __init__(self):
self.val = None
self.avg = None
self.sum = None
self.count = None
self.reset()
def reset(self):
self.val = 0
... | import logging
import os
import sys
class AverageMeter(object):
"""Computes and stores the average and current value
"""
def __init__(self):
self.val = None
self.avg = None
self.sum = None
self.count = None
self.reset()
def reset(self):
self.val = 0
... | |
4,603 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/face3d/models/arcface_torch/utils/utils_logging.py | 17,18 | 6,30 | reset | AverageMeter | 18,23 | 18,23 | class AverageMeter(object):
"""Computes and stores the average and current value
"""
def __init__(self):
self.val = None
self.avg = None
self.sum = None
self.count = None
self.reset()
def reset(self):
FILL_FUNC_BODY def update(self, val, n=1):
self.va... | class AverageMeter(object):
"""Computes and stores the average and current value
"""
def __init__(self):
self.val = None
self.avg = None
self.sum = None
self.count = None
self.reset()
def reset(self):
FILL_FUNC_BODY def update(self, val, n=1):
self.va... | self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
| self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
| 12 | 138 | 35 | 173 | import logging
import os
import sys
class AverageMeter(object):
"""Computes and stores the average and current value
"""
def __init__(self):
self.val = None
self.avg = None
self.sum = None
self.count = None
self.reset()
def reset(self):
FILL_FUNC_BODY def u... | import logging
import os
import sys
class AverageMeter(object):
"""Computes and stores the average and current value
"""
def __init__(self):
self.val = None
self.avg = None
self.sum = None
self.count = None
self.reset()
def reset(self):
FILL_FUNC_BODY def u... |
4,606 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/face3d/options/test_options.py | 13,14 | 7,22 | initialize | TestOptions | 14,22 | 14,22 | class TestOptions(BaseOptions):
"""This class includes test options.
It also includes shared options defined in BaseOptions.
"""
def initialize(self, parser):
FILL_FUNC_BODY | class TestOptions(BaseOptions):
"""This class includes test options.
It also includes shared options defined in BaseOptions.
"""
def initialize(self, parser):
FILL_FUNC_BODY | parser = BaseOptions.initialize(self, parser) # define shared options
parser.add_argument('--phase', type=str, default='test', help='train, val, test, etc')
parser.add_argument('--dataset_mode', type=str, default=None, help='chooses how datasets are loaded. [None | flist]')
parser.add_a... | parser = BaseOptions.initialize(self, parser) # define shared options
parser.add_argument('--phase', type=str, default='test', help='train, val, test, etc')
parser.add_argument('--dataset_mode', type=str, default=None, help='chooses how datasets are loaded. [None | flist]')
parser.add_a... | 49 | 53 | 158 | 211 | """This script contains the test options for Deep3DFaceRecon_pytorch
"""
from .base_options import BaseOptions
class TestOptions(BaseOptions):
"""This class includes test options.
It also includes shared options defined in BaseOptions.
"""
def initialize(self, parser):
FILL_FUNC_BODY | """This script contains the test options for Deep3DFaceRecon_pytorch
"""
from .base_options import BaseOptions
class TestOptions(BaseOptions):
"""This class includes test options.
It also includes shared options defined in BaseOptions.
"""
def initialize(self, parser):
FILL_FUNC_BODY |
4,607 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/face3d/options/train_options.py | 13,14 | 7,54 | initialize | TrainOptions | 14,54 | 14,54 | class TrainOptions(BaseOptions):
"""This class includes training options.
It also includes shared options defined in BaseOptions.
"""
def initialize(self, parser):
FILL_FUNC_BODY | class TrainOptions(BaseOptions):
"""This class includes training options.
It also includes shared options defined in BaseOptions.
"""
def initialize(self, parser):
FILL_FUNC_BODY | parser = BaseOptions.initialize(self, parser)
# dataset parameters
# for train
parser.add_argument('--data_root', type=str, default='./', help='dataset root')
parser.add_argument('--flist', type=str, default='datalist/train/masks.txt', help='list of mask names of training set')
... | parser = BaseOptions.initialize(self, parser)
# dataset parameters
# for train
parser.add_argument('--data_root', type=str, default='./', help='dataset root')
parser.add_argument('--flist', type=str, default='datalist/train/masks.txt', help='list of mask names of training set')
... | 279 | 53 | 1,077 | 1,130 | """This script contains the training options for Deep3DFaceRecon_pytorch
"""
from .base_options import BaseOptions
from util import util
class TrainOptions(BaseOptions):
"""This class includes training options.
It also includes shared options defined in BaseOptions.
"""
def initialize(self, parser):... | """This script contains the training options for Deep3DFaceRecon_pytorch
"""
from .base_options import BaseOptions
from util import util
class TrainOptions(BaseOptions):
"""This class includes training options.
It also includes shared options defined in BaseOptions.
"""
def initialize(self, parser):... |
4,608 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/face3d/util/generate_list.py | 7,8 | 1,35 | write_list | 8,21 | 8,21 | """This script is to generate training list files for Deep3DFaceRecon_pytorch
"""
import os
# save path to training data
def write_list(lms_list, imgs_list, msks_list, mode='train',save_folder='datalist', save_name=''):
FILL_FUNC_BODYdef check_list(rlms_list, rimgs_list, rmsks_list):
lms_list, imgs_list, msks_lis... | """This script is to generate training list files for Deep3DFaceRecon_pytorch
"""
import os
# save path to training data
def write_list(lms_list, imgs_list, msks_list, mode='train',save_folder='datalist', save_name=''):
FILL_FUNC_BODYdef check_list(rlms_list, rimgs_list, rmsks_list):
lms_list, imgs_list, msks_lis... | save_path = os.path.join(save_folder, mode)
if not os.path.isdir(save_path):
os.makedirs(save_path)
with open(os.path.join(save_path, save_name + 'landmarks.txt'), 'w') as fd:
fd.writelines([i + '\n' for i in lms_list])
with open(os.path.join(save_path, save_name + 'images.txt'), 'w') a... | save_path = os.path.join(save_folder, mode)
if not os.path.isdir(save_path):
os.makedirs(save_path)
with open(os.path.join(save_path, save_name + 'landmarks.txt'), 'w') as fd:
fd.writelines([i + '\n' for i in lms_list])
with open(os.path.join(save_path, save_name + 'images.txt'), 'w') a... | 60 | 323 | 228 | 551 | """This script is to generate training list files for Deep3DFaceRecon_pytorch
"""
import os
# save path to training data
def write_list(lms_list, imgs_list, msks_list, mode='train',save_folder='datalist', save_name=''):
FILL_FUNC_BODYdef check_list(rlms_list, rimgs_list, rmsks_list):
lms_list, imgs_list, msks_lis... | """This script is to generate training list files for Deep3DFaceRecon_pytorch
"""
import os
# save path to training data
def write_list(lms_list, imgs_list, msks_list, mode='train',save_folder='datalist', save_name=''):
FILL_FUNC_BODYdef check_list(rlms_list, rimgs_list, rmsks_list):
lms_list, imgs_list, msks_lis... | |
4,609 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/face3d/util/load_mats.py | 32,33 | 1,121 | transferBFM09 | 33,105 | 33,105 | """This script is to load 3D face model for Deep3DFaceRecon_pytorch
"""
import numpy as np
from PIL import Image
from scipy.io import loadmat, savemat
from array import array
import os.path as osp
# load expression basis
def LoadExpBasis(bfm_folder='BFM'):
n_vertex = 53215
Expbin = open(osp.join(bfm_folder, '... | """This script is to load 3D face model for Deep3DFaceRecon_pytorch
"""
import numpy as np
from PIL import Image
from scipy.io import loadmat, savemat
from array import array
import os.path as osp
# load expression basis
def LoadExpBasis(bfm_folder='BFM'):
n_vertex = 53215
Expbin = open(osp.join(bfm_folder, '... | print('Transfer BFM09 to BFM_model_front......')
original_BFM = loadmat(osp.join(bfm_folder, '01_MorphableModel.mat'))
shapePC = original_BFM['shapePC'] # shape basis
shapeEV = original_BFM['shapeEV'] # corresponding eigen value
shapeMU = original_BFM['shapeMU'] # mean face
texPC = original_B... | print('Transfer BFM09 to BFM_model_front......')
original_BFM = loadmat(osp.join(bfm_folder, '01_MorphableModel.mat'))
shapePC = original_BFM['shapePC'] # shape basis
shapeEV = original_BFM['shapeEV'] # corresponding eigen value
shapeMU = original_BFM['shapeMU'] # mean face
texPC = original_B... | 357 | 627 | 1,286 | 1,913 | """This script is to load 3D face model for Deep3DFaceRecon_pytorch
"""
import numpy as np
from PIL import Image
from scipy.io import loadmat, savemat
from array import array
import os.path as osp
# load expression basis
def LoadExpBasis(bfm_folder='BFM'):
n_vertex = 53215
Expbin = open(osp.join(bfm_folder, '... | """This script is to load 3D face model for Deep3DFaceRecon_pytorch
"""
import numpy as np
from PIL import Image
from scipy.io import loadmat, savemat
from array import array
import os.path as osp
# load expression basis
def LoadExpBasis(bfm_folder='BFM'):
n_vertex = 53215
Expbin = open(osp.join(bfm_folder, '... | |
4,611 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/face3d/util/skin_mask.py | 23,24 | 9,42 | likelihood | GMM | 24,42 | 24,42 | class GMM:
def __init__(self, dim, num, w, mu, cov, cov_det, cov_inv):
self.dim = dim # feature dimension
self.num = num # number of Gaussian components
self.w = w # weights of Gaussian components (a list of scalars)
self.mu= mu # mean of Gaussian components (a list of 1xdim vectors)... | class GMM:
def __init__(self, dim, num, w, mu, cov, cov_det, cov_inv):
self.dim = dim # feature dimension
self.num = num # number of Gaussian components
self.w = w # weights of Gaussian components (a list of scalars)
self.mu= mu # mean of Gaussian components (a list of 1xdim vectors)... | assert(data.shape[1] == self.dim)
N = data.shape[0]
lh = np.zeros(N)
for i in range(self.num):
data_ = data - self.mu[i]
tmp = np.matmul(data_,self.cov_inv[i]) * data_
tmp = np.sum(tmp,axis=1)
power = -0.5 * tmp
p = np.array(... | assert(data.shape[1] == self.dim)
N = data.shape[0]
lh = np.zeros(N)
for i in range(self.num):
data_ = data - self.mu[i]
tmp = np.matmul(data_,self.cov_inv[i]) * data_
tmp = np.sum(tmp,axis=1)
power = -0.5 * tmp
p = np.array(... | 46 | 253 | 187 | 440 | """This script is to generate skin attention mask for Deep3DFaceRecon_pytorch
"""
import math
import numpy as np
import os
import cv2
class GMM:
def __init__(self, dim, num, w, mu, cov, cov_det, cov_inv):
self.dim = dim # feature dimension
self.num = num # number of Gaussian components
sel... | """This script is to generate skin attention mask for Deep3DFaceRecon_pytorch
"""
import math
import numpy as np
import os
import cv2
class GMM:
def __init__(self, dim, num, w, mu, cov, cov_det, cov_inv):
self.dim = dim # feature dimension
self.num = num # number of Gaussian components
sel... |
4,613 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/face3d/util/visualizer.py | 174,176 | 150,228 | display_current_results | MyVisualizer | 184,205 | 176,205 | class MyVisualizer:
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... | class MyVisualizer:
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... | # if (not add_image) and (not save_results): return
for label, image in visuals.items():
for i in range(image.shape[0]):
image_numpy = util.tensor2im(image[i])
if add_image:
self.writer.add_image(label + '%s_%02d'%(dataset, i + cou... | """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'... | 66 | 827 | 310 | 1,137 | """This script defines the visualizer for Deep3DFaceRecon_pytorch
"""
import numpy as np
import os
import sys
import ntpath
import time
from . import util, html
from subprocess import Popen, PIPE
from torch.utils.tensorboard import SummaryWriter
def save_images(webpage, visuals, image_path, aspect_ratio=1.0, width=25... | """This script defines the visualizer for Deep3DFaceRecon_pytorch
"""
import numpy as np
import os
import sys
import ntpath
import time
from . import util, html
from subprocess import Popen, PIPE
from torch.utils.tensorboard import SummaryWriter
def save_images(webpage, visuals, image_path, aspect_ratio=1.0, width=25... |
4,614 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/face3d/util/visualizer.py | 117,118 | 44,150 | plot_current_losses | Visualizer | 118,131 | 118,131 | class Visualizer():
"""This class includes several functions that can display/save images and print/save logging information.
It uses a Python library tensprboardX for display, and a Python library 'dominate' (wrapped in 'HTML') for creating HTML files with images.
"""
def __init__(self, opt):
... | class Visualizer():
"""This class includes several functions that can display/save images and print/save logging information.
It uses a Python library tensprboardX for display, and a Python library 'dominate' (wrapped in 'HTML') for creating HTML files with images.
"""
def __init__(self, opt):
... | # G_loss_collection = {}
# D_loss_collection = {}
# for name, value in losses.items():
# if 'G' in name or 'NCE' in name or 'idt' in name:
# G_loss_collection[name] = value
# else:
# D_loss_collection[name] = value
# self.writer.add... | # G_loss_collection = {}
# D_loss_collection = {}
# for name, value in losses.items():
# if 'G' in name or 'NCE' in name or 'idt' in name:
# G_loss_collection[name] = value
# else:
# D_loss_collection[name] = value
# self.writer.add... | 61 | 1,336 | 213 | 1,549 | """This script defines the visualizer for Deep3DFaceRecon_pytorch
"""
import numpy as np
import os
import sys
import ntpath
import time
from . import util, html
from subprocess import Popen, PIPE
from torch.utils.tensorboard import SummaryWriter
def save_images(webpage, visuals, image_path, aspect_ratio=1.0, width=25... | """This script defines the visualizer for Deep3DFaceRecon_pytorch
"""
import numpy as np
import os
import sys
import ntpath
import time
from . import util, html
from subprocess import Popen, PIPE
from torch.utils.tensorboard import SummaryWriter
def save_images(webpage, visuals, image_path, aspect_ratio=1.0, width=25... |
4,615 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/face3d/visualize.py | 12,13 | 1,49 | gen_composed_video | 13,49 | 13,49 | # check the sync of 3dmm feature and the audio
import cv2
import numpy as np
from src.face3d.models.bfm import ParametricFaceModel
from src.face3d.models.facerecon_model import FaceReconModel
import torch
import subprocess, platform
import scipy.io as scio
from tqdm import tqdm
# draft
def gen_composed_video(args, de... | # check the sync of 3dmm feature and the audio
import cv2
import numpy as np
from src.face3d.models.bfm import ParametricFaceModel
from src.face3d.models.facerecon_model import FaceReconModel
import torch
import subprocess, platform
import scipy.io as scio
from tqdm import tqdm
# draft
def gen_composed_video(args, de... |
coeff_first = scio.loadmat(first_frame_coeff)['full_3dmm']
coeff_pred = scio.loadmat(coeff_path)['coeff_3dmm']
coeff_full = np.repeat(coeff_first, coeff_pred.shape[0], axis=0) # 257
coeff_full[:, 80:144] = coeff_pred[:, 0:64]
coeff_full[:, 224:227] = coeff_pred[:, 64:67] # 3 dim translation... |
coeff_first = scio.loadmat(first_frame_coeff)['full_3dmm']
coeff_pred = scio.loadmat(coeff_path)['coeff_3dmm']
coeff_full = np.repeat(coeff_first, coeff_pred.shape[0], axis=0) # 257
coeff_full[:, 80:144] = coeff_pred[:, 0:64]
coeff_full[:, 224:227] = coeff_pred[:, 64:67] # 3 dim translation... | 105 | 147 | 591 | 738 | # check the sync of 3dmm feature and the audio
import cv2
import numpy as np
from src.face3d.models.bfm import ParametricFaceModel
from src.face3d.models.facerecon_model import FaceReconModel
import torch
import subprocess, platform
import scipy.io as scio
from tqdm import tqdm
# draft
def gen_composed_video(args, de... | # check the sync of 3dmm feature and the audio
import cv2
import numpy as np
from src.face3d.models.bfm import ParametricFaceModel
from src.face3d.models.facerecon_model import FaceReconModel
import torch
import subprocess, platform
import scipy.io as scio
from tqdm import tqdm
# draft
def gen_composed_video(args, de... | |
4,617 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/facerender/modules/generator.py | 61,62 | 8,120 | deform_input | OcclusionAwareGenerator | 62,70 | 62,70 | class OcclusionAwareGenerator(nn.Module):
"""
Generator follows NVIDIA architecture.
"""
def __init__(self, image_channel, feature_channel, num_kp, block_expansion, max_features, num_down_blocks, reshape_channel, reshape_depth,
num_resblocks, estimate_occlusion_map=False, dense_motion_... | class OcclusionAwareGenerator(nn.Module):
"""
Generator follows NVIDIA architecture.
"""
def __init__(self, image_channel, feature_channel, num_kp, block_expansion, max_features, num_down_blocks, reshape_channel, reshape_depth,
num_resblocks, estimate_occlusion_map=False, dense_motion_... | _, d_old, h_old, w_old, _ = deformation.shape
_, _, d, h, w = inp.shape
if d_old != d or h_old != h or w_old != w:
deformation = deformation.permute(0, 4, 1, 2, 3)
deformation = F.interpolate(deformation, size=(d, h, w), mode='trilinear')
deformation = deforma... | _, d_old, h_old, w_old, _ = deformation.shape
_, _, d, h, w = inp.shape
if d_old != d or h_old != h or w_old != w:
deformation = deformation.permute(0, 4, 1, 2, 3)
deformation = F.interpolate(deformation, size=(d, h, w), mode='trilinear')
deformation = deforma... | 50 | 1,597 | 166 | 1,763 | import torch
from torch import nn
import torch.nn.functional as F
from src.facerender.modules.util import ResBlock2d, SameBlock2d, UpBlock2d, DownBlock2d, ResBlock3d, SPADEResnetBlock
from src.facerender.modules.dense_motion import DenseMotionNetwork
class OcclusionAwareGenerator(nn.Module):
"""
Generator fol... | import torch
from torch import nn
import torch.nn.functional as F
from src.facerender.modules.util import ResBlock2d, SameBlock2d, UpBlock2d, DownBlock2d, ResBlock3d, SPADEResnetBlock
from src.facerender.modules.dense_motion import DenseMotionNetwork
class OcclusionAwareGenerator(nn.Module):
"""
Generator fol... |
4,618 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/facerender/modules/generator.py | 210,211 | 161,256 | forward | OcclusionAwareSPADEGenerator | 211,256 | 211,256 | class OcclusionAwareSPADEGenerator(nn.Module):
def __init__(self, image_channel, feature_channel, num_kp, block_expansion, max_features, num_down_blocks, reshape_channel, reshape_depth,
num_resblocks, estimate_occlusion_map=False, dense_motion_params=None, estimate_jacobian=False):
super(O... | class OcclusionAwareSPADEGenerator(nn.Module):
def __init__(self, image_channel, feature_channel, num_kp, block_expansion, max_features, num_down_blocks, reshape_channel, reshape_depth,
num_resblocks, estimate_occlusion_map=False, dense_motion_params=None, estimate_jacobian=False):
super(O... | # Encoding (downsampling) part
out = self.first(source_image)
for i in range(len(self.down_blocks)):
out = self.down_blocks[i](out)
out = self.second(out)
bs, c, h, w = out.shape
# print(out.shape)
feature_3d = out.view(bs, self.reshape_channel, self.r... | # Encoding (downsampling) part
out = self.first(source_image)
for i in range(len(self.down_blocks)):
out = self.down_blocks[i](out)
out = self.second(out)
bs, c, h, w = out.shape
# print(out.shape)
feature_3d = out.view(bs, self.reshape_channel, self.r... | 146 | 887 | 615 | 1,502 | import torch
from torch import nn
import torch.nn.functional as F
from src.facerender.modules.util import ResBlock2d, SameBlock2d, UpBlock2d, DownBlock2d, ResBlock3d, SPADEResnetBlock
from src.facerender.modules.dense_motion import DenseMotionNetwork
class OcclusionAwareGenerator(nn.Module):
"""
Generator fol... | import torch
from torch import nn
import torch.nn.functional as F
from src.facerender.modules.util import ResBlock2d, SameBlock2d, UpBlock2d, DownBlock2d, ResBlock3d, SPADEResnetBlock
from src.facerender.modules.dense_motion import DenseMotionNetwork
class OcclusionAwareGenerator(nn.Module):
"""
Generator fol... |
4,619 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/facerender/modules/generator.py | 140,141 | 120,161 | forward | SPADEDecoder | 141,161 | 141,161 | class SPADEDecoder(nn.Module):
def __init__(self):
super().__init__()
ic = 256
oc = 64
norm_G = 'spadespectralinstance'
label_nc = 256
self.fc = nn.Conv2d(ic, 2 * ic, 3, padding=1)
self.G_middle_0 = SPADEResnetBlock(2 * ic, 2 * ic, norm_G, label_nc)
... | class SPADEDecoder(nn.Module):
def __init__(self):
super().__init__()
ic = 256
oc = 64
norm_G = 'spadespectralinstance'
label_nc = 256
self.fc = nn.Conv2d(ic, 2 * ic, 3, padding=1)
self.G_middle_0 = SPADEResnetBlock(2 * ic, 2 * ic, norm_G, label_nc)
... | seg = feature
x = self.fc(feature)
x = self.G_middle_0(x, seg)
x = self.G_middle_1(x, seg)
x = self.G_middle_2(x, seg)
x = self.G_middle_3(x, seg)
x = self.G_middle_4(x, seg)
x = self.G_middle_5(x, seg)
x = self.up(x)
x = se... | seg = feature
x = self.fc(feature)
x = self.G_middle_0(x, seg)
x = self.G_middle_1(x, seg)
x = self.G_middle_2(x, seg)
x = self.G_middle_3(x, seg)
x = self.G_middle_4(x, seg)
x = self.G_middle_5(x, seg)
x = self.up(x)
x = se... | 65 | 421 | 272 | 693 | import torch
from torch import nn
import torch.nn.functional as F
from src.facerender.modules.util import ResBlock2d, SameBlock2d, UpBlock2d, DownBlock2d, ResBlock3d, SPADEResnetBlock
from src.facerender.modules.dense_motion import DenseMotionNetwork
class OcclusionAwareGenerator(nn.Module):
"""
Generator fol... | import torch
from torch import nn
import torch.nn.functional as F
from src.facerender.modules.util import ResBlock2d, SameBlock2d, UpBlock2d, DownBlock2d, ResBlock3d, SPADEResnetBlock
from src.facerender.modules.dense_motion import DenseMotionNetwork
class OcclusionAwareGenerator(nn.Module):
"""
Generator fol... |
4,620 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/facerender/modules/keypoint_detector.py | 136,137 | 85,180 | forward | HEEstimator | 137,180 | 137,180 | class HEEstimator(nn.Module):
"""
Estimating head pose and expression.
"""
def __init__(self, block_expansion, feature_channel, num_kp, image_channel, max_features, num_bins=66, estimate_jacobian=True):
super(HEEstimator, self).__init__()
self.conv1 = nn.Conv2d(in_channels=image_channe... | class HEEstimator(nn.Module):
"""
Estimating head pose and expression.
"""
def __init__(self, block_expansion, feature_channel, num_kp, image_channel, max_features, num_bins=66, estimate_jacobian=True):
super(HEEstimator, self).__init__()
self.conv1 = nn.Conv2d(in_channels=image_channe... | out = self.conv1(x)
out = self.norm1(out)
out = F.relu(out)
out = self.maxpool(out)
out = self.conv2(out)
out = self.norm2(out)
out = F.relu(out)
out = self.block1(out)
out = self.conv3(out)
out = self.norm3(out)
out = F.relu(out... | out = self.conv1(x)
out = self.norm1(out)
out = F.relu(out)
out = self.maxpool(out)
out = self.conv2(out)
out = self.norm2(out)
out = F.relu(out)
out = self.block1(out)
out = self.conv3(out)
out = self.norm3(out)
out = F.relu(out... | 103 | 929 | 440 | 1,369 | from torch import nn
import torch
import torch.nn.functional as F
from src.facerender.sync_batchnorm import SynchronizedBatchNorm2d as BatchNorm2d
from src.facerender.modules.util import KPHourglass, make_coordinate_grid, AntiAliasInterpolation2d, ResBottleneck
class KPDetector(nn.Module):
"""
Detecting cano... | from torch import nn
import torch
import torch.nn.functional as F
from src.facerender.sync_batchnorm import SynchronizedBatchNorm2d as BatchNorm2d
from src.facerender.modules.util import KPHourglass, make_coordinate_grid, AntiAliasInterpolation2d, ResBottleneck
class KPDetector(nn.Module):
"""
Detecting cano... |
4,621 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/facerender/modules/keypoint_detector.py | 56,57 | 9,85 | forward | KPDetector | 57,85 | 57,85 | class KPDetector(nn.Module):
"""
Detecting canonical keypoints. Return keypoint position and jacobian near each keypoint.
"""
def __init__(self, block_expansion, feature_channel, num_kp, image_channel, max_features, reshape_channel, reshape_depth,
num_blocks, temperature, estimate_jaco... | class KPDetector(nn.Module):
"""
Detecting canonical keypoints. Return keypoint position and jacobian near each keypoint.
"""
def __init__(self, block_expansion, feature_channel, num_kp, image_channel, max_features, reshape_channel, reshape_depth,
num_blocks, temperature, estimate_jaco... | if self.scale_factor != 1:
x = self.down(x)
feature_map = self.predictor(x)
prediction = self.kp(feature_map)
final_shape = prediction.shape
heatmap = prediction.view(final_shape[0], final_shape[1], -1)
heatmap = F.softmax(heatmap / self.temperature, dim=2)
... | if self.scale_factor != 1:
x = self.down(x)
feature_map = self.predictor(x)
prediction = self.kp(feature_map)
final_shape = prediction.shape
heatmap = prediction.view(final_shape[0], final_shape[1], -1)
heatmap = F.softmax(heatmap / self.temperature, dim=2)
... | 77 | 803 | 384 | 1,187 | from torch import nn
import torch
import torch.nn.functional as F
from src.facerender.sync_batchnorm import SynchronizedBatchNorm2d as BatchNorm2d
from src.facerender.modules.util import KPHourglass, make_coordinate_grid, AntiAliasInterpolation2d, ResBottleneck
class KPDetector(nn.Module):
"""
Detecting cano... | from torch import nn
import torch
import torch.nn.functional as F
from src.facerender.sync_batchnorm import SynchronizedBatchNorm2d as BatchNorm2d
from src.facerender.modules.util import KPHourglass, make_coordinate_grid, AntiAliasInterpolation2d, ResBottleneck
class KPDetector(nn.Module):
"""
Detecting cano... |
4,622 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/facerender/modules/mapping.py | 32,33 | 8,48 | forward | MappingNet | 33,48 | 33,48 | class MappingNet(nn.Module):
def __init__(self, coeff_nc, descriptor_nc, layer, num_kp, num_bins):
super( MappingNet, self).__init__()
self.layer = layer
nonlinearity = nn.LeakyReLU(0.1)
self.first = nn.Sequential(
torch.nn.Conv1d(coeff_nc, descriptor_nc, kernel_size=7,... | class MappingNet(nn.Module):
def __init__(self, coeff_nc, descriptor_nc, layer, num_kp, num_bins):
super( MappingNet, self).__init__()
self.layer = layer
nonlinearity = nn.LeakyReLU(0.1)
self.first = nn.Sequential(
torch.nn.Conv1d(coeff_nc, descriptor_nc, kernel_size=7,... | out = self.first(input_3dmm)
for i in range(self.layer):
model = getattr(self, 'encoder' + str(i))
out = model(out) + out[:,:,3:-3]
out = self.pooling(out)
out = out.view(out.shape[0], -1)
#print('out:', out.shape)
yaw = self.fc_yaw(out)
p... | out = self.first(input_3dmm)
for i in range(self.layer):
model = getattr(self, 'encoder' + str(i))
out = model(out) + out[:,:,3:-3]
out = self.pooling(out)
out = out.view(out.shape[0], -1)
#print('out:', out.shape)
yaw = self.fc_yaw(out)
p... | 53 | 384 | 212 | 596 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class MappingNet(nn.Module):
def __init__(self, coeff_nc, descriptor_nc, layer, num_kp, num_bins):
super( MappingNet, self).__init__()
self.layer = layer
nonlinearity = nn.LeakyReLU(0.1)
self.f... | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class MappingNet(nn.Module):
def __init__(self, coeff_nc, descriptor_nc, layer, num_kp, num_bins):
super( MappingNet, self).__init__()
self.layer = layer
nonlinearity = nn.LeakyReLU(0.1)
self.f... |
4,624 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/facerender/sync_batchnorm/batchnorm.py | 184,185 | 128,191 | _check_input_dim | SynchronizedBatchNorm1d | 185,191 | 185,191 | class SynchronizedBatchNorm1d(_SynchronizedBatchNorm):
r"""Applies Synchronized Batch Normalization over a 2d or 3d input that is seen as a
mini-batch.
.. math::
y = \frac{x - mean[x]}{ \sqrt{Var[x] + \epsilon}} * gamma + beta
This module differs from the built-in PyTorch BatchNorm1d as the m... | class SynchronizedBatchNorm1d(_SynchronizedBatchNorm):
r"""Applies Synchronized Batch Normalization over a 2d or 3d input that is seen as a
mini-batch.
.. math::
y = \frac{x - mean[x]}{ \sqrt{Var[x] + \epsilon}} * gamma + beta
This module differs from the built-in PyTorch BatchNorm1d as the m... | if input.dim() != 2 and input.dim() != 3:
raise ValueError('expected 2D or 3D input (got {}D input)'
.format(input.dim()))
super(SynchronizedBatchNorm1d, self)._check_input_dim(input)
| if input.dim() != 2 and input.dim() != 3:
raise ValueError('expected 2D or 3D input (got {}D input)'
.format(input.dim()))
super(SynchronizedBatchNorm1d, self)._check_input_dim(input)
| 20 | 715 | 80 | 795 | # -*- coding: utf-8 -*-
# File : batchnorm.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import collections
import torch
import tor... | # -*- coding: utf-8 -*-
# File : batchnorm.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import collections
import torch
import tor... |
4,625 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/facerender/sync_batchnorm/batchnorm.py | 247,248 | 191,254 | _check_input_dim | SynchronizedBatchNorm2d | 248,254 | 248,254 | class SynchronizedBatchNorm2d(_SynchronizedBatchNorm):
r"""Applies Batch Normalization over a 4d input that is seen as a mini-batch
of 3d inputs
.. math::
y = \frac{x - mean[x]}{ \sqrt{Var[x] + \epsilon}} * gamma + beta
This module differs from the built-in PyTorch BatchNorm2d as the mean and... | class SynchronizedBatchNorm2d(_SynchronizedBatchNorm):
r"""Applies Batch Normalization over a 4d input that is seen as a mini-batch
of 3d inputs
.. math::
y = \frac{x - mean[x]}{ \sqrt{Var[x] + \epsilon}} * gamma + beta
This module differs from the built-in PyTorch BatchNorm2d as the mean and... | if input.dim() != 4:
raise ValueError('expected 4D input (got {}D input)'
.format(input.dim()))
super(SynchronizedBatchNorm2d, self)._check_input_dim(input)
| if input.dim() != 4:
raise ValueError('expected 4D input (got {}D input)'
.format(input.dim()))
super(SynchronizedBatchNorm2d, self)._check_input_dim(input)
| 14 | 701 | 68 | 769 | # -*- coding: utf-8 -*-
# File : batchnorm.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import collections
import torch
import tor... | # -*- coding: utf-8 -*-
# File : batchnorm.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import collections
import torch
import tor... |
4,626 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/facerender/sync_batchnorm/batchnorm.py | 311,312 | 254,316 | _check_input_dim | SynchronizedBatchNorm3d | 312,316 | 312,316 | class SynchronizedBatchNorm3d(_SynchronizedBatchNorm):
r"""Applies Batch Normalization over a 5d input that is seen as a mini-batch
of 4d inputs
.. math::
y = \frac{x - mean[x]}{ \sqrt{Var[x] + \epsilon}} * gamma + beta
This module differs from the built-in PyTorch BatchNorm3d as the mean and... | class SynchronizedBatchNorm3d(_SynchronizedBatchNorm):
r"""Applies Batch Normalization over a 5d input that is seen as a mini-batch
of 4d inputs
.. math::
y = \frac{x - mean[x]}{ \sqrt{Var[x] + \epsilon}} * gamma + beta
This module differs from the built-in PyTorch BatchNorm3d as the mean and... | if input.dim() != 5:
raise ValueError('expected 5D input (got {}D input)'
.format(input.dim()))
super(SynchronizedBatchNorm3d, self)._check_input_dim(input)
| if input.dim() != 5:
raise ValueError('expected 5D input (got {}D input)'
.format(input.dim()))
super(SynchronizedBatchNorm3d, self)._check_input_dim(input)
| 14 | 727 | 64 | 791 | # -*- coding: utf-8 -*-
# File : batchnorm.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import collections
import torch
import tor... | # -*- coding: utf-8 -*-
# File : batchnorm.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import collections
import torch
import tor... |
4,627 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/facerender/sync_batchnorm/batchnorm.py | 48,49 | 38,128 | forward | _SynchronizedBatchNorm | 49,80 | 49,80 | class _SynchronizedBatchNorm(_BatchNorm):
def __init__(self, num_features, eps=1e-5, momentum=0.1, affine=True):
super(_SynchronizedBatchNorm, self).__init__(num_features, eps=eps, momentum=momentum, affine=affine)
self._sync_master = SyncMaster(self._data_parallel_master)
self._is_paralle... | class _SynchronizedBatchNorm(_BatchNorm):
def __init__(self, num_features, eps=1e-5, momentum=0.1, affine=True):
super(_SynchronizedBatchNorm, self).__init__(num_features, eps=eps, momentum=momentum, affine=affine)
self._sync_master = SyncMaster(self._data_parallel_master)
self._is_paralle... | # If it is not parallel computation or is in evaluation mode, use PyTorch's implementation.
if not (self._is_parallel and self.training):
return F.batch_norm(
input, self.running_mean, self.running_var, self.weight, self.bias,
self.training, self.momentum, sel... | # If it is not parallel computation or is in evaluation mode, use PyTorch's implementation.
if not (self._is_parallel and self.training):
return F.batch_norm(
input, self.running_mean, self.running_var, self.weight, self.bias,
self.training, self.momentum, sel... | 123 | 802 | 462 | 1,264 | # -*- coding: utf-8 -*-
# File : batchnorm.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import collections
import torch
import tor... | # -*- coding: utf-8 -*-
# File : batchnorm.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import collections
import torch
import tor... |
4,628 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/facerender/sync_batchnorm/comm.py | 26,27 | 18,42 | put | FutureResult | 27,32 | 27,32 | class FutureResult(object):
"""A thread-safe future implementation. Used only as one-to-one pipe."""
def __init__(self):
self._result = None
self._lock = threading.Lock()
self._cond = threading.Condition(self._lock)
def put(self, result):
FILL_FUNC_BODY def get(self):
wi... | class FutureResult(object):
"""A thread-safe future implementation. Used only as one-to-one pipe."""
def __init__(self):
self._result = None
self._lock = threading.Lock()
self._cond = threading.Condition(self._lock)
def put(self, result):
FILL_FUNC_BODY def get(self):
wi... | with self._lock:
assert self._result is None, 'Previous result has\'t been fetched.'
self._result = result
self._cond.notify()
| with self._lock:
assert self._result is None, 'Previous result has\'t been fetched.'
self._result = result
self._cond.notify()
| 15 | 141 | 47 | 188 | # -*- coding: utf-8 -*-
# File : comm.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import queue
import collections
import threading... | # -*- coding: utf-8 -*-
# File : comm.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import queue
import collections
import threading... |
4,629 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/facerender/sync_batchnorm/comm.py | 49,50 | 46,56 | run_slave | SlavePipe | 50,56 | 50,56 | class SlavePipe(_SlavePipeBase):
"""Pipe for master-slave communication."""
def run_slave(self, msg):
FILL_FUNC_BODY | class SlavePipe(_SlavePipeBase):
"""Pipe for master-slave communication."""
def run_slave(self, msg):
FILL_FUNC_BODY | self.queue.put((self.identifier, msg))
ret = self.result.get()
self.queue.put(True)
return ret
| self.queue.put((self.identifier, msg))
ret = self.result.get()
self.queue.put(True)
return ret
| 8 | 46 | 46 | 92 | # -*- coding: utf-8 -*-
# File : comm.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import queue
import collections
import threading... | # -*- coding: utf-8 -*-
# File : comm.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import queue
import collections
import threading... |
4,630 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/facerender/sync_batchnorm/comm.py | 102,103 | 56,138 | run_master | SyncMaster | 116,135 | 103,135 | class SyncMaster(object):
"""An abstract `SyncMaster` object.
- During the replication, as the data parallel will trigger an callback of each module, all slave devices should
call `register(id)` and obtain an `SlavePipe` to communicate with the master.
- During the forward pass, master device invokes `... | class SyncMaster(object):
"""An abstract `SyncMaster` object.
- During the replication, as the data parallel will trigger an callback of each module, all slave devices should
call `register(id)` and obtain an `SlavePipe` to communicate with the master.
- During the forward pass, master device invokes `... | self._activated = True
intermediates = [(0, master_msg)]
for i in range(self.nr_slaves):
intermediates.append(self._queue.get())
results = self._master_callback(intermediates)
assert results[0][0] == 0, 'The first result should belongs to the master.'
for i... | """
Main entry for the master device in each forward pass.
The messages were first collected from each devices (including the master device), and then
an callback will be invoked to compute the message to be sent back to each devices
(including the master device).
Args:
... | 48 | 609 | 181 | 790 | # -*- coding: utf-8 -*-
# File : comm.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import queue
import collections
import threading... | # -*- coding: utf-8 -*-
# File : comm.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import queue
import collections
import threading... |
4,631 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/facerender/sync_batchnorm/replicate.py | 27,28 | 1,95 | execute_replication_callbacks | 40,50 | 28,50 | # -*- coding: utf-8 -*-
# File : replicate.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import functools
from torch.nn.parallel.da... | # -*- coding: utf-8 -*-
# File : replicate.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import functools
from torch.nn.parallel.da... | master_copy = modules[0]
nr_modules = len(list(master_copy.modules()))
ctxs = [CallbackContext() for _ in range(nr_modules)]
for i, module in enumerate(modules):
for j, m in enumerate(module.modules()):
if hasattr(m, '__data_parallel_replicate__'):
m.__data_parallel_... | """
Execute an replication callback `__data_parallel_replicate__` on each module created by original replication.
The callback will be invoked with arguments `__data_parallel_replicate__(ctx, copy_id)`
Note that, as all modules are isomorphism, we assign each sub-module with a context
(shared amon... | 28 | 896 | 125 | 1,021 | # -*- coding: utf-8 -*-
# File : replicate.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import functools
from torch.nn.parallel.da... | # -*- coding: utf-8 -*-
# File : replicate.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import functools
from torch.nn.parallel.da... | |
4,632 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/facerender/sync_batchnorm/replicate.py | 64,65 | 50,70 | replicate | DataParallelWithCallback | 65,70 | 65,70 | class DataParallelWithCallback(DataParallel):
"""
Data Parallel with a replication callback.
An replication callback `__data_parallel_replicate__` of each module will be invoked after being created by
original `replicate` function.
The callback will be invoked with arguments `__data_parallel_replic... | class DataParallelWithCallback(DataParallel):
"""
Data Parallel with a replication callback.
An replication callback `__data_parallel_replicate__` of each module will be invoked after being created by
original `replicate` function.
The callback will be invoked with arguments `__data_parallel_replic... | modules = super(DataParallelWithCallback, self).replicate(module, device_ids)
execute_replication_callbacks(modules)
return modules
| modules = super(DataParallelWithCallback, self).replicate(module, device_ids)
execute_replication_callbacks(modules)
return modules
| 8 | 201 | 47 | 248 | # -*- coding: utf-8 -*-
# File : replicate.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import functools
from torch.nn.parallel.da... | # -*- coding: utf-8 -*-
# File : replicate.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import functools
from torch.nn.parallel.da... |
4,633 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/facerender/sync_batchnorm/unittest.py | 17,18 | 1,30 | as_numpy | 18,23 | 18,23 | # -*- coding: utf-8 -*-
# File : unittest.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import unittest
import numpy as np
from tor... | # -*- coding: utf-8 -*-
# File : unittest.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import unittest
import numpy as np
from tor... | if isinstance(v, Variable):
v = v.data
return v.cpu().numpy()
| if isinstance(v, Variable):
v = v.data
return v.cpu().numpy()
| 8 | 327 | 36 | 363 | # -*- coding: utf-8 -*-
# File : unittest.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import unittest
import numpy as np
from tor... | # -*- coding: utf-8 -*-
# File : unittest.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import unittest
import numpy as np
from tor... | |
4,634 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/facerender/sync_batchnorm/unittest.py | 24,25 | 23,30 | assertTensorClose | TorchTestCase | 25,30 | 25,30 | class TorchTestCase(unittest.TestCase):
def assertTensorClose(self, a, b, atol=1e-3, rtol=1e-3):
FILL_FUNC_BODY | class TorchTestCase(unittest.TestCase):
def assertTensorClose(self, a, b, atol=1e-3, rtol=1e-3):
FILL_FUNC_BODY | npa, npb = as_numpy(a), as_numpy(b)
self.assertTrue(
np.allclose(npa, npb, atol=atol),
'Tensor close check failed\n{}\n{}\nadiff={}, rdiff={}'.format(a, b, np.abs(npa - npb).max(), np.abs((npa - npb) / np.fmax(npa, 1e-5)).max())
)
| npa, npb = as_numpy(a), as_numpy(b)
self.assertTrue(
np.allclose(npa, npb, atol=atol),
'Tensor close check failed\n{}\n{}\nadiff={}, rdiff={}'.format(a, b, np.abs(npa - npb).max(), np.abs((npa - npb) / np.fmax(npa, 1e-5)).max())
)
| 25 | 53 | 129 | 182 | # -*- coding: utf-8 -*-
# File : unittest.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import unittest
import numpy as np
from tor... | # -*- coding: utf-8 -*-
# File : unittest.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import unittest
import numpy as np
from tor... |
4,635 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/generate_batch.py | 51,52 | 1,121 | get_data | 52,121 | 52,121 | import os
from tqdm import tqdm
import torch
import numpy as np
import random
import scipy.io as scio
import src.utils.audio as audio
def crop_pad_audio(wav, audio_length):
if len(wav) > audio_length:
wav = wav[:audio_length]
elif len(wav) < audio_length:
wav = np.pad(wav, [0, audio_length - l... | import os
from tqdm import tqdm
import torch
import numpy as np
import random
import scipy.io as scio
import src.utils.audio as audio
def crop_pad_audio(wav, audio_length):
if len(wav) > audio_length:
wav = wav[:audio_length]
elif len(wav) < audio_length:
wav = np.pad(wav, [0, audio_length - l... |
syncnet_mel_step_size = 16
fps = 25
pic_name = os.path.splitext(os.path.split(first_coeff_path)[-1])[0]
audio_name = os.path.splitext(os.path.split(audio_path)[-1])[0]
if idlemode:
num_frames = int(length_of_audio * 25)
indiv_mels = np.zeros((num_frames, 80, 16))
else:
... |
syncnet_mel_step_size = 16
fps = 25
pic_name = os.path.splitext(os.path.split(first_coeff_path)[-1])[0]
audio_name = os.path.splitext(os.path.split(audio_path)[-1])[0]
if idlemode:
num_frames = int(length_of_audio * 25)
indiv_mels = np.zeros((num_frames, 80, 16))
else:
... | 216 | 636 | 1,193 | 1,829 | import os
from tqdm import tqdm
import torch
import numpy as np
import random
import scipy.io as scio
import src.utils.audio as audio
def crop_pad_audio(wav, audio_length):
if len(wav) > audio_length:
wav = wav[:audio_length]
elif len(wav) < audio_length:
wav = np.pad(wav, [0, audio_length - l... | import os
from tqdm import tqdm
import torch
import numpy as np
import random
import scipy.io as scio
import src.utils.audio as audio
def crop_pad_audio(wav, audio_length):
if len(wav) > audio_length:
wav = wav[:audio_length]
elif len(wav) < audio_length:
wav = np.pad(wav, [0, audio_length - l... | |
4,636 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/test_audio2coeff.py | 16,17 | 1,124 | load_cpk | 17,25 | 17,25 | import os
import torch
import numpy as np
from scipy.io import savemat, loadmat
from yacs.config import CfgNode as CN
from scipy.signal import savgol_filter
import safetensors
import safetensors.torch
from src.audio2pose_models.audio2pose import Audio2Pose
from src.audio2exp_models.networks import SimpleWrapperV2
... | import os
import torch
import numpy as np
from scipy.io import savemat, loadmat
from yacs.config import CfgNode as CN
from scipy.signal import savgol_filter
import safetensors
import safetensors.torch
from src.audio2pose_models.audio2pose import Audio2Pose
from src.audio2exp_models.networks import SimpleWrapperV2
... | checkpoint = torch.load(checkpoint_path, map_location=torch.device(device))
if model is not None:
model.load_state_dict(checkpoint['model'])
if optimizer is not None:
optimizer.load_state_dict(checkpoint['optimizer'])
return checkpoint['epoch']
| checkpoint = torch.load(checkpoint_path, map_location=torch.device(device))
if model is not None:
model.load_state_dict(checkpoint['model'])
if optimizer is not None:
optimizer.load_state_dict(checkpoint['optimizer'])
return checkpoint['epoch']
| 18 | 1,768 | 94 | 1,862 | import os
import torch
import numpy as np
from scipy.io import savemat, loadmat
from yacs.config import CfgNode as CN
from scipy.signal import savgol_filter
import safetensors
import safetensors.torch
from src.audio2pose_models.audio2pose import Audio2Pose
from src.audio2exp_models.networks import SimpleWrapperV2
... | import os
import torch
import numpy as np
from scipy.io import savemat, loadmat
from yacs.config import CfgNode as CN
from scipy.signal import savgol_filter
import safetensors
import safetensors.torch
from src.audio2pose_models.audio2pose import Audio2Pose
from src.audio2exp_models.networks import SimpleWrapperV2
... | |
4,637 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/test_audio2coeff.py | 107,108 | 25,124 | using_refpose | Audio2Coeff | 108,124 | 108,124 | class Audio2Coeff():
def __init__(self, sadtalker_path, device):
#load config
fcfg_pose = open(sadtalker_path['audio2pose_yaml_path'])
cfg_pose = CN.load_cfg(fcfg_pose)
cfg_pose.freeze()
fcfg_exp = open(sadtalker_path['audio2exp_yaml_path'])
cfg_exp = CN.load_cfg(fcf... | class Audio2Coeff():
def __init__(self, sadtalker_path, device):
#load config
fcfg_pose = open(sadtalker_path['audio2pose_yaml_path'])
cfg_pose = CN.load_cfg(fcfg_pose)
cfg_pose.freeze()
fcfg_exp = open(sadtalker_path['audio2exp_yaml_path'])
cfg_exp = CN.load_cfg(fcf... | num_frames = coeffs_pred_numpy.shape[0]
refpose_coeff_dict = loadmat(ref_pose_coeff_path)
refpose_coeff = refpose_coeff_dict['coeff_3dmm'][:,64:70]
refpose_num_frames = refpose_coeff.shape[0]
if refpose_num_frames<num_frames:
div = num_frames//refpose_num_frames
... | num_frames = coeffs_pred_numpy.shape[0]
refpose_coeff_dict = loadmat(ref_pose_coeff_path)
refpose_coeff = refpose_coeff_dict['coeff_3dmm'][:,64:70]
refpose_num_frames = refpose_coeff.shape[0]
if refpose_num_frames<num_frames:
div = num_frames//refpose_num_frames
... | 52 | 1,298 | 310 | 1,608 | import os
import torch
import numpy as np
from scipy.io import savemat, loadmat
from yacs.config import CfgNode as CN
from scipy.signal import savgol_filter
import safetensors
import safetensors.torch
from src.audio2pose_models.audio2pose import Audio2Pose
from src.audio2exp_models.networks import SimpleWrapperV2
... | import os
import torch
import numpy as np
from scipy.io import savemat, loadmat
from yacs.config import CfgNode as CN
from scipy.signal import savgol_filter
import safetensors
import safetensors.torch
from src.audio2pose_models.audio2pose import Audio2Pose
from src.audio2exp_models.networks import SimpleWrapperV2
... |
4,639 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/utils/hparams.py | 16,17 | 4,21 | set_hparam | HParams | 17,21 | 17,21 | class HParams:
def __init__(self, **kwargs):
self.data = {}
for key, value in kwargs.items():
self.data[key] = value
def __getattr__(self, key):
if key not in self.data:
raise AttributeError("'HParams' object has no attribute %s" % key)
return self.data[key]
def set_hparam(self, key, value):
FILL_FU... | class HParams:
def __init__(self, **kwargs):
self.data = {}
for key, value in kwargs.items():
self.data[key] = value
def __getattr__(self, key):
if key not in self.data:
raise AttributeError("'HParams' object has no attribute %s" % key)
return self.data[key]
def set_hparam(self, key, value):
FILL_FU... | self.data[key] = value
# Default hyperparameters
| self.data[key] = value
# Default hyperparameters
| 6 | 127 | 22 | 149 | from glob import glob
import os
class HParams:
def __init__(self, **kwargs):
self.data = {}
for key, value in kwargs.items():
self.data[key] = value
def __getattr__(self, key):
if key not in self.data:
raise AttributeError("'HParams' object has no attribute %s" % key)
return self.data[key]
def set_... | from glob import glob
import os
class HParams:
def __init__(self, **kwargs):
self.data = {}
for key, value in kwargs.items():
self.data[key] = value
def __getattr__(self, key):
if key not in self.data:
raise AttributeError("'HParams' object has no attribute %s" % key)
return self.data[key]
def set_... |
4,640 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/utils/init_path.py | 4,5 | 1,48 | init_path | 5,48 | 5,48 | import os
import glob
def init_path(checkpoint_dir, config_dir, size=512, old_version=False, preprocess='crop'):
FILL_FUNC_BODY | import os
import glob
def init_path(checkpoint_dir, config_dir, size=512, old_version=False, preprocess='crop'):
FILL_FUNC_BODY |
if old_version:
#### load all the checkpoint of `pth`
sadtalker_paths = {
'wav2lip_checkpoint' : os.path.join(checkpoint_dir, 'wav2lip.pth'),
'audio2pose_checkpoint' : os.path.join(checkpoint_dir, 'auido2pose_00140-model.pth'),
'audio2exp_checkpoint' ... |
if old_version:
#### load all the checkpoint of `pth`
sadtalker_paths = {
'wav2lip_checkpoint' : os.path.join(checkpoint_dir, 'wav2lip.pth'),
'audio2pose_checkpoint' : os.path.join(checkpoint_dir, 'auido2pose_00140-model.pth'),
'audio2exp_checkpoint' ... | 152 | 52 | 972 | 1,024 | import os
import glob
def init_path(checkpoint_dir, config_dir, size=512, old_version=False, preprocess='crop'):
FILL_FUNC_BODY | import os
import glob
def init_path(checkpoint_dir, config_dir, size=512, old_version=False, preprocess='crop'):
FILL_FUNC_BODY | |
4,642 | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker | /home/hieuvd/dung_repo/raw/stars_01/OpenTalker_SadTalker/SadTalker/src/utils/safetensor_helper.py | 3,4 | 1,9 | load_x_from_safetensor | 4,9 | 4,9 |
def load_x_from_safetensor(checkpoint, key):
FILL_FUNC_BODY |
def load_x_from_safetensor(checkpoint, key):
FILL_FUNC_BODY | x_generator = {}
for k,v in checkpoint.items():
if key in k:
x_generator[k.replace(key+'.', '')] = v
return x_generator | x_generator = {}
for k,v in checkpoint.items():
if key in k:
x_generator[k.replace(key+'.', '')] = v
return x_generator | 17 | 30 | 55 | 85 |
def load_x_from_safetensor(checkpoint, key):
FILL_FUNC_BODY |
def load_x_from_safetensor(checkpoint, key):
FILL_FUNC_BODY | |
4,730 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN/benchmark/analysis_log.py | 9,10 | 1,52 | analyze | 10,40 | 10,40 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# encoding=utf-8 vi:ts=4:sw=4:expandtab:ft=python
import re
import sys
import json
def analyze(model_name, log_file, res_log_file):
FILL_FUNC_BODYif __name__ == "__main__":
if len(sys.argv) != 4:
print("Usage:" + sys.argv[0] + " model_name path/to/log/file pat... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# encoding=utf-8 vi:ts=4:sw=4:expandtab:ft=python
import re
import sys
import json
def analyze(model_name, log_file, res_log_file):
FILL_FUNC_BODYif __name__ == "__main__":
if len(sys.argv) != 4:
print("Usage:" + sys.argv[0] + " model_name path/to/log/file pat... | time_pat = re.compile(r"ips: (.*) images/s")
logs = open(log_file).readlines()
logs = ";".join(logs)
time_res = time_pat.findall(logs)
fail_flag = 0
run_mode = ""
gpu_num = 0
ips = 0
if time_res == []:
fail_flag = 1
else:
gpu_num = log_file.split('_')[-1]
... | time_pat = re.compile(r"ips: (.*) images/s")
logs = open(log_file).readlines()
logs = ";".join(logs)
time_res = time_pat.findall(logs)
fail_flag = 0
run_mode = ""
gpu_num = 0
ips = 0
if time_res == []:
fail_flag = 1
else:
gpu_num = log_file.split('_')[-1]
... | 98 | 214 | 392 | 606 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# encoding=utf-8 vi:ts=4:sw=4:expandtab:ft=python
import re
import sys
import json
def analyze(model_name, log_file, res_log_file):
FILL_FUNC_BODYif __name__ == "__main__":
if len(sys.argv) != 4:
print("Usage:" + sys.argv[0] + " model_name path/to/log/file pat... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# encoding=utf-8 vi:ts=4:sw=4:expandtab:ft=python
import re
import sys
import json
def analyze(model_name, log_file, res_log_file):
FILL_FUNC_BODYif __name__ == "__main__":
if len(sys.argv) != 4:
print("Usage:" + sys.argv[0] + " model_name path/to/log/file pat... | |
4,731 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN/data/realsr_preprocess/collect_noise.py | 35,36 | 1,86 | noise_patch | 36,55 | 36,55 | from PIL import Image
import numpy as np
import os.path as osp
import glob
import os
import argparse
import yaml
parser = argparse.ArgumentParser(description='create a dataset')
parser.add_argument('--dataset',
default='df2k',
type=str,
help='selecting differ... | from PIL import Image
import numpy as np
import os.path as osp
import glob
import os
import argparse
import yaml
parser = argparse.ArgumentParser(description='create a dataset')
parser.add_argument('--dataset',
default='df2k',
type=str,
help='selecting differ... | img = rgb_img.convert('L')
rgb_img = np.array(rgb_img)
img = np.array(img)
w, h = img.shape
collect_patchs = []
for i in range(0, w - sp, sp):
for j in range(0, h - sp, sp):
patch = img[i:i + sp, j:j + sp]
var_global = np.var(patch)
mean_global = np.... | img = rgb_img.convert('L')
rgb_img = np.array(rgb_img)
img = np.array(img)
w, h = img.shape
collect_patchs = []
for i in range(0, w - sp, sp):
for j in range(0, h - sp, sp):
patch = img[i:i + sp, j:j + sp]
var_global = np.var(patch)
mean_global = np.... | 66 | 710 | 218 | 928 | from PIL import Image
import numpy as np
import os.path as osp
import glob
import os
import argparse
import yaml
parser = argparse.ArgumentParser(description='create a dataset')
parser.add_argument('--dataset',
default='df2k',
type=str,
help='selecting differ... | from PIL import Image
import numpy as np
import os.path as osp
import glob
import os
import argparse
import yaml
parser = argparse.ArgumentParser(description='create a dataset')
parser.add_argument('--dataset',
default='df2k',
type=str,
help='selecting differ... | |
4,732 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN/ppgan/datasets/base_sr_dataset.py | 40,41 | 23,62 | prepare_data_infos | SRDataset | 48,62 | 41,62 | @DATASETS.register()
class SRDataset(BaseDataset):
"""Base super resulotion dataset for image restoration."""
def __init__(self,
lq_folder,
gt_folder,
preprocess,
scale,
filename_tmpl='{}'):
super(SRDataset, self).__ini... | @DATASETS.register()
class SRDataset(BaseDataset):
"""Base super resulotion dataset for image restoration."""
def __init__(self,
lq_folder,
gt_folder,
preprocess,
scale,
filename_tmpl='{}'):
super(SRDataset, self).__ini... | self.data_infos = []
lq_paths = self.scan_folder(self.lq_folder)
gt_paths = self.scan_folder(self.gt_folder)
assert len(lq_paths) == len(gt_paths), (
f'gt and lq datasets have different number of images: '
f'{len(lq_paths)}, {len(gt_paths)}.')
for gt_path ... | """Load annoations for SR dataset.
It loads the LQ and GT image path from folders.
Returns:
dict: Returned dict for LQ and GT pairs.
"""
self.data_infos = []
lq_paths = self.scan_folder(self.lq_folder)
gt_paths = self.scan_folder(self.gt_folder)
... | 52 | 217 | 273 | 490 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... |
4,733 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN/ppgan/datasets/empty_dataset.py | 29,30 | 19,31 | prepare_data_infos | EmptyDataset | 30,31 | 30,31 | @DATASETS.register()
class EmptyDataset(BaseDataset):
'''
Dataset for models who don't need a dataset.
'''
def __init__(self, size=1):
super().__init__()
self.size = size
self.data_infos = self.prepare_data_infos()
def prepare_data_infos(self):
FILL_FUNC_BODY | @DATASETS.register()
class EmptyDataset(BaseDataset):
'''
Dataset for models who don't need a dataset.
'''
def __init__(self, size=1):
super().__init__()
self.size = size
self.data_infos = self.prepare_data_infos()
def prepare_data_infos(self):
FILL_FUNC_BODY | return [{i: 0} for i in range(self.size)]
| return [{i: 0} for i in range(self.size)]
| 7 | 108 | 20 | 128 | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... |
4,734 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN/ppgan/datasets/paired_dataset.py | 35,36 | 19,47 | prepare_data_infos | PairedDataset | 41,47 | 36,47 | @DATASETS.register()
class PairedDataset(BaseDataset):
"""A dataset class for paired image dataset.
"""
def __init__(self, dataroot, preprocess):
"""Initialize this dataset class.
Args:
dataroot (str): Directory of dataset.
preprocess (list[dict]): A sequence of data... | @DATASETS.register()
class PairedDataset(BaseDataset):
"""A dataset class for paired image dataset.
"""
def __init__(self, dataroot, preprocess):
"""Initialize this dataset class.
Args:
dataroot (str): Directory of dataset.
preprocess (list[dict]): A sequence of data... | data_infos = []
pair_paths = sorted(self.scan_folder(self.dataroot))
for pair_path in pair_paths:
data_infos.append(dict(pair_path=pair_path))
return data_infos
| """Load paired image paths.
Returns:
list[dict]: List that contains paired image paths.
"""
data_infos = []
pair_paths = sorted(self.scan_folder(self.dataroot))
for pair_path in pair_paths:
data_infos.append(dict(pair_path=pair_path))
ret... | 13 | 195 | 72 | 267 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... |
4,735 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN/ppgan/datasets/preprocess/builder.py | 54,55 | 1,77 | build_preprocess | 55,67 | 55,67 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | preproccess = []
if not isinstance(cfg, (list, tuple)):
cfg = [cfg]
for cfg_ in cfg:
process = build_from_config(cfg_, PREPROCESS)
preproccess.append(process)
preproccess = Compose(preproccess)
return preproccess
| preproccess = []
if not isinstance(cfg, (list, tuple)):
cfg = [cfg]
for cfg_ in cfg:
process = build_from_config(cfg_, PREPROCESS)
preproccess.append(process)
preproccess = Compose(preproccess)
return preproccess
| 25 | 573 | 102 | 675 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | |
4,736 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN/ppgan/datasets/single_dataset.py | 34,35 | 19,46 | prepare_data_infos | SingleDataset | 40,46 | 35,46 | @DATASETS.register()
class SingleDataset(BaseDataset):
"""
"""
def __init__(self, dataroot, preprocess):
"""Initialize single dataset class.
Args:
dataroot (str): Directory of dataset.
preprocess (list[dict]): A sequence of data preprocess config.
"""
... | @DATASETS.register()
class SingleDataset(BaseDataset):
"""
"""
def __init__(self, dataroot, preprocess):
"""Initialize single dataset class.
Args:
dataroot (str): Directory of dataset.
preprocess (list[dict]): A sequence of data preprocess config.
"""
... | data_infos = []
paths = sorted(self.scan_folder(self.dataroot))
for path in paths:
data_infos.append(dict(A_path=path))
return data_infos
| """prepare image paths from a folder.
Returns:
list[dict]: List that contains paired image paths.
"""
data_infos = []
paths = sorted(self.scan_folder(self.dataroot))
for path in paths:
data_infos.append(dict(A_path=path))
return data_info... | 13 | 186 | 64 | 250 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... |
4,737 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN/ppgan/datasets/unpaired_dataset.py | 46,47 | 22,85 | prepare_data_infos | UnpairedDataset | 56,62 | 47,62 | @DATASETS.register()
class UnpairedDataset(BaseDataset):
"""
"""
def __init__(self, dataroot_a, dataroot_b, max_size, is_train, preprocess):
"""Initialize unpaired dataset class.
Args:
dataroot_a (str): Directory of dataset a.
dataroot_b (str): Directory of dataset b... | @DATASETS.register()
class UnpairedDataset(BaseDataset):
"""
"""
def __init__(self, dataroot_a, dataroot_b, max_size, is_train, preprocess):
"""Initialize unpaired dataset class.
Args:
dataroot_a (str): Directory of dataset a.
dataroot_b (str): Directory of dataset b... | data_infos = []
paths = sorted(self.scan_folder(dataroot))
for path in paths:
data_infos.append(dict(path=path))
return data_infos
| """Load unpaired image paths of one domain.
Args:
dataroot (str): Path to the folder root for unpaired images of
one domain.
Returns:
list[dict]: List that contains unpaired image paths of one domain.
"""
data_infos = []
paths = s... | 13 | 704 | 60 | 764 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... |
4,738 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN/ppgan/datasets/vsr_reds_dataset.py | 66,67 | 23,98 | prepare_data_infos | VSRREDSDataset | 71,98 | 67,98 | @DATASETS.register()
class VSRREDSDataset(BaseDataset):
"""REDS dataset for video super resolution for Sliding-window networks.
The dataset loads several LQ (Low-Quality) frames and a center GT
(Ground-Truth) frame. Then it applies specified transforms and finally
returns a dict containing paired data ... | @DATASETS.register()
class VSRREDSDataset(BaseDataset):
"""REDS dataset for video super resolution for Sliding-window networks.
The dataset loads several LQ (Low-Quality) frames and a center GT
(Ground-Truth) frame. Then it applies specified transforms and finally
returns a dict containing paired data ... | # get keys
with open(self.ann_file, 'r') as fin:
keys = [v.strip().split('.')[0] for v in fin]
if self.val_partition == 'REDS4':
val_partition = ['000', '011', '015', '020']
elif self.val_partition == 'official':
val_partition = [f'{v:03d}' for v in r... | """Load annoations for REDS dataset.
Returns:
dict: Returned dict for LQ and GT pairs.
"""
# get keys
with open(self.ann_file, 'r') as fin:
keys = [v.strip().split('.')[0] for v in fin]
if self.val_partition == 'REDS4':
val_partition =... | 89 | 578 | 350 | 928 | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... |
4,739 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN/ppgan/datasets/vsr_reds_multiple_gt_dataset.py | 59,60 | 23,93 | prepare_data_infos | VSRREDSMultipleGTDataset | 65,93 | 60,93 | @DATASETS.register()
class VSRREDSMultipleGTDataset(BaseDataset):
"""REDS dataset for video super resolution for recurrent networks.
The dataset loads several LQ (Low-Quality) frames and GT (Ground-Truth) frames.
Then it applies specified transforms and finally returns a dict containing
paired data and... | @DATASETS.register()
class VSRREDSMultipleGTDataset(BaseDataset):
"""REDS dataset for video super resolution for recurrent networks.
The dataset loads several LQ (Low-Quality) frames and GT (Ground-Truth) frames.
Then it applies specified transforms and finally returns a dict containing
paired data and... | # get keys
with open(self.ann_file, 'r') as fin:
keys = [v.strip().split('/')[0] for v in fin]
keys = list(set(keys))
if self.val_partition == 'REDS4':
val_partition = ['000', '011', '015', '020']
elif self.val_partition == 'official':
val_par... | """Load annoations for REDS dataset.
Returns:
dict: Returned dict for LQ and GT pairs.
"""
# get keys
with open(self.ann_file, 'r') as fin:
keys = [v.strip().split('/')[0] for v in fin]
keys = list(set(keys))
if self.val_partition == 'RED... | 92 | 463 | 345 | 808 | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... |
4,740 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN/ppgan/models/criterions/builder.py | 34,35 | 1,43 | build_criterion | 35,43 | 35,43 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | cfg_ = cfg.copy()
name = cfg_.pop('name')
try:
criterion = CRITERIONS.get(name)(**cfg_)
except Exception as e:
cls_ = CRITERIONS.get(name)
raise RuntimeError('class {} {}'.format(cls_.__name__, e))
return criterion
| cfg_ = cfg.copy()
name = cfg_.pop('name')
try:
criterion = CRITERIONS.get(name)(**cfg_)
except Exception as e:
cls_ = CRITERIONS.get(name)
raise RuntimeError('class {} {}'.format(cls_.__name__, e))
return criterion
| 24 | 381 | 96 | 477 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | |
4,741 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN/ppgan/models/discriminators/builder.py | 21,22 | 1,26 | build_discriminator | 22,26 | 22,26 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | cfg_copy = copy.deepcopy(cfg)
name = cfg_copy.pop('name')
discriminator = DISCRIMINATORS.get(name)(**cfg_copy)
return discriminator
| cfg_copy = copy.deepcopy(cfg)
name = cfg_copy.pop('name')
discriminator = DISCRIMINATORS.get(name)(**cfg_copy)
return discriminator
| 11 | 221 | 59 | 280 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | |
4,742 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN/ppgan/models/generators/builder.py | 21,22 | 1,26 | build_generator | 22,26 | 22,26 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | cfg_copy = copy.deepcopy(cfg)
name = cfg_copy.pop('name')
generator = GENERATORS.get(name)(**cfg_copy)
return generator
| cfg_copy = copy.deepcopy(cfg)
name = cfg_copy.pop('name')
generator = GENERATORS.get(name)(**cfg_copy)
return generator
| 11 | 214 | 54 | 268 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | |
4,743 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN/ppgan/solver/builder.py | 27,28 | 1,31 | build_optimizer | 28,31 | 28,31 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | cfg_ = cfg.copy()
name = cfg_.pop('name')
return OPTIMIZERS.get(name)(lr_scheduler, parameters=parameters, **cfg_)
| cfg_ = cfg.copy()
name = cfg_.pop('name')
return OPTIMIZERS.get(name)(lr_scheduler, parameters=parameters, **cfg_)
| 10 | 294 | 51 | 345 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | |
4,744 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN/ppgan/utils/audio_config.py | 27,28 | 1,29 | get_audio_config | 28,29 | 28,29 | from .config import AttrDict
_audio_cfg = AttrDict()
_audio_cfg.num_mels = 80
_audio_cfg.rescale = True
_audio_cfg.rescaling_max = 0.9
_audio_cfg.use_lws = False
_audio_cfg.n_fft = 800
_audio_cfg.hop_size = 200
_audio_cfg.win_size = 800
_audio_cfg.sample_rate = 16000
_audio_cfg.frame_shift_ms = None
_audio_cfg.signal... | from .config import AttrDict
_audio_cfg = AttrDict()
_audio_cfg.num_mels = 80
_audio_cfg.rescale = True
_audio_cfg.rescaling_max = 0.9
_audio_cfg.use_lws = False
_audio_cfg.n_fft = 800
_audio_cfg.hop_size = 200
_audio_cfg.win_size = 800
_audio_cfg.sample_rate = 16000
_audio_cfg.frame_shift_ms = None
_audio_cfg.signal... | return _audio_cfg
| return _audio_cfg
| 2 | 307 | 8 | 315 | from .config import AttrDict
_audio_cfg = AttrDict()
_audio_cfg.num_mels = 80
_audio_cfg.rescale = True
_audio_cfg.rescaling_max = 0.9
_audio_cfg.use_lws = False
_audio_cfg.n_fft = 800
_audio_cfg.hop_size = 200
_audio_cfg.win_size = 800
_audio_cfg.sample_rate = 16000
_audio_cfg.frame_shift_ms = None
_audio_cfg.signal... | from .config import AttrDict
_audio_cfg = AttrDict()
_audio_cfg.num_mels = 80
_audio_cfg.rescale = True
_audio_cfg.rescaling_max = 0.9
_audio_cfg.use_lws = False
_audio_cfg.n_fft = 800
_audio_cfg.hop_size = 200
_audio_cfg.win_size = 800
_audio_cfg.sample_rate = 16000
_audio_cfg.frame_shift_ms = None
_audio_cfg.signal... | |
4,746 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN/ppgan/utils/options.py | 18,19 | 1,91 | parse_args | 19,91 | 19,91 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | parser = argparse.ArgumentParser(description='PaddleGAN')
parser.add_argument('-c',
'--config-file',
metavar="FILE",
help='config file path')
# cuda setting
parser.add_argument('--no-cuda',
action='store_true... | parser = argparse.ArgumentParser(description='PaddleGAN')
parser.add_argument('-c',
'--config-file',
metavar="FILE",
help='config file path')
# cuda setting
parser.add_argument('--no-cuda',
action='store_true... | 157 | 188 | 719 | 907 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | |
4,747 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN/ppgan/utils/registry.py | 82,83 | 1,130 | build_from_config | 93,130 | 83,130 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | if not isinstance(cfg, dict):
raise TypeError(f'cfg must be a dict, but got {type(cfg)}')
if 'name' not in cfg:
if default_args is None or 'name' not in default_args:
raise KeyError(
'`cfg` or `default_args` must contain the key "name", '
f'but got {cf... | """Build a class from config dict.
Args:
cfg (dict): Config dict. It should at least contain the key "name".
registry (ppgan.utils.Registry): The registry to search the name from.
default_args (dict, optional): Default initialization arguments.
Returns:
class: The construct... | 147 | 823 | 461 | 1,284 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | |
4,748 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN/ppgan/utils/registry.py | 50,51 | 19,82 | register | Registry | 55,70 | 51,70 | class Registry(object):
"""
The registry that provides name -> object mapping, to support third-party users' custom modules.
To create a registry (inside ppgan):
.. code-block:: python
BACKBONE_REGISTRY = Registry('BACKBONE')
To register an object:
.. code-block:: python
@BACKBON... | class Registry(object):
"""
The registry that provides name -> object mapping, to support third-party users' custom modules.
To create a registry (inside ppgan):
.. code-block:: python
BACKBONE_REGISTRY = Registry('BACKBONE')
To register an object:
.. code-block:: python
@BACKBON... | if obj is None:
# used as a decorator
def deco(func_or_class, name=name):
if name is None:
name = func_or_class.__name__
self._do_register(name, func_or_class)
return func_or_class
return deco
# use... | """
Register the given object under the the name `obj.__name__`.
Can be used as either a decorator or not. See docstring of this class for usage.
"""
if obj is None:
# used as a decorator
def deco(func_or_class, name=name):
if name is None:... | 40 | 427 | 132 | 559 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... |
4,749 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN/ppgan/utils/timer.py | 22,23 | 18,42 | reset | TimeAverager | 23,27 | 23,27 | class TimeAverager(object):
def __init__(self):
self.reset()
def reset(self):
FILL_FUNC_BODY def record(self, usetime, num_samples=None):
self._cnt += 1
self._total_time += usetime
if num_samples:
self._total_samples += num_samples
def get_average(self):
... | class TimeAverager(object):
def __init__(self):
self.reset()
def reset(self):
FILL_FUNC_BODY def record(self, usetime, num_samples=None):
self._cnt += 1
self._total_time += usetime
if num_samples:
self._total_samples += num_samples
def get_average(self):
... | self._cnt = 0
self._total_time = 0
self._total_samples = 0
| self._cnt = 0
self._total_time = 0
self._total_samples = 0
| 9 | 193 | 32 | 225 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... |
4,750 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN/ppgan/utils/video.py | 19,20 | 1,60 | video2frames | 20,48 | 20,48 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | def _dict2str(kargs):
cmd_str = ''
for k, v in kargs.items():
cmd_str += (' ' + str(k) + ' ' + str(v))
return cmd_str
ffmpeg = ['ffmpeg ', ' -y -loglevel ', ' error ']
vid_name = os.path.basename(video_path).split('.')[0]
out_full_path = os.path.join(outpath, vid_nam... | def _dict2str(kargs):
cmd_str = ''
for k, v in kargs.items():
cmd_str += (' ' + str(k) + ' ' + str(v))
return cmd_str
ffmpeg = ['ffmpeg ', ' -y -loglevel ', ' error ']
vid_name = os.path.basename(video_path).split('.')[0]
out_full_path = os.path.join(outpath, vid_nam... | 89 | 374 | 328 | 702 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | |
4,751 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN/setup.py | 25,26 | 1,55 | readme | 26,31 | 26,31 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | with open('README.md', encoding="utf-8-sig") as f:
README = f.read()
return README
| with open('README.md', encoding="utf-8-sig") as f:
README = f.read()
return README
| 10 | 545 | 43 | 588 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | |
4,752 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN/tools/export_model.py | 73,74 | 1,95 | main | 74,91 | 74,91 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | inputs_size = [[int(size) for size in input_size.split(',')]
for input_size in args.inputs_size.split(';')]
model = ppgan.models.builder.build_model(cfg.model)
model.setup_train_mode(is_train=False)
state_dicts = ppgan.utils.filesystem.load(args.load)
if 'Wav2Lip' in cfg.model.nam... | inputs_size = [[int(size) for size in input_size.split(',')]
for input_size in args.inputs_size.split(';')]
model = ppgan.models.builder.build_model(cfg.model)
model.setup_train_mode(is_train=False)
state_dicts = ppgan.utils.filesystem.load(args.load)
if 'Wav2Lip' in cfg.model.nam... | 53 | 642 | 290 | 932 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | |
4,753 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleGAN/PaddleGAN/tools/main.py | 28,29 | 1,57 | main | 29,52 | 29,52 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | # init environment, include logger, dynamic graph, seed, device, train or test mode...
setup(args, cfg)
# build trainer
trainer = Trainer(cfg)
# continue train or evaluate, checkpoint need contain epoch and optimizer info
if args.resume:
trainer.resume(args.resume)
# evaluate or fin... | # init environment, include logger, dynamic graph, seed, device, train or test mode...
setup(args, cfg)
# build trainer
trainer = Trainer(cfg)
# continue train or evaluate, checkpoint need contain epoch and optimizer info
if args.resume:
trainer.resume(args.resume)
# evaluate or fin... | 66 | 340 | 213 | 553 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | |
5,353 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/PPOCRLabel/libs/colorDialog.py | 46,47 | 24,49 | checkRestore | ColorDialog | 47,49 | 47,49 | class ColorDialog(QColorDialog):
def __init__(self, parent=None):
super(ColorDialog, self).__init__(parent)
self.setOption(QColorDialog.ShowAlphaChannel)
# The Mac native dialog does not support our restore button.
self.setOption(QColorDialog.DontUseNativeDialog)
# Add a rest... | class ColorDialog(QColorDialog):
def __init__(self, parent=None):
super(ColorDialog, self).__init__(parent)
self.setOption(QColorDialog.ShowAlphaChannel)
# The Mac native dialog does not support our restore button.
self.setOption(QColorDialog.DontUseNativeDialog)
# Add a rest... | if self.bb.buttonRole(button) & BB.ResetRole and self.default:
self.setCurrentColor(self.default)
| if self.bb.buttonRole(button) & BB.ResetRole and self.default:
self.setCurrentColor(self.default)
| 7 | 270 | 36 | 306 | # Copyright (c) <2015-Present> Tzutalin
# Copyright (C) 2013 MIT, Computer Science and Artificial Intelligence Laboratory. Bryan Russell, Antonio Torralba,
# William T. Freeman. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
# associated documentation files (the "Soft... | # Copyright (c) <2015-Present> Tzutalin
# Copyright (C) 2013 MIT, Computer Science and Artificial Intelligence Laboratory. Bryan Russell, Antonio Torralba,
# William T. Freeman. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
# associated documentation files (the "Soft... |
5,354 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/PPOCRLabel/libs/settings.py | 55,56 | 19,61 | reset | Settings | 56,61 | 56,61 | class Settings(object):
def __init__(self):
# Be default, the home will be in the same folder as labelImg
home = os.path.expanduser("~")
self.data = {}
# self.path = os.path.join(home, '.labelImgSettings.pkl')
self.path = os.path.join(home, ".autoOCRSettings.pkl")
def __... | class Settings(object):
def __init__(self):
# Be default, the home will be in the same folder as labelImg
home = os.path.expanduser("~")
self.data = {}
# self.path = os.path.join(home, '.labelImgSettings.pkl')
self.path = os.path.join(home, ".autoOCRSettings.pkl")
def __... | if os.path.exists(self.path):
os.remove(self.path)
print("Remove setting pkl file ${0}".format(self.path))
self.data = {}
self.path = None
| if os.path.exists(self.path):
os.remove(self.path)
print("Remove setting pkl file ${0}".format(self.path))
self.data = {}
self.path = None
| 14 | 335 | 62 | 397 | # Copyright (c) <2015-Present> Tzutalin
# Copyright (C) 2013 MIT, Computer Science and Artificial Intelligence Laboratory. Bryan Russell, Antonio Torralba,
# William T. Freeman. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
# associated documentation files (the "Soft... | # Copyright (c) <2015-Present> Tzutalin
# Copyright (C) 2013 MIT, Computer Science and Artificial Intelligence Laboratory. Bryan Russell, Antonio Torralba,
# William T. Freeman. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
# associated documentation files (the "Soft... |
5,355 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/PPOCRLabel/setup.py | 23,24 | 1,56 | readme | 24,29 | 24,29 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | with open("README.md", encoding="utf-8-sig") as f:
README = f.read()
return README
| with open("README.md", encoding="utf-8-sig") as f:
README = f.read()
return README
| 10 | 674 | 43 | 717 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | |
5,356 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/benchmark/PaddleOCR_DBNet/data_loader/modules/iaa_augment.py | 13,14 | 9,36 | build | AugmenterBuilder | 14,30 | 14,30 | class AugmenterBuilder(object):
def __init__(self):
pass
def build(self, args, root=True):
FILL_FUNC_BODY def to_tuple_if_list(self, obj):
if isinstance(obj, list):
return tuple(obj)
return obj
| class AugmenterBuilder(object):
def __init__(self):
pass
def build(self, args, root=True):
FILL_FUNC_BODY def to_tuple_if_list(self, obj):
if isinstance(obj, list):
return tuple(obj)
return obj
| if args is None or len(args) == 0:
return None
elif isinstance(args, list):
if root:
sequence = [self.build(value, root=False) for value in args]
return iaa.Sequential(sequence)
else:
return getattr(iaa, args[0])(
... | if args is None or len(args) == 0:
return None
elif isinstance(args, list):
if root:
sequence = [self.build(value, root=False) for value in args]
return iaa.Sequential(sequence)
else:
return getattr(iaa, args[0])(
... | 58 | 83 | 210 | 293 | # -*- coding: utf-8 -*-
# @Time : 2019/12/4 18:06
# @Author : zhoujun
import numpy as np
import imgaug
import imgaug.augmenters as iaa
class AugmenterBuilder(object):
def __init__(self):
pass
def build(self, args, root=True):
FILL_FUNC_BODY def to_tuple_if_list(self, obj):
if isinstanc... | # -*- coding: utf-8 -*-
# @Time : 2019/12/4 18:06
# @Author : zhoujun
import numpy as np
import imgaug
import imgaug.augmenters as iaa
class AugmenterBuilder(object):
def __init__(self):
pass
def build(self, args, root=True):
FILL_FUNC_BODY def to_tuple_if_list(self, obj):
if isinstanc... |
5,357 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/benchmark/PaddleOCR_DBNet/data_loader/modules/iaa_augment.py | 51,52 | 36,69 | may_augment_annotation | IaaAugment | 52,62 | 52,62 | class IaaAugment:
def __init__(self, augmenter_args):
self.augmenter_args = augmenter_args
self.augmenter = AugmenterBuilder().build(self.augmenter_args)
def __call__(self, data):
image = data["img"]
shape = image.shape
if self.augmenter:
aug = self.augmente... | class IaaAugment:
def __init__(self, augmenter_args):
self.augmenter_args = augmenter_args
self.augmenter = AugmenterBuilder().build(self.augmenter_args)
def __call__(self, data):
image = data["img"]
shape = image.shape
if self.augmenter:
aug = self.augmente... | if aug is None:
return data
line_polys = []
for poly in data["text_polys"]:
new_poly = self.may_augment_poly(aug, shape, poly)
line_polys.append(new_poly)
data["text_polys"] = np.array(line_polys)
return data
| if aug is None:
return data
line_polys = []
for poly in data["text_polys"]:
new_poly = self.may_augment_poly(aug, shape, poly)
line_polys.append(new_poly)
data["text_polys"] = np.array(line_polys)
return data
| 24 | 309 | 102 | 411 | # -*- coding: utf-8 -*-
# @Time : 2019/12/4 18:06
# @Author : zhoujun
import numpy as np
import imgaug
import imgaug.augmenters as iaa
class AugmenterBuilder(object):
def __init__(self):
pass
def build(self, args, root=True):
if args is None or len(args) == 0:
return None
... | # -*- coding: utf-8 -*-
# @Time : 2019/12/4 18:06
# @Author : zhoujun
import numpy as np
import imgaug
import imgaug.augmenters as iaa
class AugmenterBuilder(object):
def __init__(self):
pass
def build(self, args, root=True):
if args is None or len(args) == 0:
return None
... |
5,358 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/benchmark/PaddleOCR_DBNet/utils/metrics.py | 12,13 | 7,61 | _fast_hist | runningScore | 13,23 | 13,23 | class runningScore(object):
def __init__(self, n_classes):
self.n_classes = n_classes
self.confusion_matrix = np.zeros((n_classes, n_classes))
def _fast_hist(self, label_true, label_pred, n_class):
FILL_FUNC_BODY def update(self, label_trues, label_preds):
# print label_trues.dtype, ... | class runningScore(object):
def __init__(self, n_classes):
self.n_classes = n_classes
self.confusion_matrix = np.zeros((n_classes, n_classes))
def _fast_hist(self, label_true, label_pred, n_class):
FILL_FUNC_BODY def update(self, label_trues, label_preds):
# print label_trues.dtype, ... | mask = (label_true >= 0) & (label_true < n_class)
if np.sum((label_pred[mask] < 0)) > 0:
print(label_pred[label_pred < 0])
hist = np.bincount(
n_class * label_true[mask].astype(int) + label_pred[mask],
minlength=n_class**2,
).reshape(n_class, n_class)... | mask = (label_true >= 0) & (label_true < n_class)
if np.sum((label_pred[mask] < 0)) > 0:
print(label_pred[label_pred < 0])
hist = np.bincount(
n_class * label_true[mask].astype(int) + label_pred[mask],
minlength=n_class**2,
).reshape(n_class, n_class)... | 31 | 551 | 129 | 680 | # Adapted from score written by wkentaro
# https://github.com/wkentaro/pytorch-fcn/blob/master/torchfcn/utils.py
import numpy as np
class runningScore(object):
def __init__(self, n_classes):
self.n_classes = n_classes
self.confusion_matrix = np.zeros((n_classes, n_classes))
def _fast_hist(se... | # Adapted from score written by wkentaro
# https://github.com/wkentaro/pytorch-fcn/blob/master/torchfcn/utils.py
import numpy as np
class runningScore(object):
def __init__(self, n_classes):
self.n_classes = n_classes
self.confusion_matrix = np.zeros((n_classes, n_classes))
def _fast_hist(se... |
5,359 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/benchmark/PaddleOCR_DBNet/utils/ocr_metric/icdar2015/quad_metric.py | 18,19 | 6,26 | update | AverageMeter | 19,26 | 19,26 | class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
FILL_FUNC_BODY | class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
FILL_FUNC_BODY | self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
return self
| self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
return self
| 18 | 98 | 50 | 148 | import numpy as np
from .detection.iou import DetectionIoUEvaluator
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
de... | import numpy as np
from .detection.iou import DetectionIoUEvaluator
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
de... |
5,360 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/benchmark/PaddleOCR_DBNet/utils/ocr_metric/icdar2015/quad_metric.py | 31,32 | 26,99 | measure | QuadMetric | 42,69 | 32,69 | class QuadMetric:
def __init__(self, is_output_polygon=False):
self.is_output_polygon = is_output_polygon
self.evaluator = DetectionIoUEvaluator(is_output_polygon=is_output_polygon)
def measure(self, batch, output, box_thresh=0.6):
FILL_FUNC_BODY def validate_measure(self, batch, output, box... | class QuadMetric:
def __init__(self, is_output_polygon=False):
self.is_output_polygon = is_output_polygon
self.evaluator = DetectionIoUEvaluator(is_output_polygon=is_output_polygon)
def measure(self, batch, output, box_thresh=0.6):
"""
batch: (image, polygons, ignore_tags
... | results = []
gt_polyons_batch = batch["text_polys"]
ignore_tags_batch = batch["ignore_tags"]
pred_polygons_batch = np.array(output[0])
pred_scores_batch = np.array(output[1])
for polygons, pred_polygons, pred_scores, ignore_tags in zip(
gt_polyons_batch, pred_... | """
batch: (image, polygons, ignore_tags
batch: a dict produced by dataloaders.
image: tensor of shape (N, C, H, W).
polygons: tensor of shape (N, K, 4, 2), the polygons of objective regions.
ignore_tags: tensor of shape (N, K), indicates whether a region is i... | 83 | 542 | 437 | 979 | import numpy as np
from .detection.iou import DetectionIoUEvaluator
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
de... | import numpy as np
from .detection.iou import DetectionIoUEvaluator
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
de... |
5,362 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/configs/rec/multi_language/generate_multi_language_configs.py | 176,177 | 139,221 | _parse_opt | ArgsParser | 177,186 | 177,186 | class ArgsParser(ArgumentParser):
def __init__(self):
super(ArgsParser, self).__init__(formatter_class=RawDescriptionHelpFormatter)
self.add_argument("-o", "--opt", nargs="+", help="set configuration options")
self.add_argument(
"-l",
"--language",
nargs="... | class ArgsParser(ArgumentParser):
def __init__(self):
super(ArgsParser, self).__init__(formatter_class=RawDescriptionHelpFormatter)
self.add_argument("-o", "--opt", nargs="+", help="set configuration options")
self.add_argument(
"-l",
"--language",
nargs="... | config = {}
if not opts:
return config
for s in opts:
s = s.strip()
k, v = s.split("=")
config[k] = yaml.load(v, Loader=yaml.Loader)
return config
| config = {}
if not opts:
return config
for s in opts:
s = s.strip()
k, v = s.split("=")
config[k] = yaml.load(v, Loader=yaml.Loader)
return config
| 25 | 829 | 78 | 907 | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
5,363 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/deploy/hubserving/kie_ser/params.py | 26,27 | 1,39 | read_params | 27,39 | 27,39 | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | cfg = pp_ocr_read_params()
# SER params
cfg.kie_algorithm = "LayoutXLM"
cfg.use_visual_backbone = False
cfg.ser_model_dir = "./inference/ser_vi_layoutxlm_xfund_infer"
cfg.ser_dict_path = "train_data/XFUND/class_list_xfun.txt"
cfg.vis_font_path = "./doc/fonts/simfang.ttf"
cfg.ocr_order_... | cfg = pp_ocr_read_params()
# SER params
cfg.kie_algorithm = "LayoutXLM"
cfg.use_visual_backbone = False
cfg.ser_model_dir = "./inference/ser_vi_layoutxlm_xfund_infer"
cfg.ser_dict_path = "train_data/XFUND/class_list_xfun.txt"
cfg.vis_font_path = "./doc/fonts/simfang.ttf"
cfg.ocr_order_... | 26 | 248 | 167 | 415 | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | |
5,364 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/deploy/hubserving/kie_ser_re/params.py | 26,27 | 1,41 | read_params | 27,41 | 27,41 | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | cfg = pp_ocr_read_params()
# SER params
cfg.kie_algorithm = "LayoutXLM"
cfg.use_visual_backbone = False
cfg.ser_model_dir = "./inference/ser_vi_layoutxlm_xfund_infer"
cfg.re_model_dir = "./inference/re_vi_layoutxlm_xfund_infer"
cfg.ser_dict_path = "train_data/XFUND/class_list_xfun.txt"
... | cfg = pp_ocr_read_params()
# SER params
cfg.kie_algorithm = "LayoutXLM"
cfg.use_visual_backbone = False
cfg.ser_model_dir = "./inference/ser_vi_layoutxlm_xfund_infer"
cfg.re_model_dir = "./inference/re_vi_layoutxlm_xfund_infer"
cfg.ser_dict_path = "train_data/XFUND/class_list_xfun.txt"
... | 29 | 248 | 200 | 448 | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | |
5,365 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/deploy/hubserving/ocr_cls/params.py | 24,25 | 1,38 | read_params | 25,38 | 25,38 | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | cfg = Config()
# params for text classifier
cfg.cls_model_dir = "./inference/ch_ppocr_mobile_v2.0_cls_infer/"
cfg.cls_image_shape = "3, 48, 192"
cfg.label_list = ["0", "180"]
cfg.cls_batch_num = 30
cfg.cls_thresh = 0.9
cfg.use_pdserving = False
cfg.use_tensorrt = False
return ... | cfg = Config()
# params for text classifier
cfg.cls_model_dir = "./inference/ch_ppocr_mobile_v2.0_cls_infer/"
cfg.cls_image_shape = "3, 48, 192"
cfg.label_list = ["0", "180"]
cfg.cls_batch_num = 30
cfg.cls_thresh = 0.9
cfg.use_pdserving = False
cfg.use_tensorrt = False
return ... | 34 | 221 | 158 | 379 | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | |
5,366 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/deploy/hubserving/ocr_det/params.py | 24,25 | 1,49 | read_params | 25,49 | 25,49 | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | cfg = Config()
# params for text detector
cfg.det_algorithm = "DB"
cfg.det_model_dir = "./inference/ch_PP-OCRv3_det_infer/"
cfg.det_limit_side_len = 960
cfg.det_limit_type = "max"
# DB parmas
cfg.det_db_thresh = 0.3
cfg.det_db_box_thresh = 0.6
cfg.det_db_unclip_ratio = 1.5
... | cfg = Config()
# params for text detector
cfg.det_algorithm = "DB"
cfg.det_model_dir = "./inference/ch_PP-OCRv3_det_infer/"
cfg.det_limit_side_len = 960
cfg.det_limit_type = "max"
# DB parmas
cfg.det_db_thresh = 0.3
cfg.det_db_box_thresh = 0.6
cfg.det_db_unclip_ratio = 1.5
... | 61 | 221 | 288 | 509 | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | |
5,367 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/deploy/hubserving/ocr_rec/params.py | 24,25 | 1,42 | read_params | 25,42 | 25,42 | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | cfg = Config()
# params for text recognizer
cfg.rec_algorithm = "CRNN"
cfg.rec_model_dir = "./inference/ch_PP-OCRv3_rec_infer/"
cfg.rec_image_shape = "3, 48, 320"
cfg.rec_batch_num = 6
cfg.max_text_length = 25
cfg.rec_char_dict_path = "./ppocr/utils/ppocr_keys_v1.txt"
cfg.use_spac... | cfg = Config()
# params for text recognizer
cfg.rec_algorithm = "CRNN"
cfg.rec_model_dir = "./inference/ch_PP-OCRv3_rec_infer/"
cfg.rec_image_shape = "3, 48, 320"
cfg.rec_batch_num = 6
cfg.max_text_length = 25
cfg.rec_char_dict_path = "./ppocr/utils/ppocr_keys_v1.txt"
cfg.use_spac... | 39 | 221 | 198 | 419 | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | |
5,368 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/deploy/hubserving/ocr_system/params.py | 24,25 | 1,69 | read_params | 25,69 | 25,69 | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | cfg = Config()
# params for text detector
cfg.det_algorithm = "DB"
cfg.det_model_dir = "./inference/ch_PP-OCRv3_det_infer/"
cfg.det_limit_side_len = 960
cfg.det_limit_type = "max"
# DB parmas
cfg.det_db_thresh = 0.3
cfg.det_db_box_thresh = 0.5
cfg.det_db_unclip_ratio = 1.6
... | cfg = Config()
# params for text detector
cfg.det_algorithm = "DB"
cfg.det_model_dir = "./inference/ch_PP-OCRv3_det_infer/"
cfg.det_limit_side_len = 960
cfg.det_limit_type = "max"
# DB parmas
cfg.det_db_thresh = 0.3
cfg.det_db_box_thresh = 0.5
cfg.det_db_unclip_ratio = 1.6
... | 115 | 221 | 580 | 801 | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | |
5,369 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/deploy/hubserving/structure_layout/params.py | 24,25 | 1,33 | read_params | 25,33 | 25,33 | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | cfg = Config()
# params for layout analysis
cfg.layout_model_dir = "./inference/picodet_lcnet_x1_0_fgd_layout_infer/"
cfg.layout_dict_path = "./ppocr/utils/dict/layout_dict/layout_publaynet_dict.txt"
cfg.layout_score_threshold = 0.5
cfg.layout_nms_threshold = 0.5
return cfg
| cfg = Config()
# params for layout analysis
cfg.layout_model_dir = "./inference/picodet_lcnet_x1_0_fgd_layout_infer/"
cfg.layout_dict_path = "./ppocr/utils/dict/layout_dict/layout_publaynet_dict.txt"
cfg.layout_score_threshold = 0.5
cfg.layout_nms_threshold = 0.5
return cfg
| 22 | 221 | 129 | 350 | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | |
5,370 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/deploy/hubserving/structure_system/params.py | 22,23 | 1,34 | read_params | 23,34 | 23,34 | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | cfg = table_read_params()
# params for layout parser model
cfg.layout_model_dir = ""
cfg.layout_dict_path = "./ppocr/utils/dict/layout_publaynet_dict.txt"
cfg.layout_score_threshold = 0.5
cfg.layout_nms_threshold = 0.5
cfg.mode = "structure"
cfg.output = "./output"
return cfg
| cfg = table_read_params()
# params for layout parser model
cfg.layout_model_dir = ""
cfg.layout_dict_path = "./ppocr/utils/dict/layout_publaynet_dict.txt"
cfg.layout_score_threshold = 0.5
cfg.layout_nms_threshold = 0.5
cfg.mode = "structure"
cfg.output = "./output"
return cfg
| 29 | 235 | 131 | 366 | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | |
5,371 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/deploy/hubserving/structure_table/params.py | 22,23 | 1,31 | read_params | 23,31 | 23,31 | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | cfg = pp_ocr_read_params()
# params for table structure model
cfg.table_max_len = 488
cfg.table_model_dir = "./inference/en_ppocr_mobile_v2.0_table_structure_infer/"
cfg.table_char_dict_path = "./ppocr/utils/dict/table_structure_dict.txt"
cfg.show_log = False
return cfg
| cfg = pp_ocr_read_params()
# params for table structure model
cfg.table_max_len = 488
cfg.table_model_dir = "./inference/en_ppocr_mobile_v2.0_table_structure_infer/"
cfg.table_char_dict_path = "./ppocr/utils/dict/table_structure_dict.txt"
cfg.show_log = False
return cfg
| 23 | 237 | 124 | 361 | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | |
5,372 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/ppocr/data/imaug/iaa_augment.py | 49,50 | 28,55 | to_tuple_if_list | AugmenterBuilder | 50,55 | 50,55 | class AugmenterBuilder(object):
def __init__(self):
pass
def build(self, args, root=True):
if args is None or len(args) == 0:
return None
elif isinstance(args, list):
if root:
sequence = [self.build(value, root=False) for value in args]
... | class AugmenterBuilder(object):
def __init__(self):
pass
def build(self, args, root=True):
if args is None or len(args) == 0:
return None
elif isinstance(args, list):
if root:
sequence = [self.build(value, root=False) for value in args]
... | if isinstance(obj, list):
return tuple(obj)
return obj
| if isinstance(obj, list):
return tuple(obj)
return obj
| 7 | 254 | 28 | 282 | # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
5,373 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/ppocr/data/imaug/iaa_augment.py | 75,76 | 55,93 | may_augment_annotation | IaaAugment | 76,86 | 76,86 | class IaaAugment:
def __init__(self, augmenter_args=None, **kwargs):
if augmenter_args is None:
augmenter_args = [
{"type": "Fliplr", "args": {"p": 0.5}},
{"type": "Affine", "args": {"rotate": [-10, 10]}},
{"type": "Resize", "args": {"size": [0.5, ... | class IaaAugment:
def __init__(self, augmenter_args=None, **kwargs):
if augmenter_args is None:
augmenter_args = [
{"type": "Fliplr", "args": {"p": 0.5}},
{"type": "Affine", "args": {"rotate": [-10, 10]}},
{"type": "Resize", "args": {"size": [0.5, ... | if aug is None:
return data
line_polys = []
for poly in data["polys"]:
new_poly = self.may_augment_poly(aug, shape, poly)
line_polys.append(new_poly)
data["polys"] = np.array(line_polys)
return data
| if aug is None:
return data
line_polys = []
for poly in data["polys"]:
new_poly = self.may_augment_poly(aug, shape, poly)
line_polys.append(new_poly)
data["polys"] = np.array(line_polys)
return data
| 24 | 391 | 98 | 489 | # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.