code
stringlengths
17
6.64M
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...
class UnpairedMaskDataset(data.Dataset): 'A dataset class for loading images within a single folder\n ' def __init__(self, opt, im_path, label, is_val=False): 'Initialize this dataset class.\n\n Parameters:\n opt -- experiment options\n im_path -- path to folder of ima...
class Struct(): def __init__(self, **entries): self.__dict__.update(entries)
def find_model_using_name(model_name): model_filename = (('models.' + model_name) + '_model') modellib = importlib.import_module(model_filename) model = None target_model_name = (model_name.replace('_', '') + 'model') for (name, cls) in modellib.__dict__.items(): if ((name.lower() == targe...
def get_option_setter(model_name): model_class = find_model_using_name(model_name) return model_class.modify_commandline_options
def create_model(opt, **kwargs): model = find_model_using_name(opt.model) instance = model(opt, **kwargs) print(('model [%s] was created' % instance.name())) return instance
class BaseModel(): @staticmethod def modify_commandline_options(parser): networks.modify_commandline_options(parser) return parser def __init__(self, opt): self.opt = opt self.gpu_ids = opt.gpu_ids self.isTrain = opt.isTrain self.device = (torch.device('cu...
def compute_mhsa(q, k, v, scale_factor=1, mask=None): scaled_dot_prod = (torch.einsum('... i d , ... j d -> ... i j', q, k) * scale_factor) if (mask is not None): assert (mask.shape == scaled_dot_prod.shape[2:]) scaled_dot_prod = scaled_dot_prod.masked_fill(mask, (- np.inf)) attention = to...
class MultiHeadSelfAttention(nn.Module): def __init__(self, dim, heads=8, dim_head=None): "\n Implementation of multi-head attention layer of the original transformer model.\n einsum and einops.rearrange is used whenever possible\n Args:\n dim: token's dimension, i.e. word...
class NLBlockND(nn.Module): def __init__(self, in_channels=256): "Implementation of Non-Local Block with 4 different pairwise functions but doesn't include subsampling trick\n args:\n in_channels: original channel size (1024 in the paper)\n inter_channels: channel size inside...
def make_patch_resnet(depth, layername, num_classes=2, extra_output=None): def change_out(layers): (ind, layer) = [(i, l) for (i, (n, l)) in enumerate(layers) if (n == layername)][0] if layername.startswith('layer'): bn = list(layer.modules())[((- 1) if (depth < 50) else (- 2))] ...
def make_patch_xceptionnet(layername, num_classes=2, extra_output=None): def change_out(layers): (ind, layer) = [(i, l) for (i, (n, l)) in enumerate(layers) if (n == layername)][0] if layername.startswith('block'): module_list = list(layer.modules()) bn = module_list[(- 1)...
def make_pcl(backbone='xception', layername='block3', input_size=128): if (backbone == 'xception'): channels = [128, 256, 728, 728, 728, 728, 728, 728, 728, 728, 728, 1024] (b1, b2, b3, b12) = (int((input_size / 4)), int((input_size / 8)), int((input_size / 16)), int((input_size / 32))) ou...
def make_xceptionnet_long(): from . import xception def change_out(layers): channels = [3, 32, 64, 128, 256, 728, 728, 728, 728, 728, 728, 728, 728, 728, 1024, 1536, 2048] (ind, layer) = [(i, l) for (i, (n, l)) in enumerate(layers) if (n == 'block2')][0] new_layers = [('pblock3', xcep...
class CustomResNet(nn.Module): "\n Customizable ResNet, compatible with pytorch's resnet, but:\n * The top-level sequence of modules can be modified to add\n or remove or alter layers.\n * Extra outputs can be produced, to allow backprop and access\n to internal features.\n * Pooling is...
class CustomXceptionNet(nn.Module): '\n Customizable Xceptionnet, compatible with https://github.com/Cadene/pretrained-models.pytorch/blob/master/pretrainedmodels/models/xception.py\n but:\n * The top-level sequence of modules can be modified to add\n or remove or alter layers.\n * Extra outpu...
class Vectorize(nn.Module): def __init__(self): super(Vectorize, self).__init__() def forward(self, x): x = x.view(x.size(0), int(numpy.prod(x.size()[1:]))) return x
class GlobalAveragePool2d(nn.Module): def __init__(self): super(GlobalAveragePool2d, self).__init__() def forward(self, x): x = torch.mean(x.view(x.size(0), x.size(1), (- 1)), dim=2) return x
def get_scheduler(optimizer, opt): if (opt.lr_policy == 'plateau'): scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, mode='max', factor=0.1, threshold=0.0001, patience=opt.patience, eps=1e-06) elif (opt.lr_policy == 'constant'): scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, mode='...
def init_weights(net, init_type='xavier', gain=0.02): def init_func(m): classname = m.__class__.__name__ if (hasattr(m, 'weight') and ((classname.find('Conv') != (- 1)) or (classname.find('Linear') != (- 1)))): if (init_type == 'normal'): init.normal_(m.weight.data, 0....
def init_net(net, init_type='xavier', gpu_ids=[]): if (len(gpu_ids) > 0): assert torch.cuda.is_available() net.to(gpu_ids[0]) net = torch.nn.DataParallel(net, gpu_ids) if (init_type is None): return net init_weights(net, init_type) return net
def modify_commandline_options(parser): (opt, _) = parser.parse_known_args() if ('xception' in opt.which_model_netD): parser.set_defaults(loadSize=333, fineSize=299) elif ('resnet' in opt.which_model_netD): parser.set_defaults(loadSize=256, fineSize=224) else: raise NotImplemen...
def define_D(which_model_netD, init_type, gpu_ids=[]): if ('resnet' in which_model_netD): from torchvision.models import resnet model = getattr(resnet, which_model_netD) netD = model(pretrained=False, num_classes=2) elif ('xception' in which_model_netD): from . import xception ...
def define_patch_D(which_model_netD, init_type, gpu_ids=[]): if which_model_netD.startswith('resnet'): from . import customnet splits = which_model_netD.split('_') depth = int(splits[0][6:]) layer = splits[1] if (len(splits) == 2): netD = customnet.make_patch_re...
def define_PCL(which_model_netD, init_type, gpu_ids=[], input_size=128): if which_model_netD.startswith('resnet'): from . import customnet backbone = which_model_netD.split('_')[0] layer = which_model_netD.split('_')[1] (netPCL, out_ch) = customnet.make_pcl(backbone=backbone, layer...
class WideNet(nn.Module): def __init__(self, kernel_size=7, dilation=1): super().__init__() sequence = [nn.Conv2d(3, 256, kernel_size=kernel_size, dilation=dilation, stride=2, padding=(kernel_size // 2), bias=False), nn.BatchNorm2d(256), nn.ReLU(inplace=True), nn.MaxPool2d(3, stride=2, padding=1)...
class SeparableConv2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=1, stride=1, padding=0, dilation=1, bias=False): super(SeparableConv2d, self).__init__() self.conv1 = nn.Conv2d(in_channels, in_channels, kernel_size, stride, padding, dilation, groups=in_channels, bias=bi...
class PixelBlock(nn.Module): def __init__(self, in_filters, out_filters, reps, strides=1, start_with_relu=True, grow_first=True): super(PixelBlock, self).__init__() assert (strides == 1) if ((out_filters != in_filters) or (strides != 1)): self.skip = nn.Conv2d(in_filters, out_...
class Block(nn.Module): def __init__(self, in_filters, out_filters, reps, strides=1, start_with_relu=True, grow_first=True): super(Block, self).__init__() if ((out_filters != in_filters) or (strides != 1)): self.skip = nn.Conv2d(in_filters, out_filters, 1, stride=strides, bias=False) ...
class Xception(nn.Module): '\n Xception optimized for the ImageNet dataset, as specified in\n https://arxiv.org/pdf/1610.02357.pdf\n ' def __init__(self, num_classes=1000): ' Constructor\n Args:\n num_classes: number of classes\n ' super(Xception, self).__ini...
def xception(num_classes=1000, pretrained='imagenet'): model = Xception(num_classes=num_classes) if pretrained: settings = pretrained_settings['xception'][pretrained] model = Xception(num_classes=num_classes) pretrained_state = model_zoo.load_url(settings['url']) model_state = ...
class BaseOptions(options.Options): def __init__(self, print_opt=True): options.Options.__init__(self) self.isTrain = False self.print_opt = print_opt parser = self.parser parser.add_argument('--model', type=str, default='basic_discriminator', help='chooses which model to ...
class TestOptions(BaseOptions): def __init__(self): BaseOptions.__init__(self, print_opt=False) parser = self.parser parser.add_argument('--train_config', type=argparse.FileType(mode='r'), required=True, help='config file saved from model training') parser.add_argument('--partitio...
class TrainOptions(BaseOptions): def __init__(self, print_opt=True): BaseOptions.__init__(self, print_opt) parser = self.parser parser.add_argument('--display_freq', type=int, default=1000, help='frequency of showing training results visualization') parser.add_argument('--print_fr...
def train(opt): torch.manual_seed(opt.seed) if (opt.model == 'patch_inconsistency_discriminator'): WITH_MASK = True else: WITH_MASK = False if (not WITH_MASK): dset = PairedDataset(opt, os.path.join(opt.real_im_path, 'train'), os.path.join(opt.fake_im_path, 'train'), with_mask=...
def validate(model, opt): logging.info('Starting evaluation loop ...') model.reset() assert (not model.net_D.training) if (opt.model == 'patch_inconsistency_discriminator'): WITH_MASK = True else: WITH_MASK = False if (not WITH_MASK): val_dset = PairedDataset(opt, os.pa...
def train(opt): torch.manual_seed(opt.seed) dset = I2GDataset(opt, os.path.join(opt.real_im_path, 'train')) dset.get32frames() dl = DataLoader(dset, batch_size=opt.batch_size, num_workers=opt.nThreads, pin_memory=False, shuffle=True) assert (opt.fake_class_id in [0, 1]) fake_label = opt.fake_c...
def validate(model, opt): logging.info('Starting evaluation loop ...') model.reset() assert (not model.net_D.training) val_dset = I2GDataset(opt, os.path.join(opt.real_im_path, 'val'), is_val=True) val_dset.get32frames() val_dl = DataLoader(val_dset, batch_size=opt.batch_size, num_workers=opt....
class TqdmLoggingHandler(logging.Handler): def __init__(self, level=logging.NOTSET): super(self.__class__, self).__init__(level) def emit(self, record): try: msg = self.format(record) tqdm.tqdm.write(msg) self.flush() except (KeyboardInterrupt, Sys...
class MultiLineFormatter(logging.Formatter): def __init__(self, fmt=None, datefmt=None, style='%'): assert (style == '%') super(MultiLineFormatter, self).__init__(fmt, datefmt, style) self.multiline_fmt = fmt def format(self, record): "\n This is mostly the same as log...
def handle_exception(exc_type, exc_value, exc_traceback): if issubclass(exc_type, KeyboardInterrupt): sys.__excepthook__(exc_type, exc_value, exc_traceback) return logging.error('Uncaught exception', exc_info=(exc_type, exc_value, exc_traceback))
def configure(logging_file, log_level=logging.INFO, level_prefix='', prefix='', write_to_stdout=True, append=True): logging.getLogger().setLevel(logging.INFO) sys.excepthook = handle_exception handlers = [] if write_to_stdout: handlers.append(TqdmLoggingHandler()) delayed_logging = [] ...
@contextlib.contextmanager def disable(level): prev_level = logging.getLogger().getEffectiveLevel() logging.disable(level) (yield) logging.disable(prev_level)
class Options(): def __init__(self): self.parser = parser = argparse.ArgumentParser() self.parser.add_argument('config_file', nargs='?', type=argparse.FileType(mode='r')) self.parser.add_argument('--overwrite_config', action='store_true', help='overwrite config files if they exist') ...
def verbose(verbose): '\n Sets default verbosity level. Set to True to see progress bars.\n ' global default_verbosity default_verbosity = verbose
def post(**kwargs): '\n When within a progress loop, pbar.post(k=str) will display\n the given k=str status on the right-hand-side of the progress\n status bar. If not within a visible progress bar, does nothing.\n ' innermost = innermost_tqdm() if innermost: innermost.set_postfix(**k...
def desc(desc): '\n When within a progress loop, pbar.desc(str) changes the\n left-hand-side description of the loop toe the given description.\n ' innermost = innermost_tqdm() if innermost: innermost.set_description(str(desc))
def descnext(desc): '\n Called before starting a progress loop, pbar.descnext(str)\n sets the description text that will be used in the following loop.\n ' global next_description if ((not default_verbosity) or (tqdm is None)): return next_description = desc
def print(*args): '\n When within a progress loop, will print above the progress loop.\n ' global next_description next_description = None if default_verbosity: msg = ' '.join((str(s) for s in args)) if (tqdm is None): print(msg) else: tqdm.write(m...
def tqdm_terminal(it, *args, **kwargs): '\n Some settings for tqdm that make it run better in resizable terminals.\n ' return tqdm(it, *args, dynamic_ncols=True, ascii=True, leave=(not innermost_tqdm()), **kwargs)
def in_notebook(): '\n True if running inside a Jupyter notebook.\n ' try: shell = get_ipython().__class__.__name__ if (shell == 'ZMQInteractiveShell'): return True elif (shell == 'TerminalInteractiveShell'): return False else: return F...
def innermost_tqdm(): '\n Returns the innermost active tqdm progress loop on the stack.\n ' if (hasattr(tqdm, '_instances') and (len(tqdm._instances) > 0)): return max(tqdm._instances, key=(lambda x: x.pos)) else: return None
def __call__(x, *args, **kwargs): '\n Invokes a progress function that can wrap iterators to print\n progress messages, if verbose is True.\n \n If verbose is False or tqdm is unavailable, then a quiet\n non-printing identity function is used.\n\n verbose can also be set to a spefific progress fu...
class CallableModule(types.ModuleType): def __init__(self): types.ModuleType.__init__(self, __name__) self.__dict__.update(sys.modules[__name__].__dict__) def __call__(self, x, *args, **kwargs): return __call__(x, *args, **kwargs)
def exit_if_job_done(directory, redo=False, force=False, verbose=True): if pidfile_taken(os.path.join(directory, 'lockfile.pid'), force=force, verbose=verbose): sys.exit(0) donefile = os.path.join(directory, 'done.txt') if os.path.isfile(donefile): with open(donefile) as f: msg...
def mark_job_done(directory): with open(os.path.join(directory, 'done.txt'), 'w') as f: f.write(('done by %d@%s %s at %s' % (os.getpid(), socket.gethostname(), os.getenv('STY', ''), time.strftime('%c'))))
def pidfile_taken(path, verbose=False, force=False): "\n Usage. To grab an exclusive lock for the remaining duration of the\n current process (and exit if another process already has the lock),\n do this:\n\n if pidfile_taken('job_423/lockfile.pid', verbose=True):\n sys.exit(0)\n\n To do a ...
def delete_pidfile(lockfile, path): '\n Runs at exit after pidfile_taken succeeds.\n ' if (lockfile is not None): try: lockfile.close() except: pass try: os.unlink(path) except: pass
def blocks(obj, space=''): return IPython.display.HTML(space.join(blocks_tags(obj)))
def rows(obj, space=''): return IPython.display.HTML(space.join(rows_tags(obj)))
def rows_tags(obj): if isinstance(obj, dict): obj = obj.items() results = [] results.append('<table style="display:inline-table">') for row in obj: results.append('<tr style="padding:0">') for item in row: results.append(('<td style="text-align:left; vertical-align:...