id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
3,366
from __future__ import print_function import numpy as np import torch from PIL import Image import os import importlib import argparse from argparse import Namespace import torchvision def copyconf(default_opt, **kwargs): conf = Namespace(**vars(default_opt)) for key in kwargs: setattr(conf, key, kwargs[key]) return conf
null
3,367
from __future__ import print_function import numpy as np import torch from PIL import Image import os import importlib import argparse from argparse import Namespace import torchvision def genvalconf(train_opt, **kwargs): conf = Namespace(**vars(train_opt)) attr_dict = train_opt.__dict__ for key, value in attr_dict.items(): if 'val' in key and key.split('_')[0] in attr_dict: setattr(conf, key.split('_')[0], value) for key in kwargs: setattr(conf, key, kwargs[key]) return conf
null
3,368
from __future__ import print_function import numpy as np import torch from PIL import Image import os import importlib import argparse from argparse import Namespace import torchvision def find_class_in_module(target_cls_name, module): target_cls_name = target_cls_name.replace('_', '').lower() clslib = importlib.import_module(module) cls = None for name, clsobj in clslib.__dict__.items(): if name.lower() == target_cls_name: cls = clsobj assert cls is not None, "In %s, there should be a class whose name matches %s in lowercase without underscore(_)" % (module, target_cls_name) return cls
null
3,369
from __future__ import print_function import numpy as np import torch from PIL import Image import os import importlib import argparse from argparse import Namespace import torchvision The provided code snippet includes necessary dependencies for implementing the `diagnose_network` function. Write a Python function `def diagnose_network(net, name='network')` to solve the following problem: Calculate and print the mean of average absolute(gradients) Parameters: net (torch network) -- Torch network name (str) -- the name of the network Here is the function: def diagnose_network(net, name='network'): """Calculate and print the mean of average absolute(gradients) Parameters: net (torch network) -- Torch network name (str) -- the name of the network """ mean = 0.0 count = 0 for param in net.parameters(): if param.grad is not None: mean += torch.mean(torch.abs(param.grad.data)) count += 1 if count > 0: mean = mean / count print(name) print(mean)
Calculate and print the mean of average absolute(gradients) Parameters: net (torch network) -- Torch network name (str) -- the name of the network
3,370
from __future__ import print_function import numpy as np import torch from PIL import Image import os import importlib import argparse from argparse import Namespace import torchvision The provided code snippet includes necessary dependencies for implementing the `print_numpy` function. Write a Python function `def print_numpy(x, val=True, shp=False)` to solve the following problem: Print the mean, min, max, median, std, and size of a numpy array Parameters: val (bool) -- if print the values of the numpy array shp (bool) -- if print the shape of the numpy array Here is the function: def print_numpy(x, val=True, shp=False): """Print the mean, min, max, median, std, and size of a numpy array Parameters: val (bool) -- if print the values of the numpy array shp (bool) -- if print the shape of the numpy array """ x = x.astype(np.float64) if shp: print('shape,', x.shape) if val: x = x.flatten() print('mean = %3.3f, min = %3.3f, max = %3.3f, median = %3.3f, std=%3.3f' % ( np.mean(x), np.min(x), np.max(x), np.median(x), np.std(x)))
Print the mean, min, max, median, std, and size of a numpy array Parameters: val (bool) -- if print the values of the numpy array shp (bool) -- if print the shape of the numpy array
3,371
from __future__ import print_function import numpy as np import torch from PIL import Image import os import importlib import argparse from argparse import Namespace import torchvision def mkdir(path): """create a single empty directory if it didn't exist Parameters: path (str) -- a single directory path """ if not os.path.exists(path): os.makedirs(path) The provided code snippet includes necessary dependencies for implementing the `mkdirs` function. Write a Python function `def mkdirs(paths)` to solve the following problem: create empty directories if they don't exist Parameters: paths (str list) -- a list of directory paths Here is the function: def mkdirs(paths): """create empty directories if they don't exist Parameters: paths (str list) -- a list of directory paths """ if isinstance(paths, list) and not isinstance(paths, str): for path in paths: mkdir(path) else: mkdir(paths)
create empty directories if they don't exist Parameters: paths (str list) -- a list of directory paths
3,372
from __future__ import print_function import numpy as np import torch from PIL import Image import os import importlib import argparse from argparse import Namespace import torchvision def correct_resize_label(t, size): device = t.device t = t.detach().cpu() resized = [] for i in range(t.size(0)): one_t = t[i, :1] one_np = np.transpose(one_t.numpy().astype(np.uint8), (1, 2, 0)) one_np = one_np[:, :, 0] one_image = Image.fromarray(one_np).resize(size, Image.NEAREST) resized_t = torch.from_numpy(np.array(one_image)).long() resized.append(resized_t) return torch.stack(resized, dim=0).to(device)
null
3,373
from __future__ import print_function import numpy as np import torch from PIL import Image import os import importlib import argparse from argparse import Namespace import torchvision def tensor2im(input_image, imtype=np.uint8): """"Converts a Tensor array into a numpy image array. Parameters: input_image (tensor) -- the input image tensor array, range(0, 1) imtype (type) -- the desired type of the converted numpy array """ if not isinstance(input_image, np.ndarray): if isinstance(input_image, torch.Tensor): # get the data from a variable image_tensor = input_image.data else: return input_image image_numpy = image_tensor.clamp(0.0, 1.0).cpu().float().numpy() # convert it into a numpy array if image_numpy.shape[0] == 1: # grayscale to RGB image_numpy = np.tile(image_numpy, (3, 1, 1)) image_numpy = np.transpose(image_numpy, (1, 2, 0)) * 255.0 # post-processing: tranpose and scaling else: # if it is a numpy array, do nothing image_numpy = input_image return image_numpy.astype(imtype) def correct_resize(t, size, mode=Image.BICUBIC): device = t.device t = t.detach().cpu() resized = [] for i in range(t.size(0)): one_t = t[i:i + 1] one_image = Image.fromarray(tensor2im(one_t)).resize(size, Image.BICUBIC) resized_t = torchvision.transforms.functional.to_tensor(one_image) * 2 - 1.0 resized.append(resized_t) return torch.stack(resized, dim=0).to(device)
null
3,374
from __future__ import print_function import numpy as np import torch from PIL import Image import os import importlib import argparse from argparse import Namespace import torchvision The provided code snippet includes necessary dependencies for implementing the `draw_landmarks` function. Write a Python function `def draw_landmarks(img, landmark, color='r', step=2)` to solve the following problem: Return: img -- numpy.array, (B, H, W, 3) img with landmark, RGB order, range (0, 255) Parameters: img -- numpy.array, (B, H, W, 3), RGB order, range (0, 255) landmark -- numpy.array, (B, 68, 2), y direction is opposite to v direction color -- str, 'r' or 'b' (red or blue) Here is the function: def draw_landmarks(img, landmark, color='r', step=2): """ Return: img -- numpy.array, (B, H, W, 3) img with landmark, RGB order, range (0, 255) Parameters: img -- numpy.array, (B, H, W, 3), RGB order, range (0, 255) landmark -- numpy.array, (B, 68, 2), y direction is opposite to v direction color -- str, 'r' or 'b' (red or blue) """ if color =='r': c = np.array([255., 0, 0]) else: c = np.array([0, 0, 255.]) _, H, W, _ = img.shape img, landmark = img.copy(), landmark.copy() landmark[..., 1] = H - 1 - landmark[..., 1] landmark = np.round(landmark).astype(np.int32) for i in range(landmark.shape[1]): x, y = landmark[:, i, 0], landmark[:, i, 1] for j in range(-step, step): for k in range(-step, step): u = np.clip(x + j, 0, W - 1) v = np.clip(y + k, 0, H - 1) for m in range(landmark.shape[0]): img[m, v[m], u[m]] = c return img
Return: img -- numpy.array, (B, H, W, 3) img with landmark, RGB order, range (0, 255) Parameters: img -- numpy.array, (B, H, W, 3), RGB order, range (0, 255) landmark -- numpy.array, (B, 68, 2), y direction is opposite to v direction color -- str, 'r' or 'b' (red or blue)
3,375
import numpy as np from scipy.io import loadmat from PIL import Image import cv2 import os from skimage import transform as trans import torch import warnings def POS(xp, x): npts = xp.shape[1] A = np.zeros([2*npts, 8]) A[0:2*npts-1:2, 0:3] = x.transpose() A[0:2*npts-1:2, 3] = 1 A[1:2*npts:2, 4:7] = x.transpose() A[1:2*npts:2, 7] = 1 b = np.reshape(xp.transpose(), [2*npts, 1]) k, _, _, _ = np.linalg.lstsq(A, b) R1 = k[0:3] R2 = k[4:7] sTx = k[3] sTy = k[7] s = (np.linalg.norm(R1) + np.linalg.norm(R2))/2 t = np.stack([sTx, sTy], axis=0) return t, s def resize_n_crop_img(img, lm, t, s, target_size=224., mask=None): w0, h0 = img.size w = (w0*s).astype(np.int32) h = (h0*s).astype(np.int32) left = (w/2 - target_size/2 + float((t[0] - w0/2)*s)).astype(np.int32) right = left + target_size up = (h/2 - target_size/2 + float((h0/2 - t[1])*s)).astype(np.int32) below = up + target_size img = img.resize((w, h), resample=Image.BICUBIC) img = img.crop((left, up, right, below)) if mask is not None: mask = mask.resize((w, h), resample=Image.BICUBIC) mask = mask.crop((left, up, right, below)) lm = np.stack([lm[:, 0] - t[0] + w0/2, lm[:, 1] - t[1] + h0/2], axis=1)*s lm = lm - np.reshape( np.array([(w/2 - target_size/2), (h/2-target_size/2)]), [1, 2]) return img, lm, mask def extract_5p(lm): lm_idx = np.array([31, 37, 40, 43, 46, 49, 55]) - 1 lm5p = np.stack([lm[lm_idx[0], :], np.mean(lm[lm_idx[[1, 2]], :], 0), np.mean( lm[lm_idx[[3, 4]], :], 0), lm[lm_idx[5], :], lm[lm_idx[6], :]], axis=0) lm5p = lm5p[[1, 2, 0, 3, 4], :] return lm5p The provided code snippet includes necessary dependencies for implementing the `align_img` function. Write a Python function `def align_img(img, lm, lm3D, mask=None, target_size=224., rescale_factor=102.)` to solve the following problem: Return: transparams --numpy.array (raw_W, raw_H, scale, tx, ty) img_new --PIL.Image (target_size, target_size, 3) lm_new --numpy.array (68, 2), y direction is opposite to v direction mask_new --PIL.Image (target_size, target_size) Parameters: img --PIL.Image (raw_H, raw_W, 3) lm --numpy.array (68, 2), y direction is opposite to v direction lm3D --numpy.array (5, 3) mask --PIL.Image (raw_H, raw_W, 3) Here is the function: def align_img(img, lm, lm3D, mask=None, target_size=224., rescale_factor=102.): """ Return: transparams --numpy.array (raw_W, raw_H, scale, tx, ty) img_new --PIL.Image (target_size, target_size, 3) lm_new --numpy.array (68, 2), y direction is opposite to v direction mask_new --PIL.Image (target_size, target_size) Parameters: img --PIL.Image (raw_H, raw_W, 3) lm --numpy.array (68, 2), y direction is opposite to v direction lm3D --numpy.array (5, 3) mask --PIL.Image (raw_H, raw_W, 3) """ w0, h0 = img.size if lm.shape[0] != 5: lm5p = extract_5p(lm) else: lm5p = lm # calculate translation and scale factors using 5 facial landmarks and standard landmarks of a 3D face t, s = POS(lm5p.transpose(), lm3D.transpose()) s = rescale_factor/s # processing the image img_new, lm_new, mask_new = resize_n_crop_img(img, lm, t, s, target_size=target_size, mask=mask) trans_params = np.array([w0, h0, s, t[0], t[1]]) return trans_params, img_new, lm_new, mask_new
Return: transparams --numpy.array (raw_W, raw_H, scale, tx, ty) img_new --PIL.Image (target_size, target_size, 3) lm_new --numpy.array (68, 2), y direction is opposite to v direction mask_new --PIL.Image (target_size, target_size) Parameters: img --PIL.Image (raw_H, raw_W, 3) lm --numpy.array (68, 2), y direction is opposite to v direction lm3D --numpy.array (5, 3) mask --PIL.Image (raw_H, raw_W, 3)
3,376
import math import numpy as np import os import cv2 def skinmask(imbgr): im = _bgr2ycbcr(imbgr) data = im.reshape((-1,3)) lh_skin = gmm_skin.likelihood(data) lh_nonskin = gmm_nonskin.likelihood(data) tmp1 = prior_skin * lh_skin tmp2 = prior_nonskin * lh_nonskin post_skin = tmp1 / (tmp1+tmp2) # posterior probability post_skin = post_skin.reshape((im.shape[0],im.shape[1])) post_skin = np.round(post_skin*255) post_skin = post_skin.astype(np.uint8) post_skin = np.tile(np.expand_dims(post_skin,2),[1,1,3]) # reshape to H*W*3 return post_skin def get_skin_mask(img_path): print('generating skin masks......') names = [i for i in sorted(os.listdir( img_path)) if 'jpg' in i or 'png' in i or 'jpeg' in i or 'PNG' in i] save_path = os.path.join(img_path, 'mask') if not os.path.isdir(save_path): os.makedirs(save_path) for i in range(0, len(names)): name = names[i] print('%05d' % (i), ' ', name) full_image_name = os.path.join(img_path, name) img = cv2.imread(full_image_name).astype(np.float32) skin_img = skinmask(img) cv2.imwrite(os.path.join(save_path, name), skin_img.astype(np.uint8))
null
3,377
import os import cv2 import numpy as np from scipy.io import loadmat import tensorflow as tf from util.preprocess import align_for_lm from shutil import move def load_lm_graph(graph_filename): with tf.gfile.GFile(graph_filename, 'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) with tf.Graph().as_default() as graph: tf.import_graph_def(graph_def, name='net') img_224 = graph.get_tensor_by_name('net/input_imgs:0') output_lm = graph.get_tensor_by_name('net/lm:0') lm_sess = tf.Session(graph=graph) return lm_sess,img_224,output_lm
null
3,378
import os import cv2 import numpy as np from scipy.io import loadmat import tensorflow as tf from util.preprocess import align_for_lm from shutil import move mean_face = np.loadtxt('util/test_mean_face.txt') mean_face = mean_face.reshape([68, 2]) def save_label(labels, save_path): np.savetxt(save_path, labels) def draw_landmarks(img, landmark, save_name): landmark = landmark lm_img = np.zeros([img.shape[0], img.shape[1], 3]) lm_img[:] = img.astype(np.float32) landmark = np.round(landmark).astype(np.int32) for i in range(len(landmark)): for j in range(-1, 1): for k in range(-1, 1): if img.shape[0] - 1 - landmark[i, 1]+j > 0 and \ img.shape[0] - 1 - landmark[i, 1]+j < img.shape[0] and \ landmark[i, 0]+k > 0 and \ landmark[i, 0]+k < img.shape[1]: lm_img[img.shape[0] - 1 - landmark[i, 1]+j, landmark[i, 0]+k, :] = np.array([0, 0, 255]) lm_img = lm_img.astype(np.uint8) cv2.imwrite(save_name, lm_img) def load_data(img_name, txt_name): return cv2.imread(img_name), np.loadtxt(txt_name) def detect_68p(img_path,sess,input_op,output_op): print('detecting landmarks......') names = [i for i in sorted(os.listdir( img_path)) if 'jpg' in i or 'png' in i or 'jpeg' in i or 'PNG' in i] vis_path = os.path.join(img_path, 'vis') remove_path = os.path.join(img_path, 'remove') save_path = os.path.join(img_path, 'landmarks') if not os.path.isdir(vis_path): os.makedirs(vis_path) if not os.path.isdir(remove_path): os.makedirs(remove_path) if not os.path.isdir(save_path): os.makedirs(save_path) for i in range(0, len(names)): name = names[i] print('%05d' % (i), ' ', name) full_image_name = os.path.join(img_path, name) txt_name = '.'.join(name.split('.')[:-1]) + '.txt' full_txt_name = os.path.join(img_path, 'detections', txt_name) # 5 facial landmark path for each image # if an image does not have detected 5 facial landmarks, remove it from the training list if not os.path.isfile(full_txt_name): move(full_image_name, os.path.join(remove_path, name)) continue # load data img, five_points = load_data(full_image_name, full_txt_name) input_img, scale, bbox = align_for_lm(img, five_points) # align for 68 landmark detection # if the alignment fails, remove corresponding image from the training list if scale == 0: move(full_txt_name, os.path.join( remove_path, txt_name)) move(full_image_name, os.path.join(remove_path, name)) continue # detect landmarks input_img = np.reshape( input_img, [1, 224, 224, 3]).astype(np.float32) landmark = sess.run( output_op, feed_dict={input_op: input_img}) # transform back to original image coordinate landmark = landmark.reshape([68, 2]) + mean_face landmark[:, 1] = 223 - landmark[:, 1] landmark = landmark / scale landmark[:, 0] = landmark[:, 0] + bbox[0] landmark[:, 1] = landmark[:, 1] + bbox[1] landmark[:, 1] = img.shape[0] - 1 - landmark[:, 1] if i % 100 == 0: draw_landmarks(img, landmark, os.path.join(vis_path, name)) save_label(landmark, os.path.join(save_path, txt_name))
null
3,379
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 The provided code snippet includes necessary dependencies for implementing the `save_images` function. Write a Python function `def save_images(webpage, visuals, image_path, aspect_ratio=1.0, width=256)` to solve the following problem: Save images to the disk. Parameters: webpage (the HTML class) -- the HTML webpage class that stores these imaegs (see html.py for more details) visuals (OrderedDict) -- an ordered dictionary that stores (name, images (either tensor or numpy) ) pairs image_path (str) -- the string is used to create image paths aspect_ratio (float) -- the aspect ratio of saved images width (int) -- the images will be resized to width x width This function will save images stored in 'visuals' to the HTML file specified by 'webpage'. Here is the function: def save_images(webpage, visuals, image_path, aspect_ratio=1.0, width=256): """Save images to the disk. Parameters: webpage (the HTML class) -- the HTML webpage class that stores these imaegs (see html.py for more details) visuals (OrderedDict) -- an ordered dictionary that stores (name, images (either tensor or numpy) ) pairs image_path (str) -- the string is used to create image paths aspect_ratio (float) -- the aspect ratio of saved images width (int) -- the images will be resized to width x width This function will save images stored in 'visuals' to the HTML file specified by 'webpage'. """ image_dir = webpage.get_image_dir() short_path = ntpath.basename(image_path[0]) name = os.path.splitext(short_path)[0] webpage.add_header(name) ims, txts, links = [], [], [] for label, im_data in visuals.items(): im = util.tensor2im(im_data) image_name = '%s/%s.png' % (label, name) os.makedirs(os.path.join(image_dir, label), exist_ok=True) save_path = os.path.join(image_dir, image_name) util.save_image(im, save_path, aspect_ratio=aspect_ratio) ims.append(image_name) txts.append(label) links.append(image_name) webpage.add_images(ims, txts, links, width=width)
Save images to the disk. Parameters: webpage (the HTML class) -- the HTML webpage class that stores these imaegs (see html.py for more details) visuals (OrderedDict) -- an ordered dictionary that stores (name, images (either tensor or numpy) ) pairs image_path (str) -- the string is used to create image paths aspect_ratio (float) -- the aspect ratio of saved images width (int) -- the images will be resized to width x width This function will save images stored in 'visuals' to the HTML file specified by 'webpage'.
3,380
import numpy as np from PIL import Image from scipy.io import loadmat, savemat from array import array import os.path as osp def LoadExpBasis(bfm_folder='BFM'): def transferBFM09(bfm_folder='BFM'): 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_BFM['texPC'] # texture basis texEV = original_BFM['texEV'] # eigen value texMU = original_BFM['texMU'] # mean texture expPC, expEV = LoadExpBasis(bfm_folder) # transfer BFM09 to our face model idBase = shapePC*np.reshape(shapeEV, [-1, 199]) idBase = idBase/1e5 # unify the scale to decimeter idBase = idBase[:, :80] # use only first 80 basis exBase = expPC*np.reshape(expEV, [-1, 79]) exBase = exBase/1e5 # unify the scale to decimeter exBase = exBase[:, :64] # use only first 64 basis texBase = texPC*np.reshape(texEV, [-1, 199]) texBase = texBase[:, :80] # use only first 80 basis # our face model is cropped along face landmarks and contains only 35709 vertex. # original BFM09 contains 53490 vertex, and expression basis provided by Guo et al. contains 53215 vertex. # thus we select corresponding vertex to get our face model. index_exp = loadmat(osp.join(bfm_folder, 'BFM_front_idx.mat')) index_exp = index_exp['idx'].astype(np.int32) - 1 # starts from 0 (to 53215) index_shape = loadmat(osp.join(bfm_folder, 'BFM_exp_idx.mat')) index_shape = index_shape['trimIndex'].astype( np.int32) - 1 # starts from 0 (to 53490) index_shape = index_shape[index_exp] idBase = np.reshape(idBase, [-1, 3, 80]) idBase = idBase[index_shape, :, :] idBase = np.reshape(idBase, [-1, 80]) texBase = np.reshape(texBase, [-1, 3, 80]) texBase = texBase[index_shape, :, :] texBase = np.reshape(texBase, [-1, 80]) exBase = np.reshape(exBase, [-1, 3, 64]) exBase = exBase[index_exp, :, :] exBase = np.reshape(exBase, [-1, 64]) meanshape = np.reshape(shapeMU, [-1, 3])/1e5 meanshape = meanshape[index_shape, :] meanshape = np.reshape(meanshape, [1, -1]) meantex = np.reshape(texMU, [-1, 3]) meantex = meantex[index_shape, :] meantex = np.reshape(meantex, [1, -1]) # other info contains triangles, region used for computing photometric loss, # region used for skin texture regularization, and 68 landmarks index etc. other_info = loadmat(osp.join(bfm_folder, 'facemodel_info.mat')) frontmask2_idx = other_info['frontmask2_idx'] skinmask = other_info['skinmask'] keypoints = other_info['keypoints'] point_buf = other_info['point_buf'] tri = other_info['tri'] tri_mask2 = other_info['tri_mask2'] # save our face model savemat(osp.join(bfm_folder, 'BFM_model_front.mat'), {'meanshape': meanshape, 'meantex': meantex, 'idBase': idBase, 'exBase': exBase, 'texBase': texBase, 'tri': tri, 'point_buf': point_buf, 'tri_mask2': tri_mask2, 'keypoints': keypoints, 'frontmask2_idx': frontmask2_idx, 'skinmask': skinmask})
null
3,381
import numpy as np from PIL import Image from scipy.io import loadmat, savemat from array import array import os.path as osp def load_lm3d(bfm_folder): Lm3D = loadmat(osp.join(bfm_folder, 'similarity_Lm3D_all.mat')) Lm3D = Lm3D['lm'] # calculate 5 facial landmarks using 68 landmarks lm_idx = np.array([31, 37, 40, 43, 46, 49, 55]) - 1 Lm3D = np.stack([Lm3D[lm_idx[0], :], np.mean(Lm3D[lm_idx[[1, 2]], :], 0), np.mean( Lm3D[lm_idx[[3, 4]], :], 0), Lm3D[lm_idx[5], :], Lm3D[lm_idx[6], :]], axis=0) Lm3D = Lm3D[[1, 2, 0, 3, 4], :] return Lm3D
null
3,382
import os def write_list(lms_list, imgs_list, msks_list, mode='train',save_folder='datalist', save_name=''): 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') as fd: fd.writelines([i + '\n' for i in imgs_list]) with open(os.path.join(save_path, save_name + 'masks.txt'), 'w') as fd: fd.writelines([i + '\n' for i in msks_list])
null
3,383
import os def check_list(rlms_list, rimgs_list, rmsks_list): lms_list, imgs_list, msks_list = [], [], [] for i in range(len(rlms_list)): flag = 'false' lm_path = rlms_list[i] im_path = rimgs_list[i] msk_path = rmsks_list[i] if os.path.isfile(lm_path) and os.path.isfile(im_path) and os.path.isfile(msk_path): flag = 'true' lms_list.append(rlms_list[i]) imgs_list.append(rimgs_list[i]) msks_list.append(rmsks_list[i]) print(i, rlms_list[i], flag) return lms_list, imgs_list, msks_list
null
3,384
import os import cv2 import time import glob import argparse import face_alignment import numpy as np from PIL import Image from tqdm import tqdm from itertools import cycle from torch.multiprocessing import Pool, Process, set_start_method class KeypointExtractor(): def __init__(self, device): self.detector = face_alignment.FaceAlignment(face_alignment.LandmarksType._2D, device=device) def extract_keypoint(self, images, name=None, info=True): if isinstance(images, list): keypoints = [] if info: i_range = tqdm(images,desc='landmark Det:') else: i_range = images for image in i_range: current_kp = self.extract_keypoint(image) if np.mean(current_kp) == -1 and keypoints: keypoints.append(keypoints[-1]) else: keypoints.append(current_kp[None]) keypoints = np.concatenate(keypoints, 0) np.savetxt(os.path.splitext(name)[0]+'.txt', keypoints.reshape(-1)) return keypoints else: while True: try: keypoints = self.detector.get_landmarks_from_image(np.array(images))[0] break except RuntimeError as e: if str(e).startswith('CUDA'): print("Warning: out of memory, sleep for 1s") time.sleep(1) else: print(e) break except TypeError: print('No face detected in this image') shape = [68, 2] keypoints = -1. * np.ones(shape) break if name is not None: np.savetxt(os.path.splitext(name)[0]+'.txt', keypoints.reshape(-1)) return keypoints def read_video(filename): frames = [] cap = cv2.VideoCapture(filename) while cap.isOpened(): ret, frame = cap.read() if ret: frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) frame = Image.fromarray(frame) frames.append(frame) else: break cap.release() return frames def run(data): filename, opt, device = data os.environ['CUDA_VISIBLE_DEVICES'] = device kp_extractor = KeypointExtractor() images = read_video(filename) name = filename.split('/')[-2:] os.makedirs(os.path.join(opt.output_dir, name[-2]), exist_ok=True) kp_extractor.extract_keypoint( images, name=os.path.join(opt.output_dir, name[-2], name[-1]) )
null
3,385
import os import numpy as np from PIL import Image from skimage import img_as_float32, transform import torch import scipy.io as scio from glob import glob def transform_semantic_1(semantic, semantic_radius): semantic_list = [semantic for i in range(0, semantic_radius * 2 + 1)] coeff_3dmm = np.concatenate(semantic_list, 0) return coeff_3dmm.transpose(1, 0) def transform_semantic_target(coeff_3dmm, frame_index, semantic_radius): num_frames = coeff_3dmm.shape[0] seq = list(range(frame_index - semantic_radius, frame_index + semantic_radius + 1)) index = [min(max(item, 0), num_frames - 1) for item in seq] coeff_3dmm_g = coeff_3dmm[index, :] return coeff_3dmm_g.transpose(1, 0) def get_facerender_data(coeff_path, pic_path, first_coeff_path, audio_path, batch_size, device): semantic_radius = 13 video_name = os.path.splitext(os.path.split(coeff_path)[-1])[0] txt_path = os.path.splitext(coeff_path)[0] data = {} images_list = sorted(glob(os.path.join(pic_path, '*.png'))) source_image_ts_list = [] for single in images_list: img1 = Image.open(single) source_image = np.array(img1) source_image = img_as_float32(source_image) source_image = transform.resize(source_image, (256, 256, 3)) source_image = source_image.transpose((2, 0, 1)) source_image_ts = torch.FloatTensor(source_image).unsqueeze(0) source_image_ts = source_image_ts.repeat(batch_size, 1, 1, 1) source_image_ts = source_image_ts.to(device) source_image_ts_list.append(source_image_ts) data['source_image'] = source_image_ts_list source_semantics_dict = scio.loadmat(first_coeff_path) source_semantics = source_semantics_dict['coeff_3dmm'][:1, :73] # 1 70 source_semantics_new = transform_semantic_1(source_semantics, semantic_radius) source_semantics_ts = torch.FloatTensor(source_semantics_new).unsqueeze(0) source_semantics_ts = source_semantics_ts.repeat(batch_size, 1, 1) data['source_semantics'] = source_semantics_ts # target generated_dict = scio.loadmat(coeff_path) generated_3dmm = generated_dict['coeff_3dmm'] generated_3dmm[:, :64] = generated_3dmm[:, :64] * 1.0 generated_3dmm = np.concatenate( [generated_3dmm, np.repeat(source_semantics[:, 70:], generated_3dmm.shape[0], axis=0)], axis=1) generated_3dmm[:, 64:] = np.repeat(source_semantics[:, 64:], generated_3dmm.shape[0], axis=0) with open(txt_path + '.txt', 'w') as f: for coeff in generated_3dmm: for i in coeff: f.write(str(i)[:7] + ' ' + '\t') f.write('\n') target_semantics_list = [] frame_num = generated_3dmm.shape[0] data['frame_num'] = frame_num for frame_idx in range(frame_num): target_semantics = transform_semantic_target(generated_3dmm, frame_idx, semantic_radius) target_semantics_list.append(target_semantics) remainder = frame_num % batch_size if remainder != 0: for _ in range(batch_size - remainder): target_semantics_list.append(target_semantics) target_semantics_np = np.array(target_semantics_list) # frame_num 70 semantic_radius*2+1 target_semantics_np = target_semantics_np.reshape(batch_size, -1, target_semantics_np.shape[-2], target_semantics_np.shape[-1]) data['target_semantics_list'] = torch.FloatTensor(target_semantics_np) data['video_name'] = video_name data['audio_path'] = audio_path return data
null
3,386
import os import numpy as np from PIL import Image from skimage import img_as_float32, transform import torch import scipy.io as scio from glob import glob def gen_camera_pose(camera_degree_list, frame_num, batch_size): new_degree_list = [] if len(camera_degree_list) == 1: for _ in range(frame_num): new_degree_list.append(camera_degree_list[0]) remainder = frame_num % batch_size if remainder != 0: for _ in range(batch_size - remainder): new_degree_list.append(new_degree_list[-1]) new_degree_np = np.array(new_degree_list).reshape(batch_size, -1) return new_degree_np degree_sum = 0. for i, degree in enumerate(camera_degree_list[1:]): degree_sum += abs(degree - camera_degree_list[i]) degree_per_frame = degree_sum / (frame_num - 1) for i, degree in enumerate(camera_degree_list[1:]): degree_last = camera_degree_list[i] degree_step = degree_per_frame * abs(degree - degree_last) / (degree - degree_last) new_degree_list = new_degree_list + list(np.arange(degree_last, degree, degree_step)) if len(new_degree_list) > frame_num: new_degree_list = new_degree_list[:frame_num] elif len(new_degree_list) < frame_num: for _ in range(frame_num - len(new_degree_list)): new_degree_list.append(new_degree_list[-1]) print(len(new_degree_list)) print(frame_num) remainder = frame_num % batch_size if remainder != 0: for _ in range(batch_size - remainder): new_degree_list.append(new_degree_list[-1]) new_degree_np = np.array(new_degree_list).reshape(batch_size, -1) return new_degree_np
null
3,387
import torch import torch.nn.functional as F from torch import nn from src.audio2pose_models.res_unet import ResUnet def class2onehot(idx, class_num): assert torch.max(idx).item() < class_num onehot = torch.zeros(idx.size(0), class_num).to(idx.device) onehot.scatter_(1, idx, 1) return onehot
null
3,388
from torch import nn import torch.nn.functional as F import torch from src.facerender.sync_batchnorm import SynchronizedBatchNorm2d as BatchNorm2d from src.facerender.sync_batchnorm import SynchronizedBatchNorm3d as BatchNorm3d import torch.nn.utils.spectral_norm as spectral_norm def make_coordinate_grid(spatial_size, type): d, h, w = spatial_size x = torch.arange(w).type(type) y = torch.arange(h).type(type) z = torch.arange(d).type(type) x = (2 * (x / (w - 1)) - 1) y = (2 * (y / (h - 1)) - 1) z = (2 * (z / (d - 1)) - 1) yy = y.view(1, -1, 1).repeat(d, 1, w) xx = x.view(1, 1, -1).repeat(d, h, 1) zz = z.view(-1, 1, 1).repeat(1, h, w) meshed = torch.cat([xx.unsqueeze_(3), yy.unsqueeze_(3), zz.unsqueeze_(3)], 3) return meshed The provided code snippet includes necessary dependencies for implementing the `kp2gaussian` function. Write a Python function `def kp2gaussian(kp, spatial_size, kp_variance)` to solve the following problem: Transform a keypoint into gaussian like representation Here is the function: def kp2gaussian(kp, spatial_size, kp_variance): """ Transform a keypoint into gaussian like representation """ mean = kp['value'] coordinate_grid = make_coordinate_grid(spatial_size, mean.type()) number_of_leading_dimensions = len(mean.shape) - 1 shape = (1,) * number_of_leading_dimensions + coordinate_grid.shape coordinate_grid = coordinate_grid.view(*shape) repeats = mean.shape[:number_of_leading_dimensions] + (1, 1, 1, 1) coordinate_grid = coordinate_grid.repeat(*repeats) # Preprocess kp shape shape = mean.shape[:number_of_leading_dimensions] + (1, 1, 1, 3) mean = mean.view(*shape) mean_sub = (coordinate_grid - mean) out = torch.exp(-0.5 * (mean_sub ** 2).sum(-1) / kp_variance) return out
Transform a keypoint into gaussian like representation
3,389
from torch import nn import torch.nn.functional as F import torch from src.facerender.sync_batchnorm import SynchronizedBatchNorm2d as BatchNorm2d from src.facerender.sync_batchnorm import SynchronizedBatchNorm3d as BatchNorm3d import torch.nn.utils.spectral_norm as spectral_norm The provided code snippet includes necessary dependencies for implementing the `make_coordinate_grid_2d` function. Write a Python function `def make_coordinate_grid_2d(spatial_size, type)` to solve the following problem: Create a meshgrid [-1,1] x [-1,1] of given spatial_size. Here is the function: def make_coordinate_grid_2d(spatial_size, type): """ Create a meshgrid [-1,1] x [-1,1] of given spatial_size. """ h, w = spatial_size x = torch.arange(w).type(type) y = torch.arange(h).type(type) x = (2 * (x / (w - 1)) - 1) y = (2 * (y / (h - 1)) - 1) yy = y.view(-1, 1).repeat(1, w) xx = x.view(1, -1).repeat(h, 1) meshed = torch.cat([xx.unsqueeze_(2), yy.unsqueeze_(2)], 2) return meshed
Create a meshgrid [-1,1] x [-1,1] of given spatial_size.
3,390
from scipy.spatial import ConvexHull import torch import torch.nn.functional as F import numpy as np from tqdm import tqdm def normalize_kp(kp_source, kp_driving, kp_driving_initial, adapt_movement_scale=False, use_relative_movement=False, use_relative_jacobian=False): if adapt_movement_scale: source_area = ConvexHull(kp_source['value'][0].data.cpu().numpy()).volume driving_area = ConvexHull(kp_driving_initial['value'][0].data.cpu().numpy()).volume adapt_movement_scale = np.sqrt(source_area) / np.sqrt(driving_area) else: adapt_movement_scale = 1 kp_new = {k: v for k, v in kp_driving.items()} if use_relative_movement: kp_value_diff = (kp_driving['value'] - kp_driving_initial['value']) kp_value_diff *= adapt_movement_scale kp_new['value'] = kp_value_diff + kp_source['value'] if use_relative_jacobian: jacobian_diff = torch.matmul(kp_driving['jacobian'], torch.inverse(kp_driving_initial['jacobian'])) kp_new['jacobian'] = torch.matmul(jacobian_diff, kp_source['jacobian']) return kp_new
null
3,391
from scipy.spatial import ConvexHull import torch import torch.nn.functional as F import numpy as np from tqdm import tqdm def keypoint_transformation(kp_canonical, he, wo_exp=False): kp = kp_canonical['value'] # (bs, k, 3) yaw, pitch, roll = he['yaw'], he['pitch'], he['roll'] yaw = headpose_pred_to_degree(yaw) pitch = headpose_pred_to_degree(pitch) roll = headpose_pred_to_degree(roll) if 'yaw_in' in he: yaw = he['yaw_in'] if 'pitch_in' in he: pitch = he['pitch_in'] if 'roll_in' in he: roll = he['roll_in'] rot_mat = get_rotation_matrix(yaw, pitch, roll) # (bs, 3, 3) t, exp = he['t'], he['exp'] if wo_exp: exp = exp * 0 # keypoint rotation kp_rotated = torch.einsum('bmp,bkp->bkm', rot_mat, kp) # keypoint translation t[:, 0] = t[:, 0] * 0 t[:, 2] = t[:, 2] * 0 t = t.unsqueeze(1).repeat(1, kp.shape[1], 1) kp_t = kp_rotated + t # add expression deviation exp = exp.view(exp.shape[0], -1, 3) kp_transformed = kp_t + exp return {'value': kp_transformed} def make_animation(source_image, source_semantics, target_semantics, generator, kp_detector, mapping, frame_num): with torch.no_grad(): predictions = [] kp_canonical = [] kp_source = [] for single_image in source_image: kp_single = kp_detector(single_image) kp_canonical.append(kp_single) he_source_single = mapping(source_semantics) kp_single = keypoint_transformation(kp_single, he_source_single) kp_source.append(kp_single) for frame_idx in tqdm(range(target_semantics.shape[1]), 'Face Renderer:'): if frame_idx >= frame_num: break target_semantics_frame = target_semantics[:, frame_idx] he_driving = mapping(target_semantics_frame) kp_driving = keypoint_transformation(kp_canonical[frame_idx], he_driving) kp_norm = kp_driving out = generator(source_image[frame_idx], kp_source=kp_source[frame_idx], kp_driving=kp_norm) predictions.append(out['prediction']) predictions_ts = torch.stack(predictions, dim=1) return predictions_ts
null
3,392
import collections import torch import torch.nn.functional as F from torch.nn.modules.batchnorm import _BatchNorm from torch.nn.parallel._functions import ReduceAddCoalesced, Broadcast from .comm import SyncMaster The provided code snippet includes necessary dependencies for implementing the `_sum_ft` function. Write a Python function `def _sum_ft(tensor)` to solve the following problem: sum over the first and last dimention Here is the function: def _sum_ft(tensor): """sum over the first and last dimention""" return tensor.sum(dim=0).sum(dim=-1)
sum over the first and last dimention
3,393
import collections import torch import torch.nn.functional as F from torch.nn.modules.batchnorm import _BatchNorm from torch.nn.parallel._functions import ReduceAddCoalesced, Broadcast from .comm import SyncMaster The provided code snippet includes necessary dependencies for implementing the `_unsqueeze_ft` function. Write a Python function `def _unsqueeze_ft(tensor)` to solve the following problem: add new dementions at the front and the tail Here is the function: def _unsqueeze_ft(tensor): """add new dementions at the front and the tail""" return tensor.unsqueeze(0).unsqueeze(-1)
add new dementions at the front and the tail
3,394
import functools from torch.nn.parallel.data_parallel import DataParallel def execute_replication_callbacks(modules): """ 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 among multiple copies of this module on different devices). Through this context, different copies can share some information. We guarantee that the callback on the master copy (the first copy) will be called ahead of calling the callback of any slave copies. """ 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_replicate__(ctxs[j], i) The provided code snippet includes necessary dependencies for implementing the `patch_replication_callback` function. Write a Python function `def patch_replication_callback(data_parallel)` to solve the following problem: Monkey-patch an existing `DataParallel` object. Add the replication callback. Useful when you have customized `DataParallel` implementation. Examples: > sync_bn = SynchronizedBatchNorm1d(10, eps=1e-5, affine=False) > sync_bn = DataParallel(sync_bn, device_ids=[0, 1]) > patch_replication_callback(sync_bn) # this is equivalent to > sync_bn = SynchronizedBatchNorm1d(10, eps=1e-5, affine=False) > sync_bn = DataParallelWithCallback(sync_bn, device_ids=[0, 1]) Here is the function: def patch_replication_callback(data_parallel): """ Monkey-patch an existing `DataParallel` object. Add the replication callback. Useful when you have customized `DataParallel` implementation. Examples: > sync_bn = SynchronizedBatchNorm1d(10, eps=1e-5, affine=False) > sync_bn = DataParallel(sync_bn, device_ids=[0, 1]) > patch_replication_callback(sync_bn) # this is equivalent to > sync_bn = SynchronizedBatchNorm1d(10, eps=1e-5, affine=False) > sync_bn = DataParallelWithCallback(sync_bn, device_ids=[0, 1]) """ assert isinstance(data_parallel, DataParallel) old_replicate = data_parallel.replicate @functools.wraps(old_replicate) def new_replicate(module, device_ids): modules = old_replicate(module, device_ids) execute_replication_callbacks(modules) return modules data_parallel.replicate = new_replicate
Monkey-patch an existing `DataParallel` object. Add the replication callback. Useful when you have customized `DataParallel` implementation. Examples: > sync_bn = SynchronizedBatchNorm1d(10, eps=1e-5, affine=False) > sync_bn = DataParallel(sync_bn, device_ids=[0, 1]) > patch_replication_callback(sync_bn) # this is equivalent to > sync_bn = SynchronizedBatchNorm1d(10, eps=1e-5, affine=False) > sync_bn = DataParallelWithCallback(sync_bn, device_ids=[0, 1])
3,395
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 generate_blink_seq(num_frames): ratio = np.zeros((num_frames,1)) frame_id = 0 while frame_id in range(num_frames): start = 80 if frame_id+start+9<=num_frames - 1: ratio[frame_id+start:frame_id+start+9, 0] = [0.5,0.6,0.7,0.9,1, 0.9, 0.7,0.6,0.5] frame_id = frame_id+start+9 else: break return ratio
null
3,396
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): def parse_audio_length(audio_length, sr, fps): def generate_blink_seq_randomly(num_frames): def get_data(first_coeff_path, audio_path, device): 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] wav = audio.load_wav(audio_path, 16000) wav_length, num_frames = parse_audio_length(len(wav), 16000, 25) wav = crop_pad_audio(wav, wav_length) orig_mel = audio.melspectrogram(wav).T spec = orig_mel.copy() # nframes 80 indiv_mels = [] for i in tqdm(range(num_frames), 'mel:'): start_frame_num = i-2 start_idx = int(80. * (start_frame_num / float(fps))) end_idx = start_idx + syncnet_mel_step_size seq = list(range(start_idx, end_idx)) seq = [ min(max(item, 0), orig_mel.shape[0]-1) for item in seq ] m = spec[seq, :] indiv_mels.append(m.T) indiv_mels = np.asarray(indiv_mels) # T 80 16 ratio = generate_blink_seq_randomly(num_frames) # T source_semantics_path = first_coeff_path source_semantics_dict = scio.loadmat(source_semantics_path) # ref_coeff = source_semantics_dict['coeff_3dmm'][:num_frames,:70] #1 70 # # ref_coeff = np.repeat(ref_coeff, num_frames, axis=0) coeff_3dmm = source_semantics_dict['coeff_3dmm'] if coeff_3dmm.shape[0] >= num_frames: ref_coeff = source_semantics_dict['coeff_3dmm'][:num_frames, :70] else: ref_coeff_ori = source_semantics_dict['coeff_3dmm'][:, :70] ref_coeff_last = source_semantics_dict['coeff_3dmm'][-1, :70].reshape(1,-1) ref_coeff_add = np.repeat(ref_coeff_last, num_frames - coeff_3dmm.shape[0], axis=0) ref_coeff = np.concatenate((ref_coeff_ori, ref_coeff_add)) indiv_mels = torch.FloatTensor(indiv_mels).unsqueeze(1).unsqueeze(0) # bs T 1 80 16 ratio = torch.FloatTensor(ratio).unsqueeze(0).fill_(0.) # bs T ref_coeff = torch.FloatTensor(ref_coeff).unsqueeze(0) # bs 1 70 indiv_mels = indiv_mels.to(device) ratio = ratio.to(device) ref_coeff = ref_coeff.to(device) return {'indiv_mels': indiv_mels, 'ref': ref_coeff, 'num_frames': num_frames, 'ratio_gt': ratio, 'audio_name': audio_name, 'pic_name': pic_name}
null
3,397
import os, sys import cv2 import glob import shutil import numpy as np from tqdm import tqdm from imageio import imread, imsave from src.dain_model.base_predictor import BasePredictor def video2frames(video_path, outpath, **kargs): 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_name) if not os.path.exists(out_full_path): os.makedirs(out_full_path) # video file name outformat = os.path.join(out_full_path, '%08d.png') cmd = ffmpeg + [' -i ', video_path, ' -start_number ', ' 0 ', outformat] cmd = ''.join(cmd) + _dict2str(kargs) if os.system(cmd) != 0: raise RuntimeError('ffmpeg process video: {} error'.format(vid_name)) sys.stdout.flush() return out_full_path
null
3,398
import os, sys import cv2 import glob import shutil import numpy as np from tqdm import tqdm from imageio import imread, imsave from src.dain_model.base_predictor import BasePredictor def frames2video(frame_path, video_path, r, w, h): out = cv2.VideoWriter(video_path, cv2.VideoWriter_fourcc(*'DIVX'), int(r), (w, h)) filelist = sorted(glob.glob(os.path.join(frame_path, '*.png'))) for img_path in filelist: img = cv2.imread(img_path) out.write(img) out.release()
null
3,399
import os import cv2 import time import glob import argparse import scipy import numpy as np from PIL import Image from tqdm import tqdm from itertools import cycle from torch.multiprocessing import Pool, Process, set_start_method import numpy as np from PIL import Image import dlib def create_video(video_name, frames, fps=25, video_format='.mp4', resize_ratio=1): # video_name = os.path.dirname(image_folder) + video_format # img_list = glob.glob1(image_folder, 'frame*') # img_list.sort() # frame = cv2.imread(os.path.join(image_folder, img_list[0])) # frame = cv2.resize(frame, (0, 0), fx=resize_ratio, fy=resize_ratio) # height, width, layers = frames[0].shape height, width, layers = 512, 512, 3 if video_format == '.mp4': fourcc = cv2.VideoWriter_fourcc(*'mp4v') elif video_format == '.avi': fourcc = cv2.VideoWriter_fourcc(*'XVID') video = cv2.VideoWriter(video_name, fourcc, fps, (width, height)) for _frame in frames: _frame = cv2.resize(_frame, (height, width), interpolation=cv2.INTER_LINEAR) video.write(_frame)
null
3,400
import os import cv2 import time import glob import argparse import scipy import numpy as np from PIL import Image from tqdm import tqdm from itertools import cycle from torch.multiprocessing import Pool, Process, set_start_method import numpy as np from PIL import Image import dlib class Croper: def __init__(self, path_of_lm): # download model from: http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2 self.predictor = dlib.shape_predictor(path_of_lm) def get_landmark(self, img_np): """get landmark with dlib :return: np.array shape=(68, 2) """ detector = dlib.get_frontal_face_detector() dets = detector(img_np, 1) # print("Number of faces detected: {}".format(len(dets))) # for k, d in enumerate(dets): if len(dets) == 0: return None d = dets[0] # Get the landmarks/parts for the face in box d. shape = self.predictor(img_np, d) # print("Part 0: {}, Part 1: {} ...".format(shape.part(0), shape.part(1))) t = list(shape.parts()) a = [] for tt in t: a.append([tt.x, tt.y]) lm = np.array(a) # lm is a shape=(68,2) np.array return lm def align_face(self, img, lm, output_size=1024): """ :param filepath: str :return: PIL Image """ lm_chin = lm[0: 17] # left-right lm_eyebrow_left = lm[17: 22] # left-right lm_eyebrow_right = lm[22: 27] # left-right lm_nose = lm[27: 31] # top-down lm_nostrils = lm[31: 36] # top-down lm_eye_left = lm[36: 42] # left-clockwise lm_eye_right = lm[42: 48] # left-clockwise lm_mouth_outer = lm[48: 60] # left-clockwise lm_mouth_inner = lm[60: 68] # left-clockwise # Calculate auxiliary vectors. eye_left = np.mean(lm_eye_left, axis=0) eye_right = np.mean(lm_eye_right, axis=0) eye_avg = (eye_left + eye_right) * 0.5 eye_to_eye = eye_right - eye_left mouth_left = lm_mouth_outer[0] mouth_right = lm_mouth_outer[6] mouth_avg = (mouth_left + mouth_right) * 0.5 eye_to_mouth = mouth_avg - eye_avg # Choose oriented crop rectangle. x = eye_to_eye - np.flipud(eye_to_mouth) * [-1, 1] # 双眼差与双嘴差相加 x /= np.hypot(*x) # hypot函数计算直角三角形的斜边长,用斜边长对三角形两条直边做归一化 x *= max(np.hypot(*eye_to_eye) * 2.0, np.hypot(*eye_to_mouth) * 1.8) # 双眼差和眼嘴差,选较大的作为基准尺度 y = np.flipud(x) * [-1, 1] c = eye_avg + eye_to_mouth * 0.1 quad = np.stack([c - x - y, c - x + y, c + x + y, c + x - y]) # 定义四边形,以面部基准位置为中心上下左右平移得到四个顶点 qsize = np.hypot(*x) * 2 # 定义四边形的大小(边长),为基准尺度的2倍 # Shrink. # 如果计算出的四边形太大了,就按比例缩小它 shrink = int(np.floor(qsize / output_size * 0.5)) if shrink > 1: rsize = (int(np.rint(float(img.size[0]) / shrink)), int(np.rint(float(img.size[1]) / shrink))) img = img.resize(rsize, Image.ANTIALIAS) quad /= shrink qsize /= shrink # Crop. border = max(int(np.rint(qsize * 0.1)), 3) crop = (int(np.floor(min(quad[:, 0]))), int(np.floor(min(quad[:, 1]))), int(np.ceil(max(quad[:, 0]))), int(np.ceil(max(quad[:, 1])))) crop = (max(crop[0] - border, 0), max(crop[1] - border, 0), min(crop[2] + border, img.size[0]), min(crop[3] + border, img.size[1])) if crop[2] - crop[0] < img.size[0] or crop[3] - crop[1] < img.size[1]: # img = img.crop(crop) quad -= crop[0:2] # Pad. pad = (int(np.floor(min(quad[:, 0]))), int(np.floor(min(quad[:, 1]))), int(np.ceil(max(quad[:, 0]))), int(np.ceil(max(quad[:, 1])))) pad = (max(-pad[0] + border, 0), max(-pad[1] + border, 0), max(pad[2] - img.size[0] + border, 0), max(pad[3] - img.size[1] + border, 0)) # if enable_padding and max(pad) > border - 4: # pad = np.maximum(pad, int(np.rint(qsize * 0.3))) # img = np.pad(np.float32(img), ((pad[1], pad[3]), (pad[0], pad[2]), (0, 0)), 'reflect') # h, w, _ = img.shape # y, x, _ = np.ogrid[:h, :w, :1] # mask = np.maximum(1.0 - np.minimum(np.float32(x) / pad[0], np.float32(w - 1 - x) / pad[2]), # 1.0 - np.minimum(np.float32(y) / pad[1], np.float32(h - 1 - y) / pad[3])) # blur = qsize * 0.02 # img += (scipy.ndimage.gaussian_filter(img, [blur, blur, 0]) - img) * np.clip(mask * 3.0 + 1.0, 0.0, 1.0) # img += (np.median(img, axis=(0, 1)) - img) * np.clip(mask, 0.0, 1.0) # img = Image.fromarray(np.uint8(np.clip(np.rint(img), 0, 255)), 'RGB') # quad += pad[:2] # Transform. quad = (quad + 0.5).flatten() lx = max(min(quad[0], quad[2]), 0) ly = max(min(quad[1], quad[7]), 0) rx = min(max(quad[4], quad[6]), img.size[0]) ry = min(max(quad[3], quad[5]), img.size[0]) # img = img.transform((transform_size, transform_size), Image.QUAD, (quad + 0.5).flatten(), # Image.BILINEAR) # if output_size < transform_size: # img = img.resize((output_size, output_size), Image.ANTIALIAS) # Save aligned image. return crop, [lx, ly, rx, ry] # def crop(self, img_np_list): # for _i in range(len(img_np_list)): # img_np = img_np_list[_i] # lm = self.get_landmark(img_np) # if lm is None: # return None # crop, quad = self.align_face(img=Image.fromarray(img_np), lm=lm, output_size=512) # clx, cly, crx, cry = crop # lx, ly, rx, ry = quad # lx, ly, rx, ry = int(lx), int(ly), int(rx), int(ry) # _inp = img_np_list[_i] # _inp = _inp[cly:cry, clx:crx] # _inp = _inp[ly:ry, lx:rx] # img_np_list[_i] = _inp # return img_np_list def crop(self, img_np_list, still=False, xsize=512): # first frame for all video img_np = img_np_list[0] lm = self.get_landmark(img_np) if lm is None: return None crop, quad = self.align_face(img=Image.fromarray(img_np), lm=lm, output_size=xsize) clx, cly, crx, cry = crop lx, ly, rx, ry = quad lx, ly, rx, ry = int(lx), int(ly), int(rx), int(ry) for _i in range(len(img_np_list)): _inp = img_np_list[_i] _inp = _inp[cly:cry, clx:crx] # cv2.imwrite('test1.jpg', _inp) if not still: _inp = _inp[ly:ry, lx:rx] # cv2.imwrite('test2.jpg', _inp) img_np_list[_i] = _inp return img_np_list, crop, quad def read_video(filename, uplimit=100): frames = [] cap = cv2.VideoCapture(filename) cnt = 0 while cap.isOpened(): ret, frame = cap.read() if ret: frame = cv2.resize(frame, (512, 512)) frames.append(frame) else: break cnt += 1 if cnt >= uplimit: break cap.release() assert len(frames) > 0, f'{filename}: video with no frames!' return frames def create_images(video_name, frames): height, width, layers = 512, 512, 3 images_dir = video_name.split('.')[0] os.makedirs(images_dir, exist_ok=True) for i, _frame in enumerate(frames): _frame = cv2.resize(_frame, (height, width), interpolation=cv2.INTER_LINEAR) _frame_path = os.path.join(images_dir, str(i)+'.jpg') cv2.imwrite(_frame_path, _frame) def run(data): filename, opt, device = data os.environ['CUDA_VISIBLE_DEVICES'] = device croper = Croper() frames = read_video(filename, uplimit=opt.uplimit) name = filename.split('/')[-1] # .split('.')[0] name = os.path.join(opt.output_dir, name) frames = croper.crop(frames) if frames is None: print(f'{name}: detect no face. should removed') return # create_video(name, frames) create_images(name, frames)
null
3,401
import os import cv2 import time import glob import argparse import scipy import numpy as np from PIL import Image from tqdm import tqdm from itertools import cycle from torch.multiprocessing import Pool, Process, set_start_method import numpy as np from PIL import Image import dlib def get_data_path(video_dir): eg_video_files = ['/apdcephfs/share_1290939/quincheng/datasets/HDTF/backup_fps25/WDA_KatieHill_000.mp4'] # filenames = list() # VIDEO_EXTENSIONS_LOWERCASE = {'mp4'} # VIDEO_EXTENSIONS = VIDEO_EXTENSIONS_LOWERCASE.union({f.upper() for f in VIDEO_EXTENSIONS_LOWERCASE}) # extensions = VIDEO_EXTENSIONS # for ext in extensions: # filenames = sorted(glob.glob(f'{opt.input_dir}/**/*.{ext}')) # print('Total number of videos:', len(filenames)) return eg_video_files
null
3,402
import os import cv2 import time import glob import argparse import scipy import numpy as np from PIL import Image from tqdm import tqdm from itertools import cycle from torch.multiprocessing import Pool, Process, set_start_method import numpy as np from PIL import Image import dlib def get_wra_data_path(video_dir): if opt.option == 'video': videos_path = sorted(glob.glob(f'{video_dir}/*.mp4')) elif opt.option == 'image': videos_path = sorted(glob.glob(f'{video_dir}/*/')) else: raise NotImplementedError print('Example videos: ', videos_path[:2]) return videos_path
null
3,403
import shutil import uuid import os import cv2 def save_video_with_watermark(video, audio, save_path, watermark=False): temp_file = str(uuid.uuid4())+'.mp4' cmd = r'ffmpeg -y -i "%s" -i "%s" -vcodec copy "%s"' % (video, audio, temp_file) os.system(cmd) if watermark is False: shutil.move(temp_file, save_path) else: # watermark try: ##### check if stable-diffusion-webui import webui from modules import paths watarmark_path = paths.script_path+"/extensions/SadTalker/docs/sadtalker_logo.png" except: # get the root path of sadtalker. dir_path = os.path.dirname(os.path.realpath(__file__)) watarmark_path = dir_path+"/../../docs/sadtalker_logo.png" cmd = r'ffmpeg -y -hide_banner -i "%s" -i "%s" -filter_complex "[1]scale=100:-1[wm];[0][wm]overlay=(main_w-overlay_w)-10:10" "%s"' % (temp_file, watarmark_path, save_path) os.system(cmd) os.remove(temp_file)
null
3,404
import cv2, os import numpy as np from tqdm import tqdm import uuid from src.inference_utils import Laplacian_Pyramid_Blending_with_mask def Laplacian_Pyramid_Blending_with_mask(A, B, m, num_levels=6): def paste_pic(video_path, pic_path, crop_info, new_audio_path, full_video_path, restorer, enhancer, enhancer_region): video_stream_input = cv2.VideoCapture(pic_path) full_img_list = [] while 1: input_reading, full_img = video_stream_input.read() if not input_reading: video_stream_input.release() break full_img_list.append(full_img) frame_h = full_img_list[0].shape[0] frame_w = full_img_list[0].shape[1] video_stream = cv2.VideoCapture(video_path) fps = video_stream.get(cv2.CAP_PROP_FPS) crop_frames = [] while 1: still_reading, frame = video_stream.read() if not still_reading: video_stream.release() break crop_frames.append(frame) if len(crop_info) != 3: print("you didn't crop the image") return else: clx, cly, crx, cry = crop_info[1] tmp_path = str(uuid.uuid4()) + '.mp4' out_tmp = cv2.VideoWriter(tmp_path, cv2.VideoWriter_fourcc(*'MP4V'), fps, (frame_w, frame_h)) for index, crop_frame in enumerate(tqdm(crop_frames, 'faceClone:')): p = cv2.resize(crop_frame.astype(np.uint8), (crx - clx, cry - cly)) ff = full_img_list[index].copy() ff[cly:cry, clx:crx] = p if enhancer_region == 'none': pp = ff else: cropped_faces, restored_faces, restored_img = restorer.enhance( ff, has_aligned=False, only_center_face=True, paste_back=True) if enhancer_region == 'lip': mm = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 0, 0, 0, 0, 0, 0] else: mm = [0, 255, 255, 255, 255, 255, 255, 255, 0, 0, 255, 255, 255, 0, 0, 0, 0, 0, 0] mouse_mask = np.zeros_like(restored_img) tmp_mask = enhancer.faceparser.process(restored_img[cly:cry, clx:crx], mm)[0] mouse_mask[cly:cry, clx:crx] = cv2.resize(tmp_mask, (crx - clx, cry - cly))[:, :, np.newaxis] / 255. height, width = ff.shape[:2] restored_img, ff, full_mask = [cv2.resize(x, (512, 512)) for x in (restored_img, ff, np.float32(mouse_mask))] img = Laplacian_Pyramid_Blending_with_mask(restored_img, ff, full_mask[:, :, 0], 10) pp = np.uint8(cv2.resize(np.clip(img, 0, 255), (width, height))) pp, orig_faces, enhanced_faces = enhancer.process(pp, full_img_list[index], bbox=[cly, cry, clx, crx], face_enhance=False, possion_blending=True) out_tmp.write(pp) out_tmp.release() cmd = r'ffmpeg -y -i "%s" -i "%s" -vcodec copy "%s"' % (tmp_path, new_audio_path, full_video_path) os.system(cmd) # os.remove(tmp_path) return tmp_path, new_audio_path
null
3,405
import numpy as np import cv2, os, torch from tqdm import tqdm from PIL import Image from src.face3d.util.preprocess import align_img from src.face3d.util.load_mats import load_lm3d from src.face3d.models import networks from src.face3d.extract_kp_videos import KeypointExtractor from scipy.io import savemat from src.utils.croper import Croper import warnings The provided code snippet includes necessary dependencies for implementing the `split_coeff` function. Write a Python function `def split_coeff(coeffs)` to solve the following problem: Return: coeffs_dict -- a dict of torch.tensors Parameters: coeffs -- torch.tensor, size (B, 256) Here is the function: def split_coeff(coeffs): """ Return: coeffs_dict -- a dict of torch.tensors Parameters: coeffs -- torch.tensor, size (B, 256) """ id_coeffs = coeffs[:, :80] exp_coeffs = coeffs[:, 80: 144] tex_coeffs = coeffs[:, 144: 224] angles = coeffs[:, 224: 227] gammas = coeffs[:, 227: 254] translations = coeffs[:, 254:] return { 'id': id_coeffs, 'exp': exp_coeffs, 'tex': tex_coeffs, 'angle': angles, 'gamma': gammas, 'trans': translations }
Return: coeffs_dict -- a dict of torch.tensors Parameters: coeffs -- torch.tensor, size (B, 256)
3,406
import librosa import librosa.filters import numpy as np from scipy import signal from scipy.io import wavfile from src.utils.hparams import hparams as hp def save_wav(wav, path, sr): wav *= 32767 / max(0.01, np.max(np.abs(wav))) #proposed by @dsmiller wavfile.write(path, sr, wav.astype(np.int16))
null
3,407
import librosa import librosa.filters import numpy as np from scipy import signal from scipy.io import wavfile from src.utils.hparams import hparams as hp def save_wavenet_wav(wav, path, sr): librosa.output.write_wav(path, wav, sr=sr)
null
3,408
import librosa import librosa.filters import numpy as np from scipy import signal from scipy.io import wavfile from src.utils.hparams import hparams as hp def inv_preemphasis(wav, k, inv_preemphasize=True): if inv_preemphasize: return signal.lfilter([1], [1, -k], wav) return wav
null
3,409
import librosa import librosa.filters import numpy as np from scipy import signal from scipy.io import wavfile from src.utils.hparams import hparams as hp def preemphasis(wav, k, preemphasize=True): if preemphasize: return signal.lfilter([1, -k], [1], wav) return wav def _stft(y): if hp.use_lws: return _lws_processor(hp).stft(y).T else: return librosa.stft(y=y, n_fft=hp.n_fft, hop_length=get_hop_size(), win_length=hp.win_size) def _amp_to_db(x): min_level = np.exp(hp.min_level_db / 20 * np.log(10)) return 20 * np.log10(np.maximum(min_level, x)) def _normalize(S): if hp.allow_clipping_in_normalization: if hp.symmetric_mels: return np.clip((2 * hp.max_abs_value) * ((S - hp.min_level_db) / (-hp.min_level_db)) - hp.max_abs_value, -hp.max_abs_value, hp.max_abs_value) else: return np.clip(hp.max_abs_value * ((S - hp.min_level_db) / (-hp.min_level_db)), 0, hp.max_abs_value) assert S.max() <= 0 and S.min() - hp.min_level_db >= 0 if hp.symmetric_mels: return (2 * hp.max_abs_value) * ((S - hp.min_level_db) / (-hp.min_level_db)) - hp.max_abs_value else: return hp.max_abs_value * ((S - hp.min_level_db) / (-hp.min_level_db)) def linearspectrogram(wav): D = _stft(preemphasis(wav, hp.preemphasis, hp.preemphasize)) S = _amp_to_db(np.abs(D)) - hp.ref_level_db if hp.signal_normalization: return _normalize(S) return S
null
3,410
import librosa import librosa.filters import numpy as np from scipy import signal from scipy.io import wavfile from src.utils.hparams import hparams as hp def num_frames(length, fsize, fshift): """Compute number of time frames of spectrogram """ pad = (fsize - fshift) if length % fshift == 0: M = (length + pad * 2 - fsize) // fshift + 1 else: M = (length + pad * 2 - fsize) // fshift + 2 return M The provided code snippet includes necessary dependencies for implementing the `pad_lr` function. Write a Python function `def pad_lr(x, fsize, fshift)` to solve the following problem: Compute left and right padding Here is the function: def pad_lr(x, fsize, fshift): """Compute left and right padding """ M = num_frames(len(x), fsize, fshift) pad = (fsize - fshift) T = len(x) + 2 * pad r = (M - 1) * fshift + fsize - T return pad, pad + r
Compute left and right padding
3,411
import librosa import librosa.filters import numpy as np from scipy import signal from scipy.io import wavfile from src.utils.hparams import hparams as hp def librosa_pad_lr(x, fsize, fshift): return 0, (x.shape[0] // fshift + 1) * fshift - x.shape[0]
null
3,412
import librosa import librosa.filters import numpy as np from scipy import signal from scipy.io import wavfile from src.utils.hparams import hparams as hp def _db_to_amp(x): return np.power(10.0, (x) * 0.05)
null
3,413
import librosa import librosa.filters import numpy as np from scipy import signal from scipy.io import wavfile from src.utils.hparams import hparams as hp def _denormalize(D): if hp.allow_clipping_in_normalization: if hp.symmetric_mels: return (((np.clip(D, -hp.max_abs_value, hp.max_abs_value) + hp.max_abs_value) * -hp.min_level_db / (2 * hp.max_abs_value)) + hp.min_level_db) else: return ((np.clip(D, 0, hp.max_abs_value) * -hp.min_level_db / hp.max_abs_value) + hp.min_level_db) if hp.symmetric_mels: return (((D + hp.max_abs_value) * -hp.min_level_db / (2 * hp.max_abs_value)) + hp.min_level_db) else: return ((D * -hp.min_level_db / hp.max_abs_value) + hp.min_level_db)
null
3,414
import os import torch from gfpgan import GFPGANer from tqdm import tqdm from src.utils.videoio import load_video_to_cv2 def load_video_to_cv2(input_path): video_stream = cv2.VideoCapture(input_path) fps = video_stream.get(cv2.CAP_PROP_FPS) full_frames = [] while 1: still_reading, frame = video_stream.read() if not still_reading: video_stream.release() break full_frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) return full_frames def enhancer(images, method='gfpgan', bg_upsampler='realesrgan'): print('face enhancer....') if os.path.isfile(images): # handle video to images images = load_video_to_cv2(images) # ------------------------ set up GFPGAN restorer ------------------------ if method == 'gfpgan': arch = 'clean' channel_multiplier = 2 model_name = 'GFPGANv1.4' url = 'https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth' elif method == 'RestoreFormer': arch = 'RestoreFormer' channel_multiplier = 2 model_name = 'RestoreFormer' url = 'https://github.com/TencentARC/GFPGAN/releases/download/v1.3.4/RestoreFormer.pth' elif method == 'codeformer': arch = 'CodeFormer' channel_multiplier = 2 model_name = 'CodeFormer' url = 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer.pth' else: raise ValueError(f'Wrong model version {method}.') # ------------------------ set up background upsampler ------------------------ if bg_upsampler == 'realesrgan': if not torch.cuda.is_available(): # CPU import warnings warnings.warn('The unoptimized RealESRGAN is slow on CPU. We do not use it. ' 'If you really want to use it, please modify the corresponding codes.') bg_upsampler = None else: from basicsr.archs.rrdbnet_arch import RRDBNet from realesrgan import RealESRGANer model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=2) bg_upsampler = RealESRGANer( scale=2, model_path='https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth', model=model, tile=400, tile_pad=10, pre_pad=0, half=True) # need to set False in CPU mode else: bg_upsampler = None # determine model paths model_path = os.path.join('gfpgan/weights', model_name + '.pth') if not os.path.isfile(model_path): model_path = os.path.join('checkpoints', model_name + '.pth') if not os.path.isfile(model_path): # download pre-trained models from url model_path = url restorer = GFPGANer( model_path=model_path, upscale=2, arch=arch, channel_multiplier=channel_multiplier, bg_upsampler=bg_upsampler) # ------------------------ restore ------------------------ restored_img = [] for idx in tqdm(range(len(images)), 'Face Enhancer:'): # restore faces and background if necessary cropped_faces, restored_faces, r_img = restorer.enhance( images[idx], has_aligned=False, only_center_face=False, paste_back=True) restored_img += [r_img] return restored_img
null
3,415
from glob import glob import os hparams = HParams( num_mels=80, # Number of mel-spectrogram channels and local conditioning dimensionality # network rescale=True, # Whether to rescale audio prior to preprocessing rescaling_max=0.9, # Rescaling value # Use LWS (https://github.com/Jonathan-LeRoux/lws) for STFT and phase reconstruction # It"s preferred to set True to use with https://github.com/r9y9/wavenet_vocoder # Does not work if n_ffit is not multiple of hop_size!! use_lws=False, n_fft=800, # Extra window size is filled with 0 paddings to match this parameter hop_size=200, # For 16000Hz, 200 = 12.5 ms (0.0125 * sample_rate) win_size=800, # For 16000Hz, 800 = 50 ms (If None, win_size = n_fft) (0.05 * sample_rate) sample_rate=16000, # 16000Hz (corresponding to librispeech) (sox --i <filename>) frame_shift_ms=None, # Can replace hop_size parameter. (Recommended: 12.5) # Mel and Linear spectrograms normalization/scaling and clipping signal_normalization=True, # Whether to normalize mel spectrograms to some predefined range (following below parameters) allow_clipping_in_normalization=True, # Only relevant if mel_normalization = True symmetric_mels=True, # Whether to scale the data to be symmetric around 0. (Also multiplies the output range by 2, # faster and cleaner convergence) max_abs_value=4., # max absolute value of data. If symmetric, data will be [-max, max] else [0, max] (Must not # be too big to avoid gradient explosion, # not too small for fast convergence) # Contribution by @begeekmyfriend # Spectrogram Pre-Emphasis (Lfilter: Reduce spectrogram noise and helps model certitude # levels. Also allows for better G&L phase reconstruction) preemphasize=True, # whether to apply filter preemphasis=0.97, # filter coefficient. # Limits min_level_db=-100, ref_level_db=20, fmin=55, # Set this to 55 if your speaker is male! if female, 95 should help taking off noise. (To # test depending on dataset. Pitch info: male~[65, 260], female~[100, 525]) fmax=7600, # To be increased/reduced depending on data. ###################### Our training parameters ################################# img_size=96, fps=25, batch_size=16, initial_learning_rate=1e-4, nepochs=300000, ### ctrl + c, stop whenever eval loss is consistently greater than train loss for ~10 epochs num_workers=20, checkpoint_interval=3000, eval_interval=3000, writer_interval=300, save_optimizer_state=True, syncnet_wt=0.0, # is initially zero, will be set automatically to 0.03 later. Leads to faster convergence. syncnet_batch_size=64, syncnet_lr=1e-4, syncnet_eval_interval=1000, syncnet_checkpoint_interval=10000, disc_wt=0.07, disc_initial_learning_rate=1e-4, ) def hparams_debug_string(): values = hparams.values() hp = [" %s: %s" % (name, values[name]) for name in sorted(values) if name != "sentences"] return "Hyperparameters:\n" + "\n".join(hp)
null
3,416
import torch.nn as nn from basicsr.utils.registry import ARCH_REGISTRY The provided code snippet includes necessary dependencies for implementing the `conv3x3` function. Write a Python function `def conv3x3(inplanes, outplanes, stride=1)` to solve the following problem: A simple wrapper for 3x3 convolution with padding. Args: inplanes (int): Channel number of inputs. outplanes (int): Channel number of outputs. stride (int): Stride in convolution. Default: 1. Here is the function: def conv3x3(inplanes, outplanes, stride=1): """A simple wrapper for 3x3 convolution with padding. Args: inplanes (int): Channel number of inputs. outplanes (int): Channel number of outputs. stride (int): Stride in convolution. Default: 1. """ return nn.Conv2d(inplanes, outplanes, kernel_size=3, stride=stride, padding=1, bias=False)
A simple wrapper for 3x3 convolution with padding. Args: inplanes (int): Channel number of inputs. outplanes (int): Channel number of outputs. stride (int): Stride in convolution. Default: 1.
3,417
from face_parse.blocks import * import torch from torch import nn import numpy as np class ParseNet(nn.Module): def __init__(self, in_size=128, out_size=128, min_feat_size=32, base_ch=64, parsing_ch=19, res_depth=10, relu_type='prelu', norm_type='bn', ch_range=[32, 512], ): super().__init__() self.res_depth = res_depth act_args = {'norm_type': norm_type, 'relu_type': relu_type} min_ch, max_ch = ch_range ch_clip = lambda x: max(min_ch, min(x, max_ch)) min_feat_size = min(in_size, min_feat_size) down_steps = int(np.log2(in_size//min_feat_size)) up_steps = int(np.log2(out_size//min_feat_size)) # =============== define encoder-body-decoder ==================== self.encoder = [] self.encoder.append(ConvLayer(3, base_ch, 3, 1)) head_ch = base_ch for i in range(down_steps): cin, cout = ch_clip(head_ch), ch_clip(head_ch * 2) self.encoder.append(ResidualBlock(cin, cout, scale='down', **act_args)) head_ch = head_ch * 2 self.body = [] for i in range(res_depth): self.body.append(ResidualBlock(ch_clip(head_ch), ch_clip(head_ch), **act_args)) self.decoder = [] for i in range(up_steps): cin, cout = ch_clip(head_ch), ch_clip(head_ch // 2) self.decoder.append(ResidualBlock(cin, cout, scale='up', **act_args)) head_ch = head_ch // 2 self.encoder = nn.Sequential(*self.encoder) self.body = nn.Sequential(*self.body) self.decoder = nn.Sequential(*self.decoder) self.out_img_conv = ConvLayer(ch_clip(head_ch), 3) self.out_mask_conv = ConvLayer(ch_clip(head_ch), parsing_ch) def forward(self, x): feat = self.encoder(x) x = feat + self.body(feat) x = self.decoder(x) out_img = self.out_img_conv(x) out_mask = self.out_mask_conv(x) return out_mask, out_img def define_P(in_size=512, out_size=512, min_feat_size=32, relu_type='LeakyReLU', isTrain=False, weight_path=None): net = ParseNet(in_size, out_size, min_feat_size, 64, 19, norm_type='bn', relu_type=relu_type, ch_range=[32, 256]) if not isTrain: net.eval() if weight_path is not None: net.load_state_dict(torch.load(weight_path)) return net
null
3,418
import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.model_zoo as modelzoo The provided code snippet includes necessary dependencies for implementing the `conv3x3` function. Write a Python function `def conv3x3(in_planes, out_planes, stride=1)` to solve the following problem: 3x3 convolution with padding Here is the function: def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
3x3 convolution with padding
3,419
import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.model_zoo as modelzoo class BasicBlock(nn.Module): def __init__(self, in_chan, out_chan, stride=1): def forward(self, x): def create_layer_basic(in_chan, out_chan, bnum, stride=1): layers = [BasicBlock(in_chan, out_chan, stride=stride)] for i in range(bnum-1): layers.append(BasicBlock(out_chan, out_chan, stride=1)) return nn.Sequential(*layers)
null
3,420
import cv2 import numpy as np import os.path as path import dlib import os def boundary_points(points, width_percent=0.1, height_percent=0.1): """ Produce additional boundary points :param points: *m* x 2 array of x,y points :param width_percent: [-1, 1] percentage of width to taper inwards. Negative for opposite direction :param height_percent: [-1, 1] percentage of height to taper downwards. Negative for opposite direction :returns: 2 additional points at the top corners """ x, y, w, h = cv2.boundingRect(np.array([points], np.int32)) spacerw = int(w * width_percent) spacerh = int(h * height_percent) return [[x+spacerw, y+spacerh], [x+w-spacerw, y+spacerh]] The provided code snippet includes necessary dependencies for implementing the `face_points_stasm` function. Write a Python function `def face_points_stasm(img, add_boundary_points=True)` to solve the following problem: Locates 77 face points using stasm (http://www.milbo.users.sonic.net/stasm) :param img: an image array :param add_boundary_points: bool to add 2 additional points :returns: Array of x,y face points. Empty array if no face found Here is the function: def face_points_stasm(img, add_boundary_points=True): import stasm """ Locates 77 face points using stasm (http://www.milbo.users.sonic.net/stasm) :param img: an image array :param add_boundary_points: bool to add 2 additional points :returns: Array of x,y face points. Empty array if no face found """ try: points = stasm.search_single(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)) except Exception as e: print('Failed finding face points: ', e) return [] points = points.astype(np.int32) if len(points) == 0: return points if add_boundary_points: return np.vstack([points, boundary_points(points)]) return points
Locates 77 face points using stasm (http://www.milbo.users.sonic.net/stasm) :param img: an image array :param add_boundary_points: bool to add 2 additional points :returns: Array of x,y face points. Empty array if no face found
3,421
import cv2 import numpy as np import scipy.sparse The provided code snippet includes necessary dependencies for implementing the `apply_mask` function. Write a Python function `def apply_mask(img, mask)` to solve the following problem: Apply mask to supplied image :param img: max 3 channel image :param mask: [0-255] values in mask :returns: new image with mask applied Here is the function: def apply_mask(img, mask): """ Apply mask to supplied image :param img: max 3 channel image :param mask: [0-255] values in mask :returns: new image with mask applied """ masked_img = np.copy(img) num_channels = 3 for c in range(num_channels): masked_img[..., c] = img[..., c] * (mask / 255) return masked_img
Apply mask to supplied image :param img: max 3 channel image :param mask: [0-255] values in mask :returns: new image with mask applied
3,422
import cv2 import numpy as np import scipy.sparse def alpha_feathering(src_img, dest_img, img_mask, blur_radius=15): mask = cv2.blur(img_mask, (blur_radius, blur_radius)) mask = mask / 255.0 result_img = np.empty(src_img.shape, np.uint8) for i in range(3): result_img[..., i] = src_img[..., i] * mask + dest_img[..., i] * (1-mask) return result_img
null
3,423
import cv2 import numpy as np def check_write_video(func): def inner(self, *args, **kwargs): if self.video: return func(self, *args, **kwargs) else: pass return inner
null
3,424
import numpy as np import scipy.spatial as spatial def warp_image(src_img, src_points, dest_points, dest_shape, dtype=np.uint8): # Resultant image will not have an alpha channel num_chans = 3 src_img = src_img[:, :, :3] rows, cols = dest_shape[:2] result_img = np.zeros((rows, cols, num_chans), dtype) delaunay = spatial.Delaunay(dest_points) tri_affines = np.asarray(list(triangular_affine_matrices( delaunay.simplices, src_points, dest_points))) process_warp(src_img, result_img, tri_affines, dest_points, delaunay) return result_img def test_local(): from functools import partial import cv2 import scipy.misc import locator import aligner from matplotlib import pyplot as plt # Load source image face_points_func = partial(locator.face_points, '../data') base_path = '../females/Screenshot 2015-03-04 17.11.12.png' src_path = '../females/BlDmB5QCYAAY8iw.jpg' src_img = cv2.imread(src_path) # Define control points for warps src_points = face_points_func(src_path) base_img = cv2.imread(base_path) base_points = face_points_func(base_path) size = (600, 500) src_img, src_points = aligner.resize_align(src_img, src_points, size) base_img, base_points = aligner.resize_align(base_img, base_points, size) result_points = locator.weighted_average_points(src_points, base_points, 0.2) # Perform transform dst_img1 = warp_image(src_img, src_points, result_points, size) dst_img2 = warp_image(base_img, base_points, result_points, size) import blender ave = blender.weighted_average(dst_img1, dst_img2, 0.6) mask = blender.mask_from_points(size, result_points) blended_img = blender.poisson_blend(dst_img1, dst_img2, mask) plt.subplot(2, 2, 1) plt.imshow(ave) plt.subplot(2, 2, 2) plt.imshow(dst_img1) plt.subplot(2, 2, 3) plt.imshow(dst_img2) plt.subplot(2, 2, 4) plt.imshow(blended_img) plt.show()
null
3,425
from docopt import docopt import os import numpy as np import cv2 from facemorpher import locator from facemorpher import aligner from facemorpher import warper from facemorpher import blender from facemorpher import plotter from facemorpher import videoer def verify_args(args): if args['--images'] is None: valid = os.path.isfile(args['--src']) & os.path.isfile(args['--dest']) if not valid: print('--src=%s or --dest=%s file does not exist. Double check the supplied paths' % ( args['--src'], args['--dest'])) exit(1) else: valid = os.path.isdir(args['--images']) if not valid: print('--images=%s is not a valid directory' % args['--images']) exit(1)
null
3,426
from docopt import docopt import os import numpy as np import cv2 from facemorpher import locator from facemorpher import aligner from facemorpher import warper from facemorpher import blender from facemorpher import plotter from facemorpher import videoer def list_imgpaths(images_folder=None, src_image=None, dest_image=None): if images_folder is None: yield src_image yield dest_image else: for fname in os.listdir(images_folder): if (fname.lower().endswith('.jpg') or fname.lower().endswith('.png') or fname.lower().endswith('.jpeg')): yield os.path.join(images_folder, fname)
null
3,427
from docopt import docopt import os import numpy as np import cv2 from facemorpher import locator from facemorpher import aligner from facemorpher import warper from facemorpher import blender from facemorpher import plotter from facemorpher import videoer def load_valid_image_points(imgpaths, size): for path in imgpaths: img, points = load_image_points(path, size) if img is not None: print(path) yield (img, points) def morph(src_img, src_points, dest_img, dest_points, video, width=500, height=600, num_frames=20, fps=10, out_frames=None, out_video=None, plot=False, background='black'): """ Create a morph sequence from source to destination image :param src_img: ndarray source image :param src_points: source image array of x,y face points :param dest_img: ndarray destination image :param dest_points: destination image array of x,y face points :param video: facemorpher.videoer.Video object """ size = (height, width) stall_frames = np.clip(int(fps*0.15), 1, fps) # Show first & last longer plt = plotter.Plotter(plot, num_images=num_frames, out_folder=out_frames) num_frames -= (stall_frames * 2) # No need to process src and dest image plt.plot_one(src_img) video.write(src_img, 1) # Produce morph frames! for percent in np.linspace(1, 0, num=num_frames): points = locator.weighted_average_points(src_points, dest_points, percent) src_face = warper.warp_image(src_img, src_points, points, size) end_face = warper.warp_image(dest_img, dest_points, points, size) average_face = blender.weighted_average(src_face, end_face, percent) if background in ('transparent', 'average'): mask = blender.mask_from_points(average_face.shape[:2], points) average_face = np.dstack((average_face, mask)) if background == 'average': average_background = blender.weighted_average(src_img, dest_img, percent) average_face = blender.overlay_image(average_face, mask, average_background) plt.plot_one(average_face) plt.save(average_face) video.write(average_face) plt.plot_one(dest_img) video.write(dest_img, stall_frames) plt.show() The provided code snippet includes necessary dependencies for implementing the `morpher` function. Write a Python function `def morpher(imgpaths, width=500, height=600, num_frames=20, fps=10, out_frames=None, out_video=None, plot=False, background='black')` to solve the following problem: Create a morph sequence from multiple images in imgpaths :param imgpaths: array or generator of image paths Here is the function: def morpher(imgpaths, width=500, height=600, num_frames=20, fps=10, out_frames=None, out_video=None, plot=False, background='black'): """ Create a morph sequence from multiple images in imgpaths :param imgpaths: array or generator of image paths """ video = videoer.Video(out_video, fps, width, height) images_points_gen = load_valid_image_points(imgpaths, (height, width)) src_img, src_points = next(images_points_gen) for dest_img, dest_points in images_points_gen: morph(src_img, src_points, dest_img, dest_points, video, width, height, num_frames, fps, out_frames, out_video, plot, background) src_img, src_points = dest_img, dest_points video.end()
Create a morph sequence from multiple images in imgpaths :param imgpaths: array or generator of image paths
3,428
from docopt import docopt import os import cv2 import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg from facemorpher import locator from facemorpher import aligner from facemorpher import warper from facemorpher import blender from facemorpher import plotter def list_imgpaths(imgfolder): for fname in os.listdir(imgfolder): if (fname.lower().endswith('.jpg') or fname.lower().endswith('.png') or fname.lower().endswith('.jpeg')): yield os.path.join(imgfolder, fname)
null
3,429
from docopt import docopt import os import cv2 import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg from facemorpher import locator from facemorpher import aligner from facemorpher import warper from facemorpher import blender from facemorpher import plotter def sharpen(img): blured = cv2.GaussianBlur(img, (0, 0), 2.5) return cv2.addWeighted(img, 1.4, blured, -0.4, 0)
null
3,430
from docopt import docopt import os import cv2 import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg from facemorpher import locator from facemorpher import aligner from facemorpher import warper from facemorpher import blender from facemorpher import plotter def load_image_points(path, size): img = cv2.imread(path) points = locator.face_points(img) if len(points) == 0: print('No face in %s' % path) return None, None else: return aligner.resize_align(img, points, size) def averager(imgpaths, dest_filename=None, width=500, height=600, background='black', blur_edges=False, out_filename='result.png', plot=False): size = (height, width) images = [] point_set = [] for path in imgpaths: img, points = load_image_points(path, size) if img is not None: images.append(img) point_set.append(points) if len(images) == 0: raise FileNotFoundError('Could not find any valid images.' + ' Supported formats are .jpg, .png, .jpeg') if dest_filename is not None: dest_img, dest_points = load_image_points(dest_filename, size) if dest_img is None or dest_points is None: raise Exception('No face or detected face points in dest img: ' + dest_filename) else: dest_img = np.zeros(images[0].shape, np.uint8) dest_points = locator.average_points(point_set) num_images = len(images) result_images = np.zeros(images[0].shape, np.float32) for i in range(num_images): result_images += warper.warp_image(images[i], point_set[i], dest_points, size, np.float32) result_image = np.uint8(result_images / num_images) face_indexes = np.nonzero(result_image) dest_img[face_indexes] = result_image[face_indexes] mask = blender.mask_from_points(size, dest_points) if blur_edges: blur_radius = 10 mask = cv2.blur(mask, (blur_radius, blur_radius)) if background in ('transparent', 'average'): dest_img = np.dstack((dest_img, mask)) if background == 'average': average_background = locator.average_points(images) dest_img = blender.overlay_image(dest_img, mask, average_background) print('Averaged {} images'.format(num_images)) plt = plotter.Plotter(plot, num_images=1, out_filename=out_filename) plt.save(dest_img) plt.plot_one(dest_img) plt.show()
null
3,431
import matplotlib.pyplot as plt import matplotlib.image as mpimg import os.path import numpy as np import cv2 def bgr2rgb(img): # OpenCV's BGR to RGB rgb = np.copy(img) rgb[..., 0], rgb[..., 2] = img[..., 2], img[..., 0] return rgb
null
3,432
import matplotlib.pyplot as plt import matplotlib.image as mpimg import os.path import numpy as np import cv2 def check_do_plot(func): def inner(self, *args, **kwargs): if self.do_plot: func(self, *args, **kwargs) return inner
null
3,433
import matplotlib.pyplot as plt import matplotlib.image as mpimg import os.path import numpy as np import cv2 def check_do_save(func): def inner(self, *args, **kwargs): if self.do_save: func(self, *args, **kwargs) return inner
null
3,434
import os import platform import torch import torch.nn.functional as F from torch.autograd import Function from torch.utils.cpp_extension import load, _import_module_from_library if platform.system() == 'Linux' and torch.cuda.is_available(): module_path = os.path.dirname(__file__) upfirdn2d_op = load( 'upfirdn2d', sources=[ os.path.join(module_path, 'upfirdn2d.cpp'), os.path.join(module_path, 'upfirdn2d_kernel.cu'), ], ) class UpFirDn2d(Function): def forward(ctx, input, kernel, up, down, pad): up_x, up_y = up down_x, down_y = down pad_x0, pad_x1, pad_y0, pad_y1 = pad kernel_h, kernel_w = kernel.shape batch, channel, in_h, in_w = input.shape ctx.in_size = input.shape input = input.reshape(-1, in_h, in_w, 1) ctx.save_for_backward(kernel, torch.flip(kernel, [0, 1])) out_h = (in_h * up_y + pad_y0 + pad_y1 - kernel_h) // down_y + 1 out_w = (in_w * up_x + pad_x0 + pad_x1 - kernel_w) // down_x + 1 ctx.out_size = (out_h, out_w) ctx.up = (up_x, up_y) ctx.down = (down_x, down_y) ctx.pad = (pad_x0, pad_x1, pad_y0, pad_y1) g_pad_x0 = kernel_w - pad_x0 - 1 g_pad_y0 = kernel_h - pad_y0 - 1 g_pad_x1 = in_w * up_x - out_w * down_x + pad_x0 - up_x + 1 g_pad_y1 = in_h * up_y - out_h * down_y + pad_y0 - up_y + 1 ctx.g_pad = (g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1) out = upfirdn2d_op.upfirdn2d( input, kernel, up_x, up_y, down_x, down_y, pad_x0, pad_x1, pad_y0, pad_y1 ) # out = out.view(major, out_h, out_w, minor) out = out.view(-1, channel, out_h, out_w) return out def backward(ctx, grad_output): kernel, grad_kernel = ctx.saved_tensors grad_input = UpFirDn2dBackward.apply( grad_output, kernel, grad_kernel, ctx.up, ctx.down, ctx.pad, ctx.g_pad, ctx.in_size, ctx.out_size, ) return grad_input, None, None, None, None def upfirdn2d_native( input, kernel, up_x, up_y, down_x, down_y, pad_x0, pad_x1, pad_y0, pad_y1 ): input = input.permute(0, 2, 3, 1) _, in_h, in_w, minor = input.shape kernel_h, kernel_w = kernel.shape out = input.view(-1, in_h, 1, in_w, 1, minor) out = F.pad(out, [0, 0, 0, up_x - 1, 0, 0, 0, up_y - 1]) out = out.view(-1, in_h * up_y, in_w * up_x, minor) out = F.pad( out, [0, 0, max(pad_x0, 0), max(pad_x1, 0), max(pad_y0, 0), max(pad_y1, 0)] ) out = out[ :, max(-pad_y0, 0) : out.shape[1] - max(-pad_y1, 0), max(-pad_x0, 0) : out.shape[2] - max(-pad_x1, 0), :, ] out = out.permute(0, 3, 1, 2) out = out.reshape( [-1, 1, in_h * up_y + pad_y0 + pad_y1, in_w * up_x + pad_x0 + pad_x1] ) w = torch.flip(kernel, [0, 1]).view(1, 1, kernel_h, kernel_w) out = F.conv2d(out, w) out = out.reshape( -1, minor, in_h * up_y + pad_y0 + pad_y1 - kernel_h + 1, in_w * up_x + pad_x0 + pad_x1 - kernel_w + 1, ) # out = out.permute(0, 2, 3, 1) return out[:, :, ::down_y, ::down_x] def upfirdn2d(input, kernel, up=1, down=1, pad=(0, 0), device='cpu'): if platform.system() == 'Linux' and torch.cuda.is_available() and device != 'cpu': out = UpFirDn2d.apply( input, kernel, (up, up), (down, down), (pad[0], pad[1], pad[0], pad[1]) ) else: out = upfirdn2d_native(input, kernel, up, up, down, down, pad[0], pad[1], pad[0], pad[1]) return out
null
3,435
import os import platform import torch from torch import nn import torch.nn.functional as F from torch.autograd import Function from torch.utils.cpp_extension import load, _import_module_from_library if platform.system() == 'Linux' and torch.cuda.is_available(): module_path = os.path.dirname(__file__) fused = load( 'fused', sources=[ os.path.join(module_path, 'fused_bias_act.cpp'), os.path.join(module_path, 'fused_bias_act_kernel.cu'), ], ) class FusedLeakyReLUFunction(Function): def forward(ctx, input, bias, negative_slope, scale): empty = input.new_empty(0) out = fused.fused_bias_act(input, bias, empty, 3, 0, negative_slope, scale) ctx.save_for_backward(out) ctx.negative_slope = negative_slope ctx.scale = scale return out def backward(ctx, grad_output): out, = ctx.saved_tensors grad_input, grad_bias = FusedLeakyReLUFunctionBackward.apply( grad_output, out, ctx.negative_slope, ctx.scale ) return grad_input, grad_bias, None, None def fused_leaky_relu(input, bias, negative_slope=0.2, scale=2 ** 0.5, device='cpu'): if platform.system() == 'Linux' and torch.cuda.is_available() and device != 'cpu': return FusedLeakyReLUFunction.apply(input, bias, negative_slope, scale) else: return scale * F.leaky_relu(input + bias.view((1, -1)+(1,)*(len(input.shape)-2)), negative_slope=negative_slope)
null
3,436
import math import random import functools import operator import itertools import torch from torch import nn from torch.nn import functional as F from torch.autograd import Function from face_model.op import FusedLeakyReLU, fused_leaky_relu, upfirdn2d def make_kernel(k): k = torch.tensor(k, dtype=torch.float32) if k.ndim == 1: k = k[None, :] * k[:, None] k /= k.sum() return k
null
3,437
import cv2 import numpy as np from skimage import transform as trans REFERENCE_FACIAL_POINTS = [ [30.29459953, 51.69630051], [65.53179932, 51.50139999], [48.02519989, 71.73660278], [33.54930115, 92.3655014], [62.72990036, 92.20410156] ] def _umeyama(src, dst, estimate_scale=True, scale=1.0): """Estimate N-D similarity transformation with or without scaling. Parameters ---------- src : (M, N) array Source coordinates. dst : (M, N) array Destination coordinates. estimate_scale : bool Whether to estimate scaling factor. Returns ------- T : (N + 1, N + 1) The homogeneous similarity transformation matrix. The matrix contains NaN values only if the problem is not well-conditioned. References ---------- .. [1] "Least-squares estimation of transformation parameters between two point patterns", Shinji Umeyama, PAMI 1991, :DOI:`10.1109/34.88573` """ num = src.shape[0] dim = src.shape[1] # Compute mean of src and dst. src_mean = src.mean(axis=0) dst_mean = dst.mean(axis=0) # Subtract mean from src and dst. src_demean = src - src_mean dst_demean = dst - dst_mean # Eq. (38). A = dst_demean.T @ src_demean / num # Eq. (39). d = np.ones((dim,), dtype=np.double) if np.linalg.det(A) < 0: d[dim - 1] = -1 T = np.eye(dim + 1, dtype=np.double) U, S, V = np.linalg.svd(A) # Eq. (40) and (43). rank = np.linalg.matrix_rank(A) if rank == 0: return np.nan * T elif rank == dim - 1: if np.linalg.det(U) * np.linalg.det(V) > 0: T[:dim, :dim] = U @ V else: s = d[dim - 1] d[dim - 1] = -1 T[:dim, :dim] = U @ np.diag(d) @ V d[dim - 1] = s else: T[:dim, :dim] = U @ np.diag(d) @ V if estimate_scale: # Eq. (41) and (42). scale = 1.0 / src_demean.var(axis=0).sum() * (S @ d) else: scale = scale T[:dim, dim] = dst_mean - scale * (T[:dim, :dim] @ src_mean.T) T[:dim, :dim] *= scale return T, scale class FaceWarpException(Exception): def __str__(self): return 'In File {}:{}'.format( __file__, super.__str__(self)) def get_reference_facial_points(output_size=None, inner_padding_factor=0.0, outer_padding=(0, 0), default_square=False): tmp_5pts = np.array(REFERENCE_FACIAL_POINTS) tmp_crop_size = np.array(DEFAULT_CROP_SIZE) # 0) make the inner region a square if default_square: size_diff = max(tmp_crop_size) - tmp_crop_size tmp_5pts += size_diff / 2 tmp_crop_size += size_diff if (output_size and output_size[0] == tmp_crop_size[0] and output_size[1] == tmp_crop_size[1]): print('output_size == DEFAULT_CROP_SIZE {}: return default reference points'.format(tmp_crop_size)) return tmp_5pts if (inner_padding_factor == 0 and outer_padding == (0, 0)): if output_size is None: print('No paddings to do: return default reference points') return tmp_5pts else: raise FaceWarpException( 'No paddings to do, output_size must be None or {}'.format(tmp_crop_size)) # check output size if not (0 <= inner_padding_factor <= 1.0): raise FaceWarpException('Not (0 <= inner_padding_factor <= 1.0)') if ((inner_padding_factor > 0 or outer_padding[0] > 0 or outer_padding[1] > 0) and output_size is None): output_size = tmp_crop_size * \ (1 + inner_padding_factor * 2).astype(np.int32) output_size += np.array(outer_padding) print(' deduced from paddings, output_size = ', output_size) if not (outer_padding[0] < output_size[0] and outer_padding[1] < output_size[1]): raise FaceWarpException('Not (outer_padding[0] < output_size[0]' 'and outer_padding[1] < output_size[1])') # 1) pad the inner region according inner_padding_factor # print('---> STEP1: pad the inner region according inner_padding_factor') if inner_padding_factor > 0: size_diff = tmp_crop_size * inner_padding_factor * 2 tmp_5pts += size_diff / 2 tmp_crop_size += np.round(size_diff).astype(np.int32) # print(' crop_size = ', tmp_crop_size) # print(' reference_5pts = ', tmp_5pts) # 2) resize the padded inner region # print('---> STEP2: resize the padded inner region') size_bf_outer_pad = np.array(output_size) - np.array(outer_padding) * 2 # print(' crop_size = ', tmp_crop_size) # print(' size_bf_outer_pad = ', size_bf_outer_pad) if size_bf_outer_pad[0] * tmp_crop_size[1] != size_bf_outer_pad[1] * tmp_crop_size[0]: raise FaceWarpException('Must have (output_size - outer_padding)' '= some_scale * (crop_size * (1.0 + inner_padding_factor)') scale_factor = size_bf_outer_pad[0].astype(np.float32) / tmp_crop_size[0] # print(' resize scale_factor = ', scale_factor) tmp_5pts = tmp_5pts * scale_factor # size_diff = tmp_crop_size * (scale_factor - min(scale_factor)) # tmp_5pts = tmp_5pts + size_diff / 2 tmp_crop_size = size_bf_outer_pad # print(' crop_size = ', tmp_crop_size) # print(' reference_5pts = ', tmp_5pts) # 3) add outer_padding to make output_size reference_5point = tmp_5pts + np.array(outer_padding) tmp_crop_size = output_size # print('---> STEP3: add outer_padding to make output_size') # print(' crop_size = ', tmp_crop_size) # print(' reference_5pts = ', tmp_5pts) # # print('===> end get_reference_facial_points\n') return reference_5point def get_affine_transform_matrix(src_pts, dst_pts): tfm = np.float32([[1, 0, 0], [0, 1, 0]]) n_pts = src_pts.shape[0] ones = np.ones((n_pts, 1), src_pts.dtype) src_pts_ = np.hstack([src_pts, ones]) dst_pts_ = np.hstack([dst_pts, ones]) A, res, rank, s = np.linalg.lstsq(src_pts_, dst_pts_) if rank == 3: tfm = np.float32([ [A[0, 0], A[1, 0], A[2, 0]], [A[0, 1], A[1, 1], A[2, 1]] ]) elif rank == 2: tfm = np.float32([ [A[0, 0], A[1, 0], 0], [A[0, 1], A[1, 1], 0] ]) return tfm def warp_and_crop_face(src_img, facial_pts, reference_pts=None, crop_size=(96, 112), align_type='smilarity'): #smilarity cv2_affine affine if reference_pts is None: if crop_size[0] == 96 and crop_size[1] == 112: reference_pts = REFERENCE_FACIAL_POINTS else: default_square = False inner_padding_factor = 0 outer_padding = (0, 0) output_size = crop_size reference_pts = get_reference_facial_points(output_size, inner_padding_factor, outer_padding, default_square) ref_pts = np.float32(reference_pts) ref_pts_shp = ref_pts.shape if max(ref_pts_shp) < 3: # or min(ref_pts_shp) != 2: raise FaceWarpException( 'reference_pts.shape must be (K,2) or (2,K) and K>2') if ref_pts_shp[0] == 2 or ref_pts_shp[0] == 3: ref_pts = ref_pts.T src_pts = np.float32(facial_pts) src_pts_shp = src_pts.shape if max(src_pts_shp) < 3: # or min(src_pts_shp) != 2: raise FaceWarpException( 'facial_pts.shape must be (K,2) or (2,K) and K>2') if src_pts_shp[0] == 2 or src_pts_shp[0] == 3: src_pts = src_pts.T if src_pts.shape != ref_pts.shape: raise FaceWarpException( 'facial_pts and reference_pts must have the same shape') if align_type is 'cv2_affine': tfm = cv2.getAffineTransform(src_pts[0:3], ref_pts[0:3]) tfm_inv = cv2.getAffineTransform(ref_pts[0:3], src_pts[0:3]) elif align_type is 'cv2_rigid': tfm, _ = cv2.estimateAffinePartial2D(src_pts[0:3], ref_pts[0:3]) tfm_inv, _ = cv2.estimateAffinePartial2D(ref_pts[0:3], src_pts[0:3]) elif align_type is 'affine': tfm = get_affine_transform_matrix(src_pts, ref_pts) tfm_inv = get_affine_transform_matrix(ref_pts, src_pts) else: params, scale = _umeyama(src_pts, ref_pts) tfm = params[:2, :] params, _ = _umeyama(ref_pts, src_pts, False, scale=1.0/scale) tfm_inv = params[:2, :] # M = cv2.getPerspectiveTransform(ref_pts[0:4], src_pts[0:4]) face_img = cv2.warpAffine(src_img, tfm, (crop_size[0], crop_size[1]), flags=3) # face_img = cv2.warpPerspective(src_img, M, (crop_size[0], crop_size[1]), flags=cv2.INTER_LINEAR ) return face_img, tfm_inv
null
3,438
import time import torch import torch.nn as nn import torchvision.models._utils as _utils import torchvision.models as models import torch.nn.functional as F from torch.autograd import Variable def conv_bn(inp, oup, stride = 1, leaky = 0): return nn.Sequential( nn.Conv2d(inp, oup, 3, stride, 1, bias=False), nn.BatchNorm2d(oup), nn.LeakyReLU(negative_slope=leaky, inplace=True) )
null
3,439
import time import torch import torch.nn as nn import torchvision.models._utils as _utils import torchvision.models as models import torch.nn.functional as F from torch.autograd import Variable def conv_bn_no_relu(inp, oup, stride): return nn.Sequential( nn.Conv2d(inp, oup, 3, stride, 1, bias=False), nn.BatchNorm2d(oup), )
null
3,440
import time import torch import torch.nn as nn import torchvision.models._utils as _utils import torchvision.models as models import torch.nn.functional as F from torch.autograd import Variable def conv_bn1X1(inp, oup, stride, leaky=0): return nn.Sequential( nn.Conv2d(inp, oup, 1, stride, padding=0, bias=False), nn.BatchNorm2d(oup), nn.LeakyReLU(negative_slope=leaky, inplace=True) )
null
3,441
import time import torch import torch.nn as nn import torchvision.models._utils as _utils import torchvision.models as models import torch.nn.functional as F from torch.autograd import Variable def conv_dw(inp, oup, stride, leaky=0.1): return nn.Sequential( nn.Conv2d(inp, inp, 3, stride, 1, groups=inp, bias=False), nn.BatchNorm2d(inp), nn.LeakyReLU(negative_slope= leaky,inplace=True), nn.Conv2d(inp, oup, 1, 1, 0, bias=False), nn.BatchNorm2d(oup), nn.LeakyReLU(negative_slope= leaky,inplace=True), )
null
3,442
import os import os.path import sys import torch import torch.utils.data as data import cv2 import numpy as np The provided code snippet includes necessary dependencies for implementing the `detection_collate` function. Write a Python function `def detection_collate(batch)` to solve the following problem: Custom collate fn for dealing with batches of images that have a different number of associated object annotations (bounding boxes). Arguments: batch: (tuple) A tuple of tensor images and lists of annotations Return: A tuple containing: 1) (tensor) batch of images stacked on their 0 dim 2) (list of tensors) annotations for a given image are stacked on 0 dim Here is the function: def detection_collate(batch): """Custom collate fn for dealing with batches of images that have a different number of associated object annotations (bounding boxes). Arguments: batch: (tuple) A tuple of tensor images and lists of annotations Return: A tuple containing: 1) (tensor) batch of images stacked on their 0 dim 2) (list of tensors) annotations for a given image are stacked on 0 dim """ targets = [] imgs = [] for _, sample in enumerate(batch): for _, tup in enumerate(sample): if torch.is_tensor(tup): imgs.append(tup) elif isinstance(tup, type(np.empty(0))): annos = torch.from_numpy(tup).float() targets.append(annos) return (torch.stack(imgs, 0), targets)
Custom collate fn for dealing with batches of images that have a different number of associated object annotations (bounding boxes). Arguments: batch: (tuple) A tuple of tensor images and lists of annotations Return: A tuple containing: 1) (tensor) batch of images stacked on their 0 dim 2) (list of tensors) annotations for a given image are stacked on 0 dim
3,443
import cv2 import numpy as np import random from face_detect.utils.box_utils import matrix_iof def matrix_iof(a, b): """ return iof of a and b, numpy version for data augenmentation """ lt = np.maximum(a[:, np.newaxis, :2], b[:, :2]) rb = np.minimum(a[:, np.newaxis, 2:], b[:, 2:]) area_i = np.prod(rb - lt, axis=2) * (lt < rb).all(axis=2) area_a = np.prod(a[:, 2:] - a[:, :2], axis=1) return area_i / np.maximum(area_a[:, np.newaxis], 1) def _crop(image, boxes, labels, landm, img_dim): height, width, _ = image.shape pad_image_flag = True for _ in range(250): """ if random.uniform(0, 1) <= 0.2: scale = 1.0 else: scale = random.uniform(0.3, 1.0) """ PRE_SCALES = [0.3, 0.45, 0.6, 0.8, 1.0] scale = random.choice(PRE_SCALES) short_side = min(width, height) w = int(scale * short_side) h = w if width == w: l = 0 else: l = random.randrange(width - w) if height == h: t = 0 else: t = random.randrange(height - h) roi = np.array((l, t, l + w, t + h)) value = matrix_iof(boxes, roi[np.newaxis]) flag = (value >= 1) if not flag.any(): continue centers = (boxes[:, :2] + boxes[:, 2:]) / 2 mask_a = np.logical_and(roi[:2] < centers, centers < roi[2:]).all(axis=1) boxes_t = boxes[mask_a].copy() labels_t = labels[mask_a].copy() landms_t = landm[mask_a].copy() landms_t = landms_t.reshape([-1, 5, 2]) if boxes_t.shape[0] == 0: continue image_t = image[roi[1]:roi[3], roi[0]:roi[2]] boxes_t[:, :2] = np.maximum(boxes_t[:, :2], roi[:2]) boxes_t[:, :2] -= roi[:2] boxes_t[:, 2:] = np.minimum(boxes_t[:, 2:], roi[2:]) boxes_t[:, 2:] -= roi[:2] # landm landms_t[:, :, :2] = landms_t[:, :, :2] - roi[:2] landms_t[:, :, :2] = np.maximum(landms_t[:, :, :2], np.array([0, 0])) landms_t[:, :, :2] = np.minimum(landms_t[:, :, :2], roi[2:] - roi[:2]) landms_t = landms_t.reshape([-1, 10]) # make sure that the cropped image contains at least one face > 16 pixel at training image scale b_w_t = (boxes_t[:, 2] - boxes_t[:, 0] + 1) / w * img_dim b_h_t = (boxes_t[:, 3] - boxes_t[:, 1] + 1) / h * img_dim mask_b = np.minimum(b_w_t, b_h_t) > 0.0 boxes_t = boxes_t[mask_b] labels_t = labels_t[mask_b] landms_t = landms_t[mask_b] if boxes_t.shape[0] == 0: continue pad_image_flag = False return image_t, boxes_t, labels_t, landms_t, pad_image_flag return image, boxes, labels, landm, pad_image_flag
null
3,444
import cv2 import numpy as np import random from face_detect.utils.box_utils import matrix_iof def _distort(image): def _convert(image, alpha=1, beta=0): tmp = image.astype(float) * alpha + beta tmp[tmp < 0] = 0 tmp[tmp > 255] = 255 image[:] = tmp image = image.copy() if random.randrange(2): #brightness distortion if random.randrange(2): _convert(image, beta=random.uniform(-32, 32)) #contrast distortion if random.randrange(2): _convert(image, alpha=random.uniform(0.5, 1.5)) image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) #saturation distortion if random.randrange(2): _convert(image[:, :, 1], alpha=random.uniform(0.5, 1.5)) #hue distortion if random.randrange(2): tmp = image[:, :, 0].astype(int) + random.randint(-18, 18) tmp %= 180 image[:, :, 0] = tmp image = cv2.cvtColor(image, cv2.COLOR_HSV2BGR) else: #brightness distortion if random.randrange(2): _convert(image, beta=random.uniform(-32, 32)) image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) #saturation distortion if random.randrange(2): _convert(image[:, :, 1], alpha=random.uniform(0.5, 1.5)) #hue distortion if random.randrange(2): tmp = image[:, :, 0].astype(int) + random.randint(-18, 18) tmp %= 180 image[:, :, 0] = tmp image = cv2.cvtColor(image, cv2.COLOR_HSV2BGR) #contrast distortion if random.randrange(2): _convert(image, alpha=random.uniform(0.5, 1.5)) return image
null
3,445
import cv2 import numpy as np import random from face_detect.utils.box_utils import matrix_iof def _expand(image, boxes, fill, p): if random.randrange(2): return image, boxes height, width, depth = image.shape scale = random.uniform(1, p) w = int(scale * width) h = int(scale * height) left = random.randint(0, w - width) top = random.randint(0, h - height) boxes_t = boxes.copy() boxes_t[:, :2] += (left, top) boxes_t[:, 2:] += (left, top) expand_image = np.empty( (h, w, depth), dtype=image.dtype) expand_image[:, :] = fill expand_image[top:top + height, left:left + width] = image image = expand_image return image, boxes_t
null
3,446
import cv2 import numpy as np import random from face_detect.utils.box_utils import matrix_iof def _mirror(image, boxes, landms): _, width, _ = image.shape if random.randrange(2): image = image[:, ::-1] boxes = boxes.copy() boxes[:, 0::2] = width - boxes[:, 2::-2] # landm landms = landms.copy() landms = landms.reshape([-1, 5, 2]) landms[:, :, 0] = width - landms[:, :, 0] tmp = landms[:, 1, :].copy() landms[:, 1, :] = landms[:, 0, :] landms[:, 0, :] = tmp tmp1 = landms[:, 4, :].copy() landms[:, 4, :] = landms[:, 3, :] landms[:, 3, :] = tmp1 landms = landms.reshape([-1, 10]) return image, boxes, landms
null
3,447
import cv2 import numpy as np import random from face_detect.utils.box_utils import matrix_iof def _pad_to_square(image, rgb_mean, pad_image_flag): if not pad_image_flag: return image height, width, _ = image.shape long_side = max(width, height) image_t = np.empty((long_side, long_side, 3), dtype=image.dtype) image_t[:, :] = rgb_mean image_t[0:0 + height, 0:0 + width] = image return image_t
null
3,448
import cv2 import numpy as np import random from face_detect.utils.box_utils import matrix_iof def _resize_subtract_mean(image, insize, rgb_mean): interp_methods = [cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_NEAREST, cv2.INTER_LANCZOS4] interp_method = interp_methods[random.randrange(5)] image = cv2.resize(image, (insize, insize), interpolation=interp_method) image = image.astype(np.float32) image -= rgb_mean return image.transpose(2, 0, 1)
null
3,449
import numpy as np The provided code snippet includes necessary dependencies for implementing the `py_cpu_nms` function. Write a Python function `def py_cpu_nms(dets, thresh)` to solve the following problem: Pure Python NMS baseline. Here is the function: def py_cpu_nms(dets, thresh): """Pure Python NMS baseline.""" x1 = dets[:, 0] y1 = dets[:, 1] x2 = dets[:, 2] y2 = dets[:, 3] scores = dets[:, 4] areas = (x2 - x1 + 1) * (y2 - y1 + 1) order = scores.argsort()[::-1] keep = [] while order.size > 0: i = order[0] keep.append(i) xx1 = np.maximum(x1[i], x1[order[1:]]) yy1 = np.maximum(y1[i], y1[order[1:]]) xx2 = np.minimum(x2[i], x2[order[1:]]) yy2 = np.minimum(y2[i], y2[order[1:]]) w = np.maximum(0.0, xx2 - xx1 + 1) h = np.maximum(0.0, yy2 - yy1 + 1) inter = w * h ovr = inter / (areas[i] + areas[order[1:]] - inter) inds = np.where(ovr <= thresh)[0] order = order[inds + 1] return keep
Pure Python NMS baseline.
3,450
import torch import numpy as np The provided code snippet includes necessary dependencies for implementing the `center_size` function. Write a Python function `def center_size(boxes)` to solve the following problem: Convert prior_boxes to (cx, cy, w, h) representation for comparison to center-size form ground truth data. Args: boxes: (tensor) point_form boxes Return: boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes. Here is the function: def center_size(boxes): """ Convert prior_boxes to (cx, cy, w, h) representation for comparison to center-size form ground truth data. Args: boxes: (tensor) point_form boxes Return: boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes. """ return torch.cat((boxes[:, 2:] + boxes[:, :2])/2, # cx, cy boxes[:, 2:] - boxes[:, :2], 1) # w, h
Convert prior_boxes to (cx, cy, w, h) representation for comparison to center-size form ground truth data. Args: boxes: (tensor) point_form boxes Return: boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes.
3,451
import torch import numpy as np The provided code snippet includes necessary dependencies for implementing the `matrix_iou` function. Write a Python function `def matrix_iou(a, b)` to solve the following problem: return iou of a and b, numpy version for data augenmentation Here is the function: def matrix_iou(a, b): """ return iou of a and b, numpy version for data augenmentation """ lt = np.maximum(a[:, np.newaxis, :2], b[:, :2]) rb = np.minimum(a[:, np.newaxis, 2:], b[:, 2:]) area_i = np.prod(rb - lt, axis=2) * (lt < rb).all(axis=2) area_a = np.prod(a[:, 2:] - a[:, :2], axis=1) area_b = np.prod(b[:, 2:] - b[:, :2], axis=1) return area_i / (area_a[:, np.newaxis] + area_b - area_i)
return iou of a and b, numpy version for data augenmentation
3,452
import torch import numpy as np def point_form(boxes): """ Convert prior_boxes to (xmin, ymin, xmax, ymax) representation for comparison to point form ground truth data. Args: boxes: (tensor) center-size default boxes from priorbox layers. Return: boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes. """ return torch.cat((boxes[:, :2] - boxes[:, 2:]/2, # xmin, ymin boxes[:, :2] + boxes[:, 2:]/2), 1) # xmax, ymax def jaccard(box_a, box_b): """Compute the jaccard overlap of two sets of boxes. The jaccard overlap is simply the intersection over union of two boxes. Here we operate on ground truth boxes and default boxes. E.g.: A ∩ B / A ∪ B = A ∩ B / (area(A) + area(B) - A ∩ B) Args: box_a: (tensor) Ground truth bounding boxes, Shape: [num_objects,4] box_b: (tensor) Prior boxes from priorbox layers, Shape: [num_priors,4] Return: jaccard overlap: (tensor) Shape: [box_a.size(0), box_b.size(0)] """ inter = intersect(box_a, box_b) area_a = ((box_a[:, 2]-box_a[:, 0]) * (box_a[:, 3]-box_a[:, 1])).unsqueeze(1).expand_as(inter) # [A,B] area_b = ((box_b[:, 2]-box_b[:, 0]) * (box_b[:, 3]-box_b[:, 1])).unsqueeze(0).expand_as(inter) # [A,B] union = area_a + area_b - inter return inter / union # [A,B] def encode(matched, priors, variances): """Encode the variances from the priorbox layers into the ground truth boxes we have matched (based on jaccard overlap) with the prior boxes. Args: matched: (tensor) Coords of ground truth for each prior in point-form Shape: [num_priors, 4]. priors: (tensor) Prior boxes in center-offset form Shape: [num_priors,4]. variances: (list[float]) Variances of priorboxes Return: encoded boxes (tensor), Shape: [num_priors, 4] """ # dist b/t match center and prior's center g_cxcy = (matched[:, :2] + matched[:, 2:])/2 - priors[:, :2] # encode variance g_cxcy /= (variances[0] * priors[:, 2:]) # match wh / prior wh g_wh = (matched[:, 2:] - matched[:, :2]) / priors[:, 2:] g_wh = torch.log(g_wh) / variances[1] # return target for smooth_l1_loss return torch.cat([g_cxcy, g_wh], 1) # [num_priors,4] def encode_landm(matched, priors, variances): """Encode the variances from the priorbox layers into the ground truth boxes we have matched (based on jaccard overlap) with the prior boxes. Args: matched: (tensor) Coords of ground truth for each prior in point-form Shape: [num_priors, 10]. priors: (tensor) Prior boxes in center-offset form Shape: [num_priors,4]. variances: (list[float]) Variances of priorboxes Return: encoded landm (tensor), Shape: [num_priors, 10] """ # dist b/t match center and prior's center matched = torch.reshape(matched, (matched.size(0), 5, 2)) priors_cx = priors[:, 0].unsqueeze(1).expand(matched.size(0), 5).unsqueeze(2) priors_cy = priors[:, 1].unsqueeze(1).expand(matched.size(0), 5).unsqueeze(2) priors_w = priors[:, 2].unsqueeze(1).expand(matched.size(0), 5).unsqueeze(2) priors_h = priors[:, 3].unsqueeze(1).expand(matched.size(0), 5).unsqueeze(2) priors = torch.cat([priors_cx, priors_cy, priors_w, priors_h], dim=2) g_cxcy = matched[:, :, :2] - priors[:, :, :2] # encode variance g_cxcy /= (variances[0] * priors[:, :, 2:]) # g_cxcy /= priors[:, :, 2:] g_cxcy = g_cxcy.reshape(g_cxcy.size(0), -1) # return target for smooth_l1_loss return g_cxcy The provided code snippet includes necessary dependencies for implementing the `match` function. Write a Python function `def match(threshold, truths, priors, variances, labels, landms, loc_t, conf_t, landm_t, idx)` to solve the following problem: Match each prior box with the ground truth box of the highest jaccard overlap, encode the bounding boxes, then return the matched indices corresponding to both confidence and location preds. Args: threshold: (float) The overlap threshold used when mathing boxes. truths: (tensor) Ground truth boxes, Shape: [num_obj, 4]. priors: (tensor) Prior boxes from priorbox layers, Shape: [n_priors,4]. variances: (tensor) Variances corresponding to each prior coord, Shape: [num_priors, 4]. labels: (tensor) All the class labels for the image, Shape: [num_obj]. landms: (tensor) Ground truth landms, Shape [num_obj, 10]. loc_t: (tensor) Tensor to be filled w/ endcoded location targets. conf_t: (tensor) Tensor to be filled w/ matched indices for conf preds. landm_t: (tensor) Tensor to be filled w/ endcoded landm targets. idx: (int) current batch index Return: The matched indices corresponding to 1)location 2)confidence 3)landm preds. Here is the function: def match(threshold, truths, priors, variances, labels, landms, loc_t, conf_t, landm_t, idx): """Match each prior box with the ground truth box of the highest jaccard overlap, encode the bounding boxes, then return the matched indices corresponding to both confidence and location preds. Args: threshold: (float) The overlap threshold used when mathing boxes. truths: (tensor) Ground truth boxes, Shape: [num_obj, 4]. priors: (tensor) Prior boxes from priorbox layers, Shape: [n_priors,4]. variances: (tensor) Variances corresponding to each prior coord, Shape: [num_priors, 4]. labels: (tensor) All the class labels for the image, Shape: [num_obj]. landms: (tensor) Ground truth landms, Shape [num_obj, 10]. loc_t: (tensor) Tensor to be filled w/ endcoded location targets. conf_t: (tensor) Tensor to be filled w/ matched indices for conf preds. landm_t: (tensor) Tensor to be filled w/ endcoded landm targets. idx: (int) current batch index Return: The matched indices corresponding to 1)location 2)confidence 3)landm preds. """ # jaccard index overlaps = jaccard( truths, point_form(priors) ) # (Bipartite Matching) # [1,num_objects] best prior for each ground truth best_prior_overlap, best_prior_idx = overlaps.max(1, keepdim=True) # ignore hard gt valid_gt_idx = best_prior_overlap[:, 0] >= 0.2 best_prior_idx_filter = best_prior_idx[valid_gt_idx, :] if best_prior_idx_filter.shape[0] <= 0: loc_t[idx] = 0 conf_t[idx] = 0 return # [1,num_priors] best ground truth for each prior best_truth_overlap, best_truth_idx = overlaps.max(0, keepdim=True) best_truth_idx.squeeze_(0) best_truth_overlap.squeeze_(0) best_prior_idx.squeeze_(1) best_prior_idx_filter.squeeze_(1) best_prior_overlap.squeeze_(1) best_truth_overlap.index_fill_(0, best_prior_idx_filter, 2) # ensure best prior # TODO refactor: index best_prior_idx with long tensor # ensure every gt matches with its prior of max overlap for j in range(best_prior_idx.size(0)): # 判别此anchor是预测哪一个boxes best_truth_idx[best_prior_idx[j]] = j matches = truths[best_truth_idx] # Shape: [num_priors,4] 此处为每一个anchor对应的bbox取出来 conf = labels[best_truth_idx] # Shape: [num_priors] 此处为每一个anchor对应的label取出来 conf[best_truth_overlap < threshold] = 0 # label as background overlap<0.35的全部作为负样本 loc = encode(matches, priors, variances) matches_landm = landms[best_truth_idx] landm = encode_landm(matches_landm, priors, variances) loc_t[idx] = loc # [num_priors,4] encoded offsets to learn conf_t[idx] = conf # [num_priors] top class label for each prior landm_t[idx] = landm
Match each prior box with the ground truth box of the highest jaccard overlap, encode the bounding boxes, then return the matched indices corresponding to both confidence and location preds. Args: threshold: (float) The overlap threshold used when mathing boxes. truths: (tensor) Ground truth boxes, Shape: [num_obj, 4]. priors: (tensor) Prior boxes from priorbox layers, Shape: [n_priors,4]. variances: (tensor) Variances corresponding to each prior coord, Shape: [num_priors, 4]. labels: (tensor) All the class labels for the image, Shape: [num_obj]. landms: (tensor) Ground truth landms, Shape [num_obj, 10]. loc_t: (tensor) Tensor to be filled w/ endcoded location targets. conf_t: (tensor) Tensor to be filled w/ matched indices for conf preds. landm_t: (tensor) Tensor to be filled w/ endcoded landm targets. idx: (int) current batch index Return: The matched indices corresponding to 1)location 2)confidence 3)landm preds.
3,453
import torch import numpy as np The provided code snippet includes necessary dependencies for implementing the `decode` function. Write a Python function `def decode(loc, priors, variances)` to solve the following problem: Decode locations from predictions using priors to undo the encoding we did for offset regression at train time. Args: loc (tensor): location predictions for loc layers, Shape: [num_priors,4] priors (tensor): Prior boxes in center-offset form. Shape: [num_priors,4]. variances: (list[float]) Variances of priorboxes Return: decoded bounding box predictions Here is the function: def decode(loc, priors, variances): """Decode locations from predictions using priors to undo the encoding we did for offset regression at train time. Args: loc (tensor): location predictions for loc layers, Shape: [num_priors,4] priors (tensor): Prior boxes in center-offset form. Shape: [num_priors,4]. variances: (list[float]) Variances of priorboxes Return: decoded bounding box predictions """ boxes = torch.cat(( priors[:, :2] + loc[:, :2] * variances[0] * priors[:, 2:], priors[:, 2:] * torch.exp(loc[:, 2:] * variances[1])), 1) boxes[:, :2] -= boxes[:, 2:] / 2 boxes[:, 2:] += boxes[:, :2] return boxes
Decode locations from predictions using priors to undo the encoding we did for offset regression at train time. Args: loc (tensor): location predictions for loc layers, Shape: [num_priors,4] priors (tensor): Prior boxes in center-offset form. Shape: [num_priors,4]. variances: (list[float]) Variances of priorboxes Return: decoded bounding box predictions
3,454
import torch import numpy as np The provided code snippet includes necessary dependencies for implementing the `decode_landm` function. Write a Python function `def decode_landm(pre, priors, variances)` to solve the following problem: Decode landm from predictions using priors to undo the encoding we did for offset regression at train time. Args: pre (tensor): landm predictions for loc layers, Shape: [num_priors,10] priors (tensor): Prior boxes in center-offset form. Shape: [num_priors,4]. variances: (list[float]) Variances of priorboxes Return: decoded landm predictions Here is the function: def decode_landm(pre, priors, variances): """Decode landm from predictions using priors to undo the encoding we did for offset regression at train time. Args: pre (tensor): landm predictions for loc layers, Shape: [num_priors,10] priors (tensor): Prior boxes in center-offset form. Shape: [num_priors,4]. variances: (list[float]) Variances of priorboxes Return: decoded landm predictions """ landms = torch.cat((priors[:, :2] + pre[:, :2] * variances[0] * priors[:, 2:], priors[:, :2] + pre[:, 2:4] * variances[0] * priors[:, 2:], priors[:, :2] + pre[:, 4:6] * variances[0] * priors[:, 2:], priors[:, :2] + pre[:, 6:8] * variances[0] * priors[:, 2:], priors[:, :2] + pre[:, 8:10] * variances[0] * priors[:, 2:], ), dim=1) return landms
Decode landm from predictions using priors to undo the encoding we did for offset regression at train time. Args: pre (tensor): landm predictions for loc layers, Shape: [num_priors,10] priors (tensor): Prior boxes in center-offset form. Shape: [num_priors,4]. variances: (list[float]) Variances of priorboxes Return: decoded landm predictions
3,455
import torch import numpy as np The provided code snippet includes necessary dependencies for implementing the `log_sum_exp` function. Write a Python function `def log_sum_exp(x)` to solve the following problem: Utility function for computing log_sum_exp while determining This will be used to determine unaveraged confidence loss across all examples in a batch. Args: x (Variable(tensor)): conf_preds from conf layers Here is the function: def log_sum_exp(x): """Utility function for computing log_sum_exp while determining This will be used to determine unaveraged confidence loss across all examples in a batch. Args: x (Variable(tensor)): conf_preds from conf layers """ x_max = x.data.max() return torch.log(torch.sum(torch.exp(x-x_max), 1, keepdim=True)) + x_max
Utility function for computing log_sum_exp while determining This will be used to determine unaveraged confidence loss across all examples in a batch. Args: x (Variable(tensor)): conf_preds from conf layers
3,456
import torch import numpy as np The provided code snippet includes necessary dependencies for implementing the `nms` function. Write a Python function `def nms(boxes, scores, overlap=0.5, top_k=200)` to solve the following problem: Apply non-maximum suppression at test time to avoid detecting too many overlapping bounding boxes for a given object. Args: boxes: (tensor) The location preds for the img, Shape: [num_priors,4]. scores: (tensor) The class predscores for the img, Shape:[num_priors]. overlap: (float) The overlap thresh for suppressing unnecessary boxes. top_k: (int) The Maximum number of box preds to consider. Return: The indices of the kept boxes with respect to num_priors. Here is the function: def nms(boxes, scores, overlap=0.5, top_k=200): """Apply non-maximum suppression at test time to avoid detecting too many overlapping bounding boxes for a given object. Args: boxes: (tensor) The location preds for the img, Shape: [num_priors,4]. scores: (tensor) The class predscores for the img, Shape:[num_priors]. overlap: (float) The overlap thresh for suppressing unnecessary boxes. top_k: (int) The Maximum number of box preds to consider. Return: The indices of the kept boxes with respect to num_priors. """ keep = torch.Tensor(scores.size(0)).fill_(0).long() if boxes.numel() == 0: return keep x1 = boxes[:, 0] y1 = boxes[:, 1] x2 = boxes[:, 2] y2 = boxes[:, 3] area = torch.mul(x2 - x1, y2 - y1) v, idx = scores.sort(0) # sort in ascending order # I = I[v >= 0.01] idx = idx[-top_k:] # indices of the top-k largest vals xx1 = boxes.new() yy1 = boxes.new() xx2 = boxes.new() yy2 = boxes.new() w = boxes.new() h = boxes.new() # keep = torch.Tensor() count = 0 while idx.numel() > 0: i = idx[-1] # index of current largest val # keep.append(i) keep[count] = i count += 1 if idx.size(0) == 1: break idx = idx[:-1] # remove kept element from view # load bboxes of next highest vals torch.index_select(x1, 0, idx, out=xx1) torch.index_select(y1, 0, idx, out=yy1) torch.index_select(x2, 0, idx, out=xx2) torch.index_select(y2, 0, idx, out=yy2) # store element-wise max with next highest score xx1 = torch.clamp(xx1, min=x1[i]) yy1 = torch.clamp(yy1, min=y1[i]) xx2 = torch.clamp(xx2, max=x2[i]) yy2 = torch.clamp(yy2, max=y2[i]) w.resize_as_(xx2) h.resize_as_(yy2) w = xx2 - xx1 h = yy2 - yy1 # check sizes of xx1 and xx2.. after each iteration w = torch.clamp(w, min=0.0) h = torch.clamp(h, min=0.0) inter = w*h # IoU = i / (area(a) + area(b) - i) rem_areas = torch.index_select(area, 0, idx) # load remaining areas) union = (rem_areas - inter) + area[i] IoU = inter/union # store result in iou # keep only elements with an IoU <= overlap idx = idx[IoU.le(overlap)] return keep, count
Apply non-maximum suppression at test time to avoid detecting too many overlapping bounding boxes for a given object. Args: boxes: (tensor) The location preds for the img, Shape: [num_priors,4]. scores: (tensor) The class predscores for the img, Shape:[num_priors]. overlap: (float) The overlap thresh for suppressing unnecessary boxes. top_k: (int) The Maximum number of box preds to consider. Return: The indices of the kept boxes with respect to num_priors.
3,457
from typing import Tuple, List, Union, Iterable import numpy as np import torch import torch.nn.functional as F from transformers import PreTrainedTokenizer from transformers import logging from transformers.generation import LogitsProcessor BatchTokensType = List[List[int]] def pad_batch(batch: BatchTokensType, pad_id: int, seq_length: int) -> BatchTokensType: for tokens in batch: context_length = len(tokens) if context_length < seq_length: tokens.extend([pad_id] * (seq_length - context_length)) return batch
null
3,458
from typing import Tuple, List, Union, Iterable import numpy as np import torch import torch.nn.functional as F from transformers import PreTrainedTokenizer from transformers import logging from transformers.generation import LogitsProcessor def get_ltor_masks_and_position_ids( data, eod_token, reset_position_ids, reset_attention_mask, eod_mask_loss, ): """Build masks and position id for left to right model.""" # Extract batch size and sequence length. micro_batch_size, seq_length = data.size() # Attention mask (lower triangular). if reset_attention_mask: att_mask_batch = micro_batch_size else: att_mask_batch = 1 attention_mask = torch.tril( torch.ones((att_mask_batch, seq_length, seq_length), device=data.device) ).view(att_mask_batch, 1, seq_length, seq_length) # Loss mask. loss_mask = torch.ones(data.size(), dtype=torch.float, device=data.device) if eod_mask_loss: loss_mask[data == eod_token] = 0.0 # Position ids. position_ids = torch.arange(seq_length, dtype=torch.long, device=data.device) position_ids = position_ids.unsqueeze(0).expand_as(data) # We need to clone as the ids will be modifed based on batch index. if reset_position_ids: position_ids = position_ids.clone() if reset_position_ids or reset_attention_mask: # Loop through the batches: for b in range(micro_batch_size): # Find indecies where EOD token is. eod_index = position_ids[b, data[b] == eod_token] # Detach indecies from positions if going to modify positions. if reset_position_ids: eod_index = eod_index.clone() # Loop through EOD indecies: prev_index = 0 for j in range(eod_index.size()[0]): i = eod_index[j] # Mask attention loss. if reset_attention_mask: attention_mask[b, 0, (i + 1) :, : (i + 1)] = 0 # Reset positions. if reset_position_ids: position_ids[b, (i + 1) :] -= i + 1 - prev_index prev_index = i + 1 # Convert attention mask to binary: attention_mask = attention_mask < 0.5 return attention_mask, loss_mask, position_ids The provided code snippet includes necessary dependencies for implementing the `get_batch` function. Write a Python function `def get_batch(context_tokens: torch.LongTensor, eod_id: int)` to solve the following problem: Generate batch from context tokens. Here is the function: def get_batch(context_tokens: torch.LongTensor, eod_id: int): """Generate batch from context tokens.""" # Move to GPU. tokens = context_tokens.contiguous().to(context_tokens.device) # Get the attention mask and postition ids. attention_mask, _, position_ids = get_ltor_masks_and_position_ids( tokens, eod_id, reset_position_ids=False, reset_attention_mask=False, eod_mask_loss=False, ) return tokens, attention_mask, position_ids
Generate batch from context tokens.
3,459
from typing import Tuple, List, Union, Iterable import numpy as np import torch import torch.nn.functional as F from transformers import PreTrainedTokenizer from transformers import logging from transformers.generation import LogitsProcessor def get_stop_words_ids(chat_format, tokenizer): if chat_format == "raw": stop_words_ids = [tokenizer.encode("Human:"), [tokenizer.eod_id]] elif chat_format == "chatml": stop_words_ids = [[tokenizer.im_end_id], [tokenizer.im_start_id]] else: raise NotImplementedError(f"Unknown chat format {chat_format!r}") return stop_words_ids
null
3,460
from typing import Tuple, List, Union, Iterable import numpy as np import torch import torch.nn.functional as F from transformers import PreTrainedTokenizer from transformers import logging from transformers.generation import LogitsProcessor def make_context( tokenizer: PreTrainedTokenizer, query: str, history: List[Tuple[str, str]] = None, system: str = "", max_window_size: int = 6144, chat_format: str = "chatml", ): if history is None: history = [] if chat_format == "chatml": im_start, im_end = "<|im_start|>", "<|im_end|>" im_start_tokens = [tokenizer.im_start_id] im_end_tokens = [tokenizer.im_end_id] nl_tokens = tokenizer.encode("\n") def _tokenize_str(role, content): return f"{role}\n{content}", tokenizer.encode( role, allowed_special=set(tokenizer.IMAGE_ST) ) + nl_tokens + tokenizer.encode(content, allowed_special=set(tokenizer.IMAGE_ST)) system_text, system_tokens_part = _tokenize_str("system", system) system_tokens = im_start_tokens + system_tokens_part + im_end_tokens raw_text = "" context_tokens = [] for turn_query, turn_response in reversed(history): query_text, query_tokens_part = _tokenize_str("user", turn_query) query_tokens = im_start_tokens + query_tokens_part + im_end_tokens if turn_response is not None: response_text, response_tokens_part = _tokenize_str( "assistant", turn_response ) response_tokens = im_start_tokens + response_tokens_part + im_end_tokens next_context_tokens = nl_tokens + query_tokens + nl_tokens + response_tokens prev_chat = ( f"\n{im_start}{query_text}{im_end}\n{im_start}{response_text}{im_end}" ) else: next_context_tokens = nl_tokens + query_tokens + nl_tokens prev_chat = f"\n{im_start}{query_text}{im_end}\n" current_context_size = ( len(system_tokens) + len(next_context_tokens) + len(context_tokens) ) if current_context_size < max_window_size: context_tokens = next_context_tokens + context_tokens raw_text = prev_chat + raw_text else: break context_tokens = system_tokens + context_tokens raw_text = f"{im_start}{system_text}{im_end}" + raw_text context_tokens += ( nl_tokens + im_start_tokens + _tokenize_str("user", query)[1] + im_end_tokens + nl_tokens + im_start_tokens + tokenizer.encode("assistant") + nl_tokens ) raw_text += f"\n{im_start}user\n{query}{im_end}\n{im_start}assistant\n" elif chat_format == "raw": raw_text = query context_tokens = tokenizer.encode(raw_text) else: raise NotImplementedError(f"Unknown chat format {chat_format!r}") return raw_text, context_tokens
null
3,461
from typing import Tuple, List, Union, Iterable import numpy as np import torch import torch.nn.functional as F from transformers import PreTrainedTokenizer from transformers import logging from transformers.generation import LogitsProcessor TokensType = List[int] def _decode_default( tokens: List[int], *, stop_words: List[str], eod_words: List[str], tokenizer: PreTrainedTokenizer, raw_text_len: int, verbose: bool = False, return_end_reason: bool = False, errors: str='replace', ): trim_decode_tokens = tokenizer.decode(tokens, errors=errors)[raw_text_len:] if verbose: print("\nRaw Generate: ", trim_decode_tokens) end_reason = f"Gen length {len(tokens)}" for stop_word in stop_words: trim_decode_tokens = trim_decode_tokens.replace(stop_word, "").strip() for eod_word in eod_words: if eod_word in trim_decode_tokens: end_reason = f"Gen {eod_word!r}" trim_decode_tokens = trim_decode_tokens.split(eod_word)[0] trim_decode_tokens = trim_decode_tokens.strip() if verbose: print("\nEnd Reason:", end_reason) print("\nGenerate: ", trim_decode_tokens) if return_end_reason: return trim_decode_tokens, end_reason else: return trim_decode_tokens def _decode_chatml( tokens: List[int], *, stop_words: List[str], eod_token_ids: List[int], tokenizer: PreTrainedTokenizer, raw_text_len: int, context_length: int, verbose: bool = False, return_end_reason: bool = False, errors: str='replace' ): end_reason = f"Gen length {len(tokens)}" eod_token_idx = context_length for eod_token_idx in range(context_length, len(tokens)): if tokens[eod_token_idx] in eod_token_ids: end_reason = f"Gen {tokenizer.decode([tokens[eod_token_idx]])!r}" break trim_decode_tokens = tokenizer.decode(tokens[:eod_token_idx], errors=errors)[raw_text_len:] if verbose: print("\nRaw Generate w/o EOD:", tokenizer.decode(tokens, errors=errors)[raw_text_len:]) print("\nRaw Generate:", trim_decode_tokens) print("\nEnd Reason:", end_reason) for stop_word in stop_words: trim_decode_tokens = trim_decode_tokens.replace(stop_word, "").strip() trim_decode_tokens = trim_decode_tokens.strip() if verbose: print("\nGenerate:", trim_decode_tokens) if return_end_reason: return trim_decode_tokens, end_reason else: return trim_decode_tokens def decode_tokens( tokens: Union[torch.LongTensor, TokensType], tokenizer: PreTrainedTokenizer, raw_text_len: int, context_length: int, chat_format: str, verbose: bool = False, return_end_reason: bool = False, errors: str="replace", ) -> str: if torch.is_tensor(tokens): tokens = tokens.cpu().numpy().tolist() if chat_format == "chatml": return _decode_chatml( tokens, stop_words=[], eod_token_ids=[tokenizer.im_start_id, tokenizer.im_end_id], tokenizer=tokenizer, raw_text_len=raw_text_len, context_length=context_length, verbose=verbose, return_end_reason=return_end_reason, errors=errors, ) elif chat_format == "raw": return _decode_default( tokens, stop_words=["<|endoftext|>"], eod_words=["<|endoftext|>"], tokenizer=tokenizer, raw_text_len=raw_text_len, verbose=verbose, return_end_reason=return_end_reason, errors=errors, ) else: raise NotImplementedError(f"Unknown chat format {chat_format!r}")
null
3,462
from typing import Tuple, List, Union, Iterable import numpy as np import torch import torch.nn.functional as F from transformers import PreTrainedTokenizer from transformers import logging from transformers.generation import LogitsProcessor The provided code snippet includes necessary dependencies for implementing the `top_k_logits` function. Write a Python function `def top_k_logits(logits, top_k=0, top_p=0.0, filter_value=-float("Inf"))` to solve the following problem: This function has been mostly taken from huggingface conversational ai code at https://medium.com/huggingface/how-to-build-a-state-of-the-art- conversational-ai-with-transfer-learning-2d818ac26313 Here is the function: def top_k_logits(logits, top_k=0, top_p=0.0, filter_value=-float("Inf")): """This function has been mostly taken from huggingface conversational ai code at https://medium.com/huggingface/how-to-build-a-state-of-the-art- conversational-ai-with-transfer-learning-2d818ac26313""" if top_k > 0: # Remove all tokens with a probability less than the # last token of the top-k indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None] logits[indices_to_remove] = filter_value if top_p > 0.0: # Cconvert to 1D sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1) cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1) # Remove tokens with cumulative probability above the threshold sorted_indices_to_remove = cumulative_probs > top_p # Shift the indices to the right to keep also the first token # above the threshold sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone() sorted_indices_to_remove[..., 0] = 0 for i in range(sorted_indices.size(0)): indices_to_remove = sorted_indices[i][sorted_indices_to_remove[i]] logits[i][indices_to_remove] = filter_value return logits
This function has been mostly taken from huggingface conversational ai code at https://medium.com/huggingface/how-to-build-a-state-of-the-art- conversational-ai-with-transfer-learning-2d818ac26313
3,463
from typing import Tuple, List, Union, Iterable import numpy as np import torch import torch.nn.functional as F from transformers import PreTrainedTokenizer from transformers import logging from transformers.generation import LogitsProcessor def switch(val1, val2, boolean): boolean = boolean.type_as(val1) return (1 - boolean) * val1 + boolean * val2
null
3,464
import importlib import math from typing import TYPE_CHECKING, Optional, Tuple, Union, Callable, List, Any, Generator import torch import torch.nn.functional as F import torch.utils.checkpoint from torch.cuda.amp import autocast from torch.nn import CrossEntropyLoss from transformers import PreTrainedTokenizer, GenerationConfig, StoppingCriteriaList from transformers.generation.logits_process import LogitsProcessorList from transformers.generation.utils import GenerateOutput from transformers.modeling_outputs import ( BaseModelOutputWithPast, CausalLMOutputWithPast, ) from transformers.modeling_utils import PreTrainedModel from transformers.utils import logging from torch import nn from .configuration_qwen import QWenConfig from .qwen_generation_utils import ( HistoryType, make_context, decode_tokens, get_stop_words_ids, StopWordsLogitsProcessor, ) from .visual import VisionTransformer The provided code snippet includes necessary dependencies for implementing the `_make_causal_mask` function. Write a Python function `def _make_causal_mask( input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0 )` to solve the following problem: Make causal mask used for bi-directional self-attention. Here is the function: def _make_causal_mask( input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0 ): """ Make causal mask used for bi-directional self-attention. """ bsz, tgt_len = input_ids_shape mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device) mask_cond = torch.arange(mask.size(-1), device=device) mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0) mask = mask.to(dtype) if past_key_values_length > 0: mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1) return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
Make causal mask used for bi-directional self-attention.
3,465
import importlib import math from typing import TYPE_CHECKING, Optional, Tuple, Union, Callable, List, Any, Generator import torch import torch.nn.functional as F import torch.utils.checkpoint from torch.cuda.amp import autocast from torch.nn import CrossEntropyLoss from transformers import PreTrainedTokenizer, GenerationConfig, StoppingCriteriaList from transformers.generation.logits_process import LogitsProcessorList from transformers.generation.utils import GenerateOutput from transformers.modeling_outputs import ( BaseModelOutputWithPast, CausalLMOutputWithPast, ) from transformers.modeling_utils import PreTrainedModel from transformers.utils import logging from torch import nn from .configuration_qwen import QWenConfig from .qwen_generation_utils import ( HistoryType, make_context, decode_tokens, get_stop_words_ids, StopWordsLogitsProcessor, ) from .visual import VisionTransformer The provided code snippet includes necessary dependencies for implementing the `_expand_mask` function. Write a Python function `def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None)` to solve the following problem: Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`. Here is the function: def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None): """ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`. """ bsz, src_len = mask.size() tgt_len = tgt_len if tgt_len is not None else src_len expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype) inverted_mask = 1.0 - expanded_mask return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.