code stringlengths 17 6.64M |
|---|
@lru_cache()
def default_bpe():
return os.path.join(os.path.dirname(os.path.abspath(__file__)), 'bpe_simple_vocab_16e6.txt.gz')
|
@lru_cache()
def bytes_to_unicode():
"\n Returns list of utf-8 byte and a corresponding list of unicode strings.\n The reversible bpe codes work on unicode strings.\n This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.\n When you're at something like a 10B toke... |
def get_pairs(word):
'Return set of symbol pairs in a word.\n Word is represented as tuple of symbols (symbols being variable-length strings).\n '
pairs = set()
prev_char = word[0]
for char in word[1:]:
pairs.add((prev_char, char))
prev_char = char
return pairs
|
def basic_clean(text):
text = ftfy.fix_text(text)
text = html.unescape(html.unescape(text))
return text.strip()
|
def whitespace_clean(text):
text = re.sub('\\s+', ' ', text)
text = text.strip()
return text
|
class SimpleTokenizer(object):
def __init__(self, bpe_path: str=default_bpe()):
self.byte_encoder = bytes_to_unicode()
self.byte_decoder = {v: k for (k, v) in self.byte_encoder.items()}
merges = gzip.open(bpe_path).read().decode('utf-8').split('\n')
merges = merges[1:(((49152 - 25... |
def get_world_size():
if (not dist.is_available()):
return 1
if (not dist.is_initialized()):
return 1
return dist.get_world_size()
|
def get_rank():
if (not dist.is_available()):
return 0
if (not dist.is_initialized()):
return 0
return dist.get_rank()
|
def is_main_process():
return (get_rank() == 0)
|
def synchronize():
'\n Helper function to synchronize (barrier) among all processes when\n using distributed training\n '
if (not dist.is_available()):
return
if (not dist.is_initialized()):
return
world_size = dist.get_world_size()
if (world_size == 1):
return
... |
def all_gather(data):
'\n Run all_gather on arbitrary picklable data (not necessarily tensors)\n Args:\n data: any picklable object\n Returns:\n list[data]: list of data gathered from each rank\n '
world_size = get_world_size()
if (world_size == 1):
return [data]
buff... |
def reduce_dict(input_dict, average=True):
'\n Args:\n input_dict (dict): all the values will be reduced\n average (bool): whether to do average or sum\n Reduce the values in the dictionary from all processes so that process with rank\n 0 has the averaged results. Returns a dict with the sa... |
def setup_logger(name, save_dir, dist_rank, filename='log.txt'):
logger = logging.getLogger(name)
logger.setLevel(logging.ERROR)
if (dist_rank > 0):
return logger
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler(stream=sys.stdout)
ch.setLevel(logging.DEBUG)
formatter = log... |
class SmoothedValue(object):
'Track a series of values and provide access to smoothed values over a\n window or the global series average.\n '
def __init__(self, window_size=20):
self.deque = deque(maxlen=window_size)
self.series = []
self.total = 0.0
self.count = 0
... |
class MetricLogger(object):
def __init__(self, delimiter='\t'):
self.meters = defaultdict(SmoothedValue)
self.delimiter = delimiter
def update(self, **kwargs):
for (k, v) in kwargs.items():
if isinstance(v, torch.Tensor):
v = v.item()
assert is... |
def permutation_test(tokens, key, n, k, vocab_size, n_runs=100):
rng = mersenne_rng(key)
xi = np.array([rng.rand() for _ in range((n * vocab_size))], dtype=np.float32).reshape(n, vocab_size)
test_result = detect(tokens, n, k, xi)
p_val = 0
for run in range(n_runs):
xi_alternative = np.rand... |
def detect(tokens, n, k, xi, gamma=0.0):
m = len(tokens)
n = len(xi)
A = np.empty(((m - (k - 1)), n))
for i in range((m - (k - 1))):
for j in range(n):
A[i][j] = levenshtein(tokens[i:(i + k)], xi[((j + np.arange(k)) % n)], gamma)
return np.min(A)
|
def main(args):
with open(args.document, 'r') as f:
text = f.read()
tokenizer = AutoTokenizer.from_pretrained(args.tokenizer)
tokens = tokenizer.encode(text, return_tensors='pt', truncation=True, max_length=2048).numpy()[0]
t0 = time.time()
pval = permutation_test(tokens, args.key, args.n,... |
class mersenne_rng(object):
def __init__(self, seed=5489):
self.state = ([0] * 624)
self.f = 1812433253
self.m = 397
self.u = 11
self.s = 7
self.b = 2636928640
self.t = 15
self.c = 4022730752
self.l = 18
self.index = 624
self... |
def substitution_attack(tokens, p, vocab_size, distribution=None):
if (distribution is None):
distribution = (lambda x: (torch.ones(size=(len(tokens), vocab_size)) / vocab_size))
idx = torch.randperm(len(tokens))[:int((p * len(tokens)))]
new_probs = distribution(tokens)
samples = torch.multino... |
def deletion_attack(tokens, p):
idx = torch.randperm(len(tokens))[:int((p * len(tokens)))]
keep = torch.ones(len(tokens), dtype=torch.bool)
keep[idx] = False
tokens = tokens[keep]
return tokens
|
def insertion_attack(tokens, p, vocab_size, distribution=None):
if (distribution is None):
distribution = (lambda x: (torch.ones(size=(len(tokens), vocab_size)) / vocab_size))
idx = torch.randperm(len(tokens))[:int((p * len(tokens)))]
new_probs = distribution(tokens)
samples = torch.multinomia... |
def permutation_test(tokens, vocab_size, n, k, seed, test_stat, n_runs=100, max_seed=100000):
generator = torch.Generator()
generator.manual_seed(int(seed))
test_result = test_stat(tokens=tokens, n=n, k=k, generator=generator, vocab_size=vocab_size)
p_val = 0
for run in range(n_runs):
pi =... |
def fast_permutation_test(tokens, vocab_size, n, k, seed, test_stat, null_results):
generator = torch.Generator()
generator.manual_seed(int(seed))
test_result = test_stat(tokens=tokens, n=n, k=k, generator=generator, vocab_size=vocab_size)
p_val = (torch.searchsorted(null_results, test_result, right=T... |
def phi(tokens, n, k, generator, key_func, vocab_size, dist, null=False, normalize=False):
if null:
tokens = torch.unique(tokens, return_inverse=True, sorted=False)[1]
eff_vocab_size = (torch.max(tokens) + 1)
else:
eff_vocab_size = vocab_size
(xi, pi) = key_func(generator, n, vocab... |
def adjacency(tokens, xi, dist, k):
m = len(tokens)
n = len(xi)
A = torch.empty(size=((m - (k - 1)), n))
for i in range((m - (k - 1))):
for j in range(n):
A[i][j] = dist(tokens[i:(i + k)], xi[((j + torch.arange(k)) % n)])
return A
|
def gumbel_key_func(generator, n, vocab_size, eff_vocab_size=None):
if (eff_vocab_size is None):
eff_vocab_size = vocab_size
pi = torch.arange(eff_vocab_size)
xi = torch.rand((n, eff_vocab_size), generator=generator)
return (xi, pi)
|
def gumbel_sampling(probs, pi, xi):
return torch.argmax((xi ** (1 / torch.gather(probs, 1, pi))), axis=1).unsqueeze((- 1))
|
def gumbel_score(tokens, xi):
xi_samp = torch.gather(xi, (- 1), tokens.unsqueeze((- 1))).squeeze()
return (- torch.sum(torch.log((1 / (1 - xi_samp)))))
|
def gumbel_edit_score(tokens, xi, gamma):
return gumbel_levenshtein(tokens.numpy(), xi.numpy(), gamma)
|
class Categories():
'\n Work with aliases from ISO 15924.\n https://en.wikipedia.org/wiki/ISO_15924#List_of_codes\n '
fpath = os.path.join(DATA_LOCATION, 'categories.json')
@classmethod
def _get_ranges(cls, categories):
'\n :return: iter: (start code, end code)\n :rtype... |
class Languages():
fpath = os.path.join(DATA_LOCATION, 'languages.json')
@classmethod
def get_alphabet(cls, languages):
'\n :return: set of chars in alphabet by languages list\n :rtype: set\n '
with open(cls.fpath, encoding='utf-8') as f:
data = json.load(... |
class Homoglyphs():
def __init__(self, categories=None, languages=None, alphabet=None, strategy=STRATEGY_IGNORE, ascii_strategy=STRATEGY_IGNORE, ascii_range=ASCII_RANGE):
if (strategy not in (STRATEGY_LOAD, STRATEGY_IGNORE, STRATEGY_REMOVE)):
raise ValueError('Invalid strategy')
self.... |
def normalization_strategy_lookup(strategy_name: str) -> object:
if (strategy_name == 'unicode'):
return UnicodeSanitizer()
elif (strategy_name == 'homoglyphs'):
return HomoglyphCanonizer()
elif (strategy_name == 'truecase'):
return TrueCaser()
|
class HomoglyphCanonizer():
'Attempts to detect homoglyph attacks and find a consistent canon.\n\n This function does so on a per-ISO-category level. Language-level would also be possible (see commented code).\n '
def __init__(self):
self.homoglyphs = None
def __call__(self, homoglyphed_st... |
class UnicodeSanitizer():
'Regex-based unicode sanitzer. Has different levels of granularity.\n\n * ruleset="whitespaces" - attempts to remove only whitespace unicode characters\n * ruleset="IDN.blacklist" - does its best to remove unusual unicode based on Network.IDN.blacklist characters\n * rulese... |
class TrueCaser():
'True-casing, is a capitalization normalization that returns text to its original capitalization.\n\n This defends against attacks that wRIte TeXt lIkE spOngBoB.\n\n Here, a simple POS-tagger is used.\n '
uppercase_pos = ['PROPN']
def __init__(self, backend='spacy'):
i... |
class WatermarkBase():
def __init__(self, vocab: list[int]=None, gamma: float=0.5, delta: float=2.0, seeding_scheme: str='simple_1', hash_key: int=15485863, select_green_tokens: bool=True):
self.vocab = vocab
self.vocab_size = len(vocab)
self.gamma = gamma
self.delta = delta
... |
class WatermarkLogitsProcessor(WatermarkBase, LogitsProcessor):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def _calc_greenlist_mask(self, scores: torch.FloatTensor, greenlist_token_ids) -> torch.BoolTensor:
green_tokens_mask = torch.zeros_like(scores)
for ... |
class WatermarkDetector(WatermarkBase):
def __init__(self, *args, device: torch.device=None, tokenizer: Tokenizer=None, z_threshold: float=4.0, normalizers: list[str]=['unicode'], ignore_repeated_bigrams: bool=False, **kwargs):
super().__init__(*args, **kwargs)
assert device, 'Must pass device'
... |
def transform_key_func(generator, n, vocab_size, eff_vocab_size=None):
pi = torch.randperm(vocab_size, generator=generator)
xi = torch.rand((n, 1), generator=generator)
return (xi, pi)
|
def transform_sampling(probs, pi, xi):
cdf = torch.cumsum(torch.gather(probs, 1, pi), 1)
return torch.gather(pi, 1, torch.searchsorted(cdf, xi))
|
def transform_score(tokens, xi):
return torch.pow(torch.linalg.norm((tokens - xi.squeeze()), ord=1), 1)
|
def transform_edit_score(tokens, xi, gamma=1):
return transform_levenshtein(tokens.numpy(), xi.squeeze().numpy(), gamma)
|
def MinMaxScaler(data):
'Min Max normalizer.\n \n Args:\n - data: original data\n \n Returns:\n - norm_data: normalized data\n '
numerator = (data - np.min(data, 0))
denominator = (np.max(data, 0) - np.min(data, 0))
norm_data = (numerator / (denominator + 1e-07))
return norm_data
|
def sine_data_generation(no, seq_len, dim):
'Sine data generation.\n \n Args:\n - no: the number of samples\n - seq_len: sequence length of the time-series\n - dim: feature dimensions\n \n Returns:\n - data: generated data\n '
data = list()
for i in range(no):
temp = list()
... |
def real_data_loading(data_name, seq_len):
'Load and preprocess real-world datasets.\n \n Args:\n - data_name: stock or energy\n - seq_len: sequence length\n \n Returns:\n - data: preprocessed data.\n '
assert (data_name in ['stock', 'energy'])
if (data_name == 'stock'):
ori_data =... |
def main(args):
'Main function for timeGAN experiments.\n \n Args:\n - data_name: sine, stock, or energy\n - seq_len: sequence length\n - Network parameters (should be optimized for different datasets)\n - module: gru, lstm, or lstmLN\n - hidden_dim: hidden dimensions\n - num_layer: numb... |
def discriminative_score_metrics(ori_data, generated_data):
'Use post-hoc RNN to classify original data and synthetic data\n \n Args:\n - ori_data: original data\n - generated_data: generated synthetic data\n \n Returns:\n - discriminative_score: np.abs(classification accuracy - 0.5)\n '
tf.re... |
def is_image_file(filename):
return any((filename.endswith(extension) for extension in IMG_EXTENSIONS))
|
def make_dataset(dir, max_dataset_size=float('inf')):
cache = (dir.rstrip('/') + '.txt')
if os.path.isfile(cache):
print(('Using filelist cached at %s' % cache))
with open(cache) as f:
images = [line.strip() for line in f]
if images[0].startswith(dir):
print('Us... |
def make_multiple_dataset(dir, max_dataset_size=float('inf')):
subdir = ['Deepfakes', 'Face2Face', 'FaceSwap', 'NeuralTextures']
total_image_list = []
(last_dir, dir) = (((dir.split('/')[(- 2)] + '/') + dir.split('/')[(- 1)]), '/'.join(dir.split('/')[:(- 2)]))
print(dir)
for sdir in subdir:
... |
def make_multiple_dataset_real(dir, max_dataset_size=float('inf')):
subdir = ['faces/celebahq/real-tfr-1024-resized128', 'faces/celebahq/real-tfr-1024-resized128', 'faces/celebahq/real-tfr-1024-resized128', 'faceforensics_aligned/Deepfakes/original', 'faceforensics_aligned/Face2Face/original', 'faceforensics_alig... |
def make_multiple_dataset_fake(dir, max_dataset_size=float('inf')):
subdir = ['faces/celebahq/pgan-pretrained-128-png', 'faces/celebahq/sgan-pretrained-128-png', 'faces/celebahq/glow-pretrained-128-png', 'faceforensics_aligned/Deepfakes/manipulated', 'faceforensics_aligned/Face2Face/manipulated', 'faceforensics_a... |
def make_CNNDetection_dataset(dir, max_dataset_size=float('inf'), mode='real'):
classes = os.listdir(dir)
total_image_list = []
total_class_list = []
print(dir)
if (mode == 'real'):
sdir = '0_real'
elif (mode == 'fake'):
sdir = '1_fake'
for cls in classes:
curr_dir ... |
def default_loader(path):
return Image.open(path).convert('RGB')
|
class PairedDataset(data.Dataset):
'A dataset class for paired images\n e.g. corresponding real and manipulated images\n '
def __init__(self, opt, im_path_real, im_path_fake, is_val=False, with_mask=False):
'Initialize this dataset class.\n\n Parameters:\n opt -- experiment op... |
class UnpairedDataset(data.Dataset):
'A dataset class for loading images within a single folder\n '
def __init__(self, opt, im_path, is_val=False):
'Initialize this dataset class.\n\n Parameters:\n opt -- experiment options\n im_path -- path to folder of images\n ... |
def get_available_masks():
' Return a list of the available masks for cli '
masks = sorted([name for (name, obj) in inspect.getmembers(sys.modules[__name__]) if (inspect.isclass(obj) and (name != 'Mask'))])
masks.append('none')
return masks
|
def get_default_mask():
' Set the default mask for cli '
masks = get_available_masks()
default = 'dfl_full'
default = (default if (default in masks) else masks[0])
return default
|
class Mask():
' Parent class for masks\n the output mask will be <mask_type>.mask\n channels: 1, 3 or 4:\n 1 - Returns a single channel mask\n 3 - Returns a 3 channel mask\n 4 - Returns the original image with the mask in the alpha channel '
... |
class dfl_full(Mask):
' DFL facial mask '
def build_mask(self):
mask = np.zeros((self.face.shape[0:2] + (1,)), dtype=np.float32)
nose_ridge = (self.landmarks[27:31], self.landmarks[33:34])
jaw = (self.landmarks[0:17], self.landmarks[48:68], self.landmarks[0:1], self.landmarks[8:9], se... |
class components(Mask):
' Component model mask '
def build_mask(self):
mask = np.zeros((self.face.shape[0:2] + (1,)), dtype=np.float32)
r_jaw = (self.landmarks[0:9], self.landmarks[17:18])
l_jaw = (self.landmarks[8:17], self.landmarks[26:27])
r_cheek = (self.landmarks[17:20], ... |
class extended(Mask):
' Extended mask\n Based on components mask. Attempts to extend the eyebrow points up the forehead\n '
def build_mask(self):
mask = np.zeros((self.face.shape[0:2] + (1,)), dtype=np.float32)
landmarks = self.landmarks.copy()
ml_pnt = ((landmarks[36] + lan... |
class facehull(Mask):
' Basic face hull mask '
def build_mask(self):
mask = np.zeros((self.face.shape[0:2] + (1,)), dtype=np.float32)
hull = cv2.convexHull(np.array(self.landmarks).reshape(((- 1), 2)))
cv2.fillConvexPoly(mask, hull, 255.0, lineType=cv2.LINE_AA)
return mask
|
class random_components(Mask):
' Extended mask\n Based on components mask. Attempts to extend the eyebrow points up the forehead\n '
def build_mask(self):
mask = np.zeros((self.face.shape[0:2] + (1,)), dtype=np.float32)
landmarks = self.landmarks.copy()
ml_pnt = ((landmarks[... |
def simple_transform():
t = Compose([Resize(256, 256)])
return t
|
def strong_aug_pixel(p=0.5):
print('[DATA]: strong aug pixel')
from albumentations import Transpose, ShiftScaleRotate, Blur, OpticalDistortion, GridDistortion, HueSaturationValue, MultiplicativeNoise, IAAAdditiveGaussianNoise, GaussNoise, MotionBlur, MedianBlur, RandomBrightnessContrast, IAAPiecewiseAffine, I... |
def pixel_aug(p=0.5):
print('[DATA]: pixel aug')
from albumentations import JpegCompression, Blur, Downscale, CLAHE, HueSaturationValue, RandomBrightnessContrast, IAAAdditiveGaussianNoise, GaussNoise, GaussianBlur, MedianBlur, MotionBlur, Compose, OneOf
from random import sample, randint, uniform
retu... |
def spatial_aug(p=0.5):
print('[DATA] spatial aug')
from albumentations import GridDropout, RandomResizedCrop, Rotate, HorizontalFlip, Compose
aug = Compose([GridDropout(holes_number_x=3, holes_number_y=3, random_offset=True, p=0.5), RandomResizedCrop(256, 256, scale=(0.7, 1.0), p=1.0), HorizontalFlip(p=0... |
def pixel_aug_mild(p=0.5):
print('[DATA]: pixel aug mild')
from albumentations import JpegCompression, Blur, Downscale, CLAHE, HueSaturationValue, RandomBrightnessContrast, IAAAdditiveGaussianNoise, GaussNoise, GaussianBlur, MedianBlur, MotionBlur, Compose, OneOf
from random import sample, randint, unifor... |
class Augmentator():
def __init__(self, augment_fn=''):
if (augment_fn == 'pixel_aug'):
self.augment_fn = pixel_aug()
elif (augment_fn == 'simple'):
self.augment_fn = simple_transform()
elif (augment_fn == 'pixel_mild'):
self.augment_fn = pixel_aug_mild... |
def data_transform(size=256, normalize=True):
if normalize:
t = Compose([Resize(size, size), Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ToTensor()])
else:
t = Compose([Resize(size, size), ToTensor()])
return t
|
def color_transfer(source, target, clip=True, preserve_paper=True, mask=None):
'\n\tTransfers the color distribution from the source to the target\n\timage using the mean and standard deviations of the L*a*b*\n\tcolor space.\n\tThis implementation is (loosely) based on to the "Color Transfer\n\tbetween Images" pa... |
def image_stats(image, mask=None):
'\n\tParameters:\n\t-------\n\timage: NumPy array\n\t\tOpenCV image in L*a*b* color space\n\tReturns:\n\t-------\n\tTuple of mean and standard deviations for the L*, a*, and b*\n\tchannels, respectively\n\t'
(l, a, b) = cv2.split(image)
if (mask is not None):
(l,... |
def _min_max_scale(arr, new_range=(0, 255)):
'\n\tPerform min-max scaling to a NumPy array\n\tParameters:\n\t-------\n\tarr: NumPy array to be scaled to [new_min, new_max] range\n\tnew_range: tuple of form (min, max) specifying range of\n\t\ttransformed array\n\tReturns:\n\t-------\n\tNumPy array that has been sc... |
def _scale_array(arr, clip=True):
'\n\tTrim NumPy array values to be in [0, 255] range with option of\n\tclipping or scaling.\n\tParameters:\n\t-------\n\tarr: array to be trimmed to [0, 255] range\n\tclip: should array be scaled by np.clip? if False then input\n\t\tarray will be min-max scaled to range\n\t\t[max... |
def colorTransfer(src, dst, mask):
transferredDst = np.copy(dst)
maskIndices = np.where((mask != 0))
maskedSrc = src[(maskIndices[0], maskIndices[1])].astype(np.int32)
maskedDst = dst[(maskIndices[0], maskIndices[1])].astype(np.int32)
meanSrc = np.mean(maskedSrc, axis=0)
meanDst = np.mean(mask... |
def color_transfer(source, target, clip=None, preserve_paper=None, mask=None):
return colorTransfer(src=source, dst=target, mask=mask)
|
def mkdir_p(path):
try:
os.makedirs(os.path.abspath(path))
except OSError as exc:
if ((exc.errno == errno.EEXIST) and os.path.isdir(path)):
pass
else:
raise
|
def files(path, exts=None, r=False):
if os.path.isfile(path):
if ((exts is None) or ((exts is not None) and (splitext(path)[(- 1)] in exts))):
(yield path)
elif os.path.isdir(path):
for (p, _, fs) in os.walk(path):
for f in sorted(fs):
if (exts is not No... |
def rect_to_bb(rect):
x = rect.left()
y = rect.top()
w = (rect.right() - x)
h = (rect.bottom() - y)
return (x, y, w, h)
|
def shape_to_np(shape, dtype='int'):
if isinstance(shape, np.ndarray):
return shape.astype(dtype)
coords = np.zeros((68, 2), dtype=dtype)
for i in range(0, 68):
coords[i] = (shape.part(i).x, shape.part(i).y)
return coords
|
def shape_to_np(shape, dtype='int'):
coords = np.zeros((68, 2), dtype=dtype)
for i in range(0, 68):
coords[i] = (shape.part(i).x, shape.part(i).y)
return coords
|
def rot90(v):
return np.array([(- v[1]), v[0]])
|
def find_face_cvhull(im):
gray = cv2.cvtColor(im, cv2.COLOR_RGB2GRAY)
rects = detector(gray, 1)
if (not rects):
return None
shape = predictor(gray, rects[0])
shape = shape_to_np(shape)
hull = cv2.convexHull(shape)
return hull
|
def find_face_landmark(im):
gray = cv2.cvtColor(im, cv2.COLOR_RGB2GRAY)
rects = detector(gray, 1)
if (not rects):
return None
shape = predictor(gray, rects[0])
shape = shape_to_np(shape)
return shape
|
class Masks4D(object):
def __call__(self, masks):
first_w = True
first_h = True
first_c = True
for (k, mask) in enumerate(masks):
(h, w) = mask.shape
real_mask = torch.unsqueeze(torch.unsqueeze(torch.unsqueeze(mask, 0), 0), 0)
for (i, mask_h) in... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--model_path', help='path to pretrained model')
parser.add_argument('--pretrained', help='downloads pretrained model [celebahq]')
parser.add_argument('--output_path', required=True, help='path to save generated samples')
par... |
def sample(opt):
tf.InteractiveSession()
assert (opt.model_path or opt.pretrained), 'specify weights path or pretrained model'
if opt.model_path:
raise NotImplementedError
elif opt.pretrained:
assert (opt.pretrained == 'celebahq')
sys.path.append('resources/glow/demo')
... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--model_path', required=True, help='path to pretrained model')
parser.add_argument('--output_path', required=True, help='path to save generated samples')
parser.add_argument('--num_samples', type=int, default=100, help='number o... |
def sample(opt):
tf.InteractiveSession()
with open(opt.model_path, 'rb') as file:
(G, D, Gs) = pickle.load(file)
rng = np.random.RandomState(opt.seed)
for batch_start in tqdm(range(0, opt.num_samples, opt.batch_size)):
bs = (min(opt.num_samples, (batch_start + opt.batch_size)) - batch_... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--model_path', help='path to pretrained model')
parser.add_argument('--pretrained', help='downloads pretrained model [ffhq, celebahq]')
parser.add_argument('--output_path', required=True, help='path to save generated samples')
... |
def sample(opt):
tf.InteractiveSession()
assert (opt.model_path or opt.pretrained), 'specify weights path or pretrained model'
if opt.model_path:
with open(opt.model_path, 'rb') as file:
(G, D, Gs) = pickle.load(file)
elif opt.pretrained:
urls = dict(ffhq='https://drive.goo... |
def get_transform(opt, for_val=False):
transform_list = []
if for_val:
transform_list.append(transforms.Resize(opt.loadSize, interpolation=PIL.Image.LANCZOS))
transform_list.append(transforms.CenterCrop(opt.loadSize))
transform_list.append(transforms.ToTensor())
else:
trans... |
def get_mask_transform(opt, for_val=False):
transform_list = []
transform_list.append(transforms.ToTensor())
transform = transforms.Compose(transform_list)
return transform
|
class AllAugmentations(object):
def __init__(self):
import albumentations
self.transform = albumentations.Compose([albumentations.Blur(blur_limit=3), albumentations.JpegCompression(quality_lower=30, quality_upper=100, p=0.5), albumentations.RandomBrightnessContrast(), albumentations.augmentations... |
class JPEGCompression(object):
def __init__(self, level):
import albumentations as A
self.level = level
self.transform = A.augmentations.transforms.JpegCompression(p=1)
def __call__(self, image):
image_np = np.array(image)
image_out = self.transform.apply(image_np, qu... |
class Blur(object):
def __init__(self, level):
import albumentations as A
self.level = level
self.transform = A.Blur(blur_limit=(self.level, self.level), always_apply=True)
def __call__(self, image):
image_np = np.array(image)
augmented = self.transform(image=image_np... |
class Gamma(object):
def __init__(self, level):
import albumentations as A
self.level = level
self.transform = A.augmentations.transforms.RandomGamma(p=1)
def __call__(self, image):
image_np = np.array(image)
image_out = self.transform.apply(image_np, gamma=(self.leve... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.