python_code
stringlengths
0
679k
repo_name
stringlengths
9
41
file_path
stringlengths
6
149
# Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved. # # This document should comply with PEP-8 Style Guide # Linter: pylint """ Interface for setting up and creating a model in Tensorflow. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging import tensorflow as tf from tensorflow.python.framework import ops # Local imports import tf_data import utils as digits from utils import model_property logging.basicConfig(format='%(asctime)s [%(levelname)s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO) # Constants SUMMARIZE_TOWER_STATS = False # from # https://github.com/tensorflow/tensorflow/blob/master/tensorflow/models/image/cifar10/cifar10_multi_gpu_train.py def average_gradients(tower_grads): """Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over individual gradients. The inner list is over the gradient calculation for each tower. Returns: List of pairs of (gradient, variable) where the gradient has been averaged across all towers. """ with tf.name_scope('gradient_average'): average_grads = [] for grad_and_vars in zip(*tower_grads): # Note that each grad_and_vars looks like the following: # ((grad0_gpu0, var0_gpu0), ... , (grad0_gpuN, var0_gpuN)) grads = [] for g, _ in grad_and_vars: # Add 0 dimension to the gradients to represent the tower. expanded_g = tf.expand_dims(g, 0) # Append on a 'tower' dimension which we will average over below. grads.append(expanded_g) # Average over the 'tower' dimension. grads_transformed = tf.concat(grads, 0) grads_transformed = tf.reduce_mean(grads_transformed, 0) # Keep in mind that the Variables are redundant because they are shared # across towers. So .. we will just return the first tower's pointer to # the Variable. v = grad_and_vars[0][1] grad_and_var = (grads_transformed, v) average_grads.append(grad_and_var) return average_grads class Model(object): """ Wrapper around the actual tensorflow workflow process. This is structured in a way that the user should only care about creating the model while using the DIGITS UI to select the optimizer and other options. This class is executed to start a tensorflow workflow. """ def __init__(self, stage, croplen, nclasses, optimization=None, momentum=None, reuse_variable=False): self.stage = stage self.croplen = croplen self.nclasses = nclasses self.dataloader = None self.queue_coord = None self.queue_threads = None self._optimization = optimization self._momentum = momentum self.summaries = [] self.towers = [] self._train = None self._reuse = reuse_variable # Touch to initialize # if optimization: # self.learning_rate # self.global_step # self.optimizer def create_dataloader(self, db_path): self.dataloader = tf_data.LoaderFactory.set_source(db_path, is_inference=(self.stage == digits.STAGE_INF)) # @TODO(tzaman) communicate the dataloader summaries to our Model summary list self.dataloader.stage = self.stage self.dataloader.croplen = self.croplen self.dataloader.nclasses = self.nclasses def init_dataloader(self): with tf.device('/cpu:0'): with tf.name_scope(digits.GraphKeys.LOADER): self.dataloader.create_input_pipeline() def create_model(self, obj_UserModel, stage_scope, batch_x=None): if batch_x is None: self.init_dataloader() batch_x = self.dataloader.batch_x if self.stage != digits.STAGE_INF: batch_y = self.dataloader.batch_y else: assert self.stage == digits.STAGE_INF batch_x = batch_x available_devices = digits.get_available_gpus() if not available_devices: available_devices.append('/cpu:0') # available_devices = ['/gpu:0', '/gpu:1'] # DEVELOPMENT : virtual multi-gpu # Split the batch over the batch dimension over the number of available gpu's if len(available_devices) == 1: batch_x_split = [batch_x] if self.stage != digits.STAGE_INF: # Has no labels batch_y_split = [batch_y] else: with tf.name_scope('parallelize'): # Split them up batch_x_split = tf.split(batch_x, len(available_devices), 0, name='split_batch') if self.stage != digits.STAGE_INF: # Has no labels batch_y_split = tf.split(batch_y, len(available_devices), 0, name='split_batch') # Run the user model through the build_model function that should be filled in grad_towers = [] for dev_i, dev_name in enumerate(available_devices): with tf.device(dev_name): current_scope = stage_scope if len(available_devices) == 1 else ('tower_%d' % dev_i) with tf.name_scope(current_scope) as scope_tower: if self.stage != digits.STAGE_INF: tower_model = self.add_tower(obj_tower=obj_UserModel, x=batch_x_split[dev_i], y=batch_y_split[dev_i]) else: tower_model = self.add_tower(obj_tower=obj_UserModel, x=batch_x_split[dev_i], y=None) with tf.variable_scope(digits.GraphKeys.MODEL, reuse=dev_i > 0 or self._reuse): tower_model.inference # touch to initialize # Reuse the variables in this scope for the next tower/device tf.get_variable_scope().reuse_variables() if self.stage == digits.STAGE_INF: # For inferencing we will only use the inference part of the graph continue with tf.name_scope(digits.GraphKeys.LOSS): for loss in self.get_tower_losses(tower_model): tf.add_to_collection(digits.GraphKeys.LOSSES, loss['loss']) # Assemble all made within this scope so far. The user can add custom # losses to the digits.GraphKeys.LOSSES collection losses = tf.get_collection(digits.GraphKeys.LOSSES, scope=scope_tower) losses += ops.get_collection(ops.GraphKeys.REGULARIZATION_LOSSES, scope=None) tower_loss = tf.add_n(losses, name='loss') self.summaries.append(tf.summary.scalar(tower_loss.op.name, tower_loss)) if self.stage == digits.STAGE_TRAIN: grad_tower_losses = [] for loss in self.get_tower_losses(tower_model): grad_tower_loss = self.optimizer.compute_gradients(loss['loss'], loss['vars']) grad_tower_loss = tower_model.gradientUpdate(grad_tower_loss) grad_tower_losses.append(grad_tower_loss) grad_towers.append(grad_tower_losses) # Assemble and average the gradients from all towers if self.stage == digits.STAGE_TRAIN: n_gpus = len(available_devices) if n_gpus == 1: grad_averages = grad_towers[0] else: with tf.device(available_devices[0]): n_losses = len(grad_towers[0]) grad_averages = [] for loss in xrange(n_losses): grad_averages.append(average_gradients([grad_towers[gpu][loss] for gpu in xrange(n_gpus)])) apply_gradient_ops = [] for grad_avg in grad_averages: apply_gradient_ops.append(self.optimizer.apply_gradients(grad_avg, global_step=self.global_step)) self._train = apply_gradient_ops def start_queue_runners(self, sess): logging.info('Starting queue runners (%s)', self.stage) # Distinguish the queue runner collection (for easily obtaining them by collection key) queue_runners = tf.get_collection(tf.GraphKeys.QUEUE_RUNNERS, scope=self.stage+'.*') for qr in queue_runners: if self.stage in qr.name: tf.add_to_collection(digits.GraphKeys.QUEUE_RUNNERS, qr) self.queue_coord = tf.train.Coordinator() self.queue_threads = tf.train.start_queue_runners(sess=sess, coord=self.queue_coord, collection=digits.GraphKeys.QUEUE_RUNNERS) logging.info('Queue runners started (%s)', self.stage) def __del__(self): # Destructor if self.queue_coord: # Close and terminate the queues self.queue_coord.request_stop() self.queue_coord.join(self.queue_threads) def add_tower(self, obj_tower, x, y): is_training = self.stage == digits.STAGE_TRAIN is_inference = self.stage == digits.STAGE_INF input_shape = self.dataloader.get_shape() tower = obj_tower(x, y, input_shape, self.nclasses, is_training, is_inference) self.towers.append(tower) return tower @model_property def train(self): return self._train @model_property def summary(self): """ Merge train summaries """ for t in self.towers: self.summaries += t.summaries if not len(self.summaries): logging.error("No summaries defined. Please define at least one summary.") exit(-1) return tf.summary.merge(self.summaries) @model_property def global_step(self): # Force global_step on the CPU, becaues the GPU's first step will end at 0 instead of 1. with tf.device('/cpu:0'): return tf.get_variable('global_step', [], initializer=tf.constant_initializer(0), trainable=False) @model_property def learning_rate(self): # @TODO(tzaman): the learning rate is a function of the global step, so we could # define it entirely in tf ops, instead of a placeholder and feeding. with tf.device('/cpu:0'): lr = tf.placeholder(tf.float32, shape=[], name='learning_rate') self.summaries.append(tf.summary.scalar('lr', lr)) return lr @model_property def optimizer(self): logging.info("Optimizer:%s", self._optimization) if self._optimization == 'sgd': return tf.train.GradientDescentOptimizer(learning_rate=self.learning_rate) elif self._optimization == 'adadelta': return tf.train.AdadeltaOptimizer(learning_rate=self.learning_rate) elif self._optimization == 'adagrad': return tf.train.AdagradOptimizer(learning_rate=self.learning_rate) elif self._optimization == 'adagradda': return tf.train.AdagradDAOptimizer(learning_rate=self.learning_rate, global_step=self.global_step) elif self._optimization == 'momentum': return tf.train.MomentumOptimizer(learning_rate=self.learning_rate, momentum=self._momentum) elif self._optimization == 'adam': return tf.train.AdamOptimizer(learning_rate=self.learning_rate) elif self._optimization == 'ftrl': return tf.train.FtrlOptimizer(learning_rate=self.learning_rate) elif self._optimization == 'rmsprop': return tf.train.RMSPropOptimizer(learning_rate=self.learning_rate, momentum=self._momentum) else: logging.error("Invalid optimization flag %s", self._optimization) exit(-1) def get_tower_losses(self, tower): """ Return list of losses If user-defined model returns only one loss then this is encapsulated into the expected list of dicts structure """ if isinstance(tower.loss, list): return tower.loss else: return [{'loss': tower.loss, 'vars': tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)}] class Tower(object): def __init__(self, x, y, input_shape, nclasses, is_training, is_inference): self.input_shape = input_shape self.nclasses = nclasses self.is_training = is_training self.is_inference = is_inference self.summaries = [] self.x = x self.y = y self.train = None def gradientUpdate(self, grad): return grad
DIGITS-master
digits/tools/tensorflow/model.py
# Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved. # # This document should comply with PEP-8 Style Guide # Linter: pylint """ Digits default Tensorflow Ops as helper functions. """ import functools import tensorflow as tf from tensorflow.python.client import device_lib STAGE_TRAIN = 'train' STAGE_VAL = 'val' STAGE_INF = 'inf' class GraphKeys(object): TEMPLATE = "model" QUEUE_RUNNERS = "queue_runner" MODEL = "model" LOSS = "loss" # The namescope LOSSES = "losses" # The collection LOADER = "data" def model_property(function): # From https://danijar.com/structuring-your-tensorflow-models/ attribute = '_cache_' + function.__name__ @property @functools.wraps(function) def decorator(self): if not hasattr(self, attribute): setattr(self, attribute, function(self)) return getattr(self, attribute) return decorator def classification_loss(pred, y): """ Definition of the loss for regular classification """ ssoftmax = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=pred, labels=y, name='cross_entropy_single') return tf.reduce_mean(ssoftmax, name='cross_entropy_batch') def mse_loss(lhs, rhs): return tf.reduce_mean(tf.square(lhs - rhs)) def constrastive_loss(lhs, rhs, y, margin=1.0): """ Contrastive loss confirming to the Caffe definition """ d = tf.reduce_sum(tf.square(tf.subtract(lhs, rhs)), 1) d_sqrt = tf.sqrt(1e-6 + d) loss = (y * d) + ((1 - y) * tf.square(tf.maximum(margin - d_sqrt, 0))) return tf.reduce_mean(loss) # Note: constant component removed (/2) def classification_accuracy_top_n(pred, y, top_n): single_acc_t = tf.nn.in_top_k(pred, y, top_n) return tf.reduce_mean(tf.cast(single_acc_t, tf.float32), name='accuracy_top_%d' % top_n) def classification_accuracy(pred, y): """ Default definition of accuracy. Something is considered accurate if and only if a true label exactly matches the highest value in the prediction vector. """ single_acc = tf.equal(y, tf.argmax(pred, 1)) return tf.reduce_mean(tf.cast(single_acc, tf.float32), name='accuracy') def nhwc_to_nchw(x): return tf.transpose(x, [0, 3, 1, 2]) def hwc_to_chw(x): return tf.transpose(x, [2, 0, 1]) def nchw_to_nhwc(x): return tf.transpose(x, [0, 2, 3, 1]) def chw_to_hwc(x): return tf.transpose(x, [1, 2, 0]) def bgr_to_rgb(x): return tf.reverse(x, [2]) def rgb_to_bgr(x): return tf.reverse(x, [2]) def get_available_gpus(): """ Queries the CUDA GPU devices visible to Tensorflow. Returns: A list with tf-style gpu strings (f.e. ['/gpu:0', '/gpu:1']) """ local_device_protos = device_lib.list_local_devices() return [x.name for x in local_device_protos if x.device_type == 'GPU']
DIGITS-master
digits/tools/tensorflow/utils.py
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: caffe_tf.proto import sys from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.protobuf import descriptor_pb2 # noqa # @@protoc_insertion_point(imports) _b = (sys.version_info[0] < 3 and (lambda x: x)) or (lambda x: x.encode('latin1')) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor.FileDescriptor( name='caffe_tf.proto', package='', serialized_pb=_b('\n\x0e\x63\x61\x66\x66\x65_tf.proto\"\x1c\n\tBlobShape\x12\x0f\n\x03\x64im\x18\x01 \x03(\x03\x42\x02\x10\x01\"\xc6\x01\n\tBlobProto\x12\x19\n\x05shape\x18\x07 \x01(\x0b\x32\n.BlobShape\x12\x10\n\x04\x64\x61ta\x18\x05 \x03(\x02\x42\x02\x10\x01\x12\x10\n\x04\x64iff\x18\x06 \x03(\x02\x42\x02\x10\x01\x12\x17\n\x0b\x64ouble_data\x18\x08 \x03(\x01\x42\x02\x10\x01\x12\x17\n\x0b\x64ouble_diff\x18\t \x03(\x01\x42\x02\x10\x01\x12\x0e\n\x03num\x18\x01 \x01(\x05:\x01\x30\x12\x13\n\x08\x63hannels\x18\x02 \x01(\x05:\x01\x30\x12\x11\n\x06height\x18\x03 \x01(\x05:\x01\x30\x12\x10\n\x05width\x18\x04 \x01(\x05:\x01\x30\",\n\x0f\x42lobProtoVector\x12\x19\n\x05\x62lobs\x18\x01 \x03(\x0b\x32\n.BlobProto\"\x81\x01\n\x05\x44\x61tum\x12\x10\n\x08\x63hannels\x18\x01 \x01(\x05\x12\x0e\n\x06height\x18\x02 \x01(\x05\x12\r\n\x05width\x18\x03 \x01(\x05\x12\x0c\n\x04\x64\x61ta\x18\x04 \x01(\x0c\x12\r\n\x05label\x18\x05 \x01(\x05\x12\x12\n\nfloat_data\x18\x06 \x03(\x02\x12\x16\n\x07\x65ncoded\x18\x07 \x01(\x08:\x05\x66\x61lse') # noqa ) _sym_db.RegisterFileDescriptor(DESCRIPTOR) _BLOBSHAPE = _descriptor.Descriptor( name='BlobShape', full_name='BlobShape', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='dim', full_name='BlobShape.dim', index=0, number=1, type=3, cpp_type=2, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), _b('\020\001'))), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=18, serialized_end=46, ) _BLOBPROTO = _descriptor.Descriptor( name='BlobProto', full_name='BlobProto', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='shape', full_name='BlobProto.shape', index=0, number=7, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='data', full_name='BlobProto.data', index=1, number=5, type=2, cpp_type=6, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), _b('\020\001'))), _descriptor.FieldDescriptor( name='diff', full_name='BlobProto.diff', index=2, number=6, type=2, cpp_type=6, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), _b('\020\001'))), _descriptor.FieldDescriptor( name='double_data', full_name='BlobProto.double_data', index=3, number=8, type=1, cpp_type=5, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), _b('\020\001'))), _descriptor.FieldDescriptor( name='double_diff', full_name='BlobProto.double_diff', index=4, number=9, type=1, cpp_type=5, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), _b('\020\001'))), _descriptor.FieldDescriptor( name='num', full_name='BlobProto.num', index=5, number=1, type=5, cpp_type=1, label=1, has_default_value=True, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='channels', full_name='BlobProto.channels', index=6, number=2, type=5, cpp_type=1, label=1, has_default_value=True, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='height', full_name='BlobProto.height', index=7, number=3, type=5, cpp_type=1, label=1, has_default_value=True, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='width', full_name='BlobProto.width', index=8, number=4, type=5, cpp_type=1, label=1, has_default_value=True, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=49, serialized_end=247, ) _BLOBPROTOVECTOR = _descriptor.Descriptor( name='BlobProtoVector', full_name='BlobProtoVector', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='blobs', full_name='BlobProtoVector.blobs', index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=249, serialized_end=293, ) _DATUM = _descriptor.Descriptor( name='Datum', full_name='Datum', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='channels', full_name='Datum.channels', index=0, number=1, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='height', full_name='Datum.height', index=1, number=2, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='width', full_name='Datum.width', index=2, number=3, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='data', full_name='Datum.data', index=3, number=4, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='label', full_name='Datum.label', index=4, number=5, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='float_data', full_name='Datum.float_data', index=5, number=6, type=2, cpp_type=6, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='encoded', full_name='Datum.encoded', index=6, number=7, type=8, cpp_type=7, label=1, has_default_value=True, default_value=False, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=296, serialized_end=425, ) _BLOBPROTO.fields_by_name['shape'].message_type = _BLOBSHAPE _BLOBPROTOVECTOR.fields_by_name['blobs'].message_type = _BLOBPROTO DESCRIPTOR.message_types_by_name['BlobShape'] = _BLOBSHAPE DESCRIPTOR.message_types_by_name['BlobProto'] = _BLOBPROTO DESCRIPTOR.message_types_by_name['BlobProtoVector'] = _BLOBPROTOVECTOR DESCRIPTOR.message_types_by_name['Datum'] = _DATUM BlobShape = _reflection.GeneratedProtocolMessageType('BlobShape', (_message.Message,), dict( DESCRIPTOR=_BLOBSHAPE, __module__='caffe_tf_pb2' # @@protoc_insertion_point(class_scope:BlobShape) )) _sym_db.RegisterMessage(BlobShape) BlobProto = _reflection.GeneratedProtocolMessageType('BlobProto', (_message.Message,), dict( DESCRIPTOR=_BLOBPROTO, __module__='caffe_tf_pb2' # @@protoc_insertion_point(class_scope:BlobProto) )) _sym_db.RegisterMessage(BlobProto) BlobProtoVector = _reflection.GeneratedProtocolMessageType('BlobProtoVector', (_message.Message,), dict( DESCRIPTOR=_BLOBPROTOVECTOR, __module__='caffe_tf_pb2' # @@protoc_insertion_point(class_scope:BlobProtoVector) )) _sym_db.RegisterMessage(BlobProtoVector) Datum = _reflection.GeneratedProtocolMessageType('Datum', (_message.Message,), dict( DESCRIPTOR=_DATUM, __module__='caffe_tf_pb2' # @@protoc_insertion_point(class_scope:Datum) )) _sym_db.RegisterMessage(Datum) _BLOBSHAPE.fields_by_name['dim'].has_options = True _BLOBSHAPE.fields_by_name['dim']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), _b('\020\001')) _BLOBPROTO.fields_by_name['data'].has_options = True _BLOBPROTO.fields_by_name['data']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), _b('\020\001')) _BLOBPROTO.fields_by_name['diff'].has_options = True _BLOBPROTO.fields_by_name['diff']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), _b('\020\001')) _BLOBPROTO.fields_by_name['double_data'].has_options = True _BLOBPROTO.fields_by_name['double_data']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), _b('\020\001')) _BLOBPROTO.fields_by_name['double_diff'].has_options = True _BLOBPROTO.fields_by_name['double_diff']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), _b('\020\001')) # @@protoc_insertion_point(module_scope)
DIGITS-master
digits/tools/tensorflow/caffe_tf_pb2.py
# Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved. # # This document should comply with PEP-8 Style Guide # Linter: pylint """ Interface for data loading for Tensorflow. Data loading is done through a data loading factory,that will setup the correct functions for the respective backends. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from PIL import Image import logging import magic import math import numpy as np import os import tensorflow as tf # Local imports import caffe_tf_pb2 import utils as digits # Constants MIN_FRACTION_OF_EXAMPLES_IN_QUEUE = 0.4 MAX_ABSOLUTE_EXAMPLES_IN_QUEUE = 4096 # The queue size cannot exceed this number NUM_THREADS_DATA_LOADER = 6 LOG_MEAN_FILE = False # Logs the mean file as loaded in TF to TB # Supported extensions for Loaders DB_EXTENSIONS = { 'hdf5': ['.H5', '.HDF5'], 'lmdb': ['.MDB', '.LMDB'], 'tfrecords': ['.TFRECORDS'], 'filelist': ['.TXT'], 'file': ['.JPG', '.JPEG', '.PNG'], 'gangrid': ['.GAN'], } LIST_DELIMITER = ' ' # For the FILELIST format logging.basicConfig(format='%(asctime)s [%(levelname)s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO) def get_backend_of_source(db_path): """ Takes a path as argument and infers the format of the data. If a directory is provided, it looks for the existance of an extension in the entire directory in an order of a priority of dbs (hdf5, lmdb, filelist, file) Args: db_path: path to a file or directory Returns: backend: the backend type """ # If a directory is given, we include all its contents. Otherwise it's just the one file. if os.path.isdir(db_path): files_in_path = [fn for fn in os.listdir(db_path) if not fn.startswith('.')] else: files_in_path = [db_path] # Keep the below priority ordering for db_fmt in ['hdf5', 'lmdb', 'tfrecords', 'filelist', 'file', 'gangrid']: ext_list = DB_EXTENSIONS[db_fmt] for ext in ext_list: if any(ext in os.path.splitext(fn)[1].upper() for fn in files_in_path): return db_fmt logging.error("Cannot infer backend from db_path (%s)." % (db_path)) exit(-1) class MeanLoader(object): """ Loads in a mean file for tensorflow. This is done through using a constant variable. It needs to be loaded first, after which the constant tf op can be retrieved through a function, and can be accounted for. """ def __init__(self, mean_file_path, subtraction_type, bitdepth): self._mean_file_path = mean_file_path self._subtraction_type = subtraction_type self._bitdepth = bitdepth self.tf_mean_image = None self.load_mean() def load_mean(self): """ The mean is loaded in the graph through a tf.constant for maximum efficiency. This is first done only once through a numpy array that defines the value of the constant. All pre-processing of the mean file is done before the definition of the tf.constant to make sure these operations are not repeated in the graph """ file_extension = os.path.splitext(self._mean_file_path)[1].upper() if file_extension == '.BINARYPROTO': blob = caffe_tf_pb2.BlobProto() with open(self._mean_file_path, 'rb') as infile: blob.ParseFromString(infile.read()) data = np.array(blob.data, dtype="float32").reshape(blob.channels, blob.height, blob.width) if blob.channels == 3: # converting from BGR to RGB data = data[[2, 1, 0], ...] # channel swap # convert to (height, width, channels) data = data.transpose((1, 2, 0)) elif blob.channels == 1: # convert to (height, width) data = data[0] else: logging.error('Unknown amount of channels (%d) in mean file (%s)' % (blob.channels, self._mean_file_path)) exit(-1) # elif file_extension in IMG_FILE_EXT: # img = Image.open(self._mean_file_path) # img.load() # data = np.asarray(img, dtype="float32") else: logging.error('Failed loading mean file: Unsupported extension (%s)' % (file_extension)) exit(-1) if (self._subtraction_type == 'image') or (self._subtraction_type == 'pixel'): if self._subtraction_type == 'pixel': data = data.mean(axis=(0, 1)) data = np.reshape(data, (1, 1, -1)) elif len(data.shape) != 3: # Explicitly add channel dim data = data[:, :, None] # return data in original pixel scale self.tf_mean_image = tf.constant(data, name='Const_Mean_Image') else: logging.error('Unsupported mean subtraction type (%s)' % (self._subtraction_type)) exit(-1) def subtract_mean_op(self, tf_graph): """ Places mean subtraction on top of the tensorflow graph supplied, returns the added op Args: tf_graph: the graph the subtraction of the mean should placed upon Returns: The graph with the mean subtraction placed on top of it """ return (tf_graph - self.tf_mean_image) class LoaderFactory(object): """ A factory for data loading. It sets up a subclass with data loading done with the respective backend. Its output is a tensorflow queue op that is used to load in data, with optionally some minor postprocessing ops. """ def __init__(self): self.croplen = None self.nclasses = None self.mean_loader = None self.backend = None self.db_path = None self.batch_x = None self.batch_y = None self.batch_k = None self.stage = None self._seed = None self.unencoded_data_format = 'hwc' self.unencoded_channel_scheme = 'rgb' self.summaries = None self.aug_dict = {} # @TODO(tzaman) rewrite this factory again pass @staticmethod def set_source(db_path, is_inference=False): """ Returns the correct backend. """ backend = get_backend_of_source(db_path) loader = None if backend == 'lmdb': loader = LmdbLoader() elif backend == 'hdf5': loader = Hdf5Loader() elif backend == 'file' or backend == 'filelist': loader = FileListLoader() elif backend == 'tfrecords': loader = TFRecordsLoader() elif backend == 'gangrid': loader = GanGridLoader() else: logging.error("Backend (%s) not implemented" % (backend)) exit(-1) loader.backend = backend loader.db_path = db_path loader.is_inference = is_inference return loader def setup(self, labels_db_path, shuffle, bitdepth, batch_size, num_epochs=None, seed=None): with tf.device('/cpu:0'): self.labels_db_path = labels_db_path self.shuffle = shuffle self.bitdepth = bitdepth self.batch_size = batch_size self.num_epochs = num_epochs self._seed = seed if self.labels_db_path: self.labels_db = LoaderFactory.set_source(self.labels_db_path) self.labels_db.bitdepth = self.bitdepth self.labels_db.stage = self.stage self.labels_db.initialize() self.initialize() logging.info("Found %s images in db %s ", self.get_total(), self.db_path) def get_key_index(self, key): return self.keys.index(key) def set_augmentation(self, mean_loader, aug_dict={}): with tf.device('/cpu:0'): self.mean_loader = mean_loader self.aug_dict = aug_dict def get_shape(self): input_shape = [self.height, self.width, self.channels] # update input_shape if crop length specified # this is necessary as the input_shape is provided # below to the user-defined function that defines the network if self.croplen > 0: input_shape[0] = self.croplen input_shape[1] = self.croplen return input_shape def get_total(self): return self.total def reshape_decode(self, data, shape): if self.float_data: # @TODO(tzaman): this is LMDB specific - Make generic! data = tf.reshape(data, shape) data = digits.chw_to_hwc(data) else: # Decode image of any time option might come: https://github.com/tensorflow/tensorflow/issues/4009 # Distinguish between mime types if self.data_encoded: if self.data_mime == 'image/png': data = tf.image.decode_png(data, dtype=self.image_dtype, name='image_decoder') elif self.data_mime == 'image/jpeg': data = tf.image.decode_jpeg(data, name='image_decoder') else: logging.error('Unsupported mime type (%s); cannot be decoded' % (self.data_mime)) exit(-1) else: if self.backend == 'lmdb': data = tf.decode_raw(data, self.image_dtype, name='raw_decoder') # if data is in CHW, set the shape and convert to HWC if self.unencoded_data_format == 'chw': data = tf.reshape(data, [shape[0], shape[1], shape[2]]) data = digits.chw_to_hwc(data) else: # 'hwc' data = tf.reshape(data, shape) if (self.channels == 3) and self.unencoded_channel_scheme == 'bgr': data = digits.bgr_to_rgb(data) # Convert to float data = tf.to_float(data) # data = tf.image.convert_image_dtype(data, tf.float32) # normalize to [0:1) range return data def create_input_pipeline(self): """ This function returns part of the graph that does data loading, and includes a queueing, optional data decoding and optional post-processing like data augmentation or mean subtraction. Args: None. Produces: batch_x: Input data batch batch_y: Label data batch batch_k: A list of keys (strings) from which the batch originated Returns: None. """ # @TODO(tzaman) the container can be used if the reset function is implemented: # see https://github.com/tensorflow/tensorflow/issues/4535#issuecomment-248990633 # # with tf.container('queue-container'): key_queue = self.get_queue() single_label = None single_label_shape = None if self.stage == digits.STAGE_INF: single_key, single_data, single_data_shape, _, _ = self.get_single_data(key_queue) else: single_key, single_data, single_data_shape, single_label, single_label_shape = \ self.get_single_data(key_queue) single_data_shape = tf.reshape(single_data_shape, [3]) # Shape the shape to have three dimensions single_data = self.reshape_decode(single_data, single_data_shape) if self.labels_db_path: # Using a seperate label db; label can be anything single_label_shape = tf.reshape(single_label_shape, [3]) # Shape the shape single_label = self.labels_db.reshape_decode(single_label, single_label_shape) elif single_label is not None: # Not using a seperate label db; label is a scalar single_label = tf.reshape(single_label, []) # Mean Subtraction if self.mean_loader: with tf.name_scope('mean_subtraction'): single_data = self.mean_loader.subtract_mean_op(single_data) if LOG_MEAN_FILE: expanded_data = tf.expand_dims(self.mean_loader.tf_mean_image, 0) self.summaries.append(tf.summary.image('mean_image', expanded_data, max_outputs=1)) # (Random) Cropping if self.croplen: with tf.name_scope('cropping'): if self.stage == digits.STAGE_TRAIN: single_data = tf.random_crop(single_data, [self.croplen, self.croplen, self.channels], seed=self._seed) else: # Validation or Inference single_data = tf.image.resize_image_with_crop_or_pad(single_data, self.croplen, self.croplen) # Data Augmentation if self.aug_dict: with tf.name_scope('augmentation'): flipflag = self.aug_dict['aug_flip'] if flipflag == 'fliplr' or flipflag == 'fliplrud': single_data = tf.image.random_flip_left_right(single_data, seed=self._seed) if flipflag == 'flipud' or flipflag == 'fliplrud': single_data = tf.image.random_flip_up_down(single_data, seed=self._seed) noise_std = self.aug_dict['aug_noise'] if noise_std > 0.: # Note the tf.random_normal requires a static shape single_data = tf.add(single_data, tf.random_normal(self.get_shape(), mean=0.0, stddev=noise_std, dtype=tf.float32, seed=self._seed, name='AWGN')) contrast_fact = self.aug_dict['aug_contrast'] if contrast_fact > 0: single_data = tf.image.random_contrast(single_data, lower=1.-contrast_fact, upper=1.+contrast_fact, seed=self._seed) # @TODO(tzaman): rewrite the below HSV stuff entirely in a TF PR to be done in one single operation aug_hsv = self.aug_dict['aug_HSV'] if aug_hsv['h'] > 0.: single_data = tf.image.random_hue(single_data, aug_hsv['h'], seed=self._seed) if aug_hsv['s'] > 0.: single_data = tf.image.random_saturation(single_data, 1 - aug_hsv['s'], 1 + aug_hsv['s'], seed=self._seed) if aug_hsv['v'] > 0.: # closely resembles V - temporary until rewritten single_data = tf.image.random_brightness(single_data, aug_hsv['v'], seed=self._seed) # @TODO(tzaman) whitening is so invasive that we need a way to add it to the val/inf too in a # portable manner, like the mean file : how? If we don't find a way, don't use whitening. aug_whitening = self.aug_dict['aug_whitening'] if aug_whitening: # Subtract off its own mean and divide by the standard deviation of its own the pixels. with tf.name_scope('whitening'): single_data = tf.image.per_image_standardization(single_data) # N.B. also converts to float max_queue_capacity = min(math.ceil(self.total * MIN_FRACTION_OF_EXAMPLES_IN_QUEUE), MAX_ABSOLUTE_EXAMPLES_IN_QUEUE) single_batch = [single_key, single_data] if single_label is not None: single_batch.append(single_label) if self.backend == 'tfrecords' and self.shuffle: batch = tf.train.shuffle_batch( single_batch, batch_size=self.batch_size, num_threads=NUM_THREADS_DATA_LOADER, capacity=10*self.batch_size, # Max amount that will be loaded and queued shapes=[[0], self.get_shape(), []], # Only makes sense is dynamic_pad=False #@TODO(tzaman) - FIXME min_after_dequeue=5*self.batch_size, allow_smaller_final_batch=True, # Happens if total%batch_size!=0 name='batcher') else: batch = tf.train.batch( single_batch, batch_size=self.batch_size, dynamic_pad=True, # Allows us to not supply fixed shape a priori enqueue_many=False, # Each tensor is a single example # set number of threads to 1 for tfrecords (used for inference) num_threads=NUM_THREADS_DATA_LOADER if not self.is_inference else 1, capacity=max_queue_capacity, # Max amount that will be loaded and queued allow_smaller_final_batch=True, # Happens if total%batch_size!=0 name='batcher') self.batch_k = batch[0] # Key self.batch_x = batch[1] # Input if len(batch) == 3: # There's a label (unlike during inferencing) self.batch_y = batch[2] # Output (label) class LmdbLoader(LoaderFactory): """ Loads files from lmbd files as used in Caffe """ def __init__(self): pass def initialize(self): try: import lmdb except ImportError: logging.error("Attempt to create LMDB Loader but lmdb is not installed.") exit(-1) self.unencoded_data_format = 'chw' self.unencoded_channel_scheme = 'bgr' # Set up the data loader self.lmdb_env = lmdb.open(self.db_path, readonly=True, lock=False) self.lmdb_txn = self.lmdb_env.begin(buffers=False) self.total = self.lmdb_txn.stat()['entries'] self.keys = [key for key, _ in self.lmdb_txn.cursor()] # Read the first entry to get some info lmdb_val = self.lmdb_txn.get(self.keys[0]) datum = caffe_tf_pb2.Datum() datum.ParseFromString(lmdb_val) self.channels = datum.channels self.width = datum.width self.height = datum.height self.data_encoded = datum.encoded self.float_data = datum.float_data if self.data_encoded: # Obtain mime-type self.data_mime = magic.from_buffer(datum.data, mime=True) if not self.float_data: if self.bitdepth == 8: self.image_dtype = tf.uint8 else: if self.data_mime == 'image/jpeg': logging.error("Tensorflow does not support 16 bit jpeg decoding.") exit(-1) self.image_dtype = tf.uint16 def get_queue(self): return tf.train.string_input_producer( self.keys, num_epochs=self.num_epochs, capacity=self.total, shuffle=self.shuffle, seed=self._seed, name='input_producer' ) def get_tf_data_type(self): """Returns the type of the data, in tf format. It takes in account byte-data or floating point data. It also takes in account the possible seperate lmdb label db. Returns: The tensorflow-datatype of the data """ return tf.float32 if self.float_data else tf.string def get_tf_label_type(self): """Returns the type of the label, in tf format. It takes in account byte-data or floating point data. It also takes in account the possible seperate lmdb label db. Returns: The tensorflow-datatype of the label """ if self.labels_db_path: return self.labels_db.get_tf_data_type() else: # No seperate db, return scalar label return tf.int64 def generate_data_op(self): """Generates and returns an op that fetches a single sample of data. Args: self: Returns: A python function that is inserted as an op """ def get_data_and_shape(lmdb_txn, key): val = lmdb_txn.get(key) datum = caffe_tf_pb2.Datum() datum.ParseFromString(val) shape = np.array([datum.channels, datum.height, datum.width], dtype=np.int32) if datum.float_data: data = np.asarray(datum.float_data, dtype='float32') else: data = datum.data label = np.asarray([datum.label], dtype=np.int64) # scalar label return data, shape, label def get_data_op(key): """Fetches a sample of data and its label from lmdb. If a seperate label database exists, it will also load it from the seperate db inside this function. This is done the data and its label are loaded at the same time, avoiding multiple queues and race conditions. Args: self: the current lmdb instance Returns: single_data: One sample of training data single_data_shape: The shape of the preceeding training data single_label: The label that is the reference value describing the data single_label_shape: The shape of the preceeding label data """ single_data, single_data_shape, single_label = get_data_and_shape(self.lmdb_txn, key) single_label_shape = np.array([], dtype=np.int32) if self.labels_db_path: single_label, single_label_shape, _ = get_data_and_shape(self.labels_db.lmdb_txn, key) return single_data, [single_data_shape], single_label, [single_label_shape] return get_data_op def get_single_data(self, key_queue): """ Returns: key, single_data, single_data_shape, single_label, single_label_shape """ key = key_queue.dequeue() # Operation that dequeues one key and returns a string with the key py_func_return_type = [self.get_tf_data_type(), tf.int32, self.get_tf_label_type(), tf.int32] d, ds, l, ls = tf.py_func(self.generate_data_op(), [key], py_func_return_type, name='data_reader') return key, d, ds, l, ls def __del__(self): self.lmdb_env.close() class FileListLoader(LoaderFactory): """ The FileListLoader loads files from a list of string(s) pointing to (a) file(s). These files are then retrieved by their string and loaded according to their extension. """ def __init__(self): pass def initialize(self): self.float_data = False self.data_encoded = True if self.backend == 'file': # Single file self.total = 1 self.keys = [self.db_path] first_file_path = self.db_path elif self.backend == 'filelist': # Single file with a list of files with open(self.db_path) as f: self.keys = f.readlines() # Retain only the images in the list self.keys = [key.split(LIST_DELIMITER)[0].rstrip() for key in self.keys] if len(self.keys) > 0: # Assume the first entry in the line is a pointer to the file path first_file_path = self.keys[0] else: logging.error('Filelist (%s) contains no lines.' % (self.db_path)) exit(-1) else: logging.error('Unsupported backend in FileListLoader (%s)' % (self.backend)) exit(-1) self.total = len(self.keys) # Check first file for statistics im = Image.open(first_file_path) self.width, self.height = im.size self.channels = 1 if im.mode == 'L' else 3 # @TODO(tzaman): allow more channels self.data_mime = magic.from_file(first_file_path, mime=True) if self.bitdepth == 8: self.image_dtype = tf.uint8 else: if self.data_mime == 'image/jpeg': logging.error("Tensorflow does not support 16 bit jpeg decoding.") exit(-1) self.image_dtype = tf.uint16 self.reader = tf.WholeFileReader() def get_queue(self): return tf.train.string_input_producer( self.keys, num_epochs=self.num_epochs, capacity=self.total, shuffle=self.shuffle, seed=self._seed, name='input_producer' ) def get_single_data(self, key_queue): """ Returns: key, single_data, single_data_shape, single_label, single_label_shape """ key, value = self.reader.read(key_queue) shape = np.array([self.width, self.height, self.channels], dtype=np.int32) # @TODO: this is not dynamic return key, value, shape # @TODO(tzaman) - Note: will only work for inferencing stage! class TFRecordsLoader(LoaderFactory): """ The TFRecordsLoader connects directly into the tensorflow graph. It uses TFRecords, the 'standard' tensorflow data format. """ def __init__(self): pass def initialize(self): self.float_data = False # For now only strings self.unencoded_data_format = 'hwc' self.unencoded_channel_scheme = 'rgb' self.reader = None if self.bitdepth == 8: self.image_dtype = tf.uint8 else: self.image_dtype = tf.uint16 # Count all the records @TODO(tzaman): account for shards! # Loop the records in path @TODO(tzaman) get this from a txt? # self.db_path += '/test.tfrecords' # @TODO(tzaman) this is a hack self.shard_paths = [] list_db_files = os.path.join(self.db_path, 'list.txt') self.total = 0 if os.path.exists(list_db_files): files = [os.path.join(self.db_path, f) for f in open(list_db_files, 'r').read().splitlines()] else: files = [self.db_path] for shard_path in files: # Account for the relative path format in list.txt record_iter = tf.python_io.tf_record_iterator(shard_path) for r in record_iter: self.total += 1 if not self.total: raise ValueError('Database or shard contains no records (%s)' % (self.db_path)) self.shard_paths.append(shard_path) self.keys = ['%s:0' % p for p in self.shard_paths] # Use last record read to extract some preliminary data that is sometimes needed or useful example_proto = tf.train.Example() example_proto.ParseFromString(r) # @TODO(tzaman) - bitdepth flag? self.channels = example_proto.features.feature['depth'].int64_list.value[0] self.height = example_proto.features.feature['height'].int64_list.value[0] self.width = example_proto.features.feature['width'].int64_list.value[0] data_encoding_id = example_proto.features.feature['encoding'].int64_list.value[0] if data_encoding_id: self.data_encoded = True self.data_mime = 'image/png' if data_encoding_id == 1 else 'image/jpeg' else: self.data_encoded = False # Set up the reader # @TODO(tzaman) there's a filename queue because it can have multiple (sharded) tfrecord files (!) # .. account for that! self.reader = tf.TFRecordReader(name='tfrecord_reader') def get_queue(self): return tf.train.string_input_producer(self.shard_paths, num_epochs=self.num_epochs, shuffle=self.shuffle, seed=self._seed, name='input_producer' ) def get_single_data(self, key_queue): """ Returns: key, single_data, single_data_shape, single_label, single_label_shape """ key, serialized_example = self.reader.read(key_queue) features = tf.parse_single_example( serialized_example, # Defaults are not specified since both keys are required. features={ 'image_raw': tf.FixedLenFeature([self.height, self.width, self.channels], tf.float32), 'label': tf.FixedLenFeature([], tf.int64), }) d = features['image_raw'] ds = np.array([self.height, self.width, self.channels], dtype=np.int32) # @TODO: this is not dynamic l = features['label'] # l = tf.cast(features['label'], tf.int32) ls = np.array([], dtype=np.int32) # @TODO: this is not dynamic return key, d, ds, l, ls class Hdf5Loader(LoaderFactory): def __init__(self): pass def initialize(self): try: import h5py except ImportError: logging.error("Attempt to create HDF5 Loader but h5py is not installed.") exit(-1) self.data_encoded = False self.float_data = True # Always stored as float32 self.keys = None # Not using keys self.h5dbs = [] self.h5dbs_endrange = [] list_db_files = self.db_path + '/list.txt' self.total = 0 with open(list_db_files) as f: for line in f: # Account for the relative path format in list.txt fn = self.db_path + '/' + os.path.basename(line.strip()) db = h5py.File(fn) self.check_hdf5_db(db) self.total += len(db['data']) self.h5dbs_endrange.append(self.total) self.h5dbs.append(db) # Read the first file to get shape information self.channels, self.height, self.width = self.h5dbs[0]['data'][0].shape def check_hdf5_db(self, db): # Make sure we have data and labels in the db if "data" not in db or "label" not in db: logging.error("The HDF5 loader requires both a 'data' and 'label' group in the HDF5 root.") exit(-1) if len(db['data']) != len(db['label']): logging.error("HDF5 data and label amount mismatch (%d/%d)" % (len(db['data']), len(db['label']))) exit(-1) if len(db['data']) == 0: logging.error("HDF5 database contains no data.") exit(-1) def get_queue(self): return tf.train.range_input_producer( self.total, num_epochs=self.num_epochs, capacity=self.total, shuffle=self.shuffle, seed=self._seed, name='input_producer' ) def get_tf_data_type(self): """Returns the type of the data, in tf format. It takes in account byte-data or floating point data. It also takes in account the possible seperate lmdb label db. Returns: The tensorflow-datatype of the data """ return tf.float32 if self.float_data else tf.string def get_tf_label_type(self): """Returns the type of the label, in tf format. It takes in account byte-data or floating point data. It also takes in account the possible seperate lmdb label db. Returns: The tensorflow-datatype of the label """ if self.labels_db_path: return self.labels_db.get_tf_data_type() else: # No seperate db, return scalar label return tf.int64 def get_data_and_shape(self, sample_key): """ Gets a sample across multiple hdf5 databases """ prev_end_range = 0 for i, end_range in enumerate(self.h5dbs_endrange): if sample_key < end_range: key_within_db = sample_key-prev_end_range data = self.h5dbs[i]['data'][key_within_db] shape = np.asarray(data.shape, dtype=np.int32) label = self.h5dbs[i]['label'][key_within_db].astype(np.int64) return data, shape, label prev_end_range = end_range logging.error("Out of range") # @TODO(tzaman) out of range error exit(-1) def generate_data_op(self): """Generates and returns an op that fetches a single sample of data. Returns: A python function that is inserted as an op """ def get_data_op(key): """Fetches a sample of data and its label from db. If a seperate label database exists, it will also load it from the seperate db inside this function. This is done the data and its label are loaded at the same time, avoiding multiple queues and race conditions. Args: key: integer key id Returns: single_data: One sample of training data single_data_shape: The shape of the preceeding training data single_label: The label that is the reference value describing the data single_label_shape: The shape of the preceeding label data """ single_data, single_data_shape, single_label = self.get_data_and_shape(key) single_label_shape = np.array([], dtype=np.int32) if self.labels_db_path: single_label, single_label_shape, _ = self.labels_db.get_data_and_shape(key) return single_data, [single_data_shape], single_label, [single_label_shape] return get_data_op def get_single_data(self, key_queue): """ Returns: key, single_data, single_data_shape, single_label, single_label_shape """ key = key_queue.dequeue() # Operation that dequeues one key and returns a string with the key py_func_return_type = [self.get_tf_data_type(), tf.int32, self.get_tf_label_type(), tf.int32] d, ds, l, ls = tf.py_func(self.generate_data_op(), [key], py_func_return_type, name='data_reader') return key, d, ds, l, ls def __del__(self): for db in self.h5dbs: db.close() class GanGridLoader(LoaderFactory): """ The GanGridLoader generates data for a GAN. """ def __init__(self): pass def initialize(self): self.float_data = False # For now only strings self.keys = None # Not using keys self.unencoded_data_format = 'hwc' self.unencoded_channel_scheme = 'rgb' self.reader = None self.image_dtype = tf.float32 self.channels = 1 self.height = 1 self.width = 100 self.data_encoded = False self.total = 100000 def get_queue(self): return tf.train.range_input_producer( self.total, num_epochs=self.num_epochs, capacity=self.total, shuffle=self.shuffle, seed=self._seed, name='input_producer' ) def get_single_data(self, key_queue): """ Returns: key, single_data, single_data_shape, single_label, single_label_shape """ key = tf.to_int32(key_queue.dequeue()) # Operation that dequeues an index d = key ds = np.array([1, 1, 1], dtype=np.int32) return key, d, ds, None, None
DIGITS-master
digits/tools/tensorflow/tf_data.py
#!/usr/bin/env python2 # Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved. # # This document should comply with PEP-8 Style Guide # Linter: pylint """ TensorFlow training executable for DIGITS Defines the training procedure Usage: See the self-documenting flags below. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import time import datetime import inspect import json import logging import math import numpy as np import os from six.moves import xrange # noqa import tensorflow as tf import tensorflow.contrib.slim as slim # noqa from tensorflow.python.client import timeline, device_lib # noqa from tensorflow.python.ops import template # noqa from tensorflow.python.lib.io import file_io from tensorflow.core.framework import summary_pb2 from tensorflow.python.tools import freeze_graph # Local imports import utils as digits import lr_policy from model import Model, Tower # noqa from utils import model_property # noqa import tf_data # Constants TF_INTRA_OP_THREADS = 0 TF_INTER_OP_THREADS = 0 MIN_LOGS_PER_TRAIN_EPOCH = 8 # torch default: 8 logging.basicConfig(format='%(asctime)s [%(levelname)s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO) FLAGS = tf.app.flags.FLAGS # Basic model parameters. #float, integer, boolean, string tf.app.flags.DEFINE_integer('batch_size', 16, """Number of images to process in a batch""") tf.app.flags.DEFINE_integer( 'croplen', 0, """Crop (x and y). A zero value means no cropping will be applied""") tf.app.flags.DEFINE_integer('epoch', 1, """Number of epochs to train, -1 for unbounded""") tf.app.flags.DEFINE_string('inference_db', '', """Directory with inference file source""") tf.app.flags.DEFINE_integer( 'validation_interval', 1, """Number of train epochs to complete, to perform one validation""") tf.app.flags.DEFINE_string('labels_list', '', """Text file listing label definitions""") tf.app.flags.DEFINE_string('mean', '', """Mean image file""") tf.app.flags.DEFINE_float('momentum', '0.9', """Momentum""") # Not used by DIGITS front-end tf.app.flags.DEFINE_string('network', '', """File containing network (model)""") tf.app.flags.DEFINE_string('networkDirectory', '', """Directory in which network exists""") tf.app.flags.DEFINE_string('optimization', 'sgd', """Optimization method""") tf.app.flags.DEFINE_string('save', 'results', """Save directory""") tf.app.flags.DEFINE_integer('seed', 0, """Fixed input seed for repeatable experiments""") tf.app.flags.DEFINE_boolean('shuffle', False, """Shuffle records before training""") tf.app.flags.DEFINE_float( 'snapshotInterval', 1.0, """Specifies the training epochs to be completed before taking a snapshot""") tf.app.flags.DEFINE_string('snapshotPrefix', '', """Prefix of the weights/snapshots""") tf.app.flags.DEFINE_string( 'subtractMean', 'none', """Select mean subtraction method. Possible values are 'image', 'pixel' or 'none'""") tf.app.flags.DEFINE_string('train_db', '', """Directory with training file source""") tf.app.flags.DEFINE_string( 'train_labels', '', """Directory with an optional and seperate labels file source for training""") tf.app.flags.DEFINE_string('validation_db', '', """Directory with validation file source""") tf.app.flags.DEFINE_string( 'validation_labels', '', """Directory with an optional and seperate labels file source for validation""") tf.app.flags.DEFINE_string( 'visualizeModelPath', '', """Constructs the current model for visualization""") tf.app.flags.DEFINE_boolean( 'visualize_inf', False, """Will output weights and activations for an inference job.""") tf.app.flags.DEFINE_string( 'weights', '', """Filename for weights of a model to use for fine-tuning""") # @TODO(tzaman): is the bitdepth in line with the DIGITS team? tf.app.flags.DEFINE_integer('bitdepth', 8, """Specifies an image's bitdepth""") # @TODO(tzaman); remove torch mentions below tf.app.flags.DEFINE_float('lr_base_rate', '0.01', """Learning rate""") tf.app.flags.DEFINE_string( 'lr_policy', 'fixed', """Learning rate policy. (fixed, step, exp, inv, multistep, poly, sigmoid)""") tf.app.flags.DEFINE_float( 'lr_gamma', -1, """Required to calculate learning rate. Applies to: (step, exp, inv, multistep, sigmoid)""") tf.app.flags.DEFINE_float( 'lr_power', float('Inf'), """Required to calculate learning rate. Applies to: (inv, poly)""") tf.app.flags.DEFINE_string( 'lr_stepvalues', '', """Required to calculate stepsize of the learning rate. Applies to: (step, multistep, sigmoid). For the 'multistep' lr_policy you can input multiple values seperated by commas""") # Tensorflow-unique arguments for DIGITS tf.app.flags.DEFINE_string( 'save_vars', 'all', """Sets the collection of variables to be saved: 'all' or only 'trainable'.""") tf.app.flags.DEFINE_string('summaries_dir', '', """Directory of Tensorboard Summaries (logdir)""") tf.app.flags.DEFINE_boolean( 'serving_export', False, """Flag for exporting an Tensorflow Serving model""") tf.app.flags.DEFINE_boolean('log_device_placement', False, """Whether to log device placement.""") tf.app.flags.DEFINE_integer( 'log_runtime_stats_per_step', 0, """Logs runtime statistics for Tensorboard every x steps, defaults to 0 (off).""") # Augmentation tf.app.flags.DEFINE_string( 'augFlip', 'none', """The flip options {none, fliplr, flipud, fliplrud} as randompre-processing augmentation""") tf.app.flags.DEFINE_float( 'augNoise', 0., """The stddev of Noise in AWGN as pre-processing augmentation""") tf.app.flags.DEFINE_float( 'augContrast', 0., """The contrast factor's bounds as sampled from a random-uniform distribution as pre-processing augmentation""") tf.app.flags.DEFINE_bool( 'augWhitening', False, """Performs per-image whitening by subtracting off its own mean and dividing by its own standard deviation.""") tf.app.flags.DEFINE_float( 'augHSVh', 0., """The stddev of HSV's Hue shift as pre-processing augmentation""") tf.app.flags.DEFINE_float( 'augHSVs', 0., """The stddev of HSV's Saturation shift as pre-processing augmentation""") tf.app.flags.DEFINE_float( 'augHSVv', 0., """The stddev of HSV's Value shift as pre-processing augmentation""") def save_timeline_trace(run_metadata, save_dir, step): tl = timeline.Timeline(run_metadata.step_stats) ctf = tl.generate_chrome_trace_format(show_memory=True) tl_fn = os.path.join(save_dir, 'timeline_%s.json' % step) with open(tl_fn, 'w') as f: f.write(ctf) logging.info('Timeline trace written to %s', tl_fn) def strip_data_from_graph_def(graph_def): strip_def = tf.GraphDef() for n0 in graph_def.node: n = strip_def.node.add() n.MergeFrom(n0) if n.op == 'Const': tensor = n.attr['value'].tensor if (tensor.tensor_content): tensor.tensor_content = '' if (tensor.string_val): del tensor.string_val[:] return strip_def def visualize_graph(graph_def, path): graph_def = strip_data_from_graph_def(graph_def) logging.info('Writing Graph Definition..') file_io.write_string_to_file(path, str(graph_def)) logging.info('Graph Definition Written.') def average_head_keys(tags, vals): """ Averages keys with same end (head) name. Example: foo1/bar=1 and foo2/bar=2 should collapse to bar=1.5 """ tail_tags = [w.split('/')[-1] for w in tags] sums = {} nums = {} for a, b in zip(tail_tags, vals): if a not in sums: sums[a] = b nums[a] = 1 else: sums[a] += b nums[a] += 1 tags_clean = sums.keys() return tags_clean, np.asarray(sums.values())/np.asarray(nums.values()) def summary_to_lists(summary_str): """ Takes a Tensorflow stringified Summary object and returns only the scalar values to a list of tags and a list of values Args: summary_str: string of a Tensorflow Summary object Returns: tags: list of tags vals: list of values corresponding to the tag list """ summ = summary_pb2.Summary() summ.ParseFromString(summary_str) tags = [] vals = [] for s in summ.value: if s.HasField('simple_value'): # and s.simple_value: # Only parse scalar_summaries if s.simple_value == float('Inf') or np.isnan(s.simple_value): raise ValueError('Model diverged with %s = %s : Try decreasing your learning rate' % (s.tag, s.simple_value)) tags.append(s.tag) vals.append(s.simple_value) tags, vals = average_head_keys(tags, vals) vals = np.asarray(vals) return tags, vals def print_summarylist(tags, vals): """ Prints a nice one-line listing of tags and their values in a nice format that corresponds to how the DIGITS regex reads it. Args: tags: an array of tags vals: an array of values Returns: print_list: a string containing formatted tags and values """ print_list = '' for i, key in enumerate(tags): if vals[i] == float('Inf'): raise ValueError('Infinite value %s = Inf' % key) print_list = print_list + key + " = " + "{:.6f}".format(vals[i]) if i < len(tags)-1: print_list = print_list + ", " return print_list def dump(obj): for attr in dir(obj): print("obj.%s = %s" % (attr, getattr(obj, attr))) def load_snapshot(sess, weight_path, var_candidates): """ Loads a snapshot into a session from a weight path. Will only load the weights that are both in the weight_path file and the passed var_candidates.""" logging.info("Loading weights from pretrained model - %s ", weight_path) reader = tf.train.NewCheckpointReader(weight_path) var_map = reader.get_variable_to_shape_map() # Only obtain all the variables that are [in the current graph] AND [in the checkpoint] vars_restore = [] for vt in var_candidates: for vm in var_map.keys(): if vt.name.split(':')[0] == vm: if ("global_step" not in vt.name) and not (vt.name.startswith("train/")): vars_restore.append(vt) logging.info('restoring %s -> %s' % (vm, vt.name)) else: logging.info('NOT restoring %s -> %s' % (vm, vt.name)) logging.info('Restoring %s variable ops.' % len(vars_restore)) tf.train.Saver(vars_restore, max_to_keep=0, sharded=FLAGS.serving_export).restore(sess, weight_path) logging.info('Variables restored.') def save_snapshot(sess, saver, save_dir, snapshot_prefix, epoch, for_serving=False): """ Saves a snapshot of the current session, saving all variables previously defined in the ctor of the saver. Also saves the flow of the graph itself (only once). """ number_dec = str(FLAGS.snapshotInterval-int(FLAGS.snapshotInterval))[2:] if number_dec is '': number_dec = '0' epoch_fmt = "{:." + number_dec + "f}" snapshot_file = os.path.join(save_dir, snapshot_prefix + '_' + epoch_fmt.format(epoch) + '.ckpt') logging.info('Snapshotting to %s', snapshot_file) checkpoint_path = saver.save(sess, snapshot_file) logging.info('Snapshot saved.') if for_serving: # @TODO(tzaman) : we could further extend this by supporting tensorflow-serve logging.error('NotImplementedError: Tensorflow-Serving support.') exit(-1) # Past this point the graph shouldn't be changed, so saving it once is enough filename_graph = os.path.join(save_dir, snapshot_prefix + '.graph_def') if not os.path.isfile(filename_graph): with open(filename_graph, 'wb') as f: logging.info('Saving graph to %s', filename_graph) f.write(sess.graph_def.SerializeToString()) logging.info('Saved graph to %s', filename_graph) # meta_graph_def = tf.train.export_meta_graph(filename='?') return checkpoint_path, filename_graph def save_weight_visualization(w_names, a_names, w, a): try: import h5py except ImportError: logging.error("Attempt to create HDF5 Loader but h5py is not installed.") exit(-1) fn = os.path.join(FLAGS.save, 'vis.h5') vis_db = h5py.File(fn, 'w') db_layers = vis_db.create_group("layers") logging.info('Saving visualization to %s', fn) for i in range(0, len(w)): dset = db_layers.create_group(str(i)) dset.attrs['var'] = w_names[i].name dset.attrs['op'] = a_names[i] if w[i].shape: dset.create_dataset('weights', data=w[i]) if a[i].shape: dset.create_dataset('activations', data=a[i]) vis_db.close() def Inference(sess, model): """ Runs one inference (evaluation) epoch (all the files in the loader) """ inference_op = model.towers[0].inference if FLAGS.labels_list: # Classification -> assume softmax usage # Append a softmax op inference_op = tf.nn.softmax(inference_op) weight_vars = [] activation_ops = [] if FLAGS.visualize_inf: trainable_weights = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES) # Retrace the origin op of each variable for n in tf.get_default_graph().as_graph_def().node: for tw in trainable_weights: tw_name_reader = tw.name.split(':')[0] + '/read' if tw_name_reader in n.input: node_op_name = n.name + ':0' # @TODO(tzaman) this assumes exactly 1 output - allow to be dynamic! weight_vars.append(tw) activation_ops.append(node_op_name) continue try: while not model.queue_coord.should_stop(): keys, preds, [w], [a] = sess.run([model.dataloader.batch_k, inference_op, [weight_vars], [activation_ops]]) if FLAGS.visualize_inf: save_weight_visualization(weight_vars, activation_ops, w, a) # @TODO(tzaman): error on no output? for i in range(len(keys)): # for j in range(len(preds)): # We're allowing multiple predictions per image here. DIGITS doesnt support that iirc logging.info('Predictions for image ' + str(model.dataloader.get_key_index(keys[i])) + ': ' + json.dumps(preds[i].tolist())) except tf.errors.OutOfRangeError: print('Done: tf.errors.OutOfRangeError') def Validation(sess, model, current_epoch): """ Runs one validation epoch. """ # @TODO(tzaman): utilize the coordinator by resetting the queue after 1 epoch. # see https://github.com/tensorflow/tensorflow/issues/4535#issuecomment-248990633 print_vals_sum = 0 steps = 0 while (steps * model.dataloader.batch_size) < model.dataloader.get_total(): summary_str = sess.run(model.summary) # Parse the summary tags, print_vals = summary_to_lists(summary_str) print_vals_sum = print_vals + print_vals_sum steps += 1 print_list = print_summarylist(tags, print_vals_sum/steps) logging.info("Validation (epoch " + str(current_epoch) + "): " + print_list) def loadLabels(filename): with open(filename) as f: return f.readlines() def main(_): # Always keep the cpu as default with tf.Graph().as_default(), tf.device('/cpu:0'): if FLAGS.validation_interval == 0: FLAGS.validation_db = None # Set Tensorboard log directory if FLAGS.summaries_dir: # The following gives a nice but unrobust timestamp FLAGS.summaries_dir = os.path.join(FLAGS.summaries_dir, datetime.datetime.now().strftime("%Y%m%d_%H%M%S")) if not FLAGS.train_db and not FLAGS.validation_db and not FLAGS.inference_db and not FLAGS.visualizeModelPath: logging.error("At least one of the following file sources should be specified: " "train_db, validation_db or inference_db") exit(-1) if FLAGS.seed: tf.set_random_seed(FLAGS.seed) batch_size_train = FLAGS.batch_size batch_size_val = FLAGS.batch_size logging.info("Train batch size is %s and validation batch size is %s", batch_size_train, batch_size_val) # This variable keeps track of next epoch, when to perform validation. next_validation = FLAGS.validation_interval logging.info("Training epochs to be completed for each validation : %s", next_validation) # This variable keeps track of next epoch, when to save model weights. next_snapshot_save = FLAGS.snapshotInterval logging.info("Training epochs to be completed before taking a snapshot : %s", next_snapshot_save) last_snapshot_save_epoch = 0 snapshot_prefix = FLAGS.snapshotPrefix if FLAGS.snapshotPrefix else FLAGS.network.split('.')[0] logging.info("Model weights will be saved as %s_<EPOCH>_Model.ckpt", snapshot_prefix) if not os.path.exists(FLAGS.save): os.makedirs(FLAGS.save) logging.info("Created a directory %s to save all the snapshots", FLAGS.save) # Load mean variable if FLAGS.subtractMean == 'none': mean_loader = None else: if not FLAGS.mean: logging.error("subtractMean parameter not set to 'none' yet mean image path is unset") exit(-1) logging.info("Loading mean tensor from %s file", FLAGS.mean) mean_loader = tf_data.MeanLoader(FLAGS.mean, FLAGS.subtractMean, FLAGS.bitdepth) classes = 0 nclasses = 0 if FLAGS.labels_list: logging.info("Loading label definitions from %s file", FLAGS.labels_list) classes = loadLabels(FLAGS.labels_list) nclasses = len(classes) if not classes: logging.error("Reading labels file %s failed.", FLAGS.labels_list) exit(-1) logging.info("Found %s classes", nclasses) # Create a data-augmentation dict aug_dict = { 'aug_flip': FLAGS.augFlip, 'aug_noise': FLAGS.augNoise, 'aug_contrast': FLAGS.augContrast, 'aug_whitening': FLAGS.augWhitening, 'aug_HSV': { 'h': FLAGS.augHSVh, 's': FLAGS.augHSVs, 'v': FLAGS.augHSVv, }, } # Import the network file path_network = os.path.join(os.path.dirname(os.path.realpath(__file__)), FLAGS.networkDirectory, FLAGS.network) exec(open(path_network).read(), globals()) try: UserModel except NameError: logging.error("The user model class 'UserModel' is not defined.") exit(-1) if not inspect.isclass(UserModel): # noqa logging.error("The user model class 'UserModel' is not a class.") exit(-1) # @TODO(tzaman) - add mode checks to UserModel if FLAGS.train_db: with tf.name_scope(digits.STAGE_TRAIN) as stage_scope: train_model = Model(digits.STAGE_TRAIN, FLAGS.croplen, nclasses, FLAGS.optimization, FLAGS.momentum) train_model.create_dataloader(FLAGS.train_db) train_model.dataloader.setup(FLAGS.train_labels, FLAGS.shuffle, FLAGS.bitdepth, batch_size_train, FLAGS.epoch, FLAGS.seed) train_model.dataloader.set_augmentation(mean_loader, aug_dict) train_model.create_model(UserModel, stage_scope) # noqa if FLAGS.validation_db: with tf.name_scope(digits.STAGE_VAL) as stage_scope: val_model = Model(digits.STAGE_VAL, FLAGS.croplen, nclasses, reuse_variable=True) val_model.create_dataloader(FLAGS.validation_db) val_model.dataloader.setup(FLAGS.validation_labels, False, FLAGS.bitdepth, batch_size_val, 1e9, FLAGS.seed) # @TODO(tzaman): set numepochs to 1 val_model.dataloader.set_augmentation(mean_loader) val_model.create_model(UserModel, stage_scope) # noqa if FLAGS.inference_db: with tf.name_scope(digits.STAGE_INF) as stage_scope: inf_model = Model(digits.STAGE_INF, FLAGS.croplen, nclasses) inf_model.create_dataloader(FLAGS.inference_db) inf_model.dataloader.setup(None, False, FLAGS.bitdepth, FLAGS.batch_size, 1, FLAGS.seed) inf_model.dataloader.set_augmentation(mean_loader) inf_model.create_model(UserModel, stage_scope) # noqa # Start running operations on the Graph. allow_soft_placement must be set to # True to build towers on GPU, as some of the ops do not have GPU # implementations. sess = tf.Session(config=tf.ConfigProto( allow_soft_placement=True, # will automatically do non-gpu supported ops on cpu inter_op_parallelism_threads=TF_INTER_OP_THREADS, intra_op_parallelism_threads=TF_INTRA_OP_THREADS, log_device_placement=FLAGS.log_device_placement)) if FLAGS.visualizeModelPath: visualize_graph(sess.graph_def, FLAGS.visualizeModelPath) exit(0) # Saver creation. if FLAGS.save_vars == 'all': vars_to_save = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES) elif FLAGS.save_vars == 'trainable': vars_to_save = tf.all_variables() else: logging.error('Unknown save_var flag (%s)' % FLAGS.save_vars) exit(-1) saver = tf.train.Saver(vars_to_save, max_to_keep=0, sharded=FLAGS.serving_export) # Initialize variables init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer()) sess.run(init_op) # If weights option is set, preload weights from existing models appropriately if FLAGS.weights: load_snapshot(sess, FLAGS.weights, tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)) # Tensorboard: Merge all the summaries and write them out writer = tf.summary.FileWriter(os.path.join(FLAGS.summaries_dir, 'tb'), sess.graph) # If we are inferencing, only do that. if FLAGS.inference_db: inf_model.start_queue_runners(sess) Inference(sess, inf_model) queue_size_op = [] for n in tf.get_default_graph().as_graph_def().node: if '_Size' in n.name: queue_size_op.append(n.name+':0') start = time.time() # @TODO(tzaman) - removeme # Initial Forward Validation Pass if FLAGS.validation_db: val_model.start_queue_runners(sess) Validation(sess, val_model, 0) if FLAGS.train_db: # During training, a log output should occur at least X times per epoch or every X images, whichever lower train_steps_per_epoch = train_model.dataloader.get_total() / batch_size_train if math.ceil(train_steps_per_epoch/MIN_LOGS_PER_TRAIN_EPOCH) < math.ceil(5000/batch_size_train): logging_interval_step = int(math.ceil(train_steps_per_epoch/MIN_LOGS_PER_TRAIN_EPOCH)) else: logging_interval_step = int(math.ceil(5000/batch_size_train)) logging.info("During training. details will be logged after every %s steps (batches)", logging_interval_step) # epoch value will be calculated for every batch size. To maintain unique epoch value between batches, # it needs to be rounded to the required number of significant digits. epoch_round = 0 # holds the required number of significant digits for round function. tmp_batchsize = batch_size_train*logging_interval_step while tmp_batchsize <= train_model.dataloader.get_total(): tmp_batchsize = tmp_batchsize * 10 epoch_round += 1 logging.info("While logging, epoch value will be rounded to %s significant digits", epoch_round) # Create the learning rate policy total_training_steps = train_model.dataloader.num_epochs * train_model.dataloader.get_total() / \ train_model.dataloader.batch_size lrpolicy = lr_policy.LRPolicy(FLAGS.lr_policy, FLAGS.lr_base_rate, FLAGS.lr_gamma, FLAGS.lr_power, total_training_steps, FLAGS.lr_stepvalues) train_model.start_queue_runners(sess) # Training logging.info('Started training the model') current_epoch = 0 try: step = 0 step_last_log = 0 print_vals_sum = 0 while not train_model.queue_coord.should_stop(): log_runtime = FLAGS.log_runtime_stats_per_step and (step % FLAGS.log_runtime_stats_per_step == 0) run_options = None run_metadata = None if log_runtime: # For a HARDWARE_TRACE you need NVIDIA CUPTI, a 'CUDA-EXTRA' # SOFTWARE_TRACE HARDWARE_TRACE FULL_TRACE run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE) run_metadata = tf.RunMetadata() feed_dict = {train_model.learning_rate: lrpolicy.get_learning_rate(step)} if False: for op in train_model.train: _, summary_str, step = sess.run([op, train_model.summary, train_model.global_step], feed_dict=feed_dict, options=run_options, run_metadata=run_metadata) else: _, summary_str, step = sess.run([train_model.train, train_model.summary, train_model.global_step], feed_dict=feed_dict, options=run_options, run_metadata=run_metadata) # HACK step = step / len(train_model.train) # logging.info(sess.run(queue_size_op)) # DEVELOPMENT: for checking the queue size if log_runtime: writer.add_run_metadata(run_metadata, str(step)) save_timeline_trace(run_metadata, FLAGS.save, int(step)) writer.add_summary(summary_str, step) # Parse the summary tags, print_vals = summary_to_lists(summary_str) print_vals_sum = print_vals + print_vals_sum # @TODO(tzaman): account for variable batch_size value on very last epoch current_epoch = round((step * batch_size_train) / train_model.dataloader.get_total(), epoch_round) # Start with a forward pass if ((step % logging_interval_step) == 0): steps_since_log = step - step_last_log print_list = print_summarylist(tags, print_vals_sum/steps_since_log) logging.info("Training (epoch " + str(current_epoch) + "): " + print_list) print_vals_sum = 0 step_last_log = step # Potential Validation Pass if FLAGS.validation_db and current_epoch >= next_validation: Validation(sess, val_model, current_epoch) # Find next nearest epoch value that exactly divisible by FLAGS.validation_interval: next_validation = (round(float(current_epoch)/FLAGS.validation_interval) + 1) * \ FLAGS.validation_interval # Saving Snapshot if FLAGS.snapshotInterval > 0 and current_epoch >= next_snapshot_save: checkpoint_path, graphdef_path = save_snapshot(sess, saver, FLAGS.save, snapshot_prefix, current_epoch, FLAGS.serving_export ) # To find next nearest epoch value that exactly divisible by FLAGS.snapshotInterval next_snapshot_save = (round(float(current_epoch)/FLAGS.snapshotInterval) + 1) * \ FLAGS.snapshotInterval last_snapshot_save_epoch = current_epoch writer.flush() except tf.errors.OutOfRangeError: logging.info('Done training for epochs: tf.errors.OutOfRangeError') except ValueError as err: logging.error(err.args[0]) exit(-1) # DIGITS wants a dirty error. except (KeyboardInterrupt): logging.info('Interrupt signal received.') # If required, perform final snapshot save if FLAGS.snapshotInterval > 0 and FLAGS.epoch > last_snapshot_save_epoch: checkpoint_path, graphdef_path =\ save_snapshot(sess, saver, FLAGS.save, snapshot_prefix, FLAGS.epoch, FLAGS.serving_export) print('Training wall-time:', time.time()-start) # @TODO(tzaman) - removeme # If required, perform final Validation pass if FLAGS.validation_db and current_epoch >= next_validation: Validation(sess, val_model, current_epoch) if FLAGS.train_db: if FLAGS.labels_list: output_tensor = train_model.towers[0].inference out_name, _ = output_tensor.name.split(':') if FLAGS.train_db: del train_model if FLAGS.validation_db: del val_model if FLAGS.inference_db: del inf_model # We need to call sess.close() because we've used a with block sess.close() writer.close() tf.reset_default_graph() del sess if FLAGS.train_db: if FLAGS.labels_list: path_frozen = os.path.join(FLAGS.save, 'frozen_model.pb') print('Saving frozen model at path {}'.format(path_frozen)) freeze_graph.freeze_graph( input_graph=graphdef_path, input_saver='', input_binary=True, input_checkpoint=checkpoint_path, output_node_names=out_name, restore_op_name="save/restore_all", filename_tensor_name="save/Const:0", output_graph=path_frozen, clear_devices=True, initializer_nodes="", ) logging.info('END') exit(0) if __name__ == '__main__': tf.app.run()
DIGITS-master
digits/tools/tensorflow/main.py
#!/usr/bin/env python2 # Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved. # # This document should comply with PEP-8 Style Guide # Linter: pylint """ TensorFlow training executable for DIGITS Defines the training procedure Usage: See the self-documenting flags below. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import threading import time import datetime import inspect import logging import math import numpy as np import os import pickle from six.moves import xrange import tensorflow as tf from tensorflow.python.client import timeline from tensorflow.python.lib.io import file_io from tensorflow.core.framework import summary_pb2 # Local imports import utils as digits import lr_policy from model import Model import tf_data import gandisplay # Constants TF_INTRA_OP_THREADS = 0 TF_INTER_OP_THREADS = 0 MIN_LOGS_PER_TRAIN_EPOCH = 8 # torch default: 8 CELEBA_ALL_ATTRIBUTES = """ 5_o_Clock_Shadow Arched_Eyebrows Attractive Bags_Under_Eyes Bald Bangs Big_Lips Big_Nose Black_Hair Blond_Hair Blurry Brown_Hair Bushy_Eyebrows Chubby Double_Chin Eyeglasses Goatee Gray_Hair Heavy_Makeup High_Cheekbones Male Mouth_Slightly_Open Mustache Narrow_Eyes No_Beard Oval_Face Pale_Skin Pointy_Nose Receding_Hairline Rosy_Cheeks Sideburns Smiling Straight_Hair Wavy_Hair Wearing_Earrings Wearing_Hat Wearing_Lipstick Wearing_Necklace Wearing_Necktie Young """.split() CELEBA_EDITABLE_ATTRIBUTES = [ 'Bald', 'Black_Hair', 'Blond_Hair', 'Eyeglasses', 'Male', 'Mustache', 'Smiling', 'Young', 'Attractive', 'Pale_Skin', 'Big_Nose' ] CELEBA_EDITABLE_ATTRIBUTES_IDS = [CELEBA_ALL_ATTRIBUTES.index(attr) for attr in CELEBA_EDITABLE_ATTRIBUTES] logging.basicConfig(format='%(asctime)s [%(levelname)s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO) FLAGS = tf.app.flags.FLAGS # Basic model parameters. #float, integer, boolean, string tf.app.flags.DEFINE_integer('batch_size', 16, """Number of images to process in a batch""") tf.app.flags.DEFINE_integer( 'croplen', 0, """Crop (x and y). A zero value means no cropping will be applied""") tf.app.flags.DEFINE_integer('epoch', 1, """Number of epochs to train, -1 for unbounded""") tf.app.flags.DEFINE_string('inference_db', '', """Directory with inference file source""") tf.app.flags.DEFINE_integer( 'validation_interval', 1, """Number of train epochs to complete, to perform one validation""") tf.app.flags.DEFINE_string('labels_list', '', """Text file listing label definitions""") tf.app.flags.DEFINE_string('mean', '', """Mean image file""") tf.app.flags.DEFINE_float('momentum', '0.9', """Momentum""") # Not used by DIGITS front-end tf.app.flags.DEFINE_string('network', '', """File containing network (model)""") tf.app.flags.DEFINE_string('networkDirectory', '', """Directory in which network exists""") tf.app.flags.DEFINE_string('optimization', 'sgd', """Optimization method""") tf.app.flags.DEFINE_string('save', 'results', """Save directory""") tf.app.flags.DEFINE_integer('seed', 0, """Fixed input seed for repeatable experiments""") tf.app.flags.DEFINE_boolean('shuffle', False, """Shuffle records before training""") tf.app.flags.DEFINE_float( 'snapshotInterval', 1.0, """Specifies the training epochs to be completed before taking a snapshot""") tf.app.flags.DEFINE_string('snapshotPrefix', '', """Prefix of the weights/snapshots""") tf.app.flags.DEFINE_string( 'subtractMean', 'none', """Select mean subtraction method. Possible values are 'image', 'pixel' or 'none'""") tf.app.flags.DEFINE_string('train_db', '', """Directory with training file source""") tf.app.flags.DEFINE_string( 'train_labels', '', """Directory with an optional and seperate labels file source for training""") tf.app.flags.DEFINE_string('validation_db', '', """Directory with validation file source""") tf.app.flags.DEFINE_string( 'validation_labels', '', """Directory with an optional and seperate labels file source for validation""") tf.app.flags.DEFINE_string( 'visualizeModelPath', '', """Constructs the current model for visualization""") tf.app.flags.DEFINE_boolean( 'visualize_inf', False, """Will output weights and activations for an inference job.""") tf.app.flags.DEFINE_string( 'weights', '', """Filename for weights of a model to use for fine-tuning""") # @TODO(tzaman): is the bitdepth in line with the DIGITS team? tf.app.flags.DEFINE_integer('bitdepth', 8, """Specifies an image's bitdepth""") # @TODO(tzaman); remove torch mentions below tf.app.flags.DEFINE_float('lr_base_rate', '0.01', """Learning rate""") tf.app.flags.DEFINE_string( 'lr_policy', 'fixed', """Learning rate policy. (fixed, step, exp, inv, multistep, poly, sigmoid)""") tf.app.flags.DEFINE_float( 'lr_gamma', -1, """Required to calculate learning rate. Applies to: (step, exp, inv, multistep, sigmoid)""") tf.app.flags.DEFINE_float( 'lr_power', float('Inf'), """Required to calculate learning rate. Applies to: (inv, poly)""") tf.app.flags.DEFINE_string( 'lr_stepvalues', '', """Required to calculate stepsize of the learning rate. Applies to: (step, multistep, sigmoid). For the 'multistep' lr_policy you can input multiple values seperated by commas""") # Tensorflow-unique arguments for DIGITS tf.app.flags.DEFINE_string( 'save_vars', 'all', """Sets the collection of variables to be saved: 'all' or only 'trainable'.""") tf.app.flags.DEFINE_string('summaries_dir', '', """Directory of Tensorboard Summaries (logdir)""") tf.app.flags.DEFINE_boolean( 'serving_export', False, """Flag for exporting an Tensorflow Serving model""") tf.app.flags.DEFINE_boolean('log_device_placement', False, """Whether to log device placement.""") tf.app.flags.DEFINE_integer( 'log_runtime_stats_per_step', 0, """Logs runtime statistics for Tensorboard every x steps, defaults to 0 (off).""") # Augmentation tf.app.flags.DEFINE_string( 'augFlip', 'none', """The flip options {none, fliplr, flipud, fliplrud} as randompre-processing augmentation""") tf.app.flags.DEFINE_float( 'augNoise', 0., """The stddev of Noise in AWGN as pre-processing augmentation""") tf.app.flags.DEFINE_float( 'augContrast', 0., """The contrast factor's bounds as sampled from a random-uniform distribution as pre-processing augmentation""") tf.app.flags.DEFINE_bool( 'augWhitening', False, """Performs per-image whitening by subtracting off its own mean and dividing by its own standard deviation.""") tf.app.flags.DEFINE_float( 'augHSVh', 0., """The stddev of HSV's Hue shift as pre-processing augmentation""") tf.app.flags.DEFINE_float( 'augHSVs', 0., """The stddev of HSV's Saturation shift as pre-processing augmentation""") tf.app.flags.DEFINE_float( 'augHSVv', 0., """The stddev of HSV's Value shift as pre-processing augmentation""") # GAN Grid tf.app.flags.DEFINE_string('zs_file', 'zs.pkl', """Pickle file containing z vectors to use""") tf.app.flags.DEFINE_string('attributes_file', 'attributes.pkl', """Pickle file containing attribute vectors""") def save_timeline_trace(run_metadata, save_dir, step): tl = timeline.Timeline(run_metadata.step_stats) ctf = tl.generate_chrome_trace_format(show_memory=True) tl_fn = os.path.join(save_dir, 'timeline_%s.json' % step) with open(tl_fn, 'w') as f: f.write(ctf) logging.info('Timeline trace written to %s', tl_fn) def strip_data_from_graph_def(graph_def): strip_def = tf.GraphDef() for n0 in graph_def.node: n = strip_def.node.add() n.MergeFrom(n0) if n.op == 'Const': tensor = n.attr['value'].tensor if (tensor.tensor_content): tensor.tensor_content = '' if (tensor.string_val): del tensor.string_val[:] return strip_def def visualize_graph(graph_def, path): graph_def = strip_data_from_graph_def(graph_def) logging.info('Writing Graph Definition..') file_io.write_string_to_file(path, str(graph_def)) logging.info('Graph Definition Written.') def average_head_keys(tags, vals): """ Averages keys with same end (head) name. Example: foo1/bar=1 and foo2/bar=2 should collapse to bar=1.5 """ tail_tags = [w.split('/')[-1] for w in tags] sums = {} nums = {} for a, b in zip(tail_tags, vals): if a not in sums: sums[a] = b nums[a] = 1 else: sums[a] += b nums[a] += 1 tags_clean = sums.keys() return tags_clean, np.asarray(sums.values())/np.asarray(nums.values()) def summary_to_lists(summary_str): """ Takes a Tensorflow stringified Summary object and returns only the scalar values to a list of tags and a list of values Args: summary_str: string of a Tensorflow Summary object Returns: tags: list of tags vals: list of values corresponding to the tag list """ summ = summary_pb2.Summary() summ.ParseFromString(summary_str) tags = [] vals = [] for s in summ.value: if s.HasField('simple_value'): # and s.simple_value: # Only parse scalar_summaries if s.simple_value == float('Inf') or np.isnan(s.simple_value): raise ValueError('Model diverged with %s = %s : Try decreasing your learning rate' % (s.tag, s.simple_value)) tags.append(s.tag) vals.append(s.simple_value) tags, vals = average_head_keys(tags, vals) vals = np.asarray(vals) return tags, vals def print_summarylist(tags, vals): """ Prints a nice one-line listing of tags and their values in a nice format that corresponds to how the DIGITS regex reads it. Args: tags: an array of tags vals: an array of values Returns: print_list: a string containing formatted tags and values """ print_list = '' for i, key in enumerate(tags): if vals[i] == float('Inf'): raise ValueError('Infinite value %s = Inf' % key) print_list = print_list + key + " = " + "{:.6f}".format(vals[i]) if i < len(tags)-1: print_list = print_list + ", " return print_list def dump(obj): for attr in dir(obj): print("obj.%s = %s" % (attr, getattr(obj, attr))) def load_snapshot(sess, weight_path, var_candidates): """ Loads a snapshot into a session from a weight path. Will only load the weights that are both in the weight_path file and the passed var_candidates.""" logging.info("Loading weights from pretrained model - %s ", weight_path) reader = tf.train.NewCheckpointReader(weight_path) var_map = reader.get_variable_to_shape_map() # Only obtain all the variables that are [in the current graph] AND [in the checkpoint] vars_restore = [] for vt in var_candidates: for vm in var_map.keys(): if vt.name.split(':')[0] == vm: if ("global_step" not in vt.name) and not (vt.name.startswith("train/")): vars_restore.append(vt) logging.info('restoring %s -> %s' % (vm, vt.name)) else: logging.info('NOT restoring %s -> %s' % (vm, vt.name)) logging.info('Restoring %s variable ops.' % len(vars_restore)) tf.train.Saver(vars_restore, max_to_keep=0, sharded=FLAGS.serving_export).restore(sess, weight_path) logging.info('Variables restored.') def save_snapshot(sess, saver, save_dir, snapshot_prefix, epoch, for_serving=False): """ Saves a snapshot of the current session, saving all variables previously defined in the ctor of the saver. Also saves the flow of the graph itself (only once). """ number_dec = str(FLAGS.snapshotInterval-int(FLAGS.snapshotInterval))[2:] if number_dec is '': number_dec = '0' epoch_fmt = "{:." + number_dec + "f}" snapshot_file = os.path.join(save_dir, snapshot_prefix + '_' + epoch_fmt.format(epoch) + '.ckpt') logging.info('Snapshotting to %s', snapshot_file) saver.save(sess, snapshot_file) logging.info('Snapshot saved.') if for_serving: # @TODO(tzaman) : we could further extend this by supporting tensorflow-serve logging.error('NotImplementedError: Tensorflow-Serving support.') exit(-1) # Past this point the graph shouldn't be changed, so saving it once is enough filename_graph = os.path.join(save_dir, snapshot_prefix + '.graph_def') if not os.path.isfile(filename_graph): with open(filename_graph, 'wb') as f: logging.info('Saving graph to %s', filename_graph) f.write(sess.graph_def.SerializeToString()) logging.info('Saved graph to %s', filename_graph) # meta_graph_def = tf.train.export_meta_graph(filename='?') def save_weight_visualization(w_names, a_names, w, a): try: import h5py except ImportError: logging.error("Attempt to create HDF5 Loader but h5py is not installed.") exit(-1) fn = os.path.join(FLAGS.save, 'vis.h5') vis_db = h5py.File(fn, 'w') db_layers = vis_db.create_group("layers") logging.info('Saving visualization to %s', fn) for i in range(0, len(w)): dset = db_layers.create_group(str(i)) dset.attrs['var'] = w_names[i].name dset.attrs['op'] = a_names[i] if w[i].shape: dset.create_dataset('weights', data=w[i]) if a[i].shape: dset.create_dataset('activations', data=a[i]) vis_db.close() def Inference(sess, model): """ Runs one inference (evaluation) epoch (all the files in the loader) """ inference_op = model.towers[0].inference if FLAGS.labels_list: # Classification -> assume softmax usage # Append a softmax op inference_op = tf.nn.softmax(inference_op) weight_vars = [] activation_ops = [] if FLAGS.visualize_inf: trainable_weights = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES) # Retrace the origin op of each variable for n in tf.get_default_graph().as_graph_def().node: for tw in trainable_weights: tw_name_reader = tw.name.split(':')[0] + '/read' if tw_name_reader in n.input: node_op_name = n.name + ':0' # @TODO(tzaman) this assumes exactly 1 output - allow to be dynamic! weight_vars.append(tw) activation_ops.append(node_op_name) continue try: t = 0 with open(FLAGS.attributes_file, 'rb') as f: attribute_zs = pickle.load(f) while not False: # model.queue_coord.should_stop(): attributes = app.GetAttributes() z = np.zeros(100) for idx, attr_scale in enumerate(attributes): z += (attr_scale / 25) * attribute_zs[CELEBA_EDITABLE_ATTRIBUTES_IDS[idx]] feed_dict = {model.time_placeholder: float(t), model.attribute_placeholder: z} preds = sess.run(fetches=inference_op, feed_dict=feed_dict) app.DisplayCell(preds) t += 1e-5 * app.GetSpeed() * FLAGS.batch_size except tf.errors.OutOfRangeError: print('Done: tf.errors.OutOfRangeError') def Validation(sess, model, current_epoch): """ Runs one validation epoch. """ # @TODO(tzaman): utilize the coordinator by resetting the queue after 1 epoch. # see https://github.com/tensorflow/tensorflow/issues/4535#issuecomment-248990633 print_vals_sum = 0 steps = 0 while (steps * model.dataloader.batch_size) < model.dataloader.get_total(): summary_str = sess.run(model.summary) # Parse the summary tags, print_vals = summary_to_lists(summary_str) print_vals_sum = print_vals + print_vals_sum steps += 1 print_list = print_summarylist(tags, print_vals_sum/steps) logging.info("Validation (epoch " + str(current_epoch) + "): " + print_list) def loadLabels(filename): with open(filename) as f: return f.readlines() def input_generator(zs_file, batch_size): time_placeholder = tf.placeholder(dtype=tf.float32, shape=()) attribute_placeholder = tf.placeholder(dtype=tf.float32, shape=(100,)) def l2_norm(x): euclidean_norm = tf.sqrt(tf.reduce_sum(tf.square(x))) return euclidean_norm def dot_product(x, y): return tf.reduce_sum(tf.mul(x, y)) def slerp(initial, final, progress): omega = tf.acos(dot_product(initial / l2_norm(initial), final / l2_norm(final))) so = tf.sin(omega) return tf.sin((1.0-progress)*omega) / so * initial + tf.sin(progress*omega)/so * final with open(zs_file, 'rb') as f: zs = pickle.load(f) img_count = len(zs) zs = tf.constant(zs, dtype=tf.float32) tensors = [] epoch = tf.to_int32(time_placeholder) indices = tf.range(batch_size) indices_init = (indices * batch_size + epoch) % img_count indices_final = (indices_init + 1) % img_count for i in xrange(batch_size): z_init = zs[indices_init[i]] z_final = zs[indices_final[i]] progress = tf.mod(time_placeholder, 1) # progress = tf.Print(progress, [progress]) z = slerp(z_init, z_final, progress) tensors.append(z) batch = tf.pack(tensors) + attribute_placeholder return batch, time_placeholder, attribute_placeholder def main(_): # Always keep the cpu as default with tf.Graph().as_default(), tf.device('/cpu:0'): if FLAGS.validation_interval == 0: FLAGS.validation_db = None # Set Tensorboard log directory if FLAGS.summaries_dir: # The following gives a nice but unrobust timestamp FLAGS.summaries_dir = os.path.join(FLAGS.summaries_dir, datetime.datetime.now().strftime("%Y%m%d_%H%M%S")) if not FLAGS.train_db and not FLAGS.validation_db and not FLAGS.inference_db and not FLAGS.visualizeModelPath: logging.error("At least one of the following file sources should be specified: " "train_db, validation_db or inference_db") exit(-1) if FLAGS.seed: tf.set_random_seed(FLAGS.seed) batch_size_train = FLAGS.batch_size batch_size_val = FLAGS.batch_size logging.info("Train batch size is %s and validation batch size is %s", batch_size_train, batch_size_val) # This variable keeps track of next epoch, when to perform validation. next_validation = FLAGS.validation_interval logging.info("Training epochs to be completed for each validation : %s", next_validation) # This variable keeps track of next epoch, when to save model weights. next_snapshot_save = FLAGS.snapshotInterval logging.info("Training epochs to be completed before taking a snapshot : %s", next_snapshot_save) last_snapshot_save_epoch = 0 snapshot_prefix = FLAGS.snapshotPrefix if FLAGS.snapshotPrefix else FLAGS.network.split('.')[0] logging.info("Model weights will be saved as %s_<EPOCH>_Model.ckpt", snapshot_prefix) if not os.path.exists(FLAGS.save): os.makedirs(FLAGS.save) logging.info("Created a directory %s to save all the snapshots", FLAGS.save) # Load mean variable if FLAGS.subtractMean == 'none': mean_loader = None else: if not FLAGS.mean: logging.error("subtractMean parameter not set to 'none' yet mean image path is unset") exit(-1) logging.info("Loading mean tensor from %s file", FLAGS.mean) mean_loader = tf_data.MeanLoader(FLAGS.mean, FLAGS.subtractMean, FLAGS.bitdepth) classes = 0 nclasses = 0 if FLAGS.labels_list: logging.info("Loading label definitions from %s file", FLAGS.labels_list) classes = loadLabels(FLAGS.labels_list) nclasses = len(classes) if not classes: logging.error("Reading labels file %s failed.", FLAGS.labels_list) exit(-1) logging.info("Found %s classes", nclasses) # Create a data-augmentation dict aug_dict = { 'aug_flip': FLAGS.augFlip, 'aug_noise': FLAGS.augNoise, 'aug_contrast': FLAGS.augContrast, 'aug_whitening': FLAGS.augWhitening, 'aug_HSV': { 'h': FLAGS.augHSVh, 's': FLAGS.augHSVs, 'v': FLAGS.augHSVv, }, } # hard-code GAN inference FLAGS.inference_db = "grid.gan" # Import the network file path_network = os.path.join(os.path.dirname(os.path.realpath(__file__)), FLAGS.networkDirectory, FLAGS.network) exec(open(path_network).read(), globals()) try: UserModel except NameError: logging.error("The user model class 'UserModel' is not defined.") exit(-1) if not inspect.isclass(UserModel): # noqa logging.error("The user model class 'UserModel' is not a class.") exit(-1) # @TODO(tzaman) - add mode checks to UserModel if FLAGS.train_db: with tf.name_scope(digits.STAGE_TRAIN) as stage_scope: train_model = Model(digits.STAGE_TRAIN, FLAGS.croplen, nclasses, FLAGS.optimization, FLAGS.momentum) train_model.create_dataloader(FLAGS.train_db) train_model.dataloader.setup(FLAGS.train_labels, FLAGS.shuffle, FLAGS.bitdepth, batch_size_train, FLAGS.epoch, FLAGS.seed) train_model.dataloader.set_augmentation(mean_loader, aug_dict) train_model.create_model(UserModel, stage_scope) # noqa if FLAGS.validation_db: with tf.name_scope(digits.STAGE_VAL) as stage_scope: val_model = Model(digits.STAGE_VAL, FLAGS.croplen, nclasses) val_model.create_dataloader(FLAGS.validation_db) val_model.dataloader.setup(FLAGS.validation_labels, False, FLAGS.bitdepth, batch_size_val, 1e9, FLAGS.seed) # @TODO(tzaman): set numepochs to 1 val_model.dataloader.set_augmentation(mean_loader) val_model.create_model(UserModel, stage_scope) # noqa if FLAGS.inference_db: with tf.name_scope(digits.STAGE_INF) as stage_scope: inf_model = Model(digits.STAGE_INF, FLAGS.croplen, nclasses) inf_model.create_dataloader(FLAGS.inference_db) inf_model.dataloader.setup(None, False, FLAGS.bitdepth, FLAGS.batch_size, 1, FLAGS.seed) inf_model.dataloader.set_augmentation(mean_loader) batch_x, time_placeholder, attribute_placeholder = input_generator(FLAGS.zs_file, FLAGS.batch_size) inf_model.create_model(UserModel, stage_scope, batch_x=batch_x) # noqa inf_model.time_placeholder = time_placeholder inf_model.attribute_placeholder = attribute_placeholder # Start running operations on the Graph. allow_soft_placement must be set to # True to build towers on GPU, as some of the ops do not have GPU # implementations. sess = tf.Session(config=tf.ConfigProto( allow_soft_placement=True, # will automatically do non-gpu supported ops on cpu inter_op_parallelism_threads=TF_INTER_OP_THREADS, intra_op_parallelism_threads=TF_INTRA_OP_THREADS, log_device_placement=FLAGS.log_device_placement)) if FLAGS.visualizeModelPath: visualize_graph(sess.graph_def, FLAGS.visualizeModelPath) exit(0) # Saver creation. if FLAGS.save_vars == 'all': vars_to_save = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES) elif FLAGS.save_vars == 'trainable': vars_to_save = tf.all_variables() else: logging.error('Unknown save_var flag (%s)' % FLAGS.save_vars) exit(-1) saver = tf.train.Saver(vars_to_save, max_to_keep=0, sharded=FLAGS.serving_export) # Initialize variables init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer()) sess.run(init_op) # If weights option is set, preload weights from existing models appropriately if FLAGS.weights: load_snapshot(sess, FLAGS.weights, tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)) # Tensorboard: Merge all the summaries and write them out writer = tf.train.SummaryWriter(os.path.join(FLAGS.summaries_dir, 'tb'), sess.graph) # If we are inferencing, only do that. if FLAGS.inference_db: inf_model.start_queue_runners(sess) Inference(sess, inf_model) queue_size_op = [] for n in tf.get_default_graph().as_graph_def().node: if '_Size' in n.name: queue_size_op.append(n.name+':0') start = time.time() # @TODO(tzaman) - removeme # Initial Forward Validation Pass if FLAGS.validation_db: val_model.start_queue_runners(sess) Validation(sess, val_model, 0) if FLAGS.train_db: # During training, a log output should occur at least X times per epoch or every X images, whichever lower train_steps_per_epoch = train_model.dataloader.get_total() / batch_size_train if math.ceil(train_steps_per_epoch/MIN_LOGS_PER_TRAIN_EPOCH) < math.ceil(5000/batch_size_train): logging_interval_step = int(math.ceil(train_steps_per_epoch/MIN_LOGS_PER_TRAIN_EPOCH)) else: logging_interval_step = int(math.ceil(5000/batch_size_train)) logging.info("During training. details will be logged after every %s steps (batches)", logging_interval_step) # epoch value will be calculated for every batch size. To maintain unique epoch value between batches, # it needs to be rounded to the required number of significant digits. epoch_round = 0 # holds the required number of significant digits for round function. tmp_batchsize = batch_size_train*logging_interval_step while tmp_batchsize <= train_model.dataloader.get_total(): tmp_batchsize = tmp_batchsize * 10 epoch_round += 1 logging.info("While logging, epoch value will be rounded to %s significant digits", epoch_round) # Create the learning rate policy total_training_steps = train_model.dataloader.num_epochs * train_model.dataloader.get_total() / \ train_model.dataloader.batch_size lrpolicy = lr_policy.LRPolicy(FLAGS.lr_policy, FLAGS.lr_base_rate, FLAGS.lr_gamma, FLAGS.lr_power, total_training_steps, FLAGS.lr_stepvalues) train_model.start_queue_runners(sess) # Training logging.info('Started training the model') current_epoch = 0 try: step = 0 step_last_log = 0 print_vals_sum = 0 while not train_model.queue_coord.should_stop(): log_runtime = FLAGS.log_runtime_stats_per_step and (step % FLAGS.log_runtime_stats_per_step == 0) run_options = None run_metadata = None if log_runtime: # For a HARDWARE_TRACE you need NVIDIA CUPTI, a 'CUDA-EXTRA' # SOFTWARE_TRACE HARDWARE_TRACE FULL_TRACE run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE) run_metadata = tf.RunMetadata() feed_dict = {train_model.learning_rate: lrpolicy.get_learning_rate(step)} if False: for op in train_model.train: _, summary_str, step = sess.run([op, train_model.summary, train_model.global_step], feed_dict=feed_dict, options=run_options, run_metadata=run_metadata) else: _, summary_str, step = sess.run([train_model.train, train_model.summary, train_model.global_step], feed_dict=feed_dict, options=run_options, run_metadata=run_metadata) # HACK step = step / len(train_model.train) # logging.info(sess.run(queue_size_op)) # DEVELOPMENT: for checking the queue size if log_runtime: writer.add_run_metadata(run_metadata, str(step)) save_timeline_trace(run_metadata, FLAGS.save, int(step)) writer.add_summary(summary_str, step) # Parse the summary tags, print_vals = summary_to_lists(summary_str) print_vals_sum = print_vals + print_vals_sum # @TODO(tzaman): account for variable batch_size value on very last epoch current_epoch = round((step * batch_size_train) / train_model.dataloader.get_total(), epoch_round) # Start with a forward pass if ((step % logging_interval_step) == 0): steps_since_log = step - step_last_log print_list = print_summarylist(tags, print_vals_sum/steps_since_log) logging.info("Training (epoch " + str(current_epoch) + "): " + print_list) print_vals_sum = 0 step_last_log = step # Potential Validation Pass if FLAGS.validation_db and current_epoch >= next_validation: Validation(sess, val_model, current_epoch) # Find next nearest epoch value that exactly divisible by FLAGS.validation_interval: next_validation = (round(float(current_epoch)/FLAGS.validation_interval) + 1) * \ FLAGS.validation_interval # Saving Snapshot if FLAGS.snapshotInterval > 0 and current_epoch >= next_snapshot_save: save_snapshot(sess, saver, FLAGS.save, snapshot_prefix, current_epoch, FLAGS.serving_export) # To find next nearest epoch value that exactly divisible by FLAGS.snapshotInterval next_snapshot_save = (round(float(current_epoch)/FLAGS.snapshotInterval) + 1) * \ FLAGS.snapshotInterval last_snapshot_save_epoch = current_epoch writer.flush() except tf.errors.OutOfRangeError: logging.info('Done training for epochs: tf.errors.OutOfRangeError') except ValueError as err: logging.error(err.args[0]) exit(-1) # DIGITS wants a dirty error. except (KeyboardInterrupt): logging.info('Interrupt signal received.') # If required, perform final snapshot save if FLAGS.snapshotInterval > 0 and FLAGS.epoch > last_snapshot_save_epoch: save_snapshot(sess, saver, FLAGS.save, snapshot_prefix, FLAGS.epoch, FLAGS.serving_export) print('Training wall-time:', time.time()-start) # @TODO(tzaman) - removeme # If required, perform final Validation pass if FLAGS.validation_db and current_epoch >= next_validation: Validation(sess, val_model, current_epoch) if FLAGS.train_db: del train_model if FLAGS.validation_db: del val_model if FLAGS.inference_db: del inf_model # We need to call sess.close() because we've used a with block sess.close() writer.close() logging.info('END') exit(0) if __name__ == '__main__': app = gandisplay.DemoApp(0, grid_size=np.sqrt(FLAGS.batch_size)*64, attributes=CELEBA_EDITABLE_ATTRIBUTES) t = threading.Thread(target=tf.app.run, args=()) t.start() app.MainLoop()
DIGITS-master
digits/tools/tensorflow/gan_grid.py
# Copyright (c) 2015-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import imp import os import platform import re import subprocess import sys from . import option_list from digits import device_query from digits.utils import parse_version def load_from_envvar(envvar): """ Load information from an installation indicated by an environment variable """ value = os.environ[envvar].strip().strip("\"' ") if platform.system() == 'Windows': executable_dir = os.path.join(value, 'install', 'bin') python_dir = os.path.join(value, 'install', 'python') else: executable_dir = os.path.join(value, 'build', 'tools') python_dir = os.path.join(value, 'python') try: executable = find_executable_in_dir(executable_dir) if executable is None: raise ValueError('Caffe executable not found at "%s"' % executable_dir) if not is_pycaffe_in_dir(python_dir): raise ValueError('Pycaffe not found in "%s"' % python_dir) import_pycaffe(python_dir) version, flavor = get_version_and_flavor(executable) except: print ('"%s" from %s does not point to a valid installation of Caffe.' % (value, envvar)) print 'Use the envvar CAFFE_ROOT to indicate a valid installation.' raise return executable, version, flavor def load_from_path(): """ Load information from an installation on standard paths (PATH and PYTHONPATH) """ try: executable = find_executable_in_dir() if executable is None: raise ValueError('Caffe executable not found in PATH') if not is_pycaffe_in_dir(): raise ValueError('Pycaffe not found in PYTHONPATH') import_pycaffe() version, flavor = get_version_and_flavor(executable) except: print 'A valid Caffe installation was not found on your system.' print 'Use the envvar CAFFE_ROOT to indicate a valid installation.' raise return executable, version, flavor def find_executable_in_dir(dirname=None): """ Returns the path to the caffe executable at dirname If dirname is None, search all directories in sys.path Returns None if not found """ if platform.system() == 'Windows': exe_name = 'caffe.exe' else: exe_name = 'caffe' if dirname is None: dirnames = [path.strip("\"' ") for path in os.environ['PATH'].split(os.pathsep)] else: dirnames = [dirname] for dirname in dirnames: path = os.path.join(dirname, exe_name) if os.path.isfile(path) and os.access(path, os.X_OK): return path return None def is_pycaffe_in_dir(dirname=None): """ Returns True if you can "import caffe" from dirname If dirname is None, search all directories in sys.path """ old_path = sys.path if dirname is not None: sys.path = [dirname] # temporarily replace sys.path try: imp.find_module('caffe') except ImportError: return False finally: sys.path = old_path return True def import_pycaffe(dirname=None): """ Imports caffe If dirname is not None, prepend it to sys.path first """ if dirname is not None: sys.path.insert(0, dirname) # Add to PYTHONPATH so that build/tools/caffe is aware of python layers there os.environ['PYTHONPATH'] = '%s%s%s' % ( dirname, os.pathsep, os.environ.get('PYTHONPATH')) # Suppress GLOG output for python bindings GLOG_minloglevel = os.environ.pop('GLOG_minloglevel', None) # Show only "ERROR" and "FATAL" os.environ['GLOG_minloglevel'] = '2' # for Windows environment, loading h5py before caffe solves the issue mentioned in # https://github.com/NVIDIA/DIGITS/issues/47#issuecomment-206292824 import h5py # noqa try: import caffe except ImportError: print 'Did you forget to "make pycaffe"?' raise # Strange issue with protocol buffers and pickle - see issue #32 sys.path.insert(0, os.path.join( os.path.dirname(caffe.__file__), 'proto')) # Turn GLOG output back on for subprocess calls if GLOG_minloglevel is None: del os.environ['GLOG_minloglevel'] else: os.environ['GLOG_minloglevel'] = GLOG_minloglevel def get_version_and_flavor(executable): """ Returns (version, flavor) Should be called after import_pycaffe() """ version_string = get_version_from_pycaffe() if version_string is None: version_string = get_version_from_cmdline(executable) if version_string is None: version_string = get_version_from_soname(executable) if version_string is None: raise ValueError('Could not find version information for Caffe build ' + 'at "%s". Upgrade your installation' % executable) version = parse_version(version_string) if parse_version(0, 99, 0) > version > parse_version(0, 9, 0): flavor = 'NVIDIA' minimum_version = '0.11.0' if version < parse_version(minimum_version): raise ValueError( 'Required version "%s" is greater than "%s". Upgrade your installation.' % (minimum_version, version_string)) else: flavor = 'BVLC' return version_string, flavor def get_version_from_pycaffe(): try: from caffe import __version__ as version return version except ImportError: return None def get_version_from_cmdline(executable): command = [executable, '-version'] p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if p.wait(): print p.stderr.read().strip() raise RuntimeError('"%s" returned error code %s' % (command, p.returncode)) pattern = 'version' for line in p.stdout: if pattern in line: return line[line.find(pattern) + len(pattern) + 1:].strip() return None def get_version_from_soname(executable): command = ['ldd', executable] p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if p.wait(): print p.stderr.read().strip() raise RuntimeError('"%s" returned error code %s' % (command, p.returncode)) # Search output for caffe library libname = 'libcaffe' caffe_line = None for line in p.stdout: if libname in line: caffe_line = line break if caffe_line is None: raise ValueError('libcaffe not found in linked libraries for "%s"' % executable) # Read the symlink for libcaffe from ldd output symlink = caffe_line.split()[2] filename = os.path.basename(os.path.realpath(symlink)) # parse the version string match = re.match(r'%s(.*)\.so\.(\S+)$' % (libname), filename) if match: return match.group(2) else: return None if 'CAFFE_ROOT' in os.environ: executable, version, flavor = load_from_envvar('CAFFE_ROOT') elif 'CAFFE_HOME' in os.environ: executable, version, flavor = load_from_envvar('CAFFE_HOME') else: executable, version, flavor = load_from_path() option_list['caffe'] = { 'executable': executable, 'version': version, 'flavor': flavor, 'multi_gpu': (flavor == 'BVLC' or parse_version(version) >= parse_version(0, 12)), 'cuda_enabled': (len(device_query.get_devices()) > 0), }
DIGITS-master
digits/config/caffe.py
# Copyright (c) 2015-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import os import tempfile from . import option_list import digits if 'DIGITS_MODE_TEST' in os.environ: value = tempfile.mkdtemp() elif 'DIGITS_JOBS_DIR' in os.environ: value = os.environ['DIGITS_JOBS_DIR'] else: value = os.path.join(os.path.dirname(digits.__file__), 'jobs') try: value = os.path.abspath(value) if os.path.exists(value): if not os.path.isdir(value): raise IOError('No such directory: "%s"' % value) if not os.access(value, os.W_OK): raise IOError('Permission denied: "%s"' % value) if not os.path.exists(value): os.makedirs(value) except: print '"%s" is not a valid value for jobs_dir.' % value print 'Set the envvar DIGITS_JOBS_DIR to fix your configuration.' raise option_list['jobs_dir'] = value
DIGITS-master
digits/config/jobs_dir.py
# Copyright (c) 2015-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import # Create this object before importing the following imports, since they edit the list option_list = {} from . import ( # noqa caffe, gpu_list, jobs_dir, log_file, torch, server_name, store_option, tensorflow, url_prefix, ) def config_value(option): """ Return the current configuration value for the given option """ return option_list[option]
DIGITS-master
digits/config/__init__.py
# Copyright (c) 2015-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import os import platform from . import option_list if 'DIGITS_SERVER_NAME' in os.environ: value = os.environ['DIGITS_SERVER_NAME'] else: value = platform.node() option_list['server_name'] = value
DIGITS-master
digits/config/server_name.py
# Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import from . import option_list def test_tf_import(): """ Tests if tensorflow can be imported, returns if it went okay and optional error. """ try: import tensorflow # noqa return True except (ImportError, TypeError): return False tf_enabled = test_tf_import() if not tf_enabled: print('Tensorflow support disabled.') if tf_enabled: option_list['tensorflow'] = { 'enabled': True } else: option_list['tensorflow'] = { 'enabled': False }
DIGITS-master
digits/config/tensorflow.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import os from urlparse import urlparse from . import option_list def validate(value): if value == '': return value valid_url_list = list() if isinstance(value, str): url_list = value.split(',') for url in url_list: if url is not None and urlparse(url).scheme != "" and not os.path.exists(url): valid_url_list.append(url) else: raise ValueError('"%s" is not a valid URL' % url) return ','.join(valid_url_list) def load_url_list(): """ Return Model Store URL's as a list Verify if each URL is valid """ if 'DIGITS_MODEL_STORE_URL' in os.environ: url_list = os.environ['DIGITS_MODEL_STORE_URL'] else: url_list = "http://developer.download.nvidia.com/compute/machine-learning/modelstore/6.0" return validate(url_list).split(',') option_list['model_store'] = { 'url_list': load_url_list() }
DIGITS-master
digits/config/store_option.py
# Copyright (c) 2015-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import logging import os from . import option_list import digits def load_logfile_filename(): """ Return the configured log file or None Throws an exception only if a manually specified log file is invalid """ throw_error = False if 'DIGITS_MODE_TEST' in os.environ: filename = None elif 'DIGITS_LOGFILE_FILENAME' in os.environ: filename = os.environ['DIGITS_LOGFILE_FILENAME'] throw_error = True else: filename = os.path.join(os.path.dirname(digits.__file__), 'digits.log') if filename is not None: try: filename = os.path.abspath(filename) dirname = os.path.dirname(filename) if not os.path.exists(dirname): os.makedirs(os.path.dirname(filename)) with open(filename, 'a'): pass except: if throw_error: print '"%s" is not a valid value for logfile_filename.' % filename print 'Set the envvar DIGITS_LOGFILE_FILENAME to fix your configuration.' raise else: filename = None return filename def load_logfile_level(): """ Return the configured logging level, or throw an exception """ if 'DIGITS_MODE_TEST' in os.environ: return logging.DEBUG elif 'DIGITS_LOGFILE_LEVEL' in os.environ: level = os.environ['DIGITS_LOGFILE_LEVEL'].strip().lower() if level == 'debug': return logging.DEBUG elif level == 'info': return logging.INFO elif level == 'warning': return logging.WARNING elif level == 'error': return logging.ERROR elif level == 'critical': return logging.CRITICAL else: raise ValueError( 'Invalid value "%s" for logfile_level. ' 'Set DIGITS_LOGFILE_LEVEL to fix your configuration.' % level) else: return logging.INFO option_list['log_file'] = { 'filename': load_logfile_filename(), 'level': load_logfile_level(), }
DIGITS-master
digits/config/log_file.py
# Copyright (c) 2015-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import from . import option_list import digits.device_query option_list['gpu_list'] = ','.join([str(x) for x in xrange(len(digits.device_query.get_devices()))])
DIGITS-master
digits/config/gpu_list.py
# Copyright (c) 2015-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import os from . import option_list def find_executable(path=None): """ Finds th on the given path and returns it if found If path is None, searches through PATH """ if path is None: dirnames = os.environ['PATH'].split(os.pathsep) suffixes = ['th'] else: dirnames = [path] # fuzzy search suffixes = ['th', os.path.join('bin', 'th'), os.path.join('install', 'bin', 'th')] for dirname in dirnames: dirname = dirname.strip('"') for suffix in suffixes: path = os.path.join(dirname, suffix) if os.path.isfile(path) and os.access(path, os.X_OK): return path return None if 'TORCH_ROOT' in os.environ: executable = find_executable(os.environ['TORCH_ROOT']) if executable is None: raise ValueError('Torch executable not found at "%s" (TORCH_ROOT)' % os.environ['TORCH_ROOT']) elif 'TORCH_HOME' in os.environ: executable = find_executable(os.environ['TORCH_HOME']) if executable is None: raise ValueError('Torch executable not found at "%s" (TORCH_HOME)' % os.environ['TORCH_HOME']) else: executable = find_executable() if executable is None: option_list['torch'] = { 'enabled': False, } else: option_list['torch'] = { 'enabled': True, 'executable': executable, }
DIGITS-master
digits/config/torch.py
# Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import os from . import option_list option_list['url_prefix'] = os.environ.get('DIGITS_URL_PREFIX', '')
DIGITS-master
digits/config/url_prefix.py
# Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import from digits.job import Job from digits.utils import subclass # NOTE: Increment this every time the pickled object changes PICKLE_VERSION = 1 @subclass class DatasetJob(Job): """ A Job that creates a dataset """ def __init__(self, **kwargs): """ """ super(DatasetJob, self).__init__(**kwargs) self.pickver_job_dataset = PICKLE_VERSION def get_backend(self): """ Return the DB backend used to create this dataset """ raise NotImplementedError('Please implement me') def get_entry_count(self, stage): """ Return the number of entries in the DB matching the specified stage """ raise NotImplementedError('Please implement me') def get_feature_db_path(self, stage): """ Return the absolute feature DB path for the specified stage """ raise NotImplementedError('Please implement me') def get_feature_dims(self): """ Return the shape of the feature N-D array """ raise NotImplementedError('Please implement me') def get_label_db_path(self, stage): """ Return the absolute label DB path for the specified stage """ raise NotImplementedError('Please implement me') def get_mean_file(self): """ Return the mean file """ raise NotImplementedError('Please implement me')
DIGITS-master
digits/dataset/job.py
# Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import from .images import ImageClassificationDatasetJob, GenericImageDatasetJob from .generic import GenericDatasetJob from .job import DatasetJob __all__ = [ 'ImageClassificationDatasetJob', 'GenericImageDatasetJob', 'GenericDatasetJob', 'DatasetJob', ]
DIGITS-master
digits/dataset/__init__.py
# Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import from flask_wtf import Form from wtforms.validators import DataRequired from digits import utils class DatasetForm(Form): """ Defines the form used to create a new Dataset (abstract class) """ dataset_name = utils.forms.StringField(u'Dataset Name', validators=[DataRequired()] ) group_name = utils.forms.StringField('Group Name', tooltip="An optional group name for organization on the main page." )
DIGITS-master
digits/dataset/forms.py
# Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import flask import werkzeug.exceptions from . import images as dataset_images from . import generic from digits import extensions from digits.utils.routing import job_from_request, request_wants_json from digits.webapp import scheduler blueprint = flask.Blueprint(__name__, __name__) @blueprint.route('/<job_id>/json', methods=['GET']) @blueprint.route('/<job_id>', methods=['GET']) def show(job_id): """ Show a DatasetJob Returns JSON when requested: {id, name, directory, status} """ job = scheduler.get_job(job_id) if job is None: raise werkzeug.exceptions.NotFound('Job not found') related_jobs = scheduler.get_related_jobs(job) if request_wants_json(): return flask.jsonify(job.json_dict(True)) else: if isinstance(job, dataset_images.ImageClassificationDatasetJob): return dataset_images.classification.views.show(job, related_jobs=related_jobs) elif isinstance(job, dataset_images.GenericImageDatasetJob): return dataset_images.generic.views.show(job, related_jobs=related_jobs) elif isinstance(job, generic.GenericDatasetJob): return generic.views.show(job, related_jobs=related_jobs) else: raise werkzeug.exceptions.BadRequest('Invalid job type') @blueprint.route('/summary', methods=['GET']) def summary(): """ Return a short HTML summary of a DatasetJob """ job = job_from_request() if isinstance(job, dataset_images.ImageClassificationDatasetJob): return dataset_images.classification.views.summary(job) elif isinstance(job, dataset_images.GenericImageDatasetJob): return dataset_images.generic.views.summary(job) elif isinstance(job, generic.GenericDatasetJob): return generic.views.summary(job) else: raise werkzeug.exceptions.BadRequest('Invalid job type') @blueprint.route('/inference-form/<extension_id>/<job_id>', methods=['GET']) def inference_form(extension_id, job_id): """ Returns a rendering of an inference form """ inference_form_html = "" if extension_id != "all-default": extension_class = extensions.data.get_extension(extension_id) if not extension_class: raise RuntimeError("Unable to find data extension with ID=%s" % job_id.dataset.extension_id) job = scheduler.get_job(job_id) if hasattr(job, 'extension_userdata'): extension_userdata = job.extension_userdata else: extension_userdata = {} extension_userdata.update({'is_inference_db': True}) extension = extension_class(**extension_userdata) form = extension.get_inference_form() if form: template, context = extension.get_inference_template(form) inference_form_html = flask.render_template_string(template, **context) return inference_form_html
DIGITS-master
digits/dataset/views.py
# Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import os.path import re import sys import digits from digits import utils from digits.task import Task from digits.utils import subclass, override # NOTE: Increment this every time the pickled object PICKLE_VERSION = 1 @subclass class ParseS3Task(Task): """Parses a folder into textfiles""" def __init__(self, s3_endpoint_url, s3_bucket, s3_path, s3_accesskey, s3_secretkey, **kwargs): """ Arguments: s3_endpoint_url -- endpoint url s3_bucket -- bucekt name s3_path -- a path to images s3_accesskey -- accesskey s3_secretkey -- secretkey Keyword arguments: percent_val -- percent of images used in the validation set percent_test -- percent of images used in the test set min_per_category -- minimum number of images per category max_per_category -- maximum number of images per category """ # Take keyword arguments out of kwargs percent_val = kwargs.pop('percent_val', None) percent_test = kwargs.pop('percent_test', None) self.min_per_category = kwargs.pop('min_per_category', 2) self.max_per_category = kwargs.pop('max_per_category', None) super(ParseS3Task, self).__init__(**kwargs) self.pickver_task_parsefolder = PICKLE_VERSION self.s3_endpoint_url = s3_endpoint_url self.s3_bucket = s3_bucket self.s3_path = s3_path self.s3_accesskey = s3_accesskey self.s3_secretkey = s3_secretkey if percent_val is None: self.percent_val = 0 else: pct = float(percent_val) if pct < 0: pct = 0 elif pct > 100: raise ValueError('percent_val must not exceed 100') self.percent_val = pct if percent_test is None: self.percent_test = 0 else: pct = float(percent_test) if pct < 0: pct = 0 elif pct > 100: raise ValueError('percent_test must not exceed 100') self.percent_test = pct if percent_val is not None and percent_test is not None and percent_val + percent_test > 100: raise ValueError('the sum of percent_val and percent_test must not exceed 100') self.train_file = utils.constants.TRAIN_FILE self.val_file = utils.constants.VAL_FILE self.labels_file = utils.constants.LABELS_FILE # Results self.train_count = None self.val_count = None self.test_count = None self.label_count = None def __getstate__(self): state = super(ParseS3Task, self).__getstate__() return state def __setstate__(self, state): super(ParseS3Task, self).__setstate__(state) @override def name(self): sets = [] if (self.percent_val + self.percent_test) < 100: sets.append('train') if self.percent_val > 0: sets.append('val') if self.percent_test > 0: sets.append('test') return 'Parse Folder (%s)' % ('/'.join(sets)) @override def html_id(self): sets = [] if (self.percent_val + self.percent_test) < 100: sets.append('train') if self.percent_val > 0: sets.append('val') if self.percent_test > 0: sets.append('test') return 'task-parse-folder-%s' % ('-'.join(sets)) @override def offer_resources(self, resources): key = 'parse_folder_task_pool' if key not in resources: return None for resource in resources[key]: if resource.remaining() >= 1: return {key: [(resource.identifier, 1)]} return None @override def task_arguments(self, resources, env): args = [sys.executable, os.path.join( os.path.dirname(os.path.abspath(digits.__file__)), 'tools', 'parse_s3.py'), self.s3_endpoint_url, self.s3_bucket, self.s3_path, self.s3_accesskey, self.s3_secretkey, self.path(utils.constants.LABELS_FILE), '--min=%s' % self.min_per_category, ] if (self.percent_val + self.percent_test) < 100: args.append('--train_file=%s' % self.path(utils.constants.TRAIN_FILE)) if self.percent_val > 0: args.append('--val_file=%s' % self.path(utils.constants.VAL_FILE)) args.append('--percent_val=%s' % self.percent_val) if self.percent_test > 0: args.append('--test_file=%s' % self.path(utils.constants.TEST_FILE)) args.append('--percent_test=%s' % self.percent_test) if self.max_per_category is not None: args.append('--max=%s' % self.max_per_category) return args @override def process_output(self, line): timestamp, level, message = self.preprocess_output_digits(line) if not message: return False # progress match = re.match(r'Progress: ([-+]?[0-9]*\.?[0-9]+(e[-+]?[0-9]+)?)', message) if match: self.progress = float(match.group(1)) self.emit_progress_update() return True # totals match = re.match(r'Found (\d+) images in (\d+) categories', message) if match: self.label_count = int(match.group(2)) return True # splits match = re.match(r'Selected (\d+) for (\w+)', message) if match: if match.group(2).startswith('training'): self.train_count = int(match.group(1)) elif match.group(2).startswith('validation'): self.val_count = int(match.group(1)) elif match.group(2).startswith('test'): self.test_count = int(match.group(1)) return True if level == 'warning': self.logger.warning('%s: %s' % (self.name(), message)) return True if level in ['error', 'critical']: self.logger.error('%s: %s' % (self.name(), message)) self.exception = message return True return True
DIGITS-master
digits/dataset/tasks/parse_s3.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import os import re import sys import digits from digits.task import Task from digits.utils import subclass, override # NOTE: Increment this every time the pickled version changes PICKLE_VERSION = 1 @subclass class CreateGenericDbTask(Task): """ A task to create a db using a user-defined extension """ def __init__(self, job, backend, stage, **kwargs): """ Arguments: """ self.job = job self.backend = backend self.stage = stage self.create_db_log_file = "create_%s_db.log" % stage self.dbs = {'features': None, 'labels': None} self.entry_count = 0 self.feature_shape = None self.label_shape = None self.mean_file = None super(CreateGenericDbTask, self).__init__(**kwargs) self.pickver_task_create_generic_db = PICKLE_VERSION @override def name(self): return 'Create %s DB' % self.stage @override def __getstate__(self): state = super(CreateGenericDbTask, self).__getstate__() if 'create_db_log' in state: # don't save file handle del state['create_db_log'] return state @override def __setstate__(self, state): super(CreateGenericDbTask, self).__setstate__(state) self.pickver_task_create_generic_db = PICKLE_VERSION @override def before_run(self): super(CreateGenericDbTask, self).before_run() # create log file self.create_db_log = open(self.path(self.create_db_log_file), 'a') # save job before spawning sub-process self.job.save() def get_encoding(self, name): if name == 'features': return self.job.feature_encoding elif name == 'labels': return self.job.label_encoding else: raise ValueError("Unknown db: %s" % name) @override def process_output(self, line): self.create_db_log.write('%s\n' % line) self.create_db_log.flush() timestamp, level, message = self.preprocess_output_digits(line) if not message: return False # keep track of which databases were created match = re.match( r'Created (features|labels) db for stage %s in (.*)' % self.stage, message) if match: db_type = match.group(1) self.dbs[db_type] = match.group(2) return True # mean file match = re.match( r'Created mean file for stage %s in (.*)' % self.stage, message) if match: self.mean_file = match.group(1) return True # entry counts match = re.match( r'Found (\d+) entries for stage %s' % self.stage, message) if match: count = int(match.group(1)) self.entry_count = count return True # feature shape match = re.match( r'Feature shape for stage %s: (.*)' % self.stage, message) if match: self.feature_shape = eval(match.group(1)) return True # label shape match = re.match( r'Label shape for stage %s: (.*)' % self.stage, message) if match: self.label_shape = eval(match.group(1)) return True # progress match = re.match( r'Processed (\d+)\/(\d+)', message) if match: self.progress = float(match.group(1)) / int(match.group(2)) self.emit_progress_update() return True # errors, warnings if level == 'warning': self.logger.warning('%s: %s' % (self.name(), message)) return True if level in ['error', 'critical']: self.logger.error('%s: %s' % (self.name(), message)) self.exception = message return True return False @override def after_run(self): super(CreateGenericDbTask, self).after_run() self.create_db_log.close() @override def offer_resources(self, resources): reserved_resources = {} # we need one CPU resource from create_db_task_pool cpu_key = 'create_db_task_pool' if cpu_key not in resources: return None for resource in resources[cpu_key]: if resource.remaining() >= 1: reserved_resources[cpu_key] = [(resource.identifier, 1)] return reserved_resources return None @override def task_arguments(self, resources, env): args = [ sys.executable, os.path.join( os.path.dirname(os.path.abspath(digits.__file__)), 'tools', 'create_generic_db.py'), self.job.id(), '--stage=%s' % self.stage, '--jobs_dir=%s' % digits.config.config_value('jobs_dir'), ] return args
DIGITS-master
digits/dataset/tasks/create_generic_db.py
# Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import from .analyze_db import AnalyzeDbTask from .create_db import CreateDbTask from .create_generic_db import CreateGenericDbTask from .parse_folder import ParseFolderTask from .parse_s3 import ParseS3Task __all__ = [ 'AnalyzeDbTask', 'CreateDbTask', 'CreateGenericDbTask', 'ParseFolderTask', 'ParseS3Task', ]
DIGITS-master
digits/dataset/tasks/__init__.py
# Copyright (c) 2015-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import os.path import re import sys import digits from digits.task import Task from digits.utils import subclass, override # NOTE: Increment this every time the pickled object PICKLE_VERSION = 1 @subclass class AnalyzeDbTask(Task): """ Reads information from a database """ def __init__(self, database, purpose, **kwargs): """ Arguments: database -- path to the database to analyze purpose -- what is this database going to be used for Keyword arguments: force_same_shape -- if True, enforce that every entry in the database has the same shape """ self.force_same_shape = kwargs.pop('force_same_shape', False) super(AnalyzeDbTask, self).__init__(**kwargs) self.pickver_task_analyzedb = PICKLE_VERSION self.database = database self.purpose = purpose self.backend = 'lmdb' # Results self.image_count = None self.image_width = None self.image_height = None self.image_channels = None self.analyze_db_log_file = 'analyze_db_%s.log' % '-'.join(p.lower() for p in self.purpose.split()) def __getstate__(self): state = super(AnalyzeDbTask, self).__getstate__() if 'analyze_db_log' in state: del state['analyze_db_log'] return state def __setstate__(self, state): super(AnalyzeDbTask, self).__setstate__(state) if not hasattr(self, 'backend') or self.backend is None: self.backend = 'lmdb' @override def name(self): return 'Analyze DB (%s)' % (self.purpose) @override def html_id(self): return 'task-analyze-db-%s' % '-'.join(p.lower() for p in self.purpose.split()) @override def offer_resources(self, resources): key = 'analyze_db_task_pool' if key not in resources: return None for resource in resources[key]: if resource.remaining() >= 1: return {key: [(resource.identifier, 1)]} return None @override def task_arguments(self, resources, env): args = [sys.executable, os.path.join( os.path.dirname(os.path.abspath(digits.__file__)), 'tools', 'analyze_db.py'), self.database, ] if self.force_same_shape: args.append('--force-same-shape') else: args.append('--only-count') return args @override def before_run(self): super(AnalyzeDbTask, self).before_run() self.analyze_db_log = open(self.path(self.analyze_db_log_file), 'a') @override def process_output(self, line): self.analyze_db_log.write('%s\n' % line) self.analyze_db_log.flush() timestamp, level, message = self.preprocess_output_digits(line) if not message: return False # progress match = re.match(r'Progress: (\d+)\/(\d+)', message) if match: self.progress = float(match.group(1)) / float(match.group(2)) self.emit_progress_update() return True # total count match = re.match(r'Total entries: (\d+)', message) if match: self.image_count = int(match.group(1)) return True # image dimensions match = re.match(r'(\d+) entries found with shape ((\d+)x(\d+)x(\d+))', message) if match: # count = int(match.group(1)) dims = match.group(2) self.image_width = int(match.group(3)) self.image_height = int(match.group(4)) self.image_channels = int(match.group(5)) self.logger.debug('Images are %s' % dims) return True if level == 'warning': self.logger.warning('%s: %s' % (self.name(), message)) return True if level in ['error', 'critical']: self.logger.error('%s: %s' % (self.name(), message)) self.exception = message return True return True @override def after_run(self): super(AnalyzeDbTask, self).after_run() self.analyze_db_log.close() def image_type(self): """ Returns an easy-to-read version of self.image_channels """ if self.image_channels is None: return None elif self.image_channels == 1: return 'GRAYSCALE' elif self.image_channels == 3: return 'COLOR' else: return '%s-channel' % self.image_channels
DIGITS-master
digits/dataset/tasks/analyze_db.py
# Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import os.path import re import sys import digits from digits import utils from digits.task import Task from digits.utils import subclass, override # NOTE: Increment this every time the pickled object PICKLE_VERSION = 1 @subclass class ParseFolderTask(Task): """Parses a folder into textfiles""" def __init__(self, folder, **kwargs): """ Arguments: folder -- the folder to parse (can be a filesystem path or a url) Keyword arguments: percent_val -- percent of images used in the validation set percent_test -- percent of images used in the test set min_per_category -- minimum number of images per category max_per_category -- maximum number of images per category """ # Take keyword arguments out of kwargs percent_val = kwargs.pop('percent_val', None) percent_test = kwargs.pop('percent_test', None) self.min_per_category = kwargs.pop('min_per_category', 2) self.max_per_category = kwargs.pop('max_per_category', None) super(ParseFolderTask, self).__init__(**kwargs) self.pickver_task_parsefolder = PICKLE_VERSION self.folder = folder if percent_val is None: self.percent_val = 0 else: pct = float(percent_val) if pct < 0: pct = 0 elif pct > 100: raise ValueError('percent_val must not exceed 100') self.percent_val = pct if percent_test is None: self.percent_test = 0 else: pct = float(percent_test) if pct < 0: pct = 0 elif pct > 100: raise ValueError('percent_test must not exceed 100') self.percent_test = pct if percent_val is not None and percent_test is not None and percent_val + percent_test > 100: raise ValueError('the sum of percent_val and percent_test must not exceed 100') self.train_file = utils.constants.TRAIN_FILE self.val_file = utils.constants.VAL_FILE self.labels_file = utils.constants.LABELS_FILE # Results self.train_count = None self.val_count = None self.test_count = None self.label_count = None def __getstate__(self): state = super(ParseFolderTask, self).__getstate__() return state def __setstate__(self, state): super(ParseFolderTask, self).__setstate__(state) @override def name(self): sets = [] if (self.percent_val + self.percent_test) < 100: sets.append('train') if self.percent_val > 0: sets.append('val') if self.percent_test > 0: sets.append('test') return 'Parse Folder (%s)' % ('/'.join(sets)) @override def html_id(self): sets = [] if (self.percent_val + self.percent_test) < 100: sets.append('train') if self.percent_val > 0: sets.append('val') if self.percent_test > 0: sets.append('test') return 'task-parse-folder-%s' % ('-'.join(sets)) @override def offer_resources(self, resources): key = 'parse_folder_task_pool' if key not in resources: return None for resource in resources[key]: if resource.remaining() >= 1: return {key: [(resource.identifier, 1)]} return None @override def task_arguments(self, resources, env): args = [sys.executable, os.path.join( os.path.dirname(os.path.abspath(digits.__file__)), 'tools', 'parse_folder.py'), self.folder, self.path(utils.constants.LABELS_FILE), '--min=%s' % self.min_per_category, ] if (self.percent_val + self.percent_test) < 100: args.append('--train_file=%s' % self.path(utils.constants.TRAIN_FILE)) if self.percent_val > 0: args.append('--val_file=%s' % self.path(utils.constants.VAL_FILE)) args.append('--percent_val=%s' % self.percent_val) if self.percent_test > 0: args.append('--test_file=%s' % self.path(utils.constants.TEST_FILE)) args.append('--percent_test=%s' % self.percent_test) if self.max_per_category is not None: args.append('--max=%s' % self.max_per_category) return args @override def process_output(self, line): timestamp, level, message = self.preprocess_output_digits(line) if not message: return False # progress match = re.match(r'Progress: ([-+]?[0-9]*\.?[0-9]+(e[-+]?[0-9]+)?)', message) if match: self.progress = float(match.group(1)) self.emit_progress_update() return True # totals match = re.match(r'Found (\d+) images in (\d+) categories', message) if match: self.label_count = int(match.group(2)) return True # splits match = re.match(r'Selected (\d+) for (\w+)', message) if match: if match.group(2).startswith('training'): self.train_count = int(match.group(1)) elif match.group(2).startswith('validation'): self.val_count = int(match.group(1)) elif match.group(2).startswith('test'): self.test_count = int(match.group(1)) return True if level == 'warning': self.logger.warning('%s: %s' % (self.name(), message)) return True if level in ['error', 'critical']: self.logger.error('%s: %s' % (self.name(), message)) self.exception = message return True return True
DIGITS-master
digits/dataset/tasks/parse_folder.py
# Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import os.path import re import sys import digits from digits import utils from digits.task import Task from digits.utils import subclass, override # NOTE: Increment this every time the pickled version changes PICKLE_VERSION = 3 @subclass class CreateDbTask(Task): """Creates a database""" def __init__(self, input_file, db_name, backend, image_dims, **kwargs): """ Arguments: input_file -- read images and labels from this file db_name -- save database to this location backend -- database backend (lmdb/hdf5) image_dims -- (height, width, channels) Keyword Arguments: image_folder -- prepend image paths with this folder shuffle -- shuffle images before saving resize_mode -- used in utils.image.resize_image() encoding -- 'none', 'png' or 'jpg' compression -- 'none' or 'gzip' mean_file -- save mean file to this location labels_file -- used to print category distribution """ # Take keyword arguments out of kwargs self.image_folder = kwargs.pop('image_folder', None) self.shuffle = kwargs.pop('shuffle', True) self.resize_mode = kwargs.pop('resize_mode', None) self.encoding = kwargs.pop('encoding', None) self.compression = kwargs.pop('compression', None) self.mean_file = kwargs.pop('mean_file', None) self.labels_file = kwargs.pop('labels_file', None) self.delete_files = kwargs.pop('delete_files', False) super(CreateDbTask, self).__init__(**kwargs) self.pickver_task_createdb = PICKLE_VERSION self.input_file = input_file self.db_name = db_name self.backend = backend if backend == 'hdf5' or backend == 'tfrecords': # the list of hdf5 files is stored in a textfile # tfrecords can be sharded as well self.textfile = os.path.join(self.db_name, 'list.txt') self.image_dims = image_dims if image_dims[2] == 3: self.image_channel_order = 'BGR' else: self.image_channel_order = None self.entries_count = None self.entries_error = None self.distribution = None self.create_db_log_file = "create_%s.log" % db_name def __getstate__(self): d = super(CreateDbTask, self).__getstate__() if 'create_db_log' in d: # don't save file handle del d['create_db_log'] if 'labels' in d: del d['labels'] return d def __setstate__(self, state): super(CreateDbTask, self).__setstate__(state) if self.pickver_task_createdb <= 1: if self.image_dims[2] == 1: self.image_channel_order = None elif self.encode: self.image_channel_order = 'BGR' else: self.image_channel_order = 'RGB' if self.pickver_task_createdb <= 2: if hasattr(self, 'encode'): if self.encode: self.encoding = 'jpg' else: self.encoding = 'none' delattr(self, 'encode') else: self.encoding = 'none' self.pickver_task_createdb = PICKLE_VERSION if not hasattr(self, 'backend') or self.backend is None: self.backend = 'lmdb' if not hasattr(self, 'compression') or self.compression is None: self.compression = 'none' if not hasattr(self, 'entries_error'): self.entries_error = 0 for key in self.distribution.keys(): self.distribution[key] = { 'count': self.distribution[key], 'error_count': 0 } @override def name(self): if self.db_name == utils.constants.TRAIN_DB or 'train' in self.db_name.lower(): return 'Create DB (train)' elif self.db_name == utils.constants.VAL_DB or 'val' in self.db_name.lower(): return 'Create DB (val)' elif self.db_name == utils.constants.TEST_DB or 'test' in self.db_name.lower(): return 'Create DB (test)' else: return 'Create DB (%s)' % self.db_name @override def before_run(self): super(CreateDbTask, self).before_run() self.create_db_log = open(self.path(self.create_db_log_file), 'a') @override def html_id(self): if self.db_name == utils.constants.TRAIN_DB or 'train' in self.db_name.lower(): return 'task-create_db-train' elif self.db_name == utils.constants.VAL_DB or 'val' in self.db_name.lower(): return 'task-create_db-val' elif self.db_name == utils.constants.TEST_DB or 'test' in self.db_name.lower(): return 'task-create_db-test' else: return super(CreateDbTask, self).html_id() @override def offer_resources(self, resources): key = 'create_db_task_pool' if key not in resources: return None for resource in resources[key]: if resource.remaining() >= 1: return {key: [(resource.identifier, 1)]} return None @override def task_arguments(self, resources, env): args = [sys.executable, os.path.join( os.path.dirname(os.path.abspath(digits.__file__)), 'tools', 'create_db.py'), self.path(self.input_file), self.path(self.db_name), self.image_dims[1], self.image_dims[0], '--backend=%s' % self.backend, '--channels=%s' % self.image_dims[2], '--resize_mode=%s' % self.resize_mode, ] if self.mean_file is not None: args.append('--mean_file=%s' % self.path(self.mean_file)) # Add a visual mean_file args.append('--mean_file=%s' % self.path(utils.constants.MEAN_FILE_IMAGE)) if self.image_folder: args.append('--image_folder=%s' % self.image_folder) if self.shuffle: args.append('--shuffle') if self.encoding and self.encoding != 'none': args.append('--encoding=%s' % self.encoding) if self.compression and self.compression != 'none': args.append('--compression=%s' % self.compression) if self.backend == 'hdf5': args.append('--hdf5_dset_limit=%d' % 2**31) if self.delete_files: args.append('--delete_files') return args @override def process_output(self, line): self.create_db_log.write('%s\n' % line) self.create_db_log.flush() timestamp, level, message = self.preprocess_output_digits(line) if not message: return False # progress match = re.match(r'Processed (\d+)\/(\d+)', message) if match: self.progress = float(match.group(1)) / int(match.group(2)) self.emit_progress_update() return True # distribution match = re.match(r'Category (\d+) has (\d+)', message) if match and self.labels_file is not None: if not hasattr(self, 'distribution') or self.distribution is None: self.distribution = {} self.distribution[match.group(1)] = { 'count': int(match.group(2)), 'error_count': 0 } self.update_distribution_graph() return True # add errors to the distribution match = re.match(r'\[(.+) (\d+)\] LoadImageError: (.+)', message) if match: self.distribution[match.group(2)]['count'] -= 1 self.distribution[match.group(2)]['error_count'] += 1 if self.entries_error is None: self.entries_error = 0 self.entries_error += 1 self.update_distribution_graph() return True # result match = re.match(r'(\d+) images written to database', message) if match: self.entries_count = int(match.group(1)) self.logger.debug(message) return True if level == 'warning': self.logger.warning('%s: %s' % (self.name(), message)) return True if level in ['error', 'critical']: self.logger.error('%s: %s' % (self.name(), message)) self.exception = message return True return True @override def after_run(self): from digits.webapp import socketio super(CreateDbTask, self).after_run() self.create_db_log.close() if self.backend == 'lmdb': socketio.emit('task update', { 'task': self.html_id(), 'update': 'exploration-ready', }, namespace='/jobs', room=self.job_id, ) elif self.backend == 'hdf5': # add more path information to the list of h5 files lines = None with open(self.path(self.textfile)) as infile: lines = infile.readlines() with open(self.path(self.textfile), 'w') as outfile: for line in lines: # XXX this works because the model job will be in an adjacent folder outfile.write('%s\n' % os.path.join( '..', self.job_id, self.db_name, line.strip())) if self.mean_file: socketio.emit('task update', { 'task': self.html_id(), 'update': 'mean-image', # XXX Can't use url_for here because we don't have a request context 'data': '/files/' + self.path('mean.jpg', relative=True), }, namespace='/jobs', room=self.job_id, ) def get_labels(self): """ Read labels from labels_file and return them in a list """ # The labels might be set already if hasattr(self, '_labels') and self._labels and len(self._labels) > 0: return self._labels assert hasattr(self, 'labels_file'), 'labels_file not set' assert self.labels_file, 'labels_file not set' assert os.path.exists(self.path(self.labels_file)), 'labels_file does not exist' labels = [] with open(self.path(self.labels_file)) as infile: for line in infile: label = line.strip() if label: labels.append(label) assert len(labels) > 0, 'no labels in labels_file' self._labels = labels return self._labels def distribution_data(self): """ Returns distribution data for a C3.js graph """ if self.distribution is None: return None try: labels = self.get_labels() except AssertionError: return None if len(self.distribution.keys()) != len(labels): return None label_count = 'Count' label_error = 'LoadImageError' error_values = [label_error] count_values = [label_count] titles = [] for key, value in sorted( self.distribution.items(), key=lambda item: item[1]['count'], reverse=True): count_values.append(value['count']) error_values.append(value['error_count']) titles.append(labels[int(key)]) # distribution graph always displays the Count data data = {'columns': [count_values], 'type': 'bar'} # only display error data if any error occurred if sum(error_values[1:]) > 0: data['columns'] = [count_values, error_values] data['groups'] = [[label_count, label_error]] data['colors'] = {label_count: '#1F77B4', label_error: '#B73540'} data['order'] = 'false' return { 'data': data, 'axis': { 'x': { 'type': 'category', 'categories': titles, } }, } def update_distribution_graph(self): from digits.webapp import socketio data = self.distribution_data() if data: socketio.emit('task update', { 'task': self.html_id(), 'update': 'distribution', 'data': data, }, namespace='/jobs', room=self.job_id, )
DIGITS-master
digits/dataset/tasks/create_db.py
# Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import from ..job import DatasetJob # NOTE: Increment this every time the pickled object changes PICKLE_VERSION = 1 class ImageDatasetJob(DatasetJob): """ A Job that creates an image dataset """ def __init__(self, **kwargs): """ Keyword arguments: image_dims -- (height, width, channels) resize_mode -- used in utils.image.resize_image() """ self.image_dims = kwargs.pop('image_dims', None) self.resize_mode = kwargs.pop('resize_mode', None) super(ImageDatasetJob, self).__init__(**kwargs) self.pickver_job_dataset_image = PICKLE_VERSION @staticmethod def resize_mode_choices(): return [ ('crop', 'Crop'), ('squash', 'Squash'), ('fill', 'Fill'), ('half_crop', 'Half crop, half fill'), ] def resize_mode_name(self): c = dict(self.resize_mode_choices()) return c[self.resize_mode]
DIGITS-master
digits/dataset/images/job.py
# Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import from .classification import * # noqa from .generic import * # noqa from .job import ImageDatasetJob __all__ = ['ImageDatasetJob']
DIGITS-master
digits/dataset/images/__init__.py
# Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import wtforms from wtforms import validators from ..forms import DatasetForm from .job import ImageDatasetJob from digits import utils class ImageDatasetForm(DatasetForm): """ Defines the form used to create a new ImageDatasetJob (abstract class) """ encoding = utils.forms.SelectField( 'Image Encoding', default='png', choices=[ ('none', 'None'), ('png', 'PNG (lossless)'), ('jpg', 'JPEG (lossy, 90% quality)'), ], tooltip=('Using either of these compression formats can save disk space, ' 'but can also require marginally more time for training.'), ) # Image resize resize_channels = utils.forms.SelectField( u'Image Type', default='3', choices=[('1', 'Grayscale'), ('3', 'Color')], tooltip="Color is 3-channel RGB. Grayscale is single channel monochrome." ) resize_width = wtforms.IntegerField( u'Resize Width', default=256, validators=[validators.DataRequired()] ) resize_height = wtforms.IntegerField( u'Resize Height', default=256, validators=[validators.DataRequired()] ) resize_mode = utils.forms.SelectField( u'Resize Transformation', default='squash', choices=ImageDatasetJob.resize_mode_choices(), tooltip="Options for dealing with aspect ratio changes during resize. See examples below." )
DIGITS-master
digits/dataset/images/forms.py
# Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import os.path # Find the best implementation available try: from cStringIO import StringIO except ImportError: from StringIO import StringIO import flask import PIL.Image import digits from digits import utils blueprint = flask.Blueprint(__name__, __name__) @blueprint.route('/resize-example', methods=['POST']) def resize_example(): """ Resizes the example image, and returns it as a string of png data """ try: example_image_path = os.path.join(os.path.dirname(digits.__file__), 'static', 'images', 'mona_lisa.jpg') image = utils.image.load_image(example_image_path) width = int(flask.request.form['width']) height = int(flask.request.form['height']) channels = int(flask.request.form['channels']) resize_mode = flask.request.form['resize_mode'] backend = flask.request.form['backend'] encoding = flask.request.form['encoding'] image = utils.image.resize_image(image, height, width, channels=channels, resize_mode=resize_mode, ) if backend != 'lmdb' or encoding == 'none': length = len(image.tostring()) else: s = StringIO() if encoding == 'png': PIL.Image.fromarray(image).save(s, format='PNG') elif encoding == 'jpg': PIL.Image.fromarray(image).save(s, format='JPEG', quality=90) else: raise ValueError('unrecognized encoding "%s"' % encoding) s.seek(0) image = PIL.Image.open(s) length = len(s.getvalue()) data = utils.image.embed_image_html(image) return '<img src=\"' + data + '\" style=\"width:%spx;height=%spx\" />\n<br>\n<i>Image size: %s</i>' % ( width, height, utils.sizeof_fmt(length) ) except Exception as e: return '%s: %s' % (type(e).__name__, e)
DIGITS-master
digits/dataset/images/views.py
# Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import os from ..job import ImageDatasetJob from digits.dataset import tasks from digits.status import Status from digits.utils import subclass, override, constants # NOTE: Increment this every time the pickled object changes PICKLE_VERSION = 2 @subclass class ImageClassificationDatasetJob(ImageDatasetJob): """ A Job that creates an image dataset for a classification network """ def __init__(self, **kwargs): super(ImageClassificationDatasetJob, self).__init__(**kwargs) self.pickver_job_dataset_image_classification = PICKLE_VERSION self.labels_file = None def __setstate__(self, state): super(ImageClassificationDatasetJob, self).__setstate__(state) if self.pickver_job_dataset_image_classification <= 1: task = self.train_db_task() if task.image_dims[2] == 3: if task.encoding == "jpg": if task.mean_file.endswith('.binaryproto'): import numpy as np import caffe_pb2 old_blob = caffe_pb2.BlobProto() with open(task.path(task.mean_file), 'rb') as infile: old_blob.ParseFromString(infile.read()) data = np.array(old_blob.data).reshape( old_blob.channels, old_blob.height, old_blob.width) data = data[[2, 1, 0], ...] # channel swap new_blob = caffe_pb2.BlobProto() new_blob.num = 1 new_blob.channels, new_blob.height, new_blob.width = data.shape new_blob.data.extend(data.astype(float).flat) with open(task.path(task.mean_file), 'wb') as outfile: outfile.write(new_blob.SerializeToString()) else: self.status = Status.ERROR for task in self.tasks: task.status = Status.ERROR task.exception = ('This dataset was created with unencoded ' 'RGB channels. Caffe requires BGR input.') self.pickver_job_dataset_image_classification = PICKLE_VERSION def create_db_tasks(self): """ Return all CreateDbTasks for this job """ return [t for t in self.tasks if isinstance(t, tasks.CreateDbTask)] @override def get_backend(self): """ Return the DB backend used to create this dataset """ return self.train_db_task().backend def get_encoding(self): """ Return the DB encoding used to create this dataset """ return self.train_db_task().encoding def get_compression(self): """ Return the DB compression used to create this dataset """ return self.train_db_task().compression @override def get_entry_count(self, stage): """ Return the number of entries in the DB matching the specified stage """ if stage == constants.TRAIN_DB: db = self.train_db_task() elif stage == constants.VAL_DB: db = self.val_db_task() elif stage == constants.TEST_DB: db = self.test_db_task() else: return 0 return db.entries_count if db is not None else 0 @override def get_feature_dims(self): """ Return the shape of the feature N-D array """ return self.image_dims @override def get_feature_db_path(self, stage): """ Return the absolute feature DB path for the specified stage """ path = self.path(stage) return path if os.path.exists(path) else None @override def get_label_db_path(self, stage): """ Return the absolute label DB path for the specified stage """ # classification datasets don't have label DBs return None @override def get_mean_file(self): """ Return the mean file """ return self.train_db_task().mean_file @override def job_type(self): return 'Image Classification Dataset' @override def json_dict(self, verbose=False): d = super(ImageClassificationDatasetJob, self).json_dict(verbose) if verbose: d.update({ 'ParseFolderTasks': [{ "name": t.name(), "label_count": t.label_count, "train_count": t.train_count, "val_count": t.val_count, "test_count": t.test_count, } for t in self.parse_folder_tasks()], 'CreateDbTasks': [{ "name": t.name(), "entries": t.entries_count, "image_width": t.image_dims[0], "image_height": t.image_dims[1], "image_channels": t.image_dims[2], "backend": t.backend, "encoding": t.encoding, "compression": t.compression, } for t in self.create_db_tasks()], }) return d def parse_folder_tasks(self): """ Return all ParseFolderTasks for this job """ return [t for t in self.tasks if isinstance(t, tasks.ParseFolderTask)] def test_db_task(self): """ Return the task that creates the test set """ for t in self.tasks: if isinstance(t, tasks.CreateDbTask) and 'test' in t.name().lower(): return t return None def train_db_task(self): """ Return the task that creates the training set """ for t in self.tasks: if isinstance(t, tasks.CreateDbTask) and 'train' in t.name().lower(): return t return None def val_db_task(self): """ Return the task that creates the validation set """ for t in self.tasks: if isinstance(t, tasks.CreateDbTask) and 'val' in t.name().lower(): return t return None
DIGITS-master
digits/dataset/images/classification/job.py
# Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import from .job import ImageClassificationDatasetJob __all__ = ['ImageClassificationDatasetJob']
DIGITS-master
digits/dataset/images/classification/__init__.py
# Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import json import os import shutil import tempfile # Find the best implementation available try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from bs4 import BeautifulSoup import PIL.Image from .test_imageset_creator import create_classification_imageset from digits import test_utils import digits.test_views # May be too short on a slow system TIMEOUT_DATASET = 45 ################################################################################ # Base classes (they don't start with "Test" so nose won't run them) ################################################################################ class BaseViewsTest(digits.test_views.BaseViewsTest): """ Provides some functions """ @classmethod def dataset_exists(cls, job_id): return cls.job_exists(job_id, 'datasets') @classmethod def dataset_status(cls, job_id): return cls.job_status(job_id, 'datasets') @classmethod def dataset_info(cls, job_id): return cls.job_info(job_id, 'datasets') @classmethod def abort_dataset(cls, job_id): return cls.abort_job(job_id, job_type='datasets') @classmethod def dataset_wait_completion(cls, job_id, **kwargs): kwargs['job_type'] = 'datasets' if 'timeout' not in kwargs: kwargs['timeout'] = TIMEOUT_DATASET return cls.job_wait_completion(job_id, **kwargs) @classmethod def delete_dataset(cls, job_id): return cls.delete_job(job_id, job_type='datasets') class BaseViewsTestWithImageset(BaseViewsTest): """ Provides an imageset and some functions """ # Inherited classes may want to override these default attributes IMAGE_COUNT = 10 # per class IMAGE_HEIGHT = 10 IMAGE_WIDTH = 10 IMAGE_CHANNELS = 3 BACKEND = 'lmdb' ENCODING = 'png' COMPRESSION = 'none' UNBALANCED_CATEGORY = False @classmethod def setUpClass(cls): super(BaseViewsTestWithImageset, cls).setUpClass() cls.imageset_folder = tempfile.mkdtemp() # create imageset cls.imageset_paths = create_classification_imageset( cls.imageset_folder, image_count=cls.IMAGE_COUNT, add_unbalanced_category=cls.UNBALANCED_CATEGORY, ) cls.created_datasets = [] @classmethod def tearDownClass(cls): # delete any created datasets for job_id in cls.created_datasets: cls.delete_dataset(job_id) # delete imageset shutil.rmtree(cls.imageset_folder) super(BaseViewsTestWithImageset, cls).tearDownClass() @classmethod def create_dataset(cls, **kwargs): """ Create a dataset Returns the job_id Raises RuntimeError if job fails to create Keyword arguments: **kwargs -- data to be sent with POST request """ data = { 'dataset_name': 'test_dataset', 'group_name': 'test_group', 'method': 'folder', 'folder_train': cls.imageset_folder, 'resize_channels': cls.IMAGE_CHANNELS, 'resize_width': cls.IMAGE_WIDTH, 'resize_height': cls.IMAGE_HEIGHT, 'backend': cls.BACKEND, 'encoding': cls.ENCODING, 'compression': cls.COMPRESSION, } data.update(kwargs) request_json = data.pop('json', False) url = '/datasets/images/classification' if request_json: url += '/json' rv = cls.app.post(url, data=data) if request_json: if rv.status_code != 200: print json.loads(rv.data) raise RuntimeError('Model creation failed with %s' % rv.status_code) return json.loads(rv.data)['id'] # expect a redirect if not 300 <= rv.status_code <= 310: s = BeautifulSoup(rv.data, 'html.parser') div = s.select('div.alert-danger') if div: print div[0] else: print rv.data raise RuntimeError('Failed to create dataset - status %s' % rv.status_code) job_id = cls.job_id_from_response(rv) assert cls.dataset_exists(job_id), 'dataset not found after successful creation' cls.created_datasets.append(job_id) return job_id @classmethod def categoryCount(cls): return len(cls.imageset_paths.keys()) class BaseViewsTestWithDataset(BaseViewsTestWithImageset): """ Provides a dataset and some functions """ @classmethod def setUpClass(cls): super(BaseViewsTestWithDataset, cls).setUpClass() cls.dataset_id = cls.create_dataset(json=True) assert cls.dataset_wait_completion(cls.dataset_id) == 'Done', 'create failed' def test_clone(self): options_1 = { 'encoding': 'png', 'folder_pct_test': 0, 'folder_pct_val': 25, 'folder_test': '', 'folder_test_max_per_class': None, 'folder_test_min_per_class': 2, 'folder_train_max_per_class': 3, 'folder_train_min_per_class': 1, 'folder_val_max_per_class': None, 'folder_val_min_per_class': 2, 'resize_mode': 'half_crop', } job1_id = self.create_dataset(**options_1) assert self.dataset_wait_completion(job1_id) == 'Done', 'first job failed' rv = self.app.get('/datasets/%s/json' % job1_id) assert rv.status_code == 200, 'json load failed with %s' % rv.status_code content1 = json.loads(rv.data) # Clone job1 as job2 options_2 = { 'clone': job1_id, } job2_id = self.create_dataset(**options_2) assert self.dataset_wait_completion(job2_id) == 'Done', 'second job failed' rv = self.app.get('/datasets/%s/json' % job2_id) assert rv.status_code == 200, 'json load failed with %s' % rv.status_code content2 = json.loads(rv.data) # These will be different content1.pop('id') content2.pop('id') content1.pop('directory') content2.pop('directory') assert (content1 == content2), 'job content does not match' job1 = digits.webapp.scheduler.get_job(job1_id) job2 = digits.webapp.scheduler.get_job(job2_id) assert (job1.form_data == job2.form_data), 'form content does not match' ################################################################################ # Test classes ################################################################################ class TestViews(BaseViewsTest, test_utils.DatasetMixin): """ Tests which don't require an imageset or a dataset """ def test_page_dataset_new(self): rv = self.app.get('/datasets/images/classification/new') assert rv.status_code == 200, 'page load failed with %s' % rv.status_code assert 'New Image Classification Dataset' in rv.data, 'unexpected page format' def test_nonexistent_dataset(self): assert not self.dataset_exists('foo'), "dataset shouldn't exist" class TestCreation(BaseViewsTestWithImageset, test_utils.DatasetMixin): """ Dataset creation tests """ def test_nonexistent_folder(self): try: self.create_dataset( folder_train='/not-a-directory' ) except RuntimeError: return raise AssertionError('Should have failed') def test_create_json(self): job_id = self.create_dataset(json=True) self.abort_dataset(job_id) def test_create_delete(self): job_id = self.create_dataset() assert self.delete_dataset(job_id) == 200, 'delete failed' assert not self.dataset_exists(job_id), 'dataset exists after delete' def test_create_abort_delete(self): job_id = self.create_dataset() assert self.abort_dataset(job_id) == 200, 'abort failed' assert self.delete_dataset(job_id) == 200, 'delete failed' assert not self.dataset_exists(job_id), 'dataset exists after delete' def test_create_wait_delete(self): job_id = self.create_dataset() assert self.dataset_wait_completion(job_id) == 'Done', 'create failed' assert self.delete_dataset(job_id) == 200, 'delete failed' assert not self.dataset_exists(job_id), 'dataset exists after delete' def test_textfiles(self): for absolute_path in (True, False): for local_path in (True, False): yield self.check_textfiles, absolute_path, local_path def check_textfiles(self, absolute_path=True, local_path=True): """ Create a dataset from textfiles Arguments: absolute_path -- if False, give relative paths and image folders """ textfile_train_images = '' textfile_labels_file = '' label_id = 0 for label, images in self.imageset_paths.iteritems(): textfile_labels_file += '%s\n' % label for image in images: image_path = image if absolute_path: image_path = os.path.join(self.imageset_folder, image_path) textfile_train_images += '%s %d\n' % (image_path, label_id) label_id += 1 data = { 'method': 'textfile', 'textfile_use_val': 'y', } if local_path: train_file = os.path.join(self.imageset_folder, "local_train.txt") labels_file = os.path.join(self.imageset_folder, "local_labels.txt") # create files in local filesystem - these will be removed in tearDownClass() function with open(train_file, "w") as outfile: outfile.write(textfile_train_images) with open(labels_file, "w") as outfile: outfile.write(textfile_labels_file) data['textfile_use_local_files'] = 'True' data['textfile_local_train_images'] = train_file # Use the same file for training and validation. data['textfile_local_val_images'] = train_file data['textfile_local_labels_file'] = labels_file else: # StringIO wrapping is needed to simulate POST file upload. train_upload = (StringIO(textfile_train_images), "train.txt") # Use the same list for training and validation. val_upload = (StringIO(textfile_train_images), "val.txt") labels_upload = (StringIO(textfile_labels_file), "labels.txt") data['textfile_train_images'] = train_upload data['textfile_val_images'] = val_upload data['textfile_labels_file'] = labels_upload if not absolute_path: data['textfile_train_folder'] = self.imageset_folder data['textfile_val_folder'] = self.imageset_folder job_id = self.create_dataset(**data) assert self.dataset_wait_completion(job_id) == 'Done', 'create failed' def test_abort_explore_fail(self): job_id = self.create_dataset() self.abort_dataset(job_id) rv = self.app.get('/datasets/images/classification/explore?job_id=%s&db=val' % job_id) assert rv.status_code == 500, 'page load should have failed' assert 'status should be' in rv.data, 'unexpected page format' class TestImageCount(BaseViewsTestWithImageset, test_utils.DatasetMixin): def test_image_count(self): for type in ['train', 'val', 'test']: yield self.check_image_count, type def check_image_count(self, type): data = {'folder_pct_val': 20, 'folder_pct_test': 10} if type == 'val': data['has_val_folder'] = 'True' data['folder_val'] = self.imageset_folder elif type == 'test': data['has_test_folder'] = 'True' data['folder_test'] = self.imageset_folder job_id = self.create_dataset(**data) assert self.dataset_wait_completion(job_id) == 'Done', 'create failed' info = self.dataset_info(job_id) if type == 'train': assert len(info['ParseFolderTasks']) == 1, 'expected exactly one ParseFolderTasks' parse_info = info['ParseFolderTasks'][0] image_count = parse_info['train_count'] + parse_info['val_count'] + parse_info['test_count'] assert parse_info['val_count'] == 0.2 * image_count assert parse_info['test_count'] == 0.1 * image_count else: assert len(info['ParseFolderTasks']) == 2, 'expected exactly one ParseFolderTasks' parse_info = info['ParseFolderTasks'][1] if type == 'val': assert parse_info['train_count'] == 0 assert parse_info['test_count'] == 0 image_count = parse_info['val_count'] else: assert parse_info['train_count'] == 0 assert parse_info['val_count'] == 0 image_count = parse_info['test_count'] assert self.categoryCount() == parse_info['label_count'] assert image_count == self.IMAGE_COUNT * parse_info['label_count'], 'image count mismatch' assert self.delete_dataset(job_id) == 200, 'delete failed' assert not self.dataset_exists(job_id), 'dataset exists after delete' class TestMaxPerClass(BaseViewsTestWithImageset, test_utils.DatasetMixin): def test_max_per_class(self): for type in ['train', 'val', 'test']: yield self.check_max_per_class, type def check_max_per_class(self, type): # create dataset, asking for at most IMAGE_COUNT/2 images per class assert self.IMAGE_COUNT % 2 == 0 max_per_class = self.IMAGE_COUNT / 2 data = {'folder_pct_val': 0} if type == 'train': data['folder_train_max_per_class'] = max_per_class if type == 'val': data['has_val_folder'] = 'True' data['folder_val'] = self.imageset_folder data['folder_val_max_per_class'] = max_per_class elif type == 'test': data['has_test_folder'] = 'True' data['folder_test'] = self.imageset_folder data['folder_test_max_per_class'] = max_per_class job_id = self.create_dataset(**data) assert self.dataset_wait_completion(job_id) == 'Done', 'create failed' info = self.dataset_info(job_id) if type == 'train': assert len(info['ParseFolderTasks']) == 1, 'expected exactly one ParseFolderTasks' parse_info = info['ParseFolderTasks'][0] else: assert len(info['ParseFolderTasks']) == 2, 'expected exactly one ParseFolderTasks' parse_info = info['ParseFolderTasks'][1] image_count = parse_info['train_count'] + parse_info['val_count'] + parse_info['test_count'] assert image_count == max_per_class * parse_info['label_count'], 'image count mismatch' assert self.delete_dataset(job_id) == 200, 'delete failed' assert not self.dataset_exists(job_id), 'dataset exists after delete' class TestMinPerClass(BaseViewsTestWithImageset, test_utils.DatasetMixin): UNBALANCED_CATEGORY = True def test_min_per_class(self): for type in ['train', 'val', 'test']: yield self.check_min_per_class, type def check_min_per_class(self, type): # create dataset, asking for one more image per class # than available in the "unbalanced" category min_per_class = self.IMAGE_COUNT / 2 + 1 data = {'folder_pct_val': 0} if type == 'train': data['folder_train_min_per_class'] = min_per_class if type == 'val': data['has_val_folder'] = 'True' data['folder_val'] = self.imageset_folder data['folder_val_min_per_class'] = min_per_class elif type == 'test': data['has_test_folder'] = 'True' data['folder_test'] = self.imageset_folder data['folder_test_min_per_class'] = min_per_class job_id = self.create_dataset(**data) assert self.dataset_wait_completion(job_id) == 'Done', 'create failed' info = self.dataset_info(job_id) if type == 'train': assert len(info['ParseFolderTasks']) == 1, 'expected exactly one ParseFolderTasks' parse_info = info['ParseFolderTasks'][0] else: assert len(info['ParseFolderTasks']) == 2, 'expected exactly two ParseFolderTasks' parse_info = info['ParseFolderTasks'][1] assert self.categoryCount() == parse_info['label_count'] + 1 assert self.delete_dataset(job_id) == 200, 'delete failed' assert not self.dataset_exists(job_id), 'dataset exists after delete' class TestCreated(BaseViewsTestWithDataset, test_utils.DatasetMixin): """ Tests on a dataset that has already been created """ def test_index_json(self): rv = self.app.get('/index/json') assert rv.status_code == 200, 'page load failed with %s' % rv.status_code content = json.loads(rv.data) found = False for d in content['datasets']: if d['id'] == self.dataset_id: found = True break assert found, 'dataset not found in list' def test_dataset_json(self): rv = self.app.get('/datasets/%s/json' % self.dataset_id) assert rv.status_code == 200, 'page load failed with %s' % rv.status_code content = json.loads(rv.data) assert content['id'] == self.dataset_id, 'expected different job_id' def test_mean_dimensions(self): img_url = '/files/%s/mean.jpg' % self.dataset_id rv = self.app.get(img_url) assert rv.status_code == 200, 'GET on %s returned %s' % (img_url, rv.status_code) buff = StringIO(rv.data) buff.seek(0) pil_image = PIL.Image.open(buff) assert pil_image.size == (self.IMAGE_WIDTH, self.IMAGE_HEIGHT), 'image size is %s' % (pil_image.size,) def test_edit_name(self): status = self.edit_job(self.dataset_id, name='new name' ) assert status == 200, 'failed with %s' % status rv = self.app.get('/datasets/summary?job_id=%s' % self.dataset_id) assert rv.status_code == 200 assert 'new name' in rv.data def test_edit_notes(self): status = self.edit_job( self.dataset_id, notes='new notes' ) assert status == 200, 'failed with %s' % status def test_backend_selection(self): rv = self.app.get('/datasets/%s/json' % self.dataset_id) content = json.loads(rv.data) for task in content['CreateDbTasks']: assert task['backend'] == self.BACKEND def test_explore_train(self): rv = self.app.get('/datasets/images/classification/explore?job_id=%s&db=train' % self.dataset_id) if self.BACKEND == 'hdf5': # Not supported yet assert rv.status_code == 500, 'page load should have failed' assert 'expected backend is lmdb' in rv.data, 'unexpected page format' else: assert rv.status_code == 200, 'page load failed with %s' % rv.status_code assert 'Items per page' in rv.data, 'unexpected page format' def test_explore_val(self): rv = self.app.get('/datasets/images/classification/explore?job_id=%s&db=val' % self.dataset_id) if self.BACKEND == 'hdf5': # Not supported yet assert rv.status_code == 500, 'page load should have failed' assert 'expected backend is lmdb' in rv.data, 'unexpected page format' else: assert rv.status_code == 200, 'page load failed with %s' % rv.status_code assert 'Items per page' in rv.data, 'unexpected page format' class TestCreatedGrayscale(TestCreated, test_utils.DatasetMixin): IMAGE_CHANNELS = 1 class TestCreatedWide(TestCreated, test_utils.DatasetMixin): IMAGE_WIDTH = 20 class TestCreatedTall(TestCreated, test_utils.DatasetMixin): IMAGE_HEIGHT = 20 class TestCreatedJPEG(TestCreated, test_utils.DatasetMixin): ENCODING = 'jpg' class TestCreatedRaw(TestCreated, test_utils.DatasetMixin): ENCODING = 'none' class TestCreatedRawGrayscale(TestCreated, test_utils.DatasetMixin): ENCODING = 'none' IMAGE_CHANNELS = 1 class TestCreatedHdf5(TestCreated, test_utils.DatasetMixin): BACKEND = 'hdf5' def test_compression_method(self): rv = self.app.get('/datasets/%s/json' % self.dataset_id) content = json.loads(rv.data) for task in content['CreateDbTasks']: assert task['compression'] == self.COMPRESSION class TestCreatedHdf5Gzip(TestCreatedHdf5, test_utils.DatasetMixin): COMPRESSION = 'gzip'
DIGITS-master
digits/dataset/images/classification/test_views.py
# Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import os.path import requests import wtforms from wtforms import validators from ..forms import ImageDatasetForm from digits import utils from digits.utils.forms import validate_required_iff, validate_greater_than class ImageClassificationDatasetForm(ImageDatasetForm): """ Defines the form used to create a new ImageClassificationDatasetJob """ backend = wtforms.SelectField('DB backend', choices=[ ('lmdb', 'LMDB'), ('hdf5', 'HDF5') ], default='lmdb', ) def validate_backend(form, field): if field.data == 'lmdb': form.compression.data = 'none' elif field.data == 'tfrecords': form.compression.data = 'none' elif field.data == 'hdf5': form.encoding.data = 'none' compression = utils.forms.SelectField( 'DB compression', choices=[ ('none', 'None'), ('gzip', 'GZIP'), ], default='none', tooltip=('Compressing the dataset may significantly decrease the size ' 'of your database files, but it may increase read and write times.'), ) # Use a SelectField instead of a HiddenField so that the default value # is used when nothing is provided (through the REST API) method = wtforms.SelectField(u'Dataset type', choices=[ ('folder', 'Folder'), ('textfile', 'Textfiles'), ('s3', 'S3'), ], default='folder', ) def validate_folder_path(form, field): if not field.data: pass elif utils.is_url(field.data): # make sure the URL exists try: r = requests.get(field.data, allow_redirects=False, timeout=utils.HTTP_TIMEOUT) if r.status_code not in [requests.codes.ok, requests.codes.moved, requests.codes.found]: raise validators.ValidationError('URL not found') except Exception as e: raise validators.ValidationError('Caught %s while checking URL: %s' % (type(e).__name__, e)) else: return True else: # make sure the filesystem path exists # and make sure the filesystem path is absolute if not os.path.exists(field.data) or not os.path.isdir(field.data): raise validators.ValidationError('Folder does not exist') elif not os.path.isabs(field.data): raise validators.ValidationError('Filesystem path is not absolute') else: return True # # Method - folder # folder_train = utils.forms.StringField( u'Training Images', validators=[ validate_required_iff(method='folder'), validate_folder_path, ], tooltip=('Indicate a folder which holds subfolders full of images. ' 'Each subfolder should be named according to the desired label for the images that it holds. ' 'Can also be a URL for an apache/nginx auto-indexed folder.'), ) folder_pct_val = utils.forms.IntegerField( u'% for validation', default=25, validators=[ validate_required_iff(method='folder'), validators.NumberRange(min=0, max=100) ], tooltip=('You can choose to set apart a certain percentage of images ' 'from the training images for the validation set.'), ) folder_pct_test = utils.forms.IntegerField( u'% for testing', default=0, validators=[ validate_required_iff(method='folder'), validators.NumberRange(min=0, max=100) ], tooltip=('You can choose to set apart a certain percentage of images ' 'from the training images for the test set.'), ) folder_train_min_per_class = utils.forms.IntegerField( u'Minimum samples per class', default=2, validators=[ validators.Optional(), validators.NumberRange(min=1), ], tooltip=('You can choose to specify a minimum number of samples per class. ' 'If a class has fewer samples than the specified amount it will be ignored. ' 'Leave blank to ignore this feature.'), ) folder_train_max_per_class = utils.forms.IntegerField( u'Maximum samples per class', validators=[ validators.Optional(), validators.NumberRange(min=1), validate_greater_than('folder_train_min_per_class'), ], tooltip=('You can choose to specify a maximum number of samples per class. ' 'If a class has more samples than the specified amount extra samples will be ignored. ' 'Leave blank to ignore this feature.'), ) has_val_folder = wtforms.BooleanField( 'Separate validation images folder', default=False, validators=[ validate_required_iff(method='folder') ] ) folder_val = wtforms.StringField( u'Validation Images', validators=[ validate_required_iff( method='folder', has_val_folder=True), ] ) folder_val_min_per_class = utils.forms.IntegerField( u'Minimum samples per class', default=2, validators=[ validators.Optional(), validators.NumberRange(min=1), ], tooltip=('You can choose to specify a minimum number of samples per class. ' 'If a class has fewer samples than the specified amount it will be ignored. ' 'Leave blank to ignore this feature.'), ) folder_val_max_per_class = utils.forms.IntegerField( u'Maximum samples per class', validators=[ validators.Optional(), validators.NumberRange(min=1), validate_greater_than('folder_val_min_per_class'), ], tooltip=('You can choose to specify a maximum number of samples per class. ' 'If a class has more samples than the specified amount extra samples will be ignored. ' 'Leave blank to ignore this feature.'), ) has_test_folder = wtforms.BooleanField( 'Separate test images folder', default=False, validators=[ validate_required_iff(method='folder') ] ) folder_test = wtforms.StringField( u'Test Images', validators=[ validate_required_iff( method='folder', has_test_folder=True), validate_folder_path, ] ) folder_test_min_per_class = utils.forms.IntegerField( u'Minimum samples per class', default=2, validators=[ validators.Optional(), validators.NumberRange(min=1) ], tooltip=('You can choose to specify a minimum number of samples per class. ' 'If a class has fewer samples than the specified amount it will be ignored. ' 'Leave blank to ignore this feature.'), ) folder_test_max_per_class = utils.forms.IntegerField( u'Maximum samples per class', validators=[ validators.Optional(), validators.NumberRange(min=1), validate_greater_than('folder_test_min_per_class'), ], tooltip=('You can choose to specify a maximum number of samples per class. ' 'If a class has more samples than the specified amount extra samples will be ignored. ' 'Leave blank to ignore this feature.'), ) # # Method - textfile # textfile_use_local_files = wtforms.BooleanField( u'Use local files', default=False, ) textfile_train_images = utils.forms.FileField( u'Training images', validators=[ validate_required_iff(method='textfile', textfile_use_local_files=False) ] ) textfile_local_train_images = wtforms.StringField( u'Training images', validators=[ validate_required_iff(method='textfile', textfile_use_local_files=True) ] ) textfile_train_folder = wtforms.StringField(u'Training images folder') def validate_textfile_train_folder(form, field): if form.method.data != 'textfile': field.errors[:] = [] raise validators.StopValidation() if not field.data.strip(): # allow null return True if not os.path.exists(field.data) or not os.path.isdir(field.data): raise validators.ValidationError('folder does not exist') return True textfile_use_val = wtforms.BooleanField(u'Validation set', default=True, validators=[ validate_required_iff(method='textfile') ] ) textfile_val_images = utils.forms.FileField(u'Validation images', validators=[ validate_required_iff( method='textfile', textfile_use_val=True, textfile_use_local_files=False) ] ) textfile_local_val_images = wtforms.StringField(u'Validation images', validators=[ validate_required_iff( method='textfile', textfile_use_val=True, textfile_use_local_files=True) ] ) textfile_val_folder = wtforms.StringField(u'Validation images folder') def validate_textfile_val_folder(form, field): if form.method.data != 'textfile' or not form.textfile_use_val.data: field.errors[:] = [] raise validators.StopValidation() if not field.data.strip(): # allow null return True if not os.path.exists(field.data) or not os.path.isdir(field.data): raise validators.ValidationError('folder does not exist') return True textfile_use_test = wtforms.BooleanField(u'Test set', default=False, validators=[ validate_required_iff(method='textfile') ] ) textfile_test_images = utils.forms.FileField(u'Test images', validators=[ validate_required_iff( method='textfile', textfile_use_test=True, textfile_use_local_files=False) ] ) textfile_local_test_images = wtforms.StringField(u'Test images', validators=[ validate_required_iff( method='textfile', textfile_use_test=True, textfile_use_local_files=True) ] ) textfile_test_folder = wtforms.StringField(u'Test images folder') def validate_textfile_test_folder(form, field): if form.method.data != 'textfile' or not form.textfile_use_test.data: field.errors[:] = [] raise validators.StopValidation() if not field.data.strip(): # allow null return True if not os.path.exists(field.data) or not os.path.isdir(field.data): raise validators.ValidationError('folder does not exist') return True # Can't use a BooleanField here because HTML doesn't submit anything # for an unchecked checkbox. Since we want to use a REST API and have # this default to True when nothing is supplied, we have to use a # SelectField textfile_shuffle = utils.forms.SelectField( 'Shuffle lines', choices=[ (1, 'Yes'), (0, 'No'), ], coerce=int, default=1, tooltip="Shuffle the list[s] of images before creating the database." ) textfile_labels_file = utils.forms.FileField( u'Labels', validators=[ validate_required_iff(method='textfile', textfile_use_local_files=False) ], tooltip=("The 'i'th line of the file should give the string label " "associated with the '(i-1)'th numeric label. (E.g. the string label " "for the numeric label 0 is supposed to be on line 1.)"), ) textfile_local_labels_file = utils.forms.StringField( u'Labels', validators=[ validate_required_iff(method='textfile', textfile_use_local_files=True) ], tooltip=("The 'i'th line of the file should give the string label " "associated with the '(i-1)'th numeric label. (E.g. the string label " "for the numeric label 0 is supposed to be on line 1.)"), ) # # Method - S3 # s3_endpoint_url = utils.forms.StringField( u'Training Images', tooltip=('S3 end point URL'), ) s3_bucket = utils.forms.StringField( u'Bucket Name', tooltip=('bucket name'), ) s3_path = utils.forms.StringField( u'Training Images Path', tooltip=('Indicate a path which holds subfolders full of images. ' 'Each subfolder should be named according to the desired label for the images that it holds. '), ) s3_accesskey = utils.forms.StringField( u'Access Key', tooltip=('Access Key to access this S3 End Point'), ) s3_secretkey = utils.forms.StringField( u'Secret Key', tooltip=('Secret Key to access this S3 End Point'), ) s3_keepcopiesondisk = utils.forms.BooleanField( u'Keep Copies of Files on Disk', tooltip=('Checking this box will keep raw files retrieved from S3 stored on disk after the job is completed'), ) s3_pct_val = utils.forms.IntegerField( u'% for validation', default=25, validators=[ validate_required_iff(method='s3'), validators.NumberRange(min=0, max=100) ], tooltip=('You can choose to set apart a certain percentage of images ' 'from the training images for the validation set.'), ) s3_pct_test = utils.forms.IntegerField( u'% for testing', default=0, validators=[ validate_required_iff(method='s3'), validators.NumberRange(min=0, max=100) ], tooltip=('You can choose to set apart a certain percentage of images ' 'from the training images for the test set.'), ) s3_train_min_per_class = utils.forms.IntegerField( u'Minimum samples per class', default=2, validators=[ validators.Optional(), validators.NumberRange(min=1), ], tooltip=('You can choose to specify a minimum number of samples per class. ' 'If a class has fewer samples than the specified amount it will be ignored. ' 'Leave blank to ignore this feature.'), ) s3_train_max_per_class = utils.forms.IntegerField( u'Maximum samples per class', validators=[ validators.Optional(), validators.NumberRange(min=1), validate_greater_than('s3_train_min_per_class'), ], tooltip=('You can choose to specify a maximum number of samples per class. ' 'If a class has more samples than the specified amount extra samples will be ignored. ' 'Leave blank to ignore this feature.'), )
DIGITS-master
digits/dataset/images/classification/forms.py
#!/usr/bin/env python2 # Copyright (c) 2015-2017, NVIDIA CORPORATION. All rights reserved. """ Functions for creating temporary datasets Used in test_views """ from __future__ import absolute_import import argparse from collections import defaultdict import os import time import numpy as np import PIL.Image def create_classification_imageset( folder, image_size=10, image_count=10, add_unbalanced_category=False, ): """ Creates a folder of folders of images for classification If requested to add an unbalanced category then a category is added with half the number of samples of other categories """ # Stores the relative path of each image of the dataset paths = defaultdict(list) config = [ ('red-to-right', 0, 0, image_count), ('green-to-top', 1, 90, image_count), ('blue-to-left', 2, 180, image_count), ] if add_unbalanced_category: config.append(('blue-to-bottom', 2, 270, image_count / 2)) for class_name, pixel_index, rotation, image_count in config: os.makedirs(os.path.join(folder, class_name)) colors = np.linspace(200, 255, image_count) for i, color in enumerate(colors): pixel = [0, 0, 0] pixel[pixel_index] = color pil_img = _create_gradient_image(image_size, (0, 0, 0), pixel, rotation) img_path = os.path.join(class_name, str(i) + '.png') pil_img.save(os.path.join(folder, img_path)) paths[class_name].append(img_path) return paths def _create_gradient_image(size, color_from, color_to, rotation): """ Make an image with a color gradient with a specific rotation """ # create gradient rgb_arrays = [np.linspace(color_from[x], color_to[x], size).astype('uint8') for x in range(3)] gradient = np.concatenate(rgb_arrays) # extend to 2d picture = np.repeat(gradient, size) picture.shape = (3, size, size) # make image and rotate image = PIL.Image.fromarray(picture.T) image = image.rotate(rotation) return image if __name__ == '__main__': parser = argparse.ArgumentParser(description='Create-Imageset tool - DIGITS') # Positional arguments parser.add_argument('folder', help='Where to save the images' ) # Optional arguments parser.add_argument('-s', '--image_size', type=int, help='Size of the images') parser.add_argument('-c', '--image_count', type=int, help='How many images') args = vars(parser.parse_args()) print 'Creating images at "%s" ...' % args['folder'] start_time = time.time() create_classification_imageset(args['folder'], image_size=args['image_size'], image_count=args['image_count'], ) print 'Done after %s seconds' % (time.time() - start_time,)
DIGITS-master
digits/dataset/images/classification/test_imageset_creator.py
# Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import os import shutil # Find the best implementation available try: from cStringIO import StringIO except ImportError: from StringIO import StringIO import caffe_pb2 import flask import PIL.Image from .forms import ImageClassificationDatasetForm from .job import ImageClassificationDatasetJob from digits import utils from digits.dataset import tasks from digits.utils.forms import fill_form_if_cloned, save_form_to_job from digits.utils.lmdbreader import DbReader from digits.utils.routing import request_wants_json, job_from_request from digits.webapp import scheduler blueprint = flask.Blueprint(__name__, __name__) def from_folders(job, form): """ Add tasks for creating a dataset by parsing folders of images """ job.labels_file = utils.constants.LABELS_FILE # Add ParseFolderTask percent_val = form.folder_pct_val.data val_parents = [] if form.has_val_folder.data: percent_val = 0 percent_test = form.folder_pct_test.data test_parents = [] if form.has_test_folder.data: percent_test = 0 min_per_class = form.folder_train_min_per_class.data max_per_class = form.folder_train_max_per_class.data parse_train_task = tasks.ParseFolderTask( job_dir=job.dir(), folder=form.folder_train.data, percent_val=percent_val, percent_test=percent_test, min_per_category=min_per_class if min_per_class > 0 else 1, max_per_category=max_per_class if max_per_class > 0 else None ) job.tasks.append(parse_train_task) # set parents if not form.has_val_folder.data: val_parents = [parse_train_task] if not form.has_test_folder.data: test_parents = [parse_train_task] if form.has_val_folder.data: min_per_class = form.folder_val_min_per_class.data max_per_class = form.folder_val_max_per_class.data parse_val_task = tasks.ParseFolderTask( job_dir=job.dir(), parents=parse_train_task, folder=form.folder_val.data, percent_val=100, percent_test=0, min_per_category=min_per_class if min_per_class > 0 else 1, max_per_category=max_per_class if max_per_class > 0 else None ) job.tasks.append(parse_val_task) val_parents = [parse_val_task] if form.has_test_folder.data: min_per_class = form.folder_test_min_per_class.data max_per_class = form.folder_test_max_per_class.data parse_test_task = tasks.ParseFolderTask( job_dir=job.dir(), parents=parse_train_task, folder=form.folder_test.data, percent_val=0, percent_test=100, min_per_category=min_per_class if min_per_class > 0 else 1, max_per_category=max_per_class if max_per_class > 0 else None ) job.tasks.append(parse_test_task) test_parents = [parse_test_task] # Add CreateDbTasks backend = form.backend.data encoding = form.encoding.data compression = form.compression.data job.tasks.append( tasks.CreateDbTask( job_dir=job.dir(), parents=parse_train_task, input_file=utils.constants.TRAIN_FILE, db_name=utils.constants.TRAIN_DB, backend=backend, image_dims=job.image_dims, resize_mode=job.resize_mode, encoding=encoding, compression=compression, mean_file=utils.constants.MEAN_FILE_CAFFE, labels_file=job.labels_file, ) ) if percent_val > 0 or form.has_val_folder.data: job.tasks.append( tasks.CreateDbTask( job_dir=job.dir(), parents=val_parents, input_file=utils.constants.VAL_FILE, db_name=utils.constants.VAL_DB, backend=backend, image_dims=job.image_dims, resize_mode=job.resize_mode, encoding=encoding, compression=compression, labels_file=job.labels_file, ) ) if percent_test > 0 or form.has_test_folder.data: job.tasks.append( tasks.CreateDbTask( job_dir=job.dir(), parents=test_parents, input_file=utils.constants.TEST_FILE, db_name=utils.constants.TEST_DB, backend=backend, image_dims=job.image_dims, resize_mode=job.resize_mode, encoding=encoding, compression=compression, labels_file=job.labels_file, ) ) def from_files(job, form): """ Add tasks for creating a dataset by reading textfiles """ # labels if form.textfile_use_local_files.data: labels_file_from = form.textfile_local_labels_file.data.strip() labels_file_to = os.path.join(job.dir(), utils.constants.LABELS_FILE) shutil.copyfile(labels_file_from, labels_file_to) else: flask.request.files[form.textfile_labels_file.name].save( os.path.join(job.dir(), utils.constants.LABELS_FILE) ) job.labels_file = utils.constants.LABELS_FILE shuffle = bool(form.textfile_shuffle.data) backend = form.backend.data encoding = form.encoding.data compression = form.compression.data # train if form.textfile_use_local_files.data: train_file = form.textfile_local_train_images.data.strip() else: flask.request.files[form.textfile_train_images.name].save( os.path.join(job.dir(), utils.constants.TRAIN_FILE) ) train_file = utils.constants.TRAIN_FILE image_folder = form.textfile_train_folder.data.strip() if not image_folder: image_folder = None job.tasks.append( tasks.CreateDbTask( job_dir=job.dir(), input_file=train_file, db_name=utils.constants.TRAIN_DB, backend=backend, image_dims=job.image_dims, image_folder=image_folder, resize_mode=job.resize_mode, encoding=encoding, compression=compression, mean_file=utils.constants.MEAN_FILE_CAFFE, labels_file=job.labels_file, shuffle=shuffle, ) ) # val if form.textfile_use_val.data: if form.textfile_use_local_files.data: val_file = form.textfile_local_val_images.data.strip() else: flask.request.files[form.textfile_val_images.name].save( os.path.join(job.dir(), utils.constants.VAL_FILE) ) val_file = utils.constants.VAL_FILE image_folder = form.textfile_val_folder.data.strip() if not image_folder: image_folder = None job.tasks.append( tasks.CreateDbTask( job_dir=job.dir(), input_file=val_file, db_name=utils.constants.VAL_DB, backend=backend, image_dims=job.image_dims, image_folder=image_folder, resize_mode=job.resize_mode, encoding=encoding, compression=compression, labels_file=job.labels_file, shuffle=shuffle, ) ) # test if form.textfile_use_test.data: if form.textfile_use_local_files.data: test_file = form.textfile_local_test_images.data.strip() else: flask.request.files[form.textfile_test_images.name].save( os.path.join(job.dir(), utils.constants.TEST_FILE) ) test_file = utils.constants.TEST_FILE image_folder = form.textfile_test_folder.data.strip() if not image_folder: image_folder = None job.tasks.append( tasks.CreateDbTask( job_dir=job.dir(), input_file=test_file, db_name=utils.constants.TEST_DB, backend=backend, image_dims=job.image_dims, image_folder=image_folder, resize_mode=job.resize_mode, encoding=encoding, compression=compression, labels_file=job.labels_file, shuffle=shuffle, ) ) def from_s3(job, form): """ Add tasks for creating a dataset by parsing s3s of images """ job.labels_file = utils.constants.LABELS_FILE # Add Parses3Task percent_val = form.s3_pct_val.data val_parents = [] percent_test = form.s3_pct_test.data test_parents = [] min_per_class = form.s3_train_min_per_class.data max_per_class = form.s3_train_max_per_class.data delete_files = not form.s3_keepcopiesondisk.data parse_train_task = tasks.ParseS3Task( job_dir=job.dir(), s3_endpoint_url=form.s3_endpoint_url.data, s3_bucket=form.s3_bucket.data, s3_path=form.s3_path.data, s3_accesskey=form.s3_accesskey.data, s3_secretkey=form.s3_secretkey.data, percent_val=percent_val, percent_test=percent_test, min_per_category=min_per_class if min_per_class > 0 else 1, max_per_category=max_per_class if max_per_class > 0 else None ) job.tasks.append(parse_train_task) # set parents val_parents = [parse_train_task] test_parents = [parse_train_task] # Add CreateDbTasks backend = form.backend.data encoding = form.encoding.data compression = form.compression.data job.tasks.append( tasks.CreateDbTask( job_dir=job.dir(), parents=parse_train_task, input_file=utils.constants.TRAIN_FILE, db_name=utils.constants.TRAIN_DB, backend=backend, image_dims=job.image_dims, resize_mode=job.resize_mode, encoding=encoding, compression=compression, mean_file=utils.constants.MEAN_FILE_CAFFE, labels_file=job.labels_file, delete_files=delete_files, ) ) if percent_val > 0: job.tasks.append( tasks.CreateDbTask( job_dir=job.dir(), parents=val_parents, input_file=utils.constants.VAL_FILE, db_name=utils.constants.VAL_DB, backend=backend, image_dims=job.image_dims, resize_mode=job.resize_mode, encoding=encoding, compression=compression, labels_file=job.labels_file, delete_files=delete_files, ) ) if percent_test > 0: job.tasks.append( tasks.CreateDbTask( job_dir=job.dir(), parents=test_parents, input_file=utils.constants.TEST_FILE, db_name=utils.constants.TEST_DB, backend=backend, image_dims=job.image_dims, resize_mode=job.resize_mode, encoding=encoding, compression=compression, labels_file=job.labels_file, delete_files=delete_files, ) ) @blueprint.route('/new', methods=['GET']) @utils.auth.requires_login def new(): """ Returns a form for a new ImageClassificationDatasetJob """ form = ImageClassificationDatasetForm() # Is there a request to clone a job with ?clone=<job_id> fill_form_if_cloned(form) return flask.render_template('datasets/images/classification/new.html', form=form) @blueprint.route('/json', methods=['POST']) @blueprint.route('', methods=['POST'], strict_slashes=False) @utils.auth.requires_login(redirect=False) def create(): """ Creates a new ImageClassificationDatasetJob Returns JSON when requested: {job_id,name,status} or {errors:[]} """ form = ImageClassificationDatasetForm() # Is there a request to clone a job with ?clone=<job_id> fill_form_if_cloned(form) if not form.validate_on_submit(): if request_wants_json(): return flask.jsonify({'errors': form.errors}), 400 else: return flask.render_template('datasets/images/classification/new.html', form=form), 400 job = None try: job = ImageClassificationDatasetJob( username=utils.auth.get_username(), name=form.dataset_name.data, group=form.group_name.data, image_dims=( int(form.resize_height.data), int(form.resize_width.data), int(form.resize_channels.data), ), resize_mode=form.resize_mode.data ) if form.method.data == 'folder': from_folders(job, form) elif form.method.data == 'textfile': from_files(job, form) elif form.method.data == 's3': from_s3(job, form) else: raise ValueError('method not supported') # Save form data with the job so we can easily clone it later. save_form_to_job(job, form) scheduler.add_job(job) if request_wants_json(): return flask.jsonify(job.json_dict()) else: return flask.redirect(flask.url_for('digits.dataset.views.show', job_id=job.id())) except: if job: scheduler.delete_job(job) raise def show(job, related_jobs=None): """ Called from digits.dataset.views.datasets_show() """ return flask.render_template('datasets/images/classification/show.html', job=job, related_jobs=related_jobs) def summary(job): """ Return a short HTML summary of an ImageClassificationDatasetJob """ return flask.render_template('datasets/images/classification/summary.html', dataset=job) @blueprint.route('/explore', methods=['GET']) def explore(): """ Returns a gallery consisting of the images of one of the dbs """ job = job_from_request() # Get LMDB db = flask.request.args.get('db', 'train') if 'train' in db.lower(): task = job.train_db_task() elif 'val' in db.lower(): task = job.val_db_task() elif 'test' in db.lower(): task = job.test_db_task() if task is None: raise ValueError('No create_db task for {0}'.format(db)) if task.status != 'D': raise ValueError("This create_db task's status should be 'D' but is '{0}'".format(task.status)) if task.backend != 'lmdb': raise ValueError("Backend is {0} while expected backend is lmdb".format(task.backend)) db_path = job.path(task.db_name) labels = task.get_labels() page = int(flask.request.args.get('page', 0)) size = int(flask.request.args.get('size', 25)) label = flask.request.args.get('label', None) if label is not None: try: label = int(label) except ValueError: label = None reader = DbReader(db_path) count = 0 imgs = [] min_page = max(0, page - 5) if label is None: total_entries = reader.total_entries else: # After PR#1500, task.distribution[str(label)] is a dictionary # with keys = 'count' and 'error_count' label_entries = task.distribution[str(label)] if isinstance(label_entries, dict): total_entries = label_entries['count'] else: total_entries = label_entries max_page = min((total_entries - 1) / size, page + 5) pages = range(min_page, max_page + 1) for key, value in reader.entries(): if count >= page * size: datum = caffe_pb2.Datum() datum.ParseFromString(value) if label is None or datum.label == label: if datum.encoded: s = StringIO() s.write(datum.data) s.seek(0) img = PIL.Image.open(s) else: import caffe.io arr = caffe.io.datum_to_array(datum) # CHW -> HWC arr = arr.transpose((1, 2, 0)) if arr.shape[2] == 1: # HWC -> HW arr = arr[:, :, 0] elif arr.shape[2] == 3: # BGR -> RGB # XXX see issue #59 arr = arr[:, :, [2, 1, 0]] img = PIL.Image.fromarray(arr) imgs.append({"label": labels[datum.label], "b64": utils.image.embed_image_html(img)}) if label is None: count += 1 else: datum = caffe_pb2.Datum() datum.ParseFromString(value) if datum.label == int(label): count += 1 if len(imgs) >= size: break return flask.render_template( 'datasets/images/explore.html', page=page, size=size, job=job, imgs=imgs, labels=labels, pages=pages, label=label, total_entries=total_entries, db=db)
DIGITS-master
digits/dataset/images/classification/views.py
# Copyright (c) 2015-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import from ..job import ImageDatasetJob from digits.dataset import tasks from digits.utils import subclass, override, constants # NOTE: Increment this every time the pickled object changes PICKLE_VERSION = 1 @subclass class GenericImageDatasetJob(ImageDatasetJob): """ A Job that creates an image dataset for a generic network """ def __init__(self, **kwargs): self.mean_file = kwargs.pop('mean_file', None) super(GenericImageDatasetJob, self).__init__(**kwargs) self.pickver_job_dataset_image_generic = PICKLE_VERSION def __setstate__(self, state): super(GenericImageDatasetJob, self).__setstate__(state) self.pickver_job_dataset_image_generic = PICKLE_VERSION def analyze_db_task(self, stage): """ Return AnalyzeDbTask for this stage """ if stage == constants.TRAIN_DB: s = 'train' elif stage == constants.VAL_DB: s = 'val' else: return None for t in self.tasks: if isinstance(t, tasks.AnalyzeDbTask) and s in t.name().lower(): return t return None def analyze_db_tasks(self): """ Return all AnalyzeDbTasks for this job """ return [t for t in self.tasks if isinstance(t, tasks.AnalyzeDbTask)] @override def get_backend(self): """ Return the DB backend used to create this dataset """ return self.analyze_db_task(constants.TRAIN_DB).backend @override def get_entry_count(self, stage): """ Return the number of entries in the DB matching the specified stage """ task = self.analyze_db_task(stage) return task.image_count if task is not None else 0 @override def get_feature_db_path(self, stage): """ Return the absolute feature DB path for the specified stage """ db = None if stage == constants.TRAIN_DB: s = 'Training' elif stage == constants.VAL_DB: s = 'Validation' else: return None for task in self.tasks: if task.purpose == '%s Images' % s: db = task return self.path(db.database) if db else None @override def get_feature_dims(self): """ Return the shape of the feature N-D array """ db_task = self.analyze_db_task(constants.TRAIN_DB) return [db_task.image_height, db_task.image_width, db_task.image_channels] @override def get_label_db_path(self, stage): """ Return the absolute label DB path for the specified stage """ db = None if stage == constants.TRAIN_DB: s = 'Training' elif stage == constants.VAL_DB: s = 'Validation' else: return None for task in self.tasks: if task.purpose == '%s Labels' % s: db = task return self.path(db.database) if db else None @override def get_mean_file(self): """ Return the mean file """ return self.mean_file @override def job_type(self): return 'Generic Image Dataset'
DIGITS-master
digits/dataset/images/generic/job.py
# Copyright (c) 2015-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import from .job import GenericImageDatasetJob __all__ = ['GenericImageDatasetJob']
DIGITS-master
digits/dataset/images/generic/__init__.py
# Copyright (c) 2015-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import json import os import tempfile from bs4 import BeautifulSoup from .test_lmdb_creator import create_lmdbs from digits import test_utils import digits.test_views # May be too short on a slow system TIMEOUT_DATASET = 45 ################################################################################ # Base classes (they don't start with "Test" so nose won't run them) ################################################################################ class BaseViewsTest(digits.test_views.BaseViewsTest): """ Provides some functions """ @classmethod def dataset_exists(cls, job_id): return cls.job_exists(job_id, 'datasets') @classmethod def dataset_status(cls, job_id): return cls.job_status(job_id, 'datasets') @classmethod def abort_dataset(cls, job_id): return cls.abort_job(job_id, job_type='datasets') @classmethod def dataset_wait_completion(cls, job_id, **kwargs): kwargs['job_type'] = 'datasets' if 'timeout' not in kwargs: kwargs['timeout'] = TIMEOUT_DATASET return cls.job_wait_completion(job_id, **kwargs) @classmethod def delete_dataset(cls, job_id): return cls.delete_job(job_id, job_type='datasets') class BaseViewsTestWithImageset(BaseViewsTest): """ Provides some LMDBs and some functions """ @classmethod def setUpClass(cls): super(BaseViewsTestWithImageset, cls).setUpClass() if not hasattr(BaseViewsTestWithImageset, 'imageset_folder'): # Create folder and LMDBs for all test classes BaseViewsTestWithImageset.imageset_folder = tempfile.mkdtemp() BaseViewsTestWithImageset.test_image = create_lmdbs(BaseViewsTestWithImageset.imageset_folder) BaseViewsTestWithImageset.val_db_path = os.path.join( BaseViewsTestWithImageset.imageset_folder, 'val_images') cls.created_datasets = [] @classmethod def tearDownClass(cls): # delete any created datasets for job_id in cls.created_datasets: cls.delete_dataset(job_id) super(BaseViewsTestWithImageset, cls).tearDownClass() @classmethod def create_dataset(cls, **kwargs): """ Create a dataset Returns the job_id Raises RuntimeError if job fails to create Keyword arguments: **kwargs -- data to be sent with POST request """ data = { 'dataset_name': 'test_dataset', 'group_name': 'test_group', 'method': 'prebuilt', 'prebuilt_train_images': os.path.join(cls.imageset_folder, 'train_images'), 'prebuilt_train_labels': os.path.join(cls.imageset_folder, 'train_labels'), 'prebuilt_val_images': os.path.join(cls.imageset_folder, 'val_images'), 'prebuilt_val_labels': os.path.join(cls.imageset_folder, 'val_labels'), 'prebuilt_mean_file': os.path.join(cls.imageset_folder, 'train_mean.binaryproto'), } data.update(kwargs) request_json = data.pop('json', False) url = '/datasets/images/generic' if request_json: url += '/json' rv = cls.app.post(url, data=data) if request_json: if rv.status_code != 200: print json.loads(rv.data) raise RuntimeError('Model creation failed with %s' % rv.status_code) return json.loads(rv.data)['id'] # expect a redirect if not 300 <= rv.status_code <= 310: s = BeautifulSoup(rv.data, 'html.parser') div = s.select('div.alert-danger') if div: print div[0] else: print rv.data raise RuntimeError('Failed to create dataset - status %s' % rv.status_code) job_id = cls.job_id_from_response(rv) assert cls.dataset_exists(job_id), 'dataset not found after successful creation' cls.created_datasets.append(job_id) return job_id class BaseViewsTestWithDataset(BaseViewsTestWithImageset): """ Provides a dataset and some functions """ @classmethod def setUpClass(cls): super(BaseViewsTestWithDataset, cls).setUpClass() cls.dataset_id = cls.create_dataset(json=True) assert cls.dataset_wait_completion(cls.dataset_id) == 'Done', 'create failed' ################################################################################ # Test classes ################################################################################ class TestViews(BaseViewsTest, test_utils.DatasetMixin): """ Tests which don't require an imageset or a dataset """ def test_page_dataset_new(self): rv = self.app.get('/datasets/images/generic/new') assert rv.status_code == 200, 'page load failed with %s' % rv.status_code assert 'New Image Dataset' in rv.data, 'unexpected page format' def test_nonexistent_dataset(self): assert not self.dataset_exists('foo'), "dataset shouldn't exist" class TestCreation(BaseViewsTestWithImageset, test_utils.DatasetMixin): """ Dataset creation tests """ def test_bad_path(self): try: self.create_dataset( prebuilt_train_images='/not-a-directory' ) except RuntimeError: return raise AssertionError('Should have failed') def test_create_json(self): job_id = self.create_dataset(json=True) self.abort_dataset(job_id) def test_create_delete(self): job_id = self.create_dataset() assert self.delete_dataset(job_id) == 200, 'delete failed' assert not self.dataset_exists(job_id), 'dataset exists after delete' def test_create_abort_delete(self): job_id = self.create_dataset() assert self.abort_dataset(job_id) == 200, 'abort failed' assert self.delete_dataset(job_id) == 200, 'delete failed' assert not self.dataset_exists(job_id), 'dataset exists after delete' def test_create_wait_delete(self): job_id = self.create_dataset() assert self.dataset_wait_completion(job_id) == 'Done', 'create failed' assert self.delete_dataset(job_id) == 200, 'delete failed' assert not self.dataset_exists(job_id), 'dataset exists after delete' def test_no_force_same_shape(self): job_id = self.create_dataset(force_same_shape=0) assert self.dataset_wait_completion(job_id) == 'Done', 'create failed' def test_clone(self): options_1 = { 'resize_channels': '1', } job1_id = self.create_dataset(**options_1) assert self.dataset_wait_completion(job1_id) == 'Done', 'first job failed' rv = self.app.get('/datasets/%s/json' % job1_id) assert rv.status_code == 200, 'json load failed with %s' % rv.status_code content1 = json.loads(rv.data) # Clone job1 as job2 options_2 = { 'clone': job1_id, } job2_id = self.create_dataset(**options_2) assert self.dataset_wait_completion(job2_id) == 'Done', 'second job failed' rv = self.app.get('/datasets/%s/json' % job2_id) assert rv.status_code == 200, 'json load failed with %s' % rv.status_code content2 = json.loads(rv.data) # These will be different content1.pop('id') content2.pop('id') content1.pop('directory') content2.pop('directory') assert (content1 == content2), 'job content does not match' job1 = digits.webapp.scheduler.get_job(job1_id) job2 = digits.webapp.scheduler.get_job(job2_id) assert (job1.form_data == job2.form_data), 'form content does not match' class TestCreated(BaseViewsTestWithDataset, test_utils.DatasetMixin): """ Tests on a dataset that has already been created """ def test_index_json(self): rv = self.app.get('/index/json') assert rv.status_code == 200, 'page load failed with %s' % rv.status_code content = json.loads(rv.data) found = False for d in content['datasets']: if d['id'] == self.dataset_id: found = True break assert found, 'dataset not found in list' def test_dataset_json(self): rv = self.app.get('/datasets/%s/json' % self.dataset_id) assert rv.status_code == 200, 'page load failed with %s' % rv.status_code content = json.loads(rv.data) assert content['id'] == self.dataset_id, 'expected different job_id' def test_edit_name(self): status = self.edit_job( self.dataset_id, name='new name' ) assert status == 200, 'failed with %s' % status rv = self.app.get('/datasets/summary?job_id=%s' % self.dataset_id) assert rv.status_code == 200 assert 'new name' in rv.data def test_edit_notes(self): status = self.edit_job( self.dataset_id, notes='new notes' ) assert status == 200, 'failed with %s' % status
DIGITS-master
digits/dataset/images/generic/test_views.py
#!/usr/bin/env python2 # Copyright (c) 2015-2017, NVIDIA CORPORATION. All rights reserved. """ Functions for creating temporary LMDBs Used in test_views """ from __future__ import absolute_import import argparse import os import sys import time # Find the best implementation available try: from cStringIO import StringIO except ImportError: from StringIO import StringIO import lmdb import numpy as np import PIL.Image if __name__ == '__main__': dirname = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.join(dirname, '..', '..', '..', '..')) import digits.config # noqa # Import digits.config first to set the path to Caffe import caffe_pb2 # noqa IMAGE_SIZE = 10 TRAIN_IMAGE_COUNT = 100 VAL_IMAGE_COUNT = 250 def create_lmdbs(folder, image_width=None, image_height=None, image_count=None): """ Creates LMDBs for generic inference Returns the filename for a test image Creates these files in "folder": train_images/ train_labels/ val_images/ val_labels/ mean.binaryproto test.png """ if image_width is None: image_width = IMAGE_SIZE if image_height is None: image_height = IMAGE_SIZE if image_count is None: train_image_count = TRAIN_IMAGE_COUNT else: train_image_count = image_count val_image_count = VAL_IMAGE_COUNT # Used to calculate the gradients later yy, xx = np.mgrid[:image_height, :image_width].astype('float') for phase, image_count in [ ('train', train_image_count), ('val', val_image_count)]: image_db = lmdb.open(os.path.join(folder, '%s_images' % phase), map_async=True, max_dbs=0) label_db = lmdb.open(os.path.join(folder, '%s_labels' % phase), map_async=True, max_dbs=0) image_sum = np.zeros((image_height, image_width), 'float64') for i in xrange(image_count): xslope, yslope = np.random.random_sample(2) - 0.5 a = xslope * 255 / image_width b = yslope * 255 / image_height image = a * (xx - image_width / 2) + b * (yy - image_height / 2) + 127.5 image_sum += image image = image.astype('uint8') pil_img = PIL.Image.fromarray(image) # create image Datum image_datum = caffe_pb2.Datum() image_datum.height = image.shape[0] image_datum.width = image.shape[1] image_datum.channels = 1 s = StringIO() pil_img.save(s, format='PNG') image_datum.data = s.getvalue() image_datum.encoded = True _write_to_lmdb(image_db, str(i), image_datum.SerializeToString()) # create label Datum label_datum = caffe_pb2.Datum() label_datum.channels, label_datum.height, label_datum.width = 1, 1, 2 label_datum.float_data.extend(np.array([xslope, yslope]).flat) _write_to_lmdb(label_db, str(i), label_datum.SerializeToString()) # close databases image_db.close() label_db.close() # save mean mean_image = (image_sum / image_count).astype('uint8') _save_mean(mean_image, os.path.join(folder, '%s_mean.png' % phase)) _save_mean(mean_image, os.path.join(folder, '%s_mean.binaryproto' % phase)) # create test image # The network should be able to easily produce two numbers >1 xslope, yslope = 0.5, 0.5 a = xslope * 255 / image_width b = yslope * 255 / image_height test_image = a * (xx - image_width / 2) + b * (yy - image_height / 2) + 127.5 test_image = test_image.astype('uint8') pil_img = PIL.Image.fromarray(test_image) test_image_filename = os.path.join(folder, 'test.png') pil_img.save(test_image_filename) return test_image_filename def _write_to_lmdb(db, key, value): """ Write (key,value) to db """ success = False while not success: txn = db.begin(write=True) try: txn.put(key, value) txn.commit() success = True except lmdb.MapFullError: txn.abort() # double the map_size curr_limit = db.info()['map_size'] new_limit = curr_limit * 2 db.set_mapsize(new_limit) # double it def _save_mean(mean, filename): """ Saves mean to file Arguments: mean -- the mean as an np.ndarray filename -- the location to save the image """ if filename.endswith('.binaryproto'): blob = caffe_pb2.BlobProto() blob.num = 1 blob.channels = 1 blob.height, blob.width = mean.shape blob.data.extend(mean.astype(float).flat) with open(filename, 'wb') as outfile: outfile.write(blob.SerializeToString()) elif filename.endswith(('.jpg', '.jpeg', '.png')): image = PIL.Image.fromarray(mean) image.save(filename) else: raise ValueError('unrecognized file extension') if __name__ == '__main__': parser = argparse.ArgumentParser(description='Create-LMDB tool - DIGITS') # Positional arguments parser.add_argument('folder', help='Where to save the images' ) # Optional arguments parser.add_argument('-x', '--image_width', type=int, help='Width of the images') parser.add_argument('-y', '--image_height', type=int, help='Height of the images') parser.add_argument('-c', '--image_count', type=int, help='How many images') args = vars(parser.parse_args()) if os.path.exists(args['folder']): print 'ERROR: Folder already exists' sys.exit(1) else: os.makedirs(args['folder']) print 'Creating images at "%s" ...' % args['folder'] start_time = time.time() create_lmdbs(args['folder'], image_width=args['image_width'], image_height=args['image_height'], image_count=args['image_count'], ) print 'Done after %s seconds' % (time.time() - start_time,)
DIGITS-master
digits/dataset/images/generic/test_lmdb_creator.py
# Copyright (c) 2015-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import os.path import wtforms from wtforms import validators from ..forms import ImageDatasetForm from digits import utils from digits.utils.forms import validate_required_iff class GenericImageDatasetForm(ImageDatasetForm): """ Defines the form used to create a new GenericImageDatasetJob """ # Use a SelectField instead of a HiddenField so that the default value # is used when nothing is provided (through the REST API) method = wtforms.SelectField( u'Dataset type', choices=[ ('prebuilt', 'Prebuilt'), ], default='prebuilt', ) def validate_lmdb_path(form, field): if not field.data: pass else: # make sure the filesystem path exists if not os.path.exists(field.data) or not os.path.isdir(field.data): raise validators.ValidationError('Folder does not exist') def validate_file_path(form, field): if not field.data: pass else: # make sure the filesystem path exists if not os.path.exists(field.data) or not os.path.isfile(field.data): raise validators.ValidationError('File does not exist') # # Method - prebuilt # prebuilt_train_images = wtforms.StringField( 'Training Images', validators=[ validate_required_iff(method='prebuilt'), validate_lmdb_path, ] ) prebuilt_train_labels = wtforms.StringField( 'Training Labels', validators=[ validate_lmdb_path, ] ) prebuilt_val_images = wtforms.StringField( 'Validation Images', validators=[ validate_lmdb_path, ] ) prebuilt_val_labels = wtforms.StringField( 'Validation Labels', validators=[ validate_lmdb_path, ] ) # Can't use a BooleanField here because HTML doesn't submit anything # for an unchecked checkbox. Since we want to use a REST API and have # this default to True when nothing is supplied, we have to use a # SelectField force_same_shape = utils.forms.SelectField( 'Enforce same shape', choices=[ (1, 'Yes'), (0, 'No'), ], coerce=int, default=1, tooltip='Check that each entry in the database has the same shape (can be time-consuming)' ) prebuilt_mean_file = utils.forms.StringField( 'Mean Image', validators=[ validate_file_path, ], tooltip="Path to a .binaryproto file on the server" )
DIGITS-master
digits/dataset/images/generic/forms.py
# Copyright (c) 2015-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import flask from .forms import GenericImageDatasetForm from .job import GenericImageDatasetJob from digits import utils from digits.dataset import tasks from digits.webapp import scheduler from digits.utils.forms import fill_form_if_cloned, save_form_to_job from digits.utils.routing import request_wants_json blueprint = flask.Blueprint(__name__, __name__) @blueprint.route('/new', methods=['GET']) @utils.auth.requires_login def new(): """ Returns a form for a new GenericImageDatasetJob """ form = GenericImageDatasetForm() # Is there a request to clone a job with ?clone=<job_id> fill_form_if_cloned(form) return flask.render_template('datasets/images/generic/new.html', form=form) @blueprint.route('/json', methods=['POST']) @blueprint.route('', methods=['POST'], strict_slashes=False) @utils.auth.requires_login(redirect=False) def create(): """ Creates a new GenericImageDatasetJob Returns JSON when requested: {job_id,name,status} or {errors:[]} """ form = GenericImageDatasetForm() # Is there a request to clone a job with ?clone=<job_id> fill_form_if_cloned(form) if not form.validate_on_submit(): if request_wants_json(): return flask.jsonify({'errors': form.errors}), 400 else: return flask.render_template('datasets/images/generic/new.html', form=form), 400 job = None try: job = GenericImageDatasetJob( username=utils.auth.get_username(), name=form.dataset_name.data, group=form.group_name.data, mean_file=form.prebuilt_mean_file.data.strip(), ) if form.method.data == 'prebuilt': pass else: raise ValueError('method not supported') force_same_shape = form.force_same_shape.data job.tasks.append( tasks.AnalyzeDbTask( job_dir=job.dir(), database=form.prebuilt_train_images.data, purpose=form.prebuilt_train_images.label.text, force_same_shape=force_same_shape, ) ) if form.prebuilt_train_labels.data: job.tasks.append( tasks.AnalyzeDbTask( job_dir=job.dir(), database=form.prebuilt_train_labels.data, purpose=form.prebuilt_train_labels.label.text, force_same_shape=force_same_shape, ) ) if form.prebuilt_val_images.data: job.tasks.append( tasks.AnalyzeDbTask( job_dir=job.dir(), database=form.prebuilt_val_images.data, purpose=form.prebuilt_val_images.label.text, force_same_shape=force_same_shape, ) ) if form.prebuilt_val_labels.data: job.tasks.append( tasks.AnalyzeDbTask( job_dir=job.dir(), database=form.prebuilt_val_labels.data, purpose=form.prebuilt_val_labels.label.text, force_same_shape=force_same_shape, ) ) # Save form data with the job so we can easily clone it later. save_form_to_job(job, form) scheduler.add_job(job) if request_wants_json(): return flask.jsonify(job.json_dict()) else: return flask.redirect(flask.url_for('digits.dataset.views.show', job_id=job.id())) except: if job: scheduler.delete_job(job) raise def show(job, related_jobs=None): """ Called from digits.dataset.views.datasets_show() """ return flask.render_template('datasets/images/generic/show.html', job=job, related_jobs=related_jobs) def summary(job): """ Return a short HTML summary of a GenericImageDatasetJob """ return flask.render_template('datasets/images/generic/summary.html', dataset=job)
DIGITS-master
digits/dataset/images/generic/views.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import from ..job import DatasetJob from digits.dataset import tasks from digits.utils import subclass, override, constants # NOTE: Increment this every time the pickled object changes PICKLE_VERSION = 1 @subclass class GenericDatasetJob(DatasetJob): """ A Job that creates a dataset using a user-defined extension """ def __init__(self, backend, feature_encoding, label_encoding, batch_size, num_threads, force_same_shape, extension_id, extension_userdata, **kwargs ): self.backend = backend self.feature_encoding = feature_encoding self.label_encoding = label_encoding self.num_threads = num_threads self.force_same_shape = force_same_shape self.batch_size = batch_size self.extension_id = extension_id self.extension_userdata = extension_userdata super(GenericDatasetJob, self).__init__(**kwargs) self.pickver_job_dataset_extension = PICKLE_VERSION # create tasks for stage in [constants.TRAIN_DB, constants.VAL_DB, constants.TEST_DB]: self.tasks.append(tasks.CreateGenericDbTask( job_dir=self.dir(), job=self, backend=self.backend, stage=stage, ) ) def __setstate__(self, state): super(GenericDatasetJob, self).__setstate__(state) self.pickver_job_dataset_extension = PICKLE_VERSION def create_db_task(self, stage): for t in self.tasks: if t.stage == stage: return t return None def create_db_tasks(self): return self.tasks @override def get_backend(self): """ Return the DB backend used to create this dataset """ return self.backend @override def get_entry_count(self, stage): """ Return the number of entries in the DB matching the specified stage """ return self.create_db_task(stage).entry_count @override def get_feature_db_path(self, stage): """ Return the absolute feature DB path for the specified stage """ return self.path(self.create_db_task(stage).dbs['features']) @override def get_feature_dims(self): """ Return the shape of the feature N-D array """ shape = self.create_db_task(constants.TRAIN_DB).feature_shape if len(shape) == 3: # assume image and convert CHW => HWC (numpy default for images) shape = [shape[1], shape[2], shape[0]] return shape @override def get_label_db_path(self, stage): """ Return the absolute label DB path for the specified stage """ return self.path(self.create_db_task(stage).dbs['labels']) @override def get_mean_file(self): """ Return the mean file (if it exists, or None) """ mean_file = self.create_db_task(constants.TRAIN_DB).mean_file return self.path(mean_file) if mean_file else '' @override def job_type(self): return 'Generic Dataset' @override def json_dict(self, verbose=False): d = super(GenericDatasetJob, self).json_dict(verbose) if verbose: d.update({ 'create_db_tasks': [{ "name": t.name(), "stage": t.stage, "entry_count": t.entry_count, "feature_db_path": t.dbs['features'], "label_db_path": t.dbs['labels'], } for t in self.create_db_tasks()], 'feature_dims': self.get_feature_dims()}) return d
DIGITS-master
digits/dataset/generic/job.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import from .job import GenericDatasetJob __all__ = ['GenericDatasetJob']
DIGITS-master
digits/dataset/generic/__init__.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import json import os import tempfile import unittest from bs4 import BeautifulSoup import numpy as np import PIL.Image import digits.test_views from digits import extensions from digits import test_utils from digits.utils import constants # May be too short on a slow system TIMEOUT_DATASET = 45 ################################################################################ # Base classes (they don't start with "Test" so nose won't run them) ################################################################################ class BaseViewsTest(digits.test_views.BaseViewsTest): """ Provides some functions """ @classmethod def dataset_exists(cls, job_id): return cls.job_exists(job_id, 'datasets') @classmethod def dataset_status(cls, job_id): return cls.job_status(job_id, 'datasets') @classmethod def abort_dataset(cls, job_id): return cls.abort_job(job_id, job_type='datasets') @classmethod def dataset_wait_completion(cls, job_id, **kwargs): kwargs['job_type'] = 'datasets' if 'timeout' not in kwargs: kwargs['timeout'] = TIMEOUT_DATASET return cls.job_wait_completion(job_id, **kwargs) @classmethod def delete_dataset(cls, job_id): return cls.delete_job(job_id, job_type='datasets') class BaseViewsTestWithDataset(BaseViewsTest): """ Provides some functions """ IMAGE_WIDTH = 32 IMAGE_HEIGHT = 32 CHANNELS = 1 @classmethod def create_dataset(cls, **kwargs): """ Create a dataset Returns the job_id Raises RuntimeError if job fails to create Keyword arguments: **kwargs -- data to be sent with POST request """ data = { 'dataset_name': 'test_dataset', 'group_name': 'test_group', } data.update(kwargs) request_json = data.pop('json', False) url = '/datasets/generic/create/%s' % cls.EXTENSION_ID if request_json: url += '/json' rv = cls.app.post(url, data=data) if request_json: if rv.status_code != 200: raise RuntimeError( 'Dataset creation failed with %s' % rv.status_code) return json.loads(rv.data)['id'] # expect a redirect if not 300 <= rv.status_code <= 310: s = BeautifulSoup(rv.data, 'html.parser') div = s.select('div.alert-danger') if div: print div[0] else: print rv.data raise RuntimeError( 'Failed to create dataset - status %s' % rv.status_code) job_id = cls.job_id_from_response(rv) assert cls.dataset_exists(job_id), 'dataset not found after successful creation' cls.created_datasets.append(job_id) return job_id @classmethod def get_dataset_json(cls): rv = cls.app.get('/datasets/%s/json' % cls.dataset_id) assert rv.status_code == 200, 'page load failed with %s' % rv.status_code return json.loads(rv.data) @classmethod def get_entry_count(cls, stage): json_data = cls.get_dataset_json() for t in json_data['create_db_tasks']: if t['stage'] == stage: return t['entry_count'] return None @classmethod def get_feature_dims(cls): json_data = cls.get_dataset_json() return json_data['feature_dims'] @classmethod def create_random_imageset(cls, **kwargs): """ Create a folder of random grayscale images """ num_images = kwargs.pop('num_images', 10) image_width = kwargs.pop('image_width', 32) image_height = kwargs.pop('image_height', 32) if not hasattr(cls, 'imageset_folder'): # create a temporary folder cls.imageset_folder = tempfile.mkdtemp() for i in xrange(num_images): x = np.random.randint( low=0, high=256, size=(image_height, image_width)) x = x.astype('uint8') pil_img = PIL.Image.fromarray(x) filename = os.path.join( cls.imageset_folder, '%d.png' % i) pil_img.save(filename) if not hasattr(cls, 'test_image'): cls.test_image = filename @classmethod def create_variable_size_random_imageset(cls, **kwargs): """ Create a folder of random grayscale images Image size varies randomly """ num_images = kwargs.pop('num_images', 10) if not hasattr(cls, 'imageset_folder'): # create a temporary folder cls.imageset_folder = tempfile.mkdtemp() for i in xrange(num_images): image_width = np.random.randint(low=8, high=32) image_height = np.random.randint(low=8, high=32) x = np.random.randint( low=0, high=256, size=(image_height, image_width)) x = x.astype('uint8') pil_img = PIL.Image.fromarray(x) filename = os.path.join( cls.imageset_folder, '%d.png' % i) pil_img.save(filename) if not hasattr(cls, 'test_image'): cls.test_image = filename @classmethod def setUpClass(cls, **kwargs): if extensions.data.get_extension(cls.EXTENSION_ID) is None: raise unittest.SkipTest('Extension "%s" is not installed' % cls.EXTENSION_ID) super(BaseViewsTestWithDataset, cls).setUpClass() cls.dataset_id = cls.create_dataset(json=True, **kwargs) assert cls.dataset_wait_completion(cls.dataset_id) == 'Done', 'create failed' # Save val DB path json = cls.get_dataset_json() for t in json['create_db_tasks']: if t['stage'] == constants.VAL_DB: if t['feature_db_path'] is not None: cls.val_db_path = os.path.join( json['directory'], t['feature_db_path']) else: cls.val_db_path = None class GenericViewsTest(BaseViewsTest): @classmethod def setUpClass(cls, **kwargs): if extensions.data.get_extension(cls.EXTENSION_ID) is None: raise unittest.SkipTest('Extension "%s" is not installed' % cls.EXTENSION_ID) super(GenericViewsTest, cls).setUpClass() def test_page_dataset_new(self): rv = self.app.get('/datasets/generic/new/%s' % self.EXTENSION_ID) print rv.data assert rv.status_code == 200, 'page load failed with %s' % rv.status_code assert extensions.data.get_extension(self.EXTENSION_ID).get_title() in rv.data, 'unexpected page format' def test_nonexistent_dataset(self): assert not self.dataset_exists('foo'), "dataset shouldn't exist" class GenericCreationTest(BaseViewsTestWithDataset): """ Dataset creation tests """ def test_create_json(self): job_id = self.create_dataset(json=True) self.abort_dataset(job_id) def test_create_delete(self): job_id = self.create_dataset() assert self.delete_dataset(job_id) == 200, 'delete failed' assert not self.dataset_exists(job_id), 'dataset exists after delete' def test_create_abort_delete(self): job_id = self.create_dataset() assert self.abort_dataset(job_id) == 200, 'abort failed' assert self.delete_dataset(job_id) == 200, 'delete failed' assert not self.dataset_exists(job_id), 'dataset exists after delete' def test_create_wait_delete(self): job_id = self.create_dataset() assert self.dataset_wait_completion(job_id) == 'Done', 'create failed' assert self.delete_dataset(job_id) == 200, 'delete failed' assert not self.dataset_exists(job_id), 'dataset exists after delete' def test_invalid_number_of_reader_threads(self): try: self.create_dataset( json=True, dsopts_num_threads=0) assert False except RuntimeError: # job is expected to fail with a RuntimeError pass def test_no_force_same_shape(self): job_id = self.create_dataset(force_same_shape=0) assert self.dataset_wait_completion(job_id) == 'Done', 'create failed' def test_clone(self): options_1 = { 'resize_channels': '1', } job1_id = self.create_dataset(**options_1) assert self.dataset_wait_completion(job1_id) == 'Done', 'first job failed' rv = self.app.get('/datasets/%s/json' % job1_id) assert rv.status_code == 200, 'json load failed with %s' % rv.status_code content1 = json.loads(rv.data) # Clone job1 as job2 options_2 = { 'clone': job1_id, } job2_id = self.create_dataset(**options_2) assert self.dataset_wait_completion(job2_id) == 'Done', 'second job failed' rv = self.app.get('/datasets/%s/json' % job2_id) assert rv.status_code == 200, 'json load failed with %s' % rv.status_code content2 = json.loads(rv.data) # These will be different content1.pop('id') content2.pop('id') content1.pop('directory') content2.pop('directory') assert (content1 == content2), 'job content does not match' job1 = digits.webapp.scheduler.get_job(job1_id) job2 = digits.webapp.scheduler.get_job(job2_id) assert (job1.form_data == job2.form_data), 'form content does not match' class GenericCreatedTest(BaseViewsTestWithDataset): """ Tests on a dataset that has already been created """ def test_index_json(self): rv = self.app.get('/index/json') assert rv.status_code == 200, 'page load failed with %s' % rv.status_code content = json.loads(rv.data) found = False for d in content['datasets']: if d['id'] == self.dataset_id: found = True break assert found, 'dataset not found in list' def test_dataset_json(self): content = self.get_dataset_json() assert content['id'] == self.dataset_id, 'expected same job_id: %s != %s' % (content['id'], self.dataset_id) def test_edit_name(self): status = self.edit_job( self.dataset_id, name='new name' ) assert status == 200, 'failed with %s' % status rv = self.app.get('/datasets/summary?job_id=%s' % self.dataset_id) assert rv.status_code == 200 assert 'new name' in rv.data def test_edit_notes(self): status = self.edit_job( self.dataset_id, notes='new notes' ) assert status == 200, 'failed with %s' % status def test_explore_features(self): # features DB is encoded by default rv = self.app.get('/datasets/generic/explore?db=train_db%%2Ffeatures&job_id=%s' % self.dataset_id) # just make sure this doesn't return an error assert rv.status_code == 200, 'page load failed with %s' % rv.status_code def test_feature_dims(self): dims = self.get_feature_dims() assert dims == [self.IMAGE_HEIGHT, self.IMAGE_WIDTH, self.CHANNELS] ################################################################################ # Test classes ################################################################################ class TestImageGradientViews(GenericViewsTest, test_utils.DatasetMixin): """ Tests which don't require an imageset or a dataset """ EXTENSION_ID = "image-gradients" class TestImageGradientCreation(GenericCreationTest, test_utils.DatasetMixin): """ Test that create datasets """ EXTENSION_ID = "image-gradients" @classmethod def setUpClass(cls, **kwargs): super(TestImageGradientCreation, cls).setUpClass( train_image_count=100, val_image_count=20, test_image_count=10, image_width=cls.IMAGE_WIDTH, image_height=cls.IMAGE_HEIGHT, ) def test_entry_counts(self): assert self.get_entry_count(constants.TRAIN_DB) == 100 assert self.get_entry_count(constants.VAL_DB) == 20 assert self.get_entry_count(constants.TEST_DB) == 10 class TestImageGradientCreated(GenericCreatedTest, test_utils.DatasetMixin): """ Test that create datasets """ EXTENSION_ID = "image-gradients" IMAGE_WIDTH = 8 IMAGE_HEIGHT = 24 @classmethod def setUpClass(cls, **kwargs): super(TestImageGradientCreated, cls).setUpClass( image_width=cls.IMAGE_WIDTH, image_height=cls.IMAGE_HEIGHT) class TestImageProcessingCreated(GenericCreatedTest, test_utils.DatasetMixin): """ Test Image processing extension """ EXTENSION_ID = "image-processing" NUM_IMAGES = 100 FOLDER_PCT_VAL = 10 @classmethod def setUpClass(cls, **kwargs): cls.create_random_imageset( num_images=cls.NUM_IMAGES, image_width=cls.IMAGE_WIDTH, image_height=cls.IMAGE_HEIGHT) super(TestImageProcessingCreated, cls).setUpClass( feature_folder=cls.imageset_folder, label_folder=cls.imageset_folder, folder_pct_val=cls.FOLDER_PCT_VAL, channel_conversion='L') def test_entry_counts(self): assert self.get_entry_count(constants.TRAIN_DB) == self.NUM_IMAGES * (1. - self.FOLDER_PCT_VAL / 100.) assert self.get_entry_count(constants.VAL_DB) == self.NUM_IMAGES * (self.FOLDER_PCT_VAL / 100.) class TestImageProcessingCreatedWithSeparateValidationDirs(GenericCreatedTest, test_utils.DatasetMixin): """ Test Image processing extension, using separate fields for the train and validation folders Use RGB channel conversion for this test """ EXTENSION_ID = "image-processing" NUM_IMAGES = 100 CHANNELS = 3 IMAGE_HEIGHT = 16 IMAGE_WIDTH = 64 @classmethod def setUpClass(cls, **kwargs): cls.create_random_imageset( num_images=cls.NUM_IMAGES, image_width=cls.IMAGE_WIDTH, image_height=cls.IMAGE_HEIGHT) super(TestImageProcessingCreatedWithSeparateValidationDirs, cls).setUpClass( feature_folder=cls.imageset_folder, label_folder=cls.imageset_folder, has_val_folder='y', validation_feature_folder=cls.imageset_folder, validation_label_folder=cls.imageset_folder, channel_conversion='RGB') def test_entry_counts(self): assert self.get_entry_count(constants.TRAIN_DB) == self.NUM_IMAGES assert self.get_entry_count(constants.VAL_DB) == self.NUM_IMAGES
DIGITS-master
digits/dataset/generic/test_views.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import wtforms from wtforms import validators from ..forms import DatasetForm from digits import utils class GenericDatasetForm(DatasetForm): """ Defines the form used to create a new GenericDatasetJob """ # Generic dataset options dsopts_feature_encoding = utils.forms.SelectField( 'Feature Encoding', default='png', choices=[('none', 'None'), ('png', 'PNG (lossless)'), ('jpg', 'JPEG (lossy, 90% quality)'), ], tooltip="Using either of these compression formats can save disk" " space, but can also require marginally more time for" " training." ) dsopts_label_encoding = utils.forms.SelectField( 'Label Encoding', default='none', choices=[ ('none', 'None'), ('png', 'PNG (lossless)'), ('jpg', 'JPEG (lossy, 90% quality)'), ], tooltip="Using either of these compression formats can save disk" " space, but can also require marginally more time for" " training." ) dsopts_batch_size = utils.forms.IntegerField( 'Encoder batch size', validators=[ validators.DataRequired(), validators.NumberRange(min=1), ], default=32, tooltip="Encode data in batches of specified number of entries" ) dsopts_num_threads = utils.forms.IntegerField( 'Number of encoder threads', validators=[ validators.DataRequired(), validators.NumberRange(min=1), ], default=4, tooltip="Use specified number of encoder threads" ) dsopts_backend = wtforms.SelectField( 'DB backend', choices=[ ('lmdb', 'LMDB'), ], default='lmdb', ) dsopts_force_same_shape = utils.forms.SelectField( 'Enforce same shape', choices=[ (1, 'Yes'), (0, 'No'), ], coerce=int, default=1, tooltip="Check that each entry in the database has the same shape." "Disabling this will also disable mean image computation." )
DIGITS-master
digits/dataset/generic/forms.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import os # Find the best implementation available try: from cStringIO import StringIO except ImportError: from StringIO import StringIO import caffe_pb2 import flask import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import PIL.Image from .forms import GenericDatasetForm from .job import GenericDatasetJob from digits import extensions, utils from digits.utils.constants import COLOR_PALETTE_ATTRIBUTE from digits.utils.routing import request_wants_json, job_from_request from digits.utils.lmdbreader import DbReader from digits.webapp import scheduler blueprint = flask.Blueprint(__name__, __name__) @blueprint.route('/new/<extension_id>', methods=['GET']) @utils.auth.requires_login def new(extension_id): """ Returns a form for a new GenericDatasetJob """ form = GenericDatasetForm() # Is there a request to clone a job with ?clone=<job_id> utils.forms.fill_form_if_cloned(form) extension = extensions.data.get_extension(extension_id) if extension is None: raise ValueError("Unknown extension '%s'" % extension_id) extension_form = extension.get_dataset_form() # Is there a request to clone a job with ?clone=<job_id> utils.forms.fill_form_if_cloned(extension_form) template, context = extension.get_dataset_template(extension_form) rendered_extension = flask.render_template_string(template, **context) return flask.render_template( 'datasets/generic/new.html', extension_title=extension.get_title(), extension_id=extension_id, extension_html=rendered_extension, form=form ) @blueprint.route('/create/<extension_id>/json', methods=['POST']) @blueprint.route('/create/<extension_id>', methods=['POST'], strict_slashes=False) @utils.auth.requires_login(redirect=False) def create(extension_id): """ Creates a new GenericDatasetJob Returns JSON when requested: {job_id,name,status} or {errors:[]} """ form = GenericDatasetForm() form_valid = form.validate_on_submit() extension_class = extensions.data.get_extension(extension_id) extension_form = extension_class.get_dataset_form() extension_form_valid = extension_form.validate_on_submit() if not (extension_form_valid and form_valid): # merge errors errors = form.errors.copy() errors.update(extension_form.errors) template, context = extension_class.get_dataset_template( extension_form) rendered_extension = flask.render_template_string( template, **context) if request_wants_json(): return flask.jsonify({'errors': errors}), 400 else: return flask.render_template( 'datasets/generic/new.html', extension_title=extension_class.get_title(), extension_id=extension_id, extension_html=rendered_extension, form=form, errors=errors), 400 # create instance of extension class extension = extension_class(**extension_form.data) job = None try: # create job job = GenericDatasetJob( username=utils.auth.get_username(), name=form.dataset_name.data, group=form.group_name.data, backend=form.dsopts_backend.data, feature_encoding=form.dsopts_feature_encoding.data, label_encoding=form.dsopts_label_encoding.data, batch_size=int(form.dsopts_batch_size.data), num_threads=int(form.dsopts_num_threads.data), force_same_shape=form.dsopts_force_same_shape.data, extension_id=extension_id, extension_userdata=extension.get_user_data(), ) # Save form data with the job so we can easily clone it later. utils.forms.save_form_to_job(job, form) utils.forms.save_form_to_job(job, extension_form) # schedule tasks scheduler.add_job(job) if request_wants_json(): return flask.jsonify(job.json_dict()) else: return flask.redirect(flask.url_for( 'digits.dataset.views.show', job_id=job.id())) except: if job: scheduler.delete_job(job) raise @blueprint.route('/explore', methods=['GET']) def explore(): """ Returns a gallery consisting of the images of one of the dbs """ job = job_from_request() # Get LMDB db = job.path(flask.request.args.get('db')) db_path = job.path(db) if (os.path.basename(db_path) == 'labels' and COLOR_PALETTE_ATTRIBUTE in job.extension_userdata and job.extension_userdata[COLOR_PALETTE_ATTRIBUTE]): # assume single-channel 8-bit palette palette = job.extension_userdata[COLOR_PALETTE_ATTRIBUTE] palette = np.array(palette).reshape((len(palette) / 3, 3)) / 255. # normalize input pixels to [0,1] norm = mpl.colors.Normalize(vmin=0, vmax=255) # create map cmap = plt.cm.ScalarMappable(norm=norm, cmap=mpl.colors.ListedColormap(palette)) else: cmap = None page = int(flask.request.args.get('page', 0)) size = int(flask.request.args.get('size', 25)) reader = DbReader(db_path) count = 0 imgs = [] min_page = max(0, page - 5) total_entries = reader.total_entries max_page = min((total_entries - 1) / size, page + 5) pages = range(min_page, max_page + 1) for key, value in reader.entries(): if count >= page * size: datum = caffe_pb2.Datum() datum.ParseFromString(value) if not datum.encoded: raise RuntimeError("Expected encoded database") s = StringIO() s.write(datum.data) s.seek(0) img = PIL.Image.open(s) if cmap and img.mode in ['L', '1']: data = np.array(img) data = cmap.to_rgba(data) * 255 data = data.astype('uint8') # keep RGB values only, remove alpha channel data = data[:, :, 0:3] img = PIL.Image.fromarray(data) imgs.append({"label": None, "b64": utils.image.embed_image_html(img)}) count += 1 if len(imgs) >= size: break return flask.render_template( 'datasets/images/explore.html', page=page, size=size, job=job, imgs=imgs, labels=None, pages=pages, label=None, total_entries=total_entries, db=db) def show(job, related_jobs=None): """ Called from digits.dataset.views.show() """ return flask.render_template('datasets/generic/show.html', job=job, related_jobs=related_jobs) def summary(job): """ Return a short HTML summary of a GenericDatasetJob """ return flask.render_template('datasets/generic/summary.html', dataset=job)
DIGITS-master
digits/dataset/generic/views.py
# Copyright (c) 2015-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import flask import functools import re import werkzeug.exceptions from .routing import get_request_arg, request_wants_json def get_username(): return get_request_arg('username') or \ flask.request.cookies.get('username', None) def validate_username(username): """ Raises a ValueError if the username is invalid """ if not username: raise ValueError('username is required') if not re.match('[a-z]', username): raise ValueError('Must start with a lowercase letter') if not re.match('[a-z0-9\.\-_]+$', username): raise ValueError('Only lowercase letters, numbers, periods, dashes and underscores allowed') def requires_login(f=None, redirect=True): """ Decorator for views that require the user to be logged in Keyword arguments: f -- the function to decorate redirect -- if True, this function may return a redirect """ if f is None: # optional arguments are handled strangely return functools.partial(requires_login, redirect=redirect) @functools.wraps(f) def decorated(*args, **kwargs): username = get_username() if not username: # Handle missing username if request_wants_json() or not redirect: raise werkzeug.exceptions.Unauthorized() else: return flask.redirect(flask.url_for('digits.views.login', next=flask.request.path)) try: # Validate username validate_username(username) except ValueError as e: raise werkzeug.exceptions.BadRequest('Invalid username - %s' % e.message) return f(*args, **kwargs) return decorated def has_permission(job, action, username=None): """ Returns True if username can perform action on job Arguments: job -- the Job in question action -- the action in question Keyword arguments: username -- the user in question (defaults to current user) """ if job.is_read_only(): return False if username is None: username = get_username() if not username: return False if not job.username: return True return username == job.username
DIGITS-master
digits/utils/auth.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import from HTMLParser import HTMLParser import time class StoreCache(): def __init__(self, ttl=86400): self.expiration_time = time.time() + ttl self.ttl = ttl self.cache = None def reset(self): self.expiration_time = time.time() + self.ttl self.cache = None def read(self): if self.expiration_time < time.time(): self.reset() return self.cache def write(self, data): self.expiration_time = time.time() + self.ttl self.cache = data class StoreParser(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.starting = False self.dirs = list() self.reset() def read(self, data): self.reset() self.clean() self.feed(data) def clean(self): pass def handle_starttag(self, tag, attrs): if tag == 'td' or tag == 'a': self.starting = True def handle_endtag(self, tag): if tag == 'td' or tag == 'a': self.starting = False def handle_data(self, data): if self.starting and data[-1] == '/': self.dirs.append(data) def get_child_dirs(self): return self.dirs
DIGITS-master
digits/utils/store.py
# Copyright (c) 2015-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import unittest from . import parse_version from digits import test_utils test_utils.skipIfNotFramework('none') class TestParseVersion(): def test_equality(self): for v1, v2 in [ ('11', '11'), ('11', 11), ('11', ('11',)), ('11', (11,)), ('11', '11.0'), ('11', '11.0.0'), ]: yield self.check_equal, v1, v2 def check_equal(self, v1, v2): assert parse_version(v1) == parse_version(v2) def test_lt(self): # Each list should be in strictly increasing order example_lists = [] # Some DIGITS versions example_lists.append( 'v1.0 v1.0.1 v1.0.2 v1.0.3 v1.1.0-rc1 v1.1.0-rc2 v1.1.0 v1.1.1 ' 'v1.1.2 v1.1.3 v2.0.0-rc v2.0.0-rc2 v2.0.0-rc3 v2.0.0-preview ' 'v2.0.0 v2.1.0 v2.2.0 v2.2.1'.split() ) # Some NVcaffe versions example_lists.append('v0.13.0 v0.13.1 v0.13.2 v0.14.0-alpha ' 'v0.14.0-beta v0.14.0-rc.1 v0.14.0-rc.2'.split()) # Semver.org examples example_lists.append( '1.0.0-alpha 1.0.0-alpha.1 1.0.0-alpha.beta 1.0.0-beta ' '1.0.0-beta.2 1.0.0-beta.11 1.0.0-rc.1 1.0.0'.split() ) # PEP 440 examples example_lists.append('0.1 0.2 0.3 1.0 1.1'.split()) example_lists.append('1.1.0 1.1.1 1.1.2 1.2.0'.split()) example_lists.append('0.9 1.0a1 1.0a2 1.0b1 1.0rc1 1.0 1.1a1'.split()) example_lists.append('0.9 1.0.dev1 1.0.dev2 1.0.dev3 1.0.dev4 1.0c1 1.0c2 1.0 1.0.post1 1.1.dev1'.split()) example_lists.append('2012.1 2012.2 2012.3 2012.15 2013.1 2013.2'.split()) for l in example_lists: for v1, v2 in zip(l[:-1], l[1:]): yield self.check_lt, v1, v2 def check_lt(self, v1, v2): bad = ( # pkg_resources handles this one differently '1.0.0-alpha.beta', # poor decision 'v2.0.0-preview') if v1 in bad or v2 in bad: raise unittest.case.SkipTest assert parse_version(v1) < parse_version(v2)
DIGITS-master
digits/utils/test_utils.py
# Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import hashlib import os.path import platform import re import shutil def get_tree_size(start_path): """ return size (in bytes) of filesystem tree """ if not os.path.exists(start_path): raise ValueError("Incorrect path: %s" % start_path) total_size = 0 for dirpath, dirnames, filenames in os.walk(start_path): for f in filenames: fp = os.path.join(dirpath, f) total_size += os.path.getsize(fp) return total_size def get_python_file_dst(dirname, basename): basename = os.path.basename(basename) (root, ext) = os.path.splitext(basename) if ext != '.py' and ext != '.pyc': ValueError('Python file, %s, needs .py or .pyc extension.' % basename) filename = os.path.join(dirname, 'digits_python_layers' + ext) if os.path.isfile(filename): ValueError('Python file, %s, already exists.' % filename) return filename def copy_python_layer_file(from_client, job_dir, client_file, server_file): if from_client and client_file: filename = get_python_file_dst(job_dir, client_file.filename) client_file.save(filename) elif server_file and len(server_file) > 0: filename = get_python_file_dst(job_dir, server_file) shutil.copy(server_file, filename) def tail(file, n=40): """ Returns last n lines of text file (or all lines if the file has fewer lines) Arguments: file -- full path of that file, calling side must ensure its existence n -- the number of tailing lines to return """ if platform.system() in ['Linux', 'Darwin']: import subprocess output = subprocess.check_output(['tail', '-n{}'.format(n), file]) else: from collections import deque tailing_lines = deque() with open(file) as f: for line in f: tailing_lines.append(line) if len(tailing_lines) > n: tailing_lines.popleft() output = ''.join(tailing_lines) return output def dir_hash(dir_name): """ Return a hash for the files in a directory tree, excluding hidden files and directoies. If any files are renamed, added, removed, or modified the hash will change. """ if not os.path.isdir(dir_name): raise TypeError('{} is not a directory.'.format(dir_name)) md5 = hashlib.md5() for root, dirs, files in os.walk(dir_name, topdown=True): # Skip if the root has a hidden directory in its path if not re.search(r'/\.', root): for f in files: # Skip if the file is hidden if not f.startswith('.') and not re.search(r'/\.', f): # Change the hash if the file name changes file_name = os.path.join(root, f) md5.update(hashlib.md5(file_name).hexdigest()) # Change the hash if the file content changes data = open(file_name, 'rb').read() md5.update(hashlib.md5(data).hexdigest()) return md5.hexdigest()
DIGITS-master
digits/utils/filesystem.py
# Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved. # Datasets TRAIN_FILE = 'train.txt' TRAIN_DB = 'train_db' VAL_FILE = 'val.txt' VAL_DB = 'val_db' TEST_FILE = 'test.txt' TEST_DB = 'test_db' MEAN_FILE_IMAGE = 'mean.jpg' # Classification jobs LABELS_FILE = 'labels.txt' DEFAULT_BATCH_SIZE = 16 # Caffe Protocol Buffers MEAN_FILE_CAFFE = 'mean.binaryproto' # Color Palette attribute COLOR_PALETTE_ATTRIBUTE = 'color_palette'
DIGITS-master
digits/utils/constants.py
# Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import os import tempfile # Find the best implementation available try: from cStringIO import StringIO except ImportError: from StringIO import StringIO import mock from nose.tools import assert_raises import numpy as np import PIL.Image from . import errors from . import image as image_utils import digits from digits import test_utils test_utils.skipIfNotFramework('none') class TestLoadImage(): def test_bad_path(self): for path in [ 'some string', '/tmp/not-a-file', 'http://not-a-url', ]: yield self.check_none, path def check_none(self, path): assert_raises( errors.LoadImageError, image_utils.load_image, path, ) def test_good_file(self): for args in [ # created mode, file extension, pixel value, loaded mode (expected) # Grayscale ('1', 'png', 1, 'L'), ('1', 'ppm', 1, 'L'), ('L', 'png', 127, 'L'), ('L', 'jpg', 127, 'L'), ('L', 'ppm', 127, 'L'), ('LA', 'png', (127, 255), 'L'), # Color ('RGB', 'png', (127, 127, 127), 'RGB'), ('RGB', 'jpg', (127, 127, 127), 'RGB'), ('RGB', 'ppm', (127, 127, 127), 'RGB'), ('RGBA', 'png', (127, 127, 127, 255), 'RGB'), ('P', 'png', 127, 'RGB'), ('CMYK', 'jpg', (127, 127, 127, 127), 'RGB'), ('YCbCr', 'jpg', (127, 127, 127), 'RGB'), ]: yield self.check_good_file, args def check_good_file(self, args): orig_mode, suffix, pixel, new_mode = args orig = PIL.Image.new(orig_mode, (10, 10), pixel) # temp files cause permission errors so just generate the name tmp = tempfile.mkstemp(suffix='.' + suffix) orig.save(tmp[1]) new = image_utils.load_image(tmp[1]) try: # sometimes on windows the file is not closed yet # which can cause an exception os.close(tmp[0]) os.remove(tmp[1]) except: pass assert new is not None, 'load_image should never return None' assert new.mode == new_mode, 'Image mode should be "%s", not "%s\nargs - %s' % (new_mode, new.mode, args) @mock.patch('digits.utils.image.requests') def test_good_url(self, mock_requests): # requests response = mock.Mock() response.status_code = mock_requests.codes.ok img_file = os.path.join( os.path.dirname(digits.__file__), 'static', 'images', 'mona_lisa.jpg', ) with open(img_file, 'rb') as infile: response.content = infile.read() mock_requests.get.return_value = response img = image_utils.load_image('http://some-url') assert img is not None def test_corrupted_file(self): image = PIL.Image.fromarray(np.zeros((10, 10, 3), dtype=np.uint8)) # Save image to a JPEG buffer. buffer_io = StringIO() image.save(buffer_io, format='jpeg') encoded = buffer_io.getvalue() buffer_io.close() # Corrupt the second half of the image buffer. size = len(encoded) corrupted = encoded[:size / 2] + encoded[size / 2:][::-1] # Save the corrupted image to a temporary file. fname = tempfile.mkstemp(suffix='.bin') f = os.fdopen(fname[0], 'wb') fname = fname[1] f.write(corrupted) f.close() assert_raises( errors.LoadImageError, image_utils.load_image, fname, ) os.remove(fname) class TestResizeImage(): @classmethod def setup_class(cls): cls.np_gray = np.random.randint(0, 255, (10, 10)).astype('uint8') cls.pil_gray = PIL.Image.fromarray(cls.np_gray) cls.np_color = np.random.randint(0, 255, (10, 10, 3)).astype('uint8') cls.pil_color = PIL.Image.fromarray(cls.np_color) def test_configs(self): # lots of configs tested here for h in [10, 15]: for w in [10, 16]: for t in ['gray', 'color']: # test channels=None (should autodetect channels) if t == 'color': s = (h, w, 3) else: s = (h, w) yield self.verify_pil, (h, w, None, None, t, s) yield self.verify_np, (h, w, None, None, t, s) # test channels={3,1} for c in [3, 1]: for m in ['squash', 'crop', 'fill', 'half_crop']: if c == 3: s = (h, w, 3) else: s = (h, w) yield self.verify_pil, (h, w, c, m, t, s) yield self.verify_np, (h, w, c, m, t, s) def verify_pil(self, args): # pass a PIL.Image to resize_image and check the returned dimensions h, w, c, m, t, s = args if t == 'gray': i = self.pil_gray else: i = self.pil_color r = image_utils.resize_image(i, h, w, c, m) assert r.shape == s, 'Resized PIL.Image (orig=%s) should have been %s, but was %s %s' % ( i.size, s, r.shape, self.args_to_str(args)) assert r.dtype == np.uint8, 'image.dtype should be uint8, not %s' % r.dtype def verify_np(self, args): # pass a numpy.ndarray to resize_image and check the returned dimensions h, w, c, m, t, s = args if t == 'gray': i = self.np_gray else: i = self.np_color r = image_utils.resize_image(i, h, w, c, m) assert r.shape == s, 'Resized np.ndarray (orig=%s) should have been %s, but was %s %s' % ( i.shape, s, r.shape, self.args_to_str(args)) assert r.dtype == np.uint8, 'image.dtype should be uint8, not %s' % r.dtype def args_to_str(self, args): return """ height=%s width=%s channels=%s resize_mode=%s image_type=%s shape=%s""" % args
DIGITS-master
digits/utils/test_image.py
# Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import time def print_time(t, ref_time=None): lt = time.localtime(t) # ref_time is for testing if ref_time is None: now = time.localtime() else: now = time.localtime(ref_time) if lt.tm_year != now.tm_year: return time.strftime('%b %d %Y, %I:%M:%S %p', lt).decode('utf-8') elif lt.tm_mon != now.tm_mon: return time.strftime('%b %d, %I:%M:%S %p', lt).decode('utf-8') elif lt.tm_mday != now.tm_mday: return time.strftime('%a %b %d, %I:%M:%S %p', lt).decode('utf-8') else: return time.strftime('%I:%M:%S %p', lt).decode('utf-8') def print_time_diff(diff): if diff is None: return '?' if diff < 0: return 'Negative Time' total_seconds = int(diff) days = total_seconds // (24 * 3600) hours = (total_seconds % (24 * 3600)) // 3600 minutes = (total_seconds % 3600) // 60 seconds = total_seconds % 60 def plural(number, name): return '%d %s%s' % (number, name, '' if number == 1 else 's') def pair(number1, name1, number2, name2): if number2 > 0: return '%s, %s' % (plural(number1, name1), plural(number2, name2)) else: return '%s' % plural(number1, name1) if days >= 1: return pair(days, 'day', hours, 'hour') elif hours >= 1: return pair(hours, 'hour', minutes, 'minute') elif minutes >= 1: return pair(minutes, 'minute', seconds, 'second') return plural(seconds, 'second') def print_time_diff_nosuffixes(diff): if diff is None: return '?' hours, rem = divmod(diff, 3600) minutes, seconds = divmod(rem, 60) return '{:02d}:{:02d}:{:02d}'.format(int(hours), int(minutes), int(seconds)) def print_time_since(t): return print_time_diff(time.time() - t)
DIGITS-master
digits/utils/time_filters.py
# Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import inspect from io import BlockingIOError import locale import math import os import pkg_resources import platform from random import uniform from urlparse import urlparse if not platform.system() == 'Windows': import fcntl else: import gevent.os HTTP_TIMEOUT = 6.05 def is_url(url): return url is not None and urlparse(url).scheme != "" and not os.path.exists(url) def wait_time(): """Wait a random number of seconds""" return uniform(0.3, 0.5) # From http://code.activestate.com/recipes/578900-non-blocking-readlines/ def nonblocking_readlines(f): """Generator which yields lines from F (a file object, used only for its fileno()) without blocking. If there is no data, you get an endless stream of empty strings until there is data again (caller is expected to sleep for a while). Newlines are normalized to the Unix standard. """ fd = f.fileno() if not platform.system() == 'Windows': fl = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK) enc = locale.getpreferredencoding(False) buf = bytearray() while True: try: if not platform.system() == 'Windows': block = os.read(fd, 8192) else: block = gevent.os.tp_read(fd, 8192) except (BlockingIOError, OSError): yield "" continue if not block: if buf: yield buf.decode(enc) break buf.extend(block) while True: r = buf.find(b'\r') n = buf.find(b'\n') if r == -1 and n == -1: break if r == -1 or r > n: yield buf[:(n + 1)].decode(enc) buf = buf[(n + 1):] elif n == -1 or n > r: yield buf[:r].decode(enc) + '\n' if n == r + 1: buf = buf[(r + 2):] else: buf = buf[(r + 1):] def subclass(cls): """ Verify all @override methods Use a class decorator to find the method's class """ for name, method in cls.__dict__.iteritems(): if hasattr(method, 'override'): found = False for base_class in inspect.getmro(cls)[1:]: if name in base_class.__dict__: if not method.__doc__: # copy docstring method.__doc__ = base_class.__dict__[name].__doc__ found = True break assert found, '"%s.%s" not found in any base class' % (cls.__name__, name) return cls def override(method): """ Decorator implementing method overriding in python Must also use the @subclass class decorator """ method.override = True return method def sizeof_fmt(size, suffix='B'): """ Return a human-readable string representation of a filesize Arguments: size -- size in bytes """ try: size = int(size) except ValueError: return None if size <= 0: return '0 %s' % suffix size_name = ('', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') i = int(math.floor(math.log(size, 1024))) if i >= len(size_name): i = len(size_name) - 1 p = math.pow(1024, i) s = size / p # round to 3 significant digits s = round(s, 2 - int(math.floor(math.log10(s)))) if s.is_integer(): s = int(s) if s > 0: return '%s %s%s' % (s, size_name[i], suffix) else: return '0 %s' % suffix def parse_version(*args): """ Returns a sortable version Arguments: args -- a string, tuple, or list of arguments to be joined with "."'s """ v = None if len(args) == 1: a = args[0] if isinstance(a, tuple): v = '.'.join(str(x) for x in a) else: v = str(a) else: v = '.'.join(str(a) for a in args) if v.startswith('v'): v = v[1:] try: return pkg_resources.SetuptoolsVersion(v) except AttributeError: return pkg_resources.parse_version(v) # Import the other utility functions from . import constants, image, time_filters, errors, forms, routing, auth # noqa
DIGITS-master
digits/utils/__init__.py
# Copyright (c) 2015-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import from werkzeug.datastructures import FileStorage import wtforms from wtforms import SubmitField from wtforms import validators from wtforms.compat import string_types from digits.utils.routing import get_request_arg def validate_required_iff(**kwargs): """ Used as a validator within a wtforms.Form This implements a conditional DataRequired Each of the kwargs is a condition that must be met in the form Otherwise, no validation is done """ def _validator(form, field): all_conditions_met = True for key, value in kwargs.iteritems(): if getattr(form, key).data != value: all_conditions_met = False if all_conditions_met: # Verify that data exists if field.data is None \ or (isinstance(field.data, (str, unicode)) and not field.data.strip()) \ or (isinstance(field.data, FileStorage) and not field.data.filename.strip()): raise validators.ValidationError('This field is required.') else: # This field is not required, ignore other errors field.errors[:] = [] raise validators.StopValidation() return _validator def validate_required_if_set(other_field, **kwargs): """ Used as a validator within a wtforms.Form This implements a conditional DataRequired `other_field` is a field name; if set, the other field makes it mandatory to set the field being tested """ def _validator(form, field): other_field_value = getattr(form, other_field).data if other_field_value: # Verify that data exists if field.data is None or \ (isinstance(field.data, (str, unicode)) and not field.data.strip()) \ or (isinstance(field.data, FileStorage) and not field.data.filename.strip()): raise validators.ValidationError('This field is required if %s is set.' % other_field) else: # This field is not required, ignore other errors field.errors[:] = [] raise validators.StopValidation() return _validator def validate_greater_than(fieldname): """ Compares the value of two fields the value of self is to be greater than the supplied field. :param fieldname: The name of the other field to compare to. """ def _validator(form, field): try: other = form[fieldname] except KeyError: raise validators.ValidationError(field.gettext(u"Invalid field name '%s'.") % fieldname) if field.data != '' and field.data < other.data: message = field.gettext(u'Field must be greater than %s.' % fieldname) raise validators.ValidationError(message) return _validator class Tooltip(object): """ An HTML form tooltip. """ def __init__(self, field_id, for_name, text): self.field_id = field_id self.text = text self.for_name = for_name def __str__(self): return self() def __unicode__(self): return self() def __html__(self): return self() def __call__(self, text=None, **kwargs): if 'for_' in kwargs: kwargs['for'] = kwargs.pop('for_') else: kwargs.setdefault('for', self.field_id) return wtforms.widgets.HTMLString( ('<span name="%s_explanation"' ' class="explanation-tooltip glyphicon glyphicon-question-sign"' ' data-container="body"' ' title="%s"' ' ></span>') % (self.for_name, self.text)) def __repr__(self): return 'Tooltip(%r, %r, %r)' % (self.field_id, self.for_name, self.text) class Explanation(object): """ An HTML form explanation. """ def __init__(self, field_id, for_name, filename): self.field_id = field_id self.file = filename self.for_name = for_name def __str__(self): return self() def __unicode__(self): return self() def __html__(self): return self() def __call__(self, file=None, **kwargs): if 'for_' in kwargs: kwargs['for'] = kwargs.pop('for_') else: kwargs.setdefault('for', self.field_id) import flask from digits.webapp import app html = '' # get the text from the html file with app.app_context(): html = flask.render_template(file if file else self.file) if len(html) == 0: return '' return wtforms.widgets.HTMLString( ('<div id="%s_explanation" style="display:none;">\n' '%s' '</div>\n' '<a href=# onClick="bootbox.alert($(\'#%s_explanation\').html()); ' 'return false;"><span class="glyphicon glyphicon-question-sign"></span></a>\n' ) % (self.for_name, html, self.for_name)) def __repr__(self): return 'Explanation(%r, %r, %r)' % (self.field_id, self.for_name, self.file) class IntegerField(wtforms.IntegerField): def __init__(self, label='', validators=None, tooltip='', explanation_file='', **kwargs): super(IntegerField, self).__init__(label, validators, **kwargs) self.tooltip = Tooltip(self.id, self.short_name, tooltip) self.explanation = Explanation(self.id, self.short_name, explanation_file) class FloatField(wtforms.FloatField): def __init__(self, label='', validators=None, tooltip='', explanation_file='', **kwargs): super(FloatField, self).__init__(label, validators, **kwargs) self.tooltip = Tooltip(self.id, self.short_name, tooltip) self.explanation = Explanation(self.id, self.short_name, explanation_file) class SelectField(wtforms.SelectField): def __init__(self, label='', validators=None, tooltip='', explanation_file='', **kwargs): super(SelectField, self).__init__(label, validators, **kwargs) self.tooltip = Tooltip(self.id, self.short_name, tooltip) self.explanation = Explanation(self.id, self.short_name, explanation_file) class SelectMultipleField(wtforms.SelectMultipleField): def __init__(self, label='', validators=None, tooltip='', explanation_file='', **kwargs): super(SelectMultipleField, self).__init__(label, validators, **kwargs) self.tooltip = Tooltip(self.id, self.short_name, tooltip) self.explanation = Explanation(self.id, self.short_name, explanation_file) class TextField(wtforms.TextField): def __init__(self, label='', validators=None, tooltip='', explanation_file='', **kwargs): super(TextField, self).__init__(label, validators, **kwargs) self.tooltip = Tooltip(self.id, self.short_name, tooltip) self.explanation = Explanation(self.id, self.short_name, explanation_file) class StringField(wtforms.StringField): def __init__(self, label='', validators=None, tooltip='', explanation_file='', **kwargs): super(StringField, self).__init__(label, validators, **kwargs) self.tooltip = Tooltip(self.id, self.short_name, tooltip) self.explanation = Explanation(self.id, self.short_name, explanation_file) class FileInput(object): """ Renders a file input chooser field. """ def __call__(self, field, **kwargs): kwargs.setdefault('id', field.id) return wtforms.widgets.HTMLString( ('<div class="input-group">' + ' <span class="input-group-btn">' + ' <span class="btn btn-info btn-file" %s>' + ' Browse&hellip;' + ' <input %s>' + ' </span>' + ' </span>' + ' <input class="form-control" %s readonly>' + '</div>') % (wtforms.widgets.html_params(id=field.name + '_btn', name=field.name + '_btn'), wtforms.widgets.html_params(name=field.name, type='file', **kwargs), wtforms.widgets.html_params(id=field.id + '_text', name=field.name + '_text', type='text'))) class FileField(wtforms.FileField): # Comment out the following line to use the native file input widget = FileInput() def __init__(self, label='', validators=None, tooltip='', explanation_file='', **kwargs): super(FileField, self).__init__(label, validators, **kwargs) self.tooltip = Tooltip(self.id, self.short_name, tooltip) self.explanation = Explanation(self.id, self.short_name, explanation_file) class TextAreaField(wtforms.TextAreaField): def __init__(self, label='', validators=None, tooltip='', explanation_file='', **kwargs): super(TextAreaField, self).__init__(label, validators, **kwargs) self.tooltip = Tooltip(self.id, self.short_name, tooltip) self.explanation = Explanation(self.id, self.short_name, explanation_file) class BooleanField(wtforms.BooleanField): def __init__(self, label='', validators=None, tooltip='', explanation_file='', **kwargs): super(BooleanField, self).__init__(label, validators, **kwargs) self.tooltip = Tooltip(self.id, self.short_name, tooltip) self.explanation = Explanation(self.id, self.short_name, explanation_file) class MultiIntegerField(wtforms.Field): """ A text field, except all input is coerced to one of more integers. Erroneous input is ignored and will not be accepted as a value. """ widget = wtforms.widgets.TextInput() def is_int(self, v): try: v = int(v) return True except: return False def __init__(self, label='', validators=None, tooltip='', explanation_file='', **kwargs): super(MultiIntegerField, self).__init__(label, validators, **kwargs) self.tooltip = Tooltip(self.id, self.short_name, tooltip + ' (accepts comma separated list)') self.explanation = Explanation(self.id, self.short_name, explanation_file) self.small_text = 'multiples allowed' def __setattr__(self, name, value): if name == 'data': if not isinstance(value, (list, tuple)): value = [value] value = [int(x) for x in value if self.is_int(x)] if len(value) == 0: value = [None] self.__dict__[name] = value def _value(self): if self.raw_data: return ','.join([str(x) for x in self.raw_data[0] if self.is_int(x)]) return ','.join([str(x) for x in self.data if self.is_int(x)]) def process_formdata(self, valuelist): if valuelist: try: valuelist[0] = valuelist[0].replace('[', '') valuelist[0] = valuelist[0].replace(']', '') valuelist[0] = valuelist[0].split(',') self.data = [int(float(datum)) for datum in valuelist[0]] except ValueError: self.data = [None] raise ValueError(self.gettext('Not a valid integer value')) class MultiFloatField(wtforms.Field): """ A text field, except all input is coerced to one of more floats. Erroneous input is ignored and will not be accepted as a value. """ widget = wtforms.widgets.TextInput() def is_float(self, v): try: v = float(v) return True except: return False def __init__(self, label='', validators=None, tooltip='', explanation_file='', **kwargs): super(MultiFloatField, self).__init__(label, validators, **kwargs) self.tooltip = Tooltip(self.id, self.short_name, tooltip + ' (accepts comma separated list)') self.explanation = Explanation(self.id, self.short_name, explanation_file) self.small_text = 'multiples allowed' def __setattr__(self, name, value): if name == 'data': if not isinstance(value, (list, tuple)): value = [value] value = [float(x) for x in value if self.is_float(x)] if len(value) == 0: value = [None] self.__dict__[name] = value def _value(self): if self.raw_data: return ','.join([str(x) for x in self.raw_data[0] if self.is_float(x)]) return ','.join([str(x) for x in self.data if self.is_float(x)]) def process_formdata(self, valuelist): if valuelist: try: valuelist[0] = valuelist[0].replace('[', '') valuelist[0] = valuelist[0].replace(']', '') valuelist[0] = valuelist[0].split(',') self.data = [float(datum) for datum in valuelist[0]] except ValueError: self.data = [None] raise ValueError(self.gettext('Not a valid float value')) def data_array(self): if isinstance(self.data, (list, tuple)): return self.data else: return [self.data] class MultiNumberRange(object): """ Validates that a number is of a minimum and/or maximum value, inclusive. This will work with any comparable number type, such as floats and decimals, not just integers. :param min: The minimum required value of the number. If not provided, minimum value will not be checked. :param max: The maximum value of the number. If not provided, maximum value will not be checked. :param message: Error message to raise in case of a validation error. Can be interpolated using `%(min)s` and `%(max)s` if desired. Useful defaults are provided depending on the existence of min and max. """ def __init__(self, min=None, max=None, min_inclusive=True, max_inclusive=True, message=None): self.min = min self.max = max self.message = message self.min_inclusive = min_inclusive self.max_inclusive = max_inclusive def __call__(self, form, field): fdata = field.data if isinstance(field.data, (list, tuple)) else [field.data] for data in fdata: flags = 0 flags |= (data is None) << 0 flags |= (self.min is not None and self.min_inclusive and data < self.min) << 1 flags |= (self.max is not None and self.max_inclusive and data > self.max) << 2 flags |= (self.min is not None and not self.min_inclusive and data <= self.min) << 3 flags |= (self.max is not None and not self.max_inclusive and data >= self.max) << 4 if flags: message = self.message if message is None: # we use %(min)s interpolation to support floats, None, and # Decimals without throwing a formatting exception. if flags & 1 << 0: message = field.gettext('No data.') elif flags & 1 << 1: message = field.gettext('Number %(data)s must be at least %(min)s.') elif flags & 1 << 2: message = field.gettext('Number %(data)s must be at most %(max)s.') elif flags & 1 << 3: message = field.gettext('Number %(data)s must be greater than %(min)s.') elif flags & 1 << 4: message = field.gettext('Number %(data)s must be less than %(max)s.') raise validators.ValidationError(message % dict(data=data, min=self.min, max=self.max)) class MultiOptional(object): """ Allows empty input and stops the validation chain from continuing. If input is empty, also removes prior errors (such as processing errors) from the field. :param strip_whitespace: If True (the default) also stop the validation chain on input which consists of only whitespace. """ field_flags = ('optional', ) def __init__(self, strip_whitespace=True): if strip_whitespace: self.string_check = lambda s: s.strip() else: self.string_check = lambda s: s def __call__(self, form, field): if (not field.raw_data or (len(field.raw_data[0]) and isinstance(field.raw_data[0][0], string_types) and not self.string_check(field.raw_data[0][0]))): field.errors[:] = [] raise validators.StopValidation() # Used to save data to populate forms when cloning def add_warning(form, warning): if not hasattr(form, 'warnings'): form.warnings = tuple([]) form.warnings += tuple([warning]) return True # Iterate over the form looking for field data to either save to or # get from the job depending on function. def iterate_over_form(job, form, function, prefix=['form'], indent=''): warnings = False if not hasattr(form, '__dict__'): return False # This is the list of Field types to save. SubmitField and # FileField is excluded. SubmitField would cause it to post and # FileField can not be populated. whitelist_fields = [ 'BooleanField', 'FloatField', 'HiddenField', 'IntegerField', 'RadioField', 'SelectField', 'SelectMultipleField', 'StringField', 'TextAreaField', 'TextField', 'MultiIntegerField', 'MultiFloatField'] blacklist_fields = ['FileField', 'SubmitField'] for attr_name in vars(form): if attr_name == 'csrf_token' or attr_name == 'flags': continue attr = getattr(form, attr_name) if isinstance(attr, object): if isinstance(attr, SubmitField): continue warnings |= iterate_over_form(job, attr, function, prefix + [attr_name], indent + ' ') if hasattr(attr, 'data') and hasattr(attr, 'type'): if (isinstance(attr.data, int) or isinstance(attr.data, float) or isinstance(attr.data, basestring) or attr.type in whitelist_fields): key = '%s.%s.data' % ('.'.join(prefix), attr_name) warnings |= function(job, attr, key, attr.data) # Warn if certain field types are not cloned if (len(attr.type) > 5 and attr.type[-5:] == 'Field' and attr.type not in whitelist_fields and attr.type not in blacklist_fields): warnings |= add_warning(attr, 'Field type, %s, not cloned' % attr.type) return warnings # function to pass to iterate_over_form to save data to job def set_data(job, form, key, value): if not hasattr(job, 'form_data'): job.form_data = dict() job.form_data[key] = value if isinstance(value, basestring): value = '\'' + value + '\'' return False # function to pass to iterate_over_form to get data from job # Don't warn if key is not in job.form_data def get_data(job, form, key, value): if key in job.form_data.keys(): form.data = job.form_data[key] return False # Save to form field data in form to the job so the form can later be # populated with the sae settings during a clone event. def save_form_to_job(job, form): iterate_over_form(job, form, set_data) # Populate the form with form field data saved in the job def fill_form_from_job(job, form): form.warnings = iterate_over_form(job, form, get_data) # This logic if used in several functions where ?clone=<job_id> may # be added to the url. If ?clone=<job_id> is specified in the url, # fill the form with that job. def fill_form_if_cloned(form): # is there a request to clone a job. from digits.webapp import scheduler clone = get_request_arg('clone') if clone is not None: clone_job = scheduler.get_job(clone) fill_form_from_job(clone_job, form)
DIGITS-master
digits/utils/forms.py
# Copyright (c) 2015-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import os import random import shutil import tempfile from nose.tools import assert_raises from . import filesystem as fs from digits import test_utils test_utils.skipIfNotFramework('none') class TestTreeSize(): def test_bad_path(self): for path in [ 'some string', '/tmp/not-a-file', 'http://not-a-url', ]: yield self.check_bad_path, path def check_bad_path(self, path): assert_raises(ValueError, fs.get_tree_size, path) def test_empty_folder(self): try: dir = tempfile.mkdtemp() assert(fs.get_tree_size(dir) == 0) finally: shutil.rmtree(dir) def test_folder_with_files(self): for n_files in [1, 5, 10]: yield self.check_folder_with_files, n_files def check_folder_with_files(self, n_files): try: dir = tempfile.mkdtemp() total_size = 0 for i in range(n_files): # create file with random size of up to 1MB size = random.randint(1, 2**20) fd, name = tempfile.mkstemp(dir=dir) f = open(name, "w") f.seek(size - 1) f.write("\0") f.close() os.close(fd) total_size += size tree_size = fs.get_tree_size(dir) assert tree_size == total_size, "Expected size=%d, got %d" % (total_size, tree_size) finally: shutil.rmtree(dir)
DIGITS-master
digits/utils/test_filesystem.py
# Copyright (c) 2015-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import flask import werkzeug.exceptions def job_from_request(): """ Returns the job after grabbing job_id from request.args or request.form Raises werkzeug.exceptions """ from digits.webapp import scheduler job_id = get_request_arg('job_id') if job_id is None: raise werkzeug.exceptions.BadRequest('job_id is a required field') job = scheduler.get_job(job_id) if job is None: raise werkzeug.exceptions.NotFound('Job not found') else: return job # Adapted from http://flask.pocoo.org/snippets/45/ def request_wants_json(): """ Returns True if the response should be JSON """ if flask.request.base_url.endswith('/json'): return True best = flask.request.accept_mimetypes \ .best_match(['application/json', 'text/html']) # Some browsers accept on */* and we don't want to deliver JSON to an ordinary browser return best == 'application/json' and \ flask.request.accept_mimetypes[best] > \ flask.request.accept_mimetypes['text/html'] # check for arguments pass to url def get_request_arg(key): value = None if key in flask.request.args: value = flask.request.args[key] elif key in flask.request.form: value = flask.request.form[key] return value
DIGITS-master
digits/utils/routing.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import lmdb class DbReader(object): """ Reads a database """ def __init__(self, location): """ Arguments: location -- where is the database """ self._db = lmdb.open( location, map_size=1024**3, # 1MB readonly=True, lock=False) with self._db.begin() as txn: self.total_entries = txn.stat()['entries'] self.txn = self._db.begin() def entries(self): """ Generator returning all entries in the DB """ with self._db.begin() as txn: cursor = txn.cursor() for item in cursor: yield item def entry(self, key): """Return single entry""" return self.txn.get(key)
DIGITS-master
digits/utils/lmdbreader.py
# Copyright (c) 2015-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import re import time from digits import test_utils from digits import utils test_utils.skipIfNotFramework('none') class TestTimeFilters(): def test_print_time(self): # Pass in a reference time to print_time, to avoid stepping into the # next year in the other tests close to December. Also avoid the # leap year and daylight savings time. t = (2009, 5, 17, 16, 0, 0, 0, 0, 0) ref_time = time.mktime(t) day = 60 * 60 * 24 # Year test (365 days) s = utils.time_filters.print_time(day * 365 + ref_time, ref_time) assert re.match('\w{3} \d{2} \d{4}, \d{2}:\d{2}:\d{2} [AP]M', s) # Month test (40 days) s = utils.time_filters.print_time(day * 40 + ref_time, ref_time) assert re.match('\w{3} \d{2}, \d{2}:\d{2}:\d{2} [AP]M', s) # Day test (4 days) s = utils.time_filters.print_time(day * 4 + ref_time, ref_time) assert re.match('\w{3} \w{3} \d{2}, \d{2}:\d{2}:\d{2} [AP]M', s) # default test (4 seconds) s = utils.time_filters.print_time(4 + ref_time, ref_time) assert re.match('\d{2}:\d{2}:\d{2} [AP]M', s) def test_print_time_diff(self): def time_string(days, hours, minutes, seconds): time = 86400 * days + 3600 * hours + 60 * minutes + seconds return utils.time_filters.print_time_diff(time) # Test days and hours assert time_string(1, 0, 0, 0) == '1 day' assert time_string(1, 1, 0, 0) == '1 day, 1 hour' assert time_string(2, 1, 0, 0) == '2 days, 1 hour' assert time_string(1, 2, 0, 0) == '1 day, 2 hours' assert time_string(2, 2, 0, 0) == '2 days, 2 hours' # Test hours and minutes assert time_string(0, 1, 0, 0) == '1 hour' assert time_string(0, 1, 1, 0) == '1 hour, 1 minute' assert time_string(0, 2, 1, 0) == '2 hours, 1 minute' assert time_string(0, 1, 2, 0) == '1 hour, 2 minutes' assert time_string(0, 2, 2, 0) == '2 hours, 2 minutes' # Test minutes and seconds assert time_string(0, 0, 1, 0) == '1 minute' assert time_string(0, 0, 1, 1) == '1 minute, 1 second' assert time_string(0, 0, 2, 1) == '2 minutes, 1 second' assert time_string(0, 0, 1, 2) == '1 minute, 2 seconds' assert time_string(0, 0, 2, 2) == '2 minutes, 2 seconds' # Test seconds assert time_string(0, 0, 0, 1) == '1 second' assert time_string(0, 0, 0, 2) == '2 seconds' # Test no time assert time_string(0, 0, 0, 0) == '0 seconds' # Test negative time assert time_string(0, 0, 0, -2) == 'Negative Time' # Test None assert utils.time_filters.print_time_diff(None) == '?' def test_print_time_diff_nosuffixes(self): def time_string(hours, minutes, seconds): time = 3600 * hours + 60 * minutes + seconds return utils.time_filters.print_time_diff_nosuffixes(time) assert time_string(0, 0, 0) == '00:00:00' assert time_string(0, 0, 1) == '00:00:01' assert time_string(0, 1, 0) == '00:01:00' assert time_string(0, 1, 1) == '00:01:01' assert time_string(1, 0, 0) == '01:00:00' assert time_string(1, 0, 1) == '01:00:01' assert time_string(1, 1, 0) == '01:01:00' assert time_string(1, 1, 1) == '01:01:01' # Test None assert utils.time_filters.print_time_diff_nosuffixes(None) == '?' def test_print_time_since(self): assert utils.time_filters.print_time_since(time.time()) == '0 seconds'
DIGITS-master
digits/utils/test_time_filters.py
# Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved. class DigitsError(Exception): """ DIGITS custom exception """ pass class DeleteError(DigitsError): """ Errors that occur when deleting a job """ pass class LoadImageError(DigitsError): """ Errors that occur while loading an image """ pass class UnsupportedPlatformError(DigitsError): """ Errors that occur while performing tasks in unsupported platforms """ pass
DIGITS-master
digits/utils/errors.py
# Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import math import os.path import requests # Find the best implementation available try: from cStringIO import StringIO except ImportError: from StringIO import StringIO import numpy as np import PIL.Image import scipy.misc from . import is_url, HTTP_TIMEOUT, errors # Library defaults: # PIL.Image: # size -- (width, height) # np.array: # shape -- (height, width, channels) # range -- [0-255] # dtype -- uint8 # channels -- RGB # caffe.datum: # datum.data type -- bytes (uint8) # datum.float_data type -- float32 # when decoding images, channels are BGR # DIGITS: # image_dims -- (height, width, channels) # List of supported file extensions # Use like "if filename.endswith(SUPPORTED_EXTENSIONS)" SUPPORTED_EXTENSIONS = ('.png', '.jpg', '.jpeg', '.bmp', '.ppm', '.pgm') def load_image(path): """ Reads a file from `path` and returns a PIL.Image with mode 'L' or 'RGB' Raises LoadImageError Arguments: path -- path to the image, can be a filesystem path or a URL """ image = None if is_url(path): try: r = requests.get(path, allow_redirects=False, timeout=HTTP_TIMEOUT) r.raise_for_status() stream = StringIO(r.content) image = PIL.Image.open(stream) except requests.exceptions.RequestException as e: raise errors.LoadImageError, e.message except IOError as e: raise errors.LoadImageError, e.message elif os.path.exists(path): try: image = PIL.Image.open(path) image.load() except IOError as e: raise errors.LoadImageError, 'IOError: Trying to load "%s": %s' % (path, e.message) else: raise errors.LoadImageError, '"%s" not found' % path if image.mode in ['L', 'RGB']: # No conversion necessary return image elif image.mode in ['1']: # Easy conversion to L return image.convert('L') elif image.mode in ['LA']: # Deal with transparencies new = PIL.Image.new('L', image.size, 255) new.paste(image, mask=image.convert('RGBA')) return new elif image.mode in ['CMYK', 'YCbCr']: # Easy conversion to RGB return image.convert('RGB') elif image.mode in ['P', 'RGBA']: # Deal with transparencies new = PIL.Image.new('RGB', image.size, (255, 255, 255)) new.paste(image, mask=image.convert('RGBA')) return new else: raise errors.LoadImageError, 'Image mode "%s" not supported' % image.mode def upscale(image, ratio): """ return upscaled image array Arguments: image -- a (H,W,C) numpy.ndarray ratio -- scaling factor (>1) """ if not isinstance(image, np.ndarray): raise ValueError('Expected ndarray') if ratio < 1: raise ValueError('Ratio must be greater than 1 (ratio=%f)' % ratio) width = int(math.floor(image.shape[1] * ratio)) height = int(math.floor(image.shape[0] * ratio)) channels = image.shape[2] out = np.ndarray((height, width, channels), dtype=np.uint8) for x, y in np.ndindex((width, height)): out[y, x] = image[int(math.floor(y / ratio)), int(math.floor(x / ratio))] return out def image_to_array(image, channels=None): """ Returns an image as a np.array Arguments: image -- a PIL.Image or numpy.ndarray Keyword Arguments: channels -- channels of new image (stays unchanged if not specified) """ if channels not in [None, 1, 3, 4]: raise ValueError('unsupported number of channels: %s' % channels) if isinstance(image, PIL.Image.Image): # Convert image mode (channels) if channels is None: image_mode = image.mode if image_mode not in ['L', 'RGB', 'RGBA']: raise ValueError('unknown image mode "%s"' % image_mode) elif channels == 1: # 8-bit pixels, black and white image_mode = 'L' elif channels == 3: # 3x8-bit pixels, true color image_mode = 'RGB' elif channels == 4: # 4x8-bit pixels, true color with alpha image_mode = 'RGBA' if image.mode != image_mode: image = image.convert(image_mode) image = np.array(image) elif isinstance(image, np.ndarray): if image.dtype != np.uint8: image = image.astype(np.uint8) if image.ndim == 3 and image.shape[2] == 1: image = image.reshape(image.shape[:2]) if channels is None: if not (image.ndim == 2 or (image.ndim == 3 and image.shape[2] in [3, 4])): raise ValueError('invalid image shape: %s' % (image.shape,)) elif channels == 1: if image.ndim != 2: if image.ndim == 3 and image.shape[2] in [3, 4]: # color to grayscale. throw away alpha image = np.dot(image[:, :, :3], [0.299, 0.587, 0.114]).astype(np.uint8) else: raise ValueError('invalid image shape: %s' % (image.shape,)) elif channels == 3: if image.ndim == 2: # grayscale to color image = np.repeat(image, 3).reshape(image.shape + (3,)) elif image.shape[2] == 4: # throw away alpha image = image[:, :, :3] elif image.shape[2] != 3: raise ValueError('invalid image shape: %s' % (image.shape,)) elif channels == 4: if image.ndim == 2: # grayscale to color image = np.repeat(image, 4).reshape(image.shape + (4,)) image[:, :, 3] = 255 elif image.shape[2] == 3: # add alpha image = np.append(image, np.zeros(image.shape[:2] + (1,), dtype='uint8'), axis=2) image[:, :, 3] = 255 elif image.shape[2] != 4: raise ValueError('invalid image shape: %s' % (image.shape,)) else: raise ValueError('resize_image() expected a PIL.Image.Image or a numpy.ndarray') return image def resize_image(image, height, width, channels=None, resize_mode=None, ): """ Resizes an image and returns it as a np.array Arguments: image -- a PIL.Image or numpy.ndarray height -- height of new image width -- width of new image Keyword Arguments: channels -- channels of new image (stays unchanged if not specified) resize_mode -- can be crop, squash, fill or half_crop """ if resize_mode is None: resize_mode = 'squash' if resize_mode not in ['crop', 'squash', 'fill', 'half_crop']: raise ValueError('resize_mode "%s" not supported' % resize_mode) # convert to array image = image_to_array(image, channels) # No need to resize if image.shape[0] == height and image.shape[1] == width: return image # Resize interp = 'bilinear' width_ratio = float(image.shape[1]) / width height_ratio = float(image.shape[0]) / height if resize_mode == 'squash' or width_ratio == height_ratio: return scipy.misc.imresize(image, (height, width), interp=interp) elif resize_mode == 'crop': # resize to smallest of ratios (relatively larger image), keeping aspect ratio if width_ratio > height_ratio: resize_height = height resize_width = int(round(image.shape[1] / height_ratio)) else: resize_width = width resize_height = int(round(image.shape[0] / width_ratio)) image = scipy.misc.imresize(image, (resize_height, resize_width), interp=interp) # chop off ends of dimension that is still too long if width_ratio > height_ratio: start = int(round((resize_width - width) / 2.0)) return image[:, start:start + width] else: start = int(round((resize_height - height) / 2.0)) return image[start:start + height, :] else: if resize_mode == 'fill': # resize to biggest of ratios (relatively smaller image), keeping aspect ratio if width_ratio > height_ratio: resize_width = width resize_height = int(round(image.shape[0] / width_ratio)) if (height - resize_height) % 2 == 1: resize_height += 1 else: resize_height = height resize_width = int(round(image.shape[1] / height_ratio)) if (width - resize_width) % 2 == 1: resize_width += 1 image = scipy.misc.imresize(image, (resize_height, resize_width), interp=interp) elif resize_mode == 'half_crop': # resize to average ratio keeping aspect ratio new_ratio = (width_ratio + height_ratio) / 2.0 resize_width = int(round(image.shape[1] / new_ratio)) resize_height = int(round(image.shape[0] / new_ratio)) if width_ratio > height_ratio and (height - resize_height) % 2 == 1: resize_height += 1 elif width_ratio < height_ratio and (width - resize_width) % 2 == 1: resize_width += 1 image = scipy.misc.imresize(image, (resize_height, resize_width), interp=interp) # chop off ends of dimension that is still too long if width_ratio > height_ratio: start = int(round((resize_width - width) / 2.0)) image = image[:, start:start + width] else: start = int(round((resize_height - height) / 2.0)) image = image[start:start + height, :] else: raise Exception('unrecognized resize_mode "%s"' % resize_mode) # fill ends of dimension that is too short with random noise if width_ratio > height_ratio: padding = (height - resize_height) / 2 noise_size = (padding, width) if channels > 1: noise_size += (channels,) noise = np.random.randint(0, 255, noise_size).astype('uint8') image = np.concatenate((noise, image, noise), axis=0) else: padding = (width - resize_width) / 2 noise_size = (height, padding) if channels > 1: noise_size += (channels,) noise = np.random.randint(0, 255, noise_size).astype('uint8') image = np.concatenate((noise, image, noise), axis=1) return image def embed_image_html(image): """ Returns an image embedded in HTML base64 format (Based on Caffe's web_demo) Arguments: image -- a PIL.Image or np.ndarray """ if image is None: return None elif isinstance(image, PIL.Image.Image): pass elif isinstance(image, np.ndarray): image = PIL.Image.fromarray(image) else: raise ValueError('image must be a PIL.Image or a np.ndarray') # Read format from the image fmt = image.format if not fmt: # default to PNG fmt = 'png' else: fmt = fmt.lower() string_buf = StringIO() image.save(string_buf, format=fmt) data = string_buf.getvalue().encode('base64').replace('\n', '') return 'data:image/%s;base64,%s' % (fmt, data) def get_layer_vis_square(data, allow_heatmap=True, normalize=True, min_img_dim=100, max_width=1200, channel_order='RGB', ): """ Returns a vis_square for the given layer data Arguments: data -- a np.ndarray Keyword arguments: allow_heatmap -- if True, convert single channel images to heatmaps normalize -- whether to normalize the data when visualizing max_width -- maximum width for the vis_square """ if channel_order not in ['RGB', 'BGR']: raise ValueError('Unsupported channel_order %s' % channel_order) if data.ndim == 1: # interpret as 1x1 grayscale images # (N, 1, 1) data = data[:, np.newaxis, np.newaxis] elif data.ndim == 2: # interpret as 1x1 grayscale images # (N, 1, 1) data = data.reshape((data.shape[0] * data.shape[1], 1, 1)) elif data.ndim == 3: if data.shape[0] == 3: # interpret as a color image # (1, H, W,3) if channel_order == 'BGR': data = data[[2, 1, 0], ...] # BGR to RGB (see issue #59) data = data.transpose(1, 2, 0) data = data[np.newaxis, ...] else: # interpret as grayscale images # (N, H, W) pass elif data.ndim == 4: if data.shape[0] == 3: # interpret as HxW color images # (N, H, W, 3) data = data.transpose(1, 2, 3, 0) if channel_order == 'BGR': data = data[:, :, :, [2, 1, 0]] # BGR to RGB (see issue #59) elif data.shape[1] == 3: # interpret as HxW color images # (N, H, W, 3) data = data.transpose(0, 2, 3, 1) if channel_order == 'BGR': data = data[:, :, :, [2, 1, 0]] # BGR to RGB (see issue #59) else: # interpret as HxW grayscale images # (N, H, W) data = data.reshape((data.shape[0] * data.shape[1], data.shape[2], data.shape[3])) else: raise RuntimeError('unrecognized data shape: %s' % (data.shape,)) # chop off data so that it will fit within max_width padsize = 0 width = data.shape[2] if width > max_width: data = data[:1, :max_width, :max_width] else: if width > 1: padsize = 1 width += 1 n = max(max_width / width, 1) n *= n data = data[:n] if not allow_heatmap and data.ndim == 3: data = data[..., np.newaxis] vis = vis_square(data, padsize=padsize, normalize=normalize, ) # find minimum dimension and upscale if necessary _min = sorted(vis.shape[:2])[0] if _min < min_img_dim: # upscale image ratio = min_img_dim / float(_min) vis = upscale(vis, ratio) return vis def vis_square(images, padsize=1, normalize=False, colormap='jet', ): """ Visualize each image in a grid of size approx sqrt(n) by sqrt(n) Returns a np.array image (Based on Caffe's filter_visualization notebook) Arguments: images -- an array of shape (N, H, W) or (N, H, W, C) if C is not set, a heatmap is computed for the result Keyword arguments: padsize -- how many pixels go between the tiles normalize -- if true, scales (min, max) across all images out to (0, 1) colormap -- a string representing one of the supported colormaps """ assert 3 <= images.ndim <= 4, 'images.ndim must be 3 or 4' # convert to float since we're going to do some math images = images.astype('float32') if normalize: images -= images.min() if images.max() > 0: images /= images.max() images *= 255 if images.ndim == 3: # they're grayscale - convert to a colormap redmap, greenmap, bluemap = get_color_map(colormap) red = np.interp(images * (len(redmap) - 1) / 255.0, xrange(len(redmap)), redmap) green = np.interp(images * (len(greenmap) - 1) / 255.0, xrange(len(greenmap)), greenmap) blue = np.interp(images * (len(bluemap) - 1) / 255.0, xrange(len(bluemap)), bluemap) # Slap the channels back together images = np.concatenate((red[..., np.newaxis], green[..., np.newaxis], blue[..., np.newaxis]), axis=3) images = np.minimum(images, 255) images = np.maximum(images, 0) # convert back to uint8 images = images.astype('uint8') # Compute the output image matrix dimensions n = int(np.ceil(np.sqrt(images.shape[0]))) ny = n nx = n length = images.shape[0] if n * (n - 1) >= length: nx = n - 1 # Add padding between the images padding = ((0, nx * ny - length), (0, padsize), (0, padsize)) + ((0, 0),) * (images.ndim - 3) padded = np.pad(images, padding, mode='constant', constant_values=255) # Tile the images beside each other tiles = padded.reshape((ny, nx) + padded.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, padded.ndim + 1))) tiles = tiles.reshape((ny * tiles.shape[1], nx * tiles.shape[3]) + tiles.shape[4:]) if tiles.shape[-1] == 1: # grayscale to color tiles = np.dstack([tiles.squeeze()] * 3) return tiles def get_color_map(name): """ Return a colormap as (redmap, greenmap, bluemap) Arguments: name -- the name of the colormap. If unrecognized, will default to 'jet'. """ redmap = [0] greenmap = [0] bluemap = [0] if name == 'white': # essentially a noop redmap = [0, 1] greenmap = [0, 1] bluemap = [0, 1] elif name == 'simple': redmap = [0, 1, 1, 1] greenmap = [0, 0, 1, 1] bluemap = [0, 0, 0, 1] elif name == 'hot': redmap = [0, 0.03968253968253968, 0.07936507936507936, 0.119047619047619, 0.1587301587301587, 0.1984126984126984, 0.2380952380952381, 0.2777777777777778, 0.3174603174603174, 0.3571428571428571, 0.3968253968253968, 0.4365079365079365, 0.4761904761904762, 0.5158730158730158, 0.5555555555555556, 0.5952380952380952, 0.6349206349206349, 0.6746031746031745, 0.7142857142857142, 0.753968253968254, 0.7936507936507936, 0.8333333333333333, 0.873015873015873, 0.9126984126984127, 0.9523809523809523, 0.992063492063492, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] # noqa greenmap = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.03174603174603163, 0.0714285714285714, 0.1111111111111112, 0.1507936507936507, 0.1904761904761905, 0.23015873015873, 0.2698412698412698, 0.3095238095238093, 0.3492063492063491, 0.3888888888888888, 0.4285714285714284, 0.4682539682539679, 0.5079365079365079, 0.5476190476190477, 0.5873015873015872, 0.6269841269841268, 0.6666666666666665, 0.7063492063492065, 0.746031746031746, 0.7857142857142856, 0.8253968253968254, 0.8650793650793651, 0.9047619047619047, 0.9444444444444442, 0.984126984126984, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] # noqa bluemap = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.04761904761904745, 0.1269841269841265, 0.2063492063492056, 0.2857142857142856, 0.3650793650793656, 0.4444444444444446, 0.5238095238095237, 0.6031746031746028, 0.6825396825396828, 0.7619047619047619, 0.8412698412698409, 0.92063492063492, 1] # noqa elif name == 'rainbow': redmap = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.9365079365079367, 0.8571428571428572, 0.7777777777777777, 0.6984126984126986, 0.6190476190476191, 0.53968253968254, 0.4603174603174605, 0.3809523809523814, 0.3015873015873018, 0.2222222222222223, 0.1428571428571432, 0.06349206349206415, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.03174603174603208, 0.08465608465608465, 0.1375661375661377, 0.1904761904761907, 0.2433862433862437, 0.2962962962962963, 0.3492063492063493, 0.4021164021164023, 0.4550264550264553, 0.5079365079365079, 0.5608465608465609, 0.6137566137566139, 0.666666666666667] # noqa greenmap = [0, 0.03968253968253968, 0.07936507936507936, 0.119047619047619, 0.1587301587301587, 0.1984126984126984, 0.2380952380952381, 0.2777777777777778, 0.3174603174603174, 0.3571428571428571, 0.3968253968253968, 0.4365079365079365, 0.4761904761904762, 0.5158730158730158, 0.5555555555555556, 0.5952380952380952, 0.6349206349206349, 0.6746031746031745, 0.7142857142857142, 0.753968253968254, 0.7936507936507936, 0.8333333333333333, 0.873015873015873, 0.9126984126984127, 0.9523809523809523, 0.992063492063492, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.9841269841269842, 0.9047619047619047, 0.8253968253968256, 0.7460317460317465, 0.666666666666667, 0.587301587301587, 0.5079365079365079, 0.4285714285714288, 0.3492063492063493, 0.2698412698412698, 0.1904761904761907, 0.1111111111111116, 0.03174603174603208, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # noqa bluemap = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.01587301587301582, 0.09523809523809534, 0.1746031746031744, 0.2539682539682535, 0.333333333333333, 0.412698412698413, 0.4920634920634921, 0.5714285714285712, 0.6507936507936507, 0.7301587301587302, 0.8095238095238093, 0.8888888888888884, 0.9682539682539679, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] # noqa elif name == 'winter': greenmap = [0, 1] bluemap = [1, 0.5] else: if name != 'jet': print 'Warning: colormap "%s" not supported. Using jet instead.' % name redmap = [0, 0, 0, 0, 0.5, 1, 1, 1, 0.5] greenmap = [0, 0, 0.5, 1, 1, 1, 0.5, 0, 0] bluemap = [0.5, 1, 1, 1, 0.5, 0, 0, 0, 0] return 255.0 * np.array(redmap), 255.0 * np.array(greenmap), 255.0 * np.array(bluemap)
DIGITS-master
digits/utils/image.py
# Preferred settings for this model is: # Training epochs = 80 # Crop Size = 224 # Learning Rate = 0.001 # Under advanced learning rate options: # Step Size = 10.0 # Gamma = 0.96 # The auxillary branches as spcified in the original googlenet V1 model do exist in this implementation of # googlenet but it is not used. To use it, be sure to check self.is_training to ensure that it is only used # during training. from model import Tower from utils import model_property import tensorflow as tf import utils as digits class UserModel(Tower): all_inception_settings = { '3a': [[64], [96, 128], [16, 32], [32]], '3b': [[128], [128, 192], [32, 96], [64]], '4a': [[192], [96, 208], [16, 48], [64]], '4b': [[160], [112, 224], [24, 64], [64]], '4c': [[128], [128, 256], [24, 64], [64]], '4d': [[112], [144, 288], [32, 64], [64]], '4e': [[256], [160, 320], [32, 128], [128]], '5a': [[256], [160, 320], [32, 128], [128]], '5b': [[384], [192, 384], [48, 128], [128]] } @model_property def inference(self): # rescale to proper form, really we expect 224 x 224 x 1 in HWC form model = tf.reshape(self.x, shape=[-1, self.input_shape[0], self.input_shape[1], self.input_shape[2]]) conv_7x7_2s_weight, conv_7x7_2s_bias = self.create_conv_vars([7, 7, self.input_shape[2], 64], 'conv_7x7_2s') model = self.conv_layer_with_relu(model, conv_7x7_2s_weight, conv_7x7_2s_bias, 2) model = self.max_pool(model, 3, 2) # model = tf.nn.local_response_normalization(model) conv_1x1_vs_weight, conv_1x1_vs_bias = self.create_conv_vars([1, 1, 64, 64], 'conv_1x1_vs') model = self.conv_layer_with_relu(model, conv_1x1_vs_weight, conv_1x1_vs_bias, 1, 'VALID') conv_3x3_1s_weight, conv_3x3_1s_bias = self.create_conv_vars([3, 3, 64, 192], 'conv_3x3_1s') model = self.conv_layer_with_relu(model, conv_3x3_1s_weight, conv_3x3_1s_bias, 1) # model = tf.nn.local_response_normalization(model) model = self.max_pool(model, 3, 2) inception_settings_3a = InceptionSettings(192, UserModel.all_inception_settings['3a']) model = self.inception(model, inception_settings_3a, '3a') inception_settings_3b = InceptionSettings(256, UserModel.all_inception_settings['3b']) model = self.inception(model, inception_settings_3b, '3b') model = self.max_pool(model, 3, 2) inception_settings_4a = InceptionSettings(480, UserModel.all_inception_settings['4a']) model = self.inception(model, inception_settings_4a, '4a') # first auxiliary branch for making training faster # aux_branch_1 = self.auxiliary_classifier(model, 512, "aux_1") inception_settings_4b = InceptionSettings(512, UserModel.all_inception_settings['4b']) model = self.inception(model, inception_settings_4b, '4b') inception_settings_4c = InceptionSettings(512, UserModel.all_inception_settings['4c']) model = self.inception(model, inception_settings_4c, '4c') inception_settings_4d = InceptionSettings(512, UserModel.all_inception_settings['4d']) model = self.inception(model, inception_settings_4d, '4d') # second auxiliary branch for making training faster # aux_branch_2 = self.auxiliary_classifier(model, 528, "aux_2") inception_settings_4e = InceptionSettings(528, UserModel.all_inception_settings['4e']) model = self.inception(model, inception_settings_4e, '4e') model = self.max_pool(model, 3, 2) inception_settings_5a = InceptionSettings(832, UserModel.all_inception_settings['5a']) model = self.inception(model, inception_settings_5a, '5a') inception_settings_5b = InceptionSettings(832, UserModel.all_inception_settings['5b']) model = self.inception(model, inception_settings_5b, '5b') model = self.avg_pool(model, 7, 1, 'VALID') fc_weight, fc_bias = self.create_fc_vars([1024, self.nclasses], 'fc') model = self.fully_connect(model, fc_weight, fc_bias) # if self.is_training: # return [aux_branch_1, aux_branch_2, model] return model @model_property def loss(self): model = self.inference loss = digits.classification_loss(model, self.y) accuracy = digits.classification_accuracy(model, self.y) self.summaries.append(tf.summary.scalar(accuracy.op.name, accuracy)) return loss def inception(self, model, inception_setting, layer_name): weights, biases = self.create_inception_variables(inception_setting, layer_name) conv_1x1 = self.conv_layer_with_relu(model, weights['conv_1x1_1'], biases['conv_1x1_1'], 1) conv_3x3 = self.conv_layer_with_relu(model, weights['conv_1x1_2'], biases['conv_1x1_2'], 1) conv_3x3 = self.conv_layer_with_relu(conv_3x3, weights['conv_3x3'], biases['conv_3x3'], 1) conv_5x5 = self.conv_layer_with_relu(model, weights['conv_1x1_3'], biases['conv_1x1_3'], 1) conv_5x5 = self.conv_layer_with_relu(conv_5x5, weights['conv_5x5'], biases['conv_5x5'], 1) conv_pool = self.max_pool(model, 3, 1) conv_pool = self.conv_layer_with_relu(conv_pool, weights['conv_pool'], biases['conv_pool'], 1) final_model = tf.concat([conv_1x1, conv_3x3, conv_5x5, conv_pool], 3) return final_model def create_inception_variables(self, inception_setting, layer_name): model_dim = inception_setting.model_dim conv_1x1_1_w, conv_1x1_1_b = self.create_conv_vars([1, 1, model_dim, inception_setting.conv_1x1_1_layers], layer_name + '-conv_1x1_1') conv_1x1_2_w, conv_1x1_2_b = self.create_conv_vars([1, 1, model_dim, inception_setting.conv_1x1_2_layers], layer_name + '-conv_1x1_2') conv_1x1_3_w, conv_1x1_3_b = self.create_conv_vars([1, 1, model_dim, inception_setting.conv_1x1_3_layers], layer_name + '-conv_1x1_3') conv_3x3_w, conv_3x3_b = self.create_conv_vars([3, 3, inception_setting.conv_1x1_2_layers, inception_setting.conv_3x3_layers], layer_name + '-conv_3x3') conv_5x5_w, conv_5x5_b = self.create_conv_vars([5, 5, inception_setting.conv_1x1_3_layers, inception_setting.conv_5x5_layers], layer_name + '-conv_5x5') conv_pool_w, conv_pool_b = self.create_conv_vars([1, 1, model_dim, inception_setting.conv_pool_layers], layer_name + '-conv_pool') weights = { 'conv_1x1_1': conv_1x1_1_w, 'conv_1x1_2': conv_1x1_2_w, 'conv_1x1_3': conv_1x1_3_w, 'conv_3x3': conv_3x3_w, 'conv_5x5': conv_5x5_w, 'conv_pool': conv_pool_w } biases = { 'conv_1x1_1': conv_1x1_1_b, 'conv_1x1_2': conv_1x1_2_b, 'conv_1x1_3': conv_1x1_3_b, 'conv_3x3': conv_3x3_b, 'conv_5x5': conv_5x5_b, 'conv_pool': conv_pool_b } return weights, biases def auxiliary_classifier(self, model, input_size, name): aux_classifier = self.avg_pool(model, 5, 3, 'VALID') conv_weight, conv_bias = self.create_conv_vars([1, 1, input_size, input_size], name + '-conv_1x1') aux_classifier = self.conv_layer_with_relu(aux_classifier, conv_weight, conv_bias, 1) fc_weight, fc_bias = self.create_fc_vars([4*4*input_size, self.nclasses], name + '-fc') aux_classifier = self.fully_connect(aux_classifier, fc_weight, fc_bias) aux_classifier = tf.nn.dropout(aux_classifier, 0.7) return aux_classifier def conv_layer_with_relu(self, model, weights, biases, stride_size, padding='SAME'): new_model = tf.nn.conv2d(model, weights, strides=[1, stride_size, stride_size, 1], padding=padding) new_model = tf.nn.bias_add(new_model, biases) new_model = tf.nn.relu(new_model) return new_model def max_pool(self, model, kernal_size, stride_size, padding='SAME'): new_model = tf.nn.max_pool(model, ksize=[1, kernal_size, kernal_size, 1], strides=[1, stride_size, stride_size, 1], padding=padding) return new_model def avg_pool(self, model, kernal_size, stride_size, padding='SAME'): new_model = tf.nn.avg_pool(model, ksize=[1, kernal_size, kernal_size, 1], strides=[1, stride_size, stride_size, 1], padding=padding) return new_model def fully_connect(self, model, weights, biases): fc_model = tf.reshape(model, [-1, weights.get_shape().as_list()[0]]) fc_model = tf.matmul(fc_model, weights) fc_model = tf.add(fc_model, biases) fc_model = tf.nn.relu(fc_model) return fc_model def create_conv_vars(self, size, name): weight = self.create_weight(size, name + '_W') bias = self.create_bias(size[3], name + '_b') return weight, bias def create_fc_vars(self, size, name): weight = self.create_weight(size, name + '_W') bias = self.create_bias(size[1], name + '_b') return weight, bias def create_weight(self, size, name): weight = tf.get_variable(name, size, initializer=tf.contrib.layers.xavier_initializer()) return weight def create_bias(self, size, name): bias = tf.get_variable(name, [size], initializer=tf.constant_initializer(0.2)) return bias class InceptionSettings(): def __init__(self, model_dim, inception_settings): self.model_dim = model_dim self.conv_1x1_1_layers = inception_settings[0][0] self.conv_1x1_2_layers = inception_settings[1][0] self.conv_1x1_3_layers = inception_settings[2][0] self.conv_3x3_layers = inception_settings[1][1] self.conv_5x5_layers = inception_settings[2][1] self.conv_pool_layers = inception_settings[3][0]
DIGITS-master
digits/standard-networks/tensorflow/googlenet.py
from model import Tower from utils import model_property import tensorflow as tf import tensorflow.contrib.slim as slim import utils as digits class UserModel(Tower): @model_property def inference(self): x = tf.reshape(self.x, shape=[-1, self.input_shape[0], self.input_shape[1], self.input_shape[2]]) # scale (divide by MNIST std) x = x * 0.0125 with slim.arg_scope([slim.conv2d, slim.fully_connected], weights_initializer=tf.contrib.layers.xavier_initializer(), weights_regularizer=slim.l2_regularizer(0.0005)): model = slim.conv2d(x, 20, [5, 5], padding='VALID', scope='conv1') model = slim.max_pool2d(model, [2, 2], padding='VALID', scope='pool1') model = slim.conv2d(model, 50, [5, 5], padding='VALID', scope='conv2') model = slim.max_pool2d(model, [2, 2], padding='VALID', scope='pool2') model = slim.flatten(model) model = slim.fully_connected(model, 500, scope='fc1') model = slim.dropout(model, 0.5, is_training=self.is_training, scope='do1') model = slim.fully_connected(model, self.nclasses, activation_fn=None, scope='fc2') return model @model_property def loss(self): model = self.inference loss = digits.classification_loss(model, self.y) accuracy = digits.classification_accuracy(model, self.y) self.summaries.append(tf.summary.scalar(accuracy.op.name, accuracy)) return loss
DIGITS-master
digits/standard-networks/tensorflow/lenet.py
from model import Tower from utils import model_property import tensorflow as tf import tensorflow.contrib.slim as slim import utils as digits class UserModel(Tower): @model_property def inference(self): x = tf.reshape(self.x, shape=[-1, self.input_shape[0], self.input_shape[1], self.input_shape[2]]) with slim.arg_scope([slim.conv2d, slim.fully_connected], weights_initializer=tf.contrib.layers.xavier_initializer(), weights_regularizer=slim.l2_regularizer(0.0005)): model = slim.repeat(x, 2, slim.conv2d, 64, [3, 3], scope='conv1') model = slim.max_pool2d(model, [2, 2], scope='pool1') model = slim.repeat(model, 2, slim.conv2d, 128, [3, 3], scope='conv2') model = slim.max_pool2d(model, [2, 2], scope='pool2') model = slim.repeat(model, 3, slim.conv2d, 256, [3, 3], scope='conv3') model = slim.max_pool2d(model, [2, 2], scope='pool3') model = slim.repeat(model, 3, slim.conv2d, 512, [3, 3], scope='conv4') model = slim.max_pool2d(model, [2, 2], scope='pool4') model = slim.repeat(model, 3, slim.conv2d, 512, [3, 3], scope='conv5') model = slim.max_pool2d(model, [2, 2], scope='pool5') model = slim.flatten(model, scope='flatten5') model = slim.fully_connected(model, 4096, scope='fc6') model = slim.dropout(model, 0.5, is_training=self.is_training, scope='do6') model = slim.fully_connected(model, 4096, scope='fc7') model = slim.dropout(model, 0.5, is_training=self.is_training, scope='do7') model = slim.fully_connected(model, self.nclasses, activation_fn=None, scope='fcX8') return model @model_property def loss(self): loss = digits.classification_loss(self.inference, self.y) accuracy = digits.classification_accuracy(self.inference, self.y) self.summaries.append(tf.summary.scalar(accuracy.op.name, accuracy)) return loss
DIGITS-master
digits/standard-networks/tensorflow/vgg16.py
# Preferred settings for this model is: # Base Learning Rate = 0.001 # Crop Size = 224 from model import Tower from utils import model_property import tensorflow as tf import tensorflow.contrib.slim as slim import utils as digits class UserModel(Tower): @model_property def inference(self): x = tf.reshape(self.x, shape=[-1, self.input_shape[0], self.input_shape[1], self.input_shape[2]]) with slim.arg_scope([slim.conv2d, slim.fully_connected], weights_initializer=tf.contrib.layers.xavier_initializer(), weights_regularizer=slim.l2_regularizer(1e-6)): model = slim.conv2d(x, 96, [11, 11], 4, padding='VALID', scope='conv1') model = slim.max_pool2d(model, [3, 3], 2, scope='pool1') model = slim.conv2d(model, 256, [5, 5], 1, scope='conv2') model = slim.max_pool2d(model, [3, 3], 2, scope='pool2') model = slim.conv2d(model, 384, [3, 3], 1, scope='conv3') model = slim.conv2d(model, 384, [3, 3], 1, scope='conv4') model = slim.conv2d(model, 256, [3, 3], 1, scope='conv5') model = slim.max_pool2d(model, [3, 3], 2, scope='pool5') model = slim.flatten(model) model = slim.fully_connected(model, 4096, activation_fn=None, scope='fc1') model = slim.dropout(model, 0.5, is_training=self.is_training, scope='do1') model = slim.fully_connected(model, 4096, activation_fn=None, scope='fc2') model = slim.dropout(model, 0.5, is_training=self.is_training, scope='do2') model = slim.fully_connected(model, self.nclasses, activation_fn=None, scope='fc3') return model @model_property def loss(self): model = self.inference loss = digits.classification_loss(model, self.y) accuracy = digits.classification_accuracy(model, self.y) self.summaries.append(tf.summary.scalar(accuracy.op.name, accuracy)) return loss
DIGITS-master
digits/standard-networks/tensorflow/alexnet.py
# Copyright (c) 2015-2017, NVIDIA CORPORATION. All rights reserved. import os import shutil import urllib class DataDownloader(object): """Base class for downloading data and setting it up for DIGITS""" def __init__(self, outdir, clean=False, file_extension='png'): """ Arguments: outdir -- directory where to download and create the dataset if this directory doesn't exist, it will be created Keyword arguments: clean -- delete outdir first if it exists file_extension -- image format for output images """ self.outdir = outdir self.mkdir(self.outdir, clean=clean) self.file_extension = file_extension.lower() def getData(self): """ This is the main function that should be called by the users! Downloads the dataset and prepares it for DIGITS consumption """ for url in self.urlList(): self.__downloadFile(url) self.uncompressData() self.processData() print "Dataset directory is created successfully at '%s'" % self.outdir def urlList(self): """ return a list of (url, output_file) tuples """ raise NotImplementedError def uncompressData(self): """ uncompress the downloaded files """ raise NotImplementedError def processData(self): """ Process the downloaded files and prepare the data for DIGITS """ raise NotImplementedError def __downloadFile(self, url): """ Downloads the url """ download_path = os.path.join(self.outdir, os.path.basename(url)) if not os.path.exists(download_path): print "Downloading url=%s ..." % url urllib.urlretrieve(url, download_path) def mkdir(self, d, clean=False): """ Safely create a directory Arguments: d -- the directory name Keyword arguments: clean -- if True and the directory already exists, it will be deleted and recreated """ if os.path.exists(d): if clean: shutil.rmtree(d) else: return os.mkdir(d)
DIGITS-master
digits/download_data/downloader.py
# Copyright (c) 2015-2017, NVIDIA CORPORATION. All rights reserved. import cPickle import os import tarfile import PIL.Image from downloader import DataDownloader class Cifar100Downloader(DataDownloader): """ See details about the CIFAR100 dataset here: http://www.cs.toronto.edu/~kriz/cifar.html """ def urlList(self): return [ 'http://www.cs.toronto.edu/~kriz/cifar-100-python.tar.gz', ] def uncompressData(self): filename = 'cifar-100-python.tar.gz' filepath = os.path.join(self.outdir, filename) assert os.path.exists(filepath), 'Expected "%s" to exist' % filename if not os.path.exists(os.path.join(self.outdir, 'cifar-100-python')): print "Uncompressing file=%s ..." % filename with tarfile.open(filepath) as tf: tf.extractall(self.outdir) def processData(self): label_filename = 'meta' label_filepath = os.path.join(self.outdir, 'cifar-100-python', label_filename) with open(label_filepath, 'rb') as infile: pickleObj = cPickle.load(infile) fine_label_names = pickleObj['fine_label_names'] coarse_label_names = pickleObj['coarse_label_names'] for level, label_names in [ ('fine', fine_label_names), ('coarse', coarse_label_names), ]: dirname = os.path.join(self.outdir, level) self.mkdir(dirname, clean=True) with open(os.path.join(dirname, 'labels.txt'), 'w') as outfile: for name in label_names: outfile.write('%s\n' % name) for filename, phase in [ ('train', 'train'), ('test', 'test'), ]: filepath = os.path.join(self.outdir, 'cifar-100-python', filename) assert os.path.exists(filepath), 'Expected "%s" to exist' % filename self.__extractData(filepath, phase, fine_label_names, coarse_label_names) def __extractData(self, input_file, phase, fine_label_names, coarse_label_names): """ Read a pickle file at input_file and output as images Arguments: input_file -- a pickle file phase -- train or test fine_label_names -- mapping from fine_labels to strings coarse_label_names -- mapping from coarse_labels to strings """ print 'Extracting images file=%s ...' % input_file # Read the pickle file with open(input_file, 'rb') as infile: pickleObj = cPickle.load(infile) # print 'Batch -', pickleObj['batch_label'] data = pickleObj['data'] assert data.shape[1] == 3072, 'Unexpected data.shape %s' % (data.shape,) count = data.shape[0] fine_labels = pickleObj['fine_labels'] assert len(fine_labels) == count, 'Expected len(fine_labels) to be %d, not %d' % (count, len(fine_labels)) coarse_labels = pickleObj['coarse_labels'] assert len(coarse_labels) == count, 'Expected len(coarse_labels) to be %d, not %d' % ( count, len(coarse_labels)) filenames = pickleObj['filenames'] assert len(filenames) == count, 'Expected len(filenames) to be %d, not %d' % (count, len(filenames)) data = data.reshape((count, 3, 32, 32)) data = data.transpose((0, 2, 3, 1)) fine_to_coarse = {} # mapping of fine labels to coarse labels fine_dirname = os.path.join(self.outdir, 'fine', phase) os.makedirs(fine_dirname) coarse_dirname = os.path.join(self.outdir, 'coarse', phase) os.makedirs(coarse_dirname) with open(os.path.join(self.outdir, 'fine', '%s.txt' % phase), 'w') as fine_textfile, \ open(os.path.join(self.outdir, 'coarse', '%s.txt' % phase), 'w') as coarse_textfile: for index, image in enumerate(data): # Create the directory fine_label = fine_label_names[fine_labels[index]] dirname = os.path.join(fine_dirname, fine_label) self.mkdir(dirname) # Get the filename filename = filenames[index] ext = os.path.splitext(filename)[1][1:].lower() if ext != self.file_extension: filename = '%s.%s' % (os.path.splitext(filename)[0], self.file_extension) filename = os.path.join(dirname, filename) # Save the image PIL.Image.fromarray(image).save(filename) fine_textfile.write('%s %s\n' % (filename, fine_labels[index])) coarse_textfile.write('%s %s\n' % (filename, coarse_labels[index])) if fine_label not in fine_to_coarse: fine_to_coarse[fine_label] = coarse_label_names[coarse_labels[index]] # Create the coarse dataset with symlinks for fine, coarse in fine_to_coarse.iteritems(): self.mkdir(os.path.join(coarse_dirname, coarse)) os.symlink( # Create relative symlinks for portability os.path.join('..', '..', '..', 'fine', phase, fine), os.path.join(coarse_dirname, coarse, fine) )
DIGITS-master
digits/download_data/cifar100.py
DIGITS-master
digits/download_data/__init__.py
# Copyright (c) 2015-2017, NVIDIA CORPORATION. All rights reserved. import cPickle import os import tarfile import PIL.Image from downloader import DataDownloader class Cifar10Downloader(DataDownloader): """ See details about the CIFAR10 dataset here: http://www.cs.toronto.edu/~kriz/cifar.html """ def urlList(self): return [ 'http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz', ] def uncompressData(self): filename = 'cifar-10-python.tar.gz' filepath = os.path.join(self.outdir, filename) assert os.path.exists(filepath), 'Expected "%s" to exist' % filename if not os.path.exists(os.path.join(self.outdir, 'cifar-10-batches-py')): print "Uncompressing file=%s ..." % filename with tarfile.open(filepath) as tf: tf.extractall(self.outdir) def processData(self): label_filename = 'batches.meta' label_filepath = os.path.join(self.outdir, 'cifar-10-batches-py', label_filename) with open(label_filepath, 'rb') as infile: pickleObj = cPickle.load(infile) label_names = pickleObj['label_names'] for phase in 'train', 'test': dirname = os.path.join(self.outdir, phase) self.mkdir(dirname, clean=True) with open(os.path.join(dirname, 'labels.txt'), 'w') as outfile: for name in label_names: outfile.write('%s\n' % name) for filename, phase in [ ('data_batch_1', 'train'), ('data_batch_2', 'train'), ('data_batch_3', 'train'), ('data_batch_4', 'train'), ('data_batch_5', 'train'), ('test_batch', 'test'), ]: filepath = os.path.join(self.outdir, 'cifar-10-batches-py', filename) assert os.path.exists(filepath), 'Expected "%s" to exist' % filename self.__extractData(filepath, phase, label_names) def __extractData(self, input_file, phase, label_names): """ Read a pickle file at input_file and output images Arguments: input_file -- the input pickle file phase -- train or test label_names -- a list of strings """ print 'Extracting images file=%s ...' % input_file # Read the pickle file with open(input_file, 'rb') as infile: pickleObj = cPickle.load(infile) # print 'Batch -', pickleObj['batch_label'] data = pickleObj['data'] assert data.shape == (10000, 3072), 'Expected data.shape to be (10000, 3072), not %s' % (data.shape,) count = data.shape[0] labels = pickleObj['labels'] assert len(labels) == count, 'Expected len(labels) to be %d, not %d' % (count, len(labels)) filenames = pickleObj['filenames'] assert len(filenames) == count, 'Expected len(filenames) to be %d, not %d' % (count, len(filenames)) data = data.reshape((10000, 3, 32, 32)) data = data.transpose((0, 2, 3, 1)) output_dir = os.path.join(self.outdir, phase) self.mkdir(output_dir) with open(os.path.join(output_dir, '%s.txt' % phase), 'a') as outfile: for index, image in enumerate(data): # Create the directory dirname = os.path.join(output_dir, label_names[labels[index]]) if not os.path.exists(dirname): os.makedirs(dirname) # Get the filename filename = filenames[index] ext = os.path.splitext(filename)[1][1:].lower() if ext != self.file_extension: filename = '%s.%s' % (os.path.splitext(filename)[0], self.file_extension) filename = os.path.join(dirname, filename) # Save the image PIL.Image.fromarray(image).save(filename) outfile.write('%s %s\n' % (filename, labels[index]))
DIGITS-master
digits/download_data/cifar10.py
# Copyright (c) 2015-2017, NVIDIA CORPORATION. All rights reserved. import argparse import sys import time from cifar10 import Cifar10Downloader from cifar100 import Cifar100Downloader from mnist import MnistDownloader if __name__ == '__main__': parser = argparse.ArgumentParser(description='Download-Data tool - DIGITS') # Positional arguments parser.add_argument('dataset', help='mnist/cifar10/cifar100' ) parser.add_argument('output_dir', help='The output directory for the data' ) # Optional arguments parser.add_argument('-c', '--clean', action='store_true', help='clean out the directory first (if it exists)' ) args = vars(parser.parse_args()) dataset = args['dataset'].lower() start = time.time() if dataset == 'mnist': d = MnistDownloader( outdir=args['output_dir'], clean=args['clean']) d.getData() elif dataset == 'cifar10': d = Cifar10Downloader( outdir=args['output_dir'], clean=args['clean']) d.getData() elif dataset == 'cifar100': d = Cifar100Downloader( outdir=args['output_dir'], clean=args['clean']) d.getData() else: print 'Unknown dataset "%s"' % args['dataset'] sys.exit(1) print 'Done after %s seconds.' % (time.time() - start)
DIGITS-master
digits/download_data/__main__.py
# Copyright (c) 2015-2017, NVIDIA CORPORATION. All rights reserved. import gzip import os import struct import numpy as np import PIL.Image from downloader import DataDownloader class MnistDownloader(DataDownloader): """ See details about the MNIST dataset here: http://yann.lecun.com/exdb/mnist/ """ def urlList(self): return [ 'http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz', 'http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz', 'http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz', 'http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz', ] def uncompressData(self): for zipped, unzipped in [ ('train-images-idx3-ubyte.gz', 'train-images.bin'), ('train-labels-idx1-ubyte.gz', 'train-labels.bin'), ('t10k-images-idx3-ubyte.gz', 'test-images.bin'), ('t10k-labels-idx1-ubyte.gz', 'test-labels.bin'), ]: zipped_path = os.path.join(self.outdir, zipped) assert os.path.exists(zipped_path), 'Expected "%s" to exist' % zipped unzipped_path = os.path.join(self.outdir, unzipped) if not os.path.exists(unzipped_path): print "Uncompressing file=%s ..." % zipped with gzip.open(zipped_path) as infile, open(unzipped_path, 'wb') as outfile: outfile.write(infile.read()) def processData(self): self.__extract_images('train-images.bin', 'train-labels.bin', 'train') self.__extract_images('test-images.bin', 'test-labels.bin', 'test') def __extract_images(self, images_file, labels_file, phase): """ Extract information from binary files and store them as images """ labels = self.__readLabels(os.path.join(self.outdir, labels_file)) images = self.__readImages(os.path.join(self.outdir, images_file)) assert len(labels) == len(images), '%d != %d' % (len(labels), len(images)) output_dir = os.path.join(self.outdir, phase) self.mkdir(output_dir, clean=True) with open(os.path.join(output_dir, 'labels.txt'), 'w') as outfile: for label in xrange(10): outfile.write('%s\n' % label) with open(os.path.join(output_dir, '%s.txt' % phase), 'w') as outfile: for index, image in enumerate(images): dirname = os.path.join(output_dir, labels[index]) self.mkdir(dirname) filename = os.path.join(dirname, '%05d.%s' % (index, self.file_extension)) image.save(filename) outfile.write('%s %s\n' % (filename, labels[index])) def __readLabels(self, filename): """ Returns a list of ints """ print 'Reading labels from %s ...' % filename labels = [] with open(filename, 'rb') as infile: infile.read(4) # ignore magic number count = struct.unpack('>i', infile.read(4))[0] data = infile.read(count) for byte in data: label = struct.unpack('>B', byte)[0] labels.append(str(label)) return labels def __readImages(self, filename): """ Returns a list of PIL.Image objects """ print 'Reading images from %s ...' % filename images = [] with open(filename, 'rb') as infile: infile.read(4) # ignore magic number count = struct.unpack('>i', infile.read(4))[0] rows = struct.unpack('>i', infile.read(4))[0] columns = struct.unpack('>i', infile.read(4))[0] for i in xrange(count): data = infile.read(rows * columns) image = np.fromstring(data, dtype=np.uint8) image = image.reshape((rows, columns)) image = 255 - image # now black digit on white background images.append(PIL.Image.fromarray(image)) return images
DIGITS-master
digits/download_data/mnist.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import from .data import * # noqa from .view import * # noqa
DIGITS-master
digits/extensions/__init__.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import class VisualizationInterface(object): """ A visualization extension """ def __init__(self, **kwargs): pass @staticmethod def get_config_form(): """ Return a form to be used to configure visualization options """ raise NotImplementedError @staticmethod def get_config_template(form): """ The config template shows a form with view config options Parameters: - form: form returned by get_config_form(). This may be populated with values if the job was cloned Returns: - (template, context) tuple - template is a Jinja template to use for rendering config options - context is a dictionary of context variables to use for rendering the form """ raise NotImplementedError @staticmethod def get_default_visibility(): """ Return whether to show extension in GUI (can be overridden through DIGITS configuration options) """ return True def get_header_template(self): """ This returns the content to be rendered at the top of the result page. This may include a summary of the job as well as utility functions and scripts to use from "view" templates. By default this method returns (None, None), an indication that there is no header to display. This method may be overridden in sub-classes to show more elaborate content. Returns: - (template, context) tuple - template is a Jinja template to use for rendering the header, or None if there is no header to display - context is a dictionary of context variables to use for rendering the form """ return None, None def get_ng_templates(self): """ This returns the angularjs content defining the app and maybe a large scope controller. By default this method returns None, an indication that there is no angular header. This method may be overridden in sub-classes to implement the app and controller. This header html protion will likely be of the form: <script> ... </script> <div ng-app="my_app"> <div ng-controller="my_controller"> and the footer needs to close any open divs: </div> </div> Returns: - (header, footer) tuple - header is the html text defining the angular app and adding the ng-app div, or None if there is no angular app defined - footer is the html text closing any open divs from the header or None if there is no angular app defined """ return None, None @staticmethod def get_id(): """ Returns a unique ID """ raise NotImplementedError @staticmethod def get_title(): """ Returns a title """ raise NotImplementedError @staticmethod def get_dirname(): """ Returns the extension's dirname for building a path to the extension's static files """ raise NotImplementedError def get_view_template(self, data): """ The view template shows the visualization of one inference output. In the case of multiple inference, this method is called once per input sample. Parameters: - data: the data returned by process_data() Returns: - (template, context) tuple - template is a Jinja template to use for rendering config options - context is a dictionary of context variables to use for rendering the form """ raise NotImplementedError def process_data( self, input_id, input_data, inference_data, ground_truth=None): """ Process one inference output Parameters: - input_id: index of input sample - input_data: input to the network - inference_data: network output - ground_truth: Ground truth. Format is application specific. None if absent. Returns: - an object reprensenting the processed data """ raise NotImplementedError
DIGITS-master
digits/extensions/view/interface.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import copy from pkg_resources import iter_entry_points from . import boundingBox from . import imageOutput from . import imageSegmentation from . import rawData # Entry point group (this is the key we use to register and # find installed plug-ins) GROUP = "digits.plugins.view" # built-in extensions builtin_view_extensions = [ boundingBox.Visualization, imageOutput.Visualization, imageSegmentation.Visualization, rawData.Visualization, ] def get_default_extension(): """ return the default view extension """ return rawData.Visualization def get_extensions(): """ return set of data data extensions """ extensions = copy.copy(builtin_view_extensions) # find installed extension plug-ins for entry_point in iter_entry_points(group=GROUP, name=None): extensions.append(entry_point.load()) return extensions def get_extension(extension_id): """ return extension associated with specified extension_id """ for extension in get_extensions(): if extension.get_id() == extension_id: return extension return None
DIGITS-master
digits/extensions/view/__init__.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import from .view import Visualization __all__ = ['Visualization']
DIGITS-master
digits/extensions/view/imageSegmentation/__init__.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import from flask_wtf import Form from digits import utils from digits.utils import subclass @subclass class ConfigForm(Form): """ A form used to display the network output as an image """ colormap = utils.forms.SelectField( 'Colormap', choices=[ ('dataset', 'From dataset'), ('paired', 'Paired (matplotlib)'), ('none', 'None (grayscale)'), ], default='dataset', tooltip='Set color map to use when displaying segmented image' )
DIGITS-master
digits/extensions/view/imageSegmentation/forms.py
"""Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved.""" from __future__ import absolute_import import json import os import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import PIL.Image import skfmm import digits from digits.utils import subclass, override from digits.utils.constants import COLOR_PALETTE_ATTRIBUTE from .forms import ConfigForm from ..interface import VisualizationInterface CONFIG_TEMPLATE = "config_template.html" HEADER_TEMPLATE = "header_template.html" APP_BEGIN_TEMPLATE = "app_begin_template.html" APP_END_TEMPLATE = "app_end_template.html" VIEW_TEMPLATE = "view_template.html" @subclass class Visualization(VisualizationInterface): """A visualization extension to display the network output as an image.""" def __init__(self, dataset, **kwargs): """Constructor for Visualization class. :param dataset: :type dataset: :param kwargs: :type kwargs: """ # memorize view template for later use extension_dir = os.path.dirname(os.path.abspath(__file__)) self.view_template = open( os.path.join(extension_dir, VIEW_TEMPLATE), "r").read() # view options if kwargs['colormap'] == 'dataset': if COLOR_PALETTE_ATTRIBUTE not in dataset.extension_userdata or \ not dataset.extension_userdata[COLOR_PALETTE_ATTRIBUTE]: raise ValueError("No palette found in dataset - choose other colormap") palette = dataset.extension_userdata[COLOR_PALETTE_ATTRIBUTE] # assume 8-bit RGB palette and convert to N*3 numpy array palette = np.array(palette).reshape((len(palette) / 3, 3)) / 255. # normalize input pixels to [0,1] norm = mpl.colors.Normalize(vmin=0, vmax=255) # create map cmap = mpl.colors.ListedColormap(palette) self.map = plt.cm.ScalarMappable(norm=norm, cmap=cmap) elif kwargs['colormap'] == 'paired': cmap = plt.cm.get_cmap('Paired') self.map = plt.cm.ScalarMappable(norm=None, cmap=cmap) elif kwargs['colormap'] == 'none': self.map = None else: raise ValueError("Unknown color map option: %s" % kwargs['colormap']) # memorize class labels if 'class_labels' in dataset.extension_userdata: self.class_labels = dataset.extension_userdata['class_labels'] else: self.class_labels = None @staticmethod def get_config_form(): """Utility function. returns: ConfigForm(). """ return ConfigForm() @staticmethod def get_config_template(form): """Get the template and context. parameters: - form: form returned by get_config_form(). This may be populated with values if the job was cloned returns: - (template, context) tuple - template is a Jinja template to use for rendering config options - context is a dictionary of context variables to use for rendering the form """ extension_dir = os.path.dirname(os.path.abspath(__file__)) template = open( os.path.join(extension_dir, CONFIG_TEMPLATE), "r").read() return (template, {'form': form}) def get_legend_for(self, found_classes, skip_classes=[]): """Return the legend color image squares and text for each class. :param found_classes: list of class indices :param skip_classes: list of class indices to skip :return: list of dicts of text hex_color for each class """ legend = [] for c in (x for x in found_classes if x not in skip_classes): # create hex color associated with the category ID if self.map: rgb_color = self.map.to_rgba([c])[0, :3] hex_color = mpl.colors.rgb2hex(rgb_color) else: # make a grey scale hex color h = hex(int(c)).split('x')[1].zfill(2) hex_color = '#%s%s%s' % (h, h, h) if self.class_labels: text = self.class_labels[int(c)] else: text = "Class #%d" % c legend.append({'index': c, 'text': text, 'hex_color': hex_color}) return legend @override def get_header_template(self): """Implement get_header_template method from view extension interface.""" extension_dir = os.path.dirname(os.path.abspath(__file__)) template = open( os.path.join(extension_dir, HEADER_TEMPLATE), "r").read() return template, {} @override def get_ng_templates(self): """Implement get_ng_templates method from view extension interface.""" extension_dir = os.path.dirname(os.path.abspath(__file__)) header = open(os.path.join(extension_dir, APP_BEGIN_TEMPLATE), "r").read() footer = open(os.path.join(extension_dir, APP_END_TEMPLATE), "r").read() return header, footer @staticmethod def get_id(): """returns: id string that identifies the extension.""" return 'image-segmentation' @staticmethod def get_title(): """returns: name string to display in html.""" return 'Image Segmentation' @staticmethod def get_dirname(): """returns: extension dir name to locate static dir.""" return 'imageSegmentation' @override def get_view_template(self, data): """Get the view template. returns: - (template, context) tuple - template is a Jinja template to use for rendering config options - context is a dictionary of context variables to use for rendering the form """ return self.view_template, { 'input_id': data['input_id'], 'input_image': digits.utils.image.embed_image_html(data['input_image']), 'fill_image': digits.utils.image.embed_image_html(data['fill_image']), 'line_image': digits.utils.image.embed_image_html(data['line_image']), 'seg_image': digits.utils.image.embed_image_html(data['seg_image']), 'mask_image': digits.utils.image.embed_image_html(data['mask_image']), 'legend': data['legend'], 'is_binary': data['is_binary'], 'class_data': json.dumps(data['class_data'].tolist()), } @override def process_data(self, input_id, input_data, output_data): """Process one inference and return data to visualize.""" # assume the only output is a CHW image where C is the number # of classes, H and W are the height and width of the image class_data = output_data[output_data.keys()[0]].astype('float32') # Is this binary segmentation? is_binary = class_data.shape[0] == 2 # retain only the top class for each pixel class_data = np.argmax(class_data, axis=0).astype('uint8') # remember the classes we found found_classes = np.unique(class_data) # convert using color map (assume 8-bit output) if self.map: fill_data = (self.map.to_rgba(class_data) * 255).astype('uint8') else: fill_data = np.ndarray((class_data.shape[0], class_data.shape[1], 4), dtype='uint8') for x in xrange(3): fill_data[:, :, x] = class_data.copy() # Assuming that class 0 is the background mask = np.greater(class_data, 0) fill_data[:, :, 3] = mask * 255 line_data = fill_data.copy() seg_data = fill_data.copy() # Black mask of non-segmented pixels mask_data = np.zeros(fill_data.shape, dtype='uint8') mask_data[:, :, 3] = (1 - mask) * 255 def normalize(array): mn = array.min() mx = array.max() return (array - mn) * 255 / (mx - mn) if (mx - mn) > 0 else array * 255 try: PIL.Image.fromarray(input_data) except TypeError: # If input_data can not be converted to an image, # normalize and convert to uint8 input_data = normalize(input_data).astype('uint8') # Generate outlines around segmented classes if len(found_classes) > 1: # Assuming that class 0 is the background. line_mask = np.zeros(class_data.shape, dtype=bool) max_distance = np.zeros(class_data.shape, dtype=float) + 1 for c in (x for x in found_classes if x != 0): c_mask = np.equal(class_data, c) # Find the signed distance from the zero contour distance = skfmm.distance(c_mask.astype('float32') - 0.5) # Accumulate the mask for all classes line_width = 3 line_mask |= c_mask & np.less(distance, line_width) max_distance = np.maximum(max_distance, distance + 128) line_data[:, :, 3] = line_mask * 255 max_distance = np.maximum(max_distance, np.zeros(max_distance.shape, dtype=float)) max_distance = np.minimum(max_distance, np.zeros(max_distance.shape, dtype=float) + 255) seg_data[:, :, 3] = max_distance # Input image with outlines input_max = input_data.max() input_min = input_data.min() input_range = input_max - input_min if input_range > 255: input_data = (input_data - input_min) * 255.0 / input_range elif input_min < 0: input_data -= input_min input_image = PIL.Image.fromarray(input_data.astype('uint8')) input_image.format = 'png' # Fill image fill_image = PIL.Image.fromarray(fill_data) fill_image.format = 'png' # Fill image line_image = PIL.Image.fromarray(line_data) line_image.format = 'png' # Seg image seg_image = PIL.Image.fromarray(seg_data) seg_image.format = 'png' seg_image.save('seg.png') # Mask image mask_image = PIL.Image.fromarray(mask_data) mask_image.format = 'png' # legend for this instance legend = self.get_legend_for(found_classes, skip_classes=[0]) return { 'input_id': input_id, 'input_image': input_image, 'fill_image': fill_image, 'line_image': line_image, 'seg_image': seg_image, 'mask_image': mask_image, 'legend': legend, 'is_binary': is_binary, 'class_data': class_data, }
DIGITS-master
digits/extensions/view/imageSegmentation/view.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import from .view import Visualization __all__ = ['Visualization']
DIGITS-master
digits/extensions/view/imageOutput/__init__.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import from flask_wtf import Form from digits import utils from digits.utils import subclass @subclass class ConfigForm(Form): """ A form used to display the network output as an image """ channel_order = utils.forms.SelectField( 'Channel order', choices=[ ('rgb', 'RGB'), ('bgr', 'BGR'), ], default='rgb', tooltip='Set channel order to BGR for Caffe networks (this field ' 'is ignored in the case of a grayscale image)' ) data_order = utils.forms.SelectField( 'Data order', choices=[ ('chw', 'CHW'), ('hwc', 'HWC'), ], default='chw', tooltip="Set the order of the data. For Caffe and Torch models this " "is often NCHW, for Tensorflow it's NHWC." "N=Batch Size, W=Width, H=Height, C=Channels" ) pixel_conversion = utils.forms.SelectField( 'Pixel conversion', choices=[ ('normalize', 'Normalize'), ('clip', 'Clip'), ], default='normalize', tooltip='Select method to convert pixel values to the target bit ' 'range' ) show_input = utils.forms.SelectField( 'Show input as image', choices=[ ('yes', 'Yes'), ('no', 'No'), ], default='no', tooltip='Show input as image' )
DIGITS-master
digits/extensions/view/imageOutput/forms.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import os import PIL.Image import PIL.ImageDraw import digits from digits.utils import subclass, override from .forms import ConfigForm from ..interface import VisualizationInterface CONFIG_TEMPLATE = "config_template.html" VIEW_TEMPLATE = "view_template.html" @subclass class Visualization(VisualizationInterface): """ A visualization extension to display the network output as an image """ def __init__(self, dataset, **kwargs): # memorize view template for later use extension_dir = os.path.dirname(os.path.abspath(__file__)) self.view_template = open( os.path.join(extension_dir, VIEW_TEMPLATE), "r").read() # view options self.channel_order = kwargs['channel_order'].upper() self.data_order = kwargs['data_order'].upper() self.normalize = (kwargs['pixel_conversion'] == 'normalize') self.show_input = (kwargs['show_input'] == 'yes') @staticmethod def get_config_form(): return ConfigForm() @staticmethod def get_config_template(form): """ parameters: - form: form returned by get_config_form(). This may be populated with values if the job was cloned returns: - (template, context) tuple - template is a Jinja template to use for rendering config options - context is a dictionary of context variables to use for rendering the form """ extension_dir = os.path.dirname(os.path.abspath(__file__)) template = open( os.path.join(extension_dir, CONFIG_TEMPLATE), "r").read() return (template, {'form': form}) @staticmethod def get_id(): return 'image-image-output' @staticmethod def get_title(): return 'Image output' @override def get_view_template(self, data): """ returns: - (template, context) tuple - template is a Jinja template to use for rendering config options - context is a dictionary of context variables to use for rendering the form """ return self.view_template, {'image_input': digits.utils.image.embed_image_html(data[0]), 'image_output': digits.utils.image.embed_image_html(data[1])} @override def process_data(self, input_id, input_data, output_data): """ Process one inference and return data to visualize """ if self.show_input: data_input = input_data.astype('float32') image_input = self.process_image(self.data_order, data_input) else: image_input = None data_output = output_data[output_data.keys()[0]].astype('float32') image_output = self.process_image(self.data_order, data_output) return [image_input, image_output] def process_image(self, data_order, data): if data_order == 'HWC': data = (data.transpose((2, 0, 1))) # assume CHW at this point channels = data.shape[0] if channels == 3 and self.channel_order == 'BGR': data = data[[2, 1, 0], ...] # BGR to RGB # convert to HWC data = data.transpose((1, 2, 0)) # assume 8-bit if self.normalize: data -= data.min() if data.max() > 0: data /= data.max() data *= 255 else: # clip data = data.clip(0, 255) # convert to uint8 data = data.astype('uint8') # convert to PIL image if channels == 1: # drop channel axis image = PIL.Image.fromarray(data[:, :, 0]) elif channels == 3: image = PIL.Image.fromarray(data) else: raise ValueError("Unhandled number of channels: %d" % channels) return image
DIGITS-master
digits/extensions/view/imageOutput/view.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import from .view import Visualization __all__ = ['Visualization']
DIGITS-master
digits/extensions/view/boundingBox/__init__.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import from digits.utils import subclass from flask_wtf import Form @subclass class ConfigForm(Form): pass
DIGITS-master
digits/extensions/view/boundingBox/forms.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import os import PIL.Image import digits from digits.utils import subclass, override from .forms import ConfigForm from ..interface import VisualizationInterface CONFIG_TEMPLATE = "config_template.html" HEADER_TEMPLATE = "header_template.html" APP_BEGIN_TEMPLATE = "app_begin_template.html" APP_END_TEMPLATE = "app_end_template.html" VIEW_TEMPLATE = "view_template.html" @subclass class Visualization(VisualizationInterface): """ A visualization extension to display bounding boxes """ def __init__(self, dataset, **kwargs): # memorize view template for later use extension_dir = os.path.dirname(os.path.abspath(__file__)) self.view_template = open( os.path.join(extension_dir, VIEW_TEMPLATE), "r").read() # stats self.image_count = 0 self.bbox_count = 0 @staticmethod def get_config_form(): return ConfigForm() @staticmethod def get_config_template(form): """ parameters: - form: form returned by get_config_form(). This may be populated with values if the job was cloned returns: - (template, context) tuple - template is a Jinja template to use for rendering config options - context is a dictionary of context variables to use for rendering the form """ extension_dir = os.path.dirname(os.path.abspath(__file__)) template = open( os.path.join(extension_dir, CONFIG_TEMPLATE), "r").read() context = {'form': form} return (template, context) @override def get_header_template(self): """ Implements get_header_template() method from view extension interface """ extension_dir = os.path.dirname(os.path.abspath(__file__)) template = open( os.path.join(extension_dir, HEADER_TEMPLATE), "r").read() return template, {'image_count': self.image_count, 'bbox_count': self.bbox_count} @override def get_ng_templates(self): """ Implements get_ng_templates() method from view extension interface """ extension_dir = os.path.dirname(os.path.abspath(__file__)) header = open(os.path.join(extension_dir, APP_BEGIN_TEMPLATE), "r").read() footer = open(os.path.join(extension_dir, APP_END_TEMPLATE), "r").read() return header, footer @staticmethod def get_id(): return 'image-bounding-boxes' @staticmethod def get_title(): return 'Bounding boxes' @override def get_view_template(self, data): """ return: - (template, context) tuple - template is a Jinja template to use for rendering config options - context is a dictionary of context variables to use for rendering the form """ return self.view_template, { 'image': data['image'], 'bboxes': data['bboxes'], 'index': data['index'], } @override def process_data( self, input_id, input_data, inference_data, ground_truth=None): """ Process one inference output """ # get source image image = PIL.Image.fromarray(input_data).convert('RGB') self.image_count += 1 # create arrays in expected format keys = inference_data.keys() bboxes = dict(zip(keys, [[] for x in range(0, len(keys))])) for key, outputs in inference_data.items(): # last number is confidence bboxes[key] = [list(o) for o in outputs if o[-1] > 0] self.bbox_count += len(bboxes[key]) image_html = digits.utils.image.embed_image_html(image) return { 'image': image_html, 'bboxes': bboxes, 'index': self.image_count, }
DIGITS-master
digits/extensions/view/boundingBox/view.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import from .view import Visualization __all__ = ['Visualization']
DIGITS-master
digits/extensions/view/rawData/__init__.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import from digits.utils import subclass from flask_wtf import Form @subclass class ConfigForm(Form): pass
DIGITS-master
digits/extensions/view/rawData/forms.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import os from digits.utils import subclass, override from .forms import ConfigForm from ..interface import VisualizationInterface CONFIG_TEMPLATE = "config_template.html" VIEW_TEMPLATE = "view_template.html" @subclass class Visualization(VisualizationInterface): """ A visualization extension to display raw data """ def __init__(self, dataset, **kwargs): # memorize view template for later use extension_dir = os.path.dirname(os.path.abspath(__file__)) self.view_template = open( os.path.join(extension_dir, VIEW_TEMPLATE), "r").read() @staticmethod def get_config_form(): return ConfigForm() @staticmethod def get_config_template(form): """ parameters: - form: form returned by get_config_form(). This may be populated with values if the job was cloned return: - (template, context) tuple - template is a Jinja template to use for rendering config options - context is a dictionary of context variables to use for rendering the form """ extension_dir = os.path.dirname(os.path.abspath(__file__)) template = open( os.path.join(extension_dir, CONFIG_TEMPLATE), "r").read() return (template, {}) @staticmethod def get_id(): return 'all-raw-data' @staticmethod def get_title(): return 'Raw Data' @override def get_view_template(self, data): """ return: - (template, context) tuple - template is a Jinja template to use for rendering config options - context is a dictionary of context variables to use for rendering the form """ return self.view_template, {'data': data} @override def process_data( self, input_id, input_data, inference_data, ground_truth=None): """ Process one inference output """ # just return the same data and ignore ground truth return inference_data
DIGITS-master
digits/extensions/view/rawData/view.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import class DataIngestionInterface(object): """ A data ingestion extension """ def __init__(self, is_inference_db=False, **kwargs): """ Initialize the data ingestion extension Parameters: - is_inference_db: boolean value, indicates whether the database is created for inference. If this is true then the extension needs to use the data from the inference form and create a database only for the test phase (stage == constants.TEST_DB) - kwargs: dataset form fields """ # save all data there - no other fields will be persisted self.userdata = kwargs # populate instance from userdata dictionary for k, v in self.userdata.items(): setattr(self, k, v) def encode_entry(self, entry): """ Encode the entry associated with specified ID (returned by itemize_entries()) Returns a list of (feature, label) tuples, or a single tuple if there is only one sample for the entry. Data are expected in HWC format Color images are expected in RGB order """ raise NotImplementedError @staticmethod def get_category(): raise NotImplementedError @staticmethod def get_dataset_form(): """ Return a Form object with all fields required to create the dataset """ raise NotImplementedError @staticmethod def get_dataset_template(form): """ Parameters: - form: form returned by get_dataset_form(). This may be populated with values if the job was cloned return: - (template, context) tuple - template is a Jinja template to use for rendering dataset creation options - context is a dictionary of context variables to use for rendering the form """ raise NotImplementedError @staticmethod def get_id(): """ Return unique ID """ raise NotImplementedError def get_inference_form(self): """ Return a Form object with all fields required to create an inference dataset """ return None @staticmethod def get_inference_template(form): """ Parameters: - form: form returned by get_inference_form(). return: - (template, context) tuple - template is a Jinja template to use for rendering the inference form - context is a dictionary of context variables to use for rendering the form """ return (None, None) @staticmethod def get_title(): """ Return get_title """ raise NotImplementedError def get_user_data(self): """ Return serializable user data The data will be persisted as part of the dataset job data """ return self.userdata def itemize_entries(self, stage): """ Return a list of entry IDs to encode This function is called on the main thread The returned list will be spread across all reader threads Reader threads will call encode_entry() with IDs returned by this function in no particular order """ raise NotImplementedError
DIGITS-master
digits/extensions/data/interface.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import copy from pkg_resources import iter_entry_points from . import imageProcessing from . import imageSegmentation from . import objectDetection # Entry point group (this is the key we use to register and # find installed plug-ins) GROUP = "digits.plugins.data" # built-in extensions builtin_data_extensions = [ imageProcessing.DataIngestion, imageSegmentation.DataIngestion, objectDetection.DataIngestion, ] def get_extensions(): """ return set of data data extensions """ extensions = copy.copy(builtin_data_extensions) # find installed extension plug-ins for entry_point in iter_entry_points(group=GROUP, name=None): extensions.append(entry_point.load()) return extensions def get_extension(extension_id): """ return extension associated with specified extension_id """ for extension in get_extensions(): if extension.get_id() == extension_id: return extension return None
DIGITS-master
digits/extensions/data/__init__.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import from .data import DataIngestion __all__ = ['DataIngestion']
DIGITS-master
digits/extensions/data/imageSegmentation/__init__.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import os from flask_wtf import Form from wtforms import validators from digits import utils from digits.utils import subclass from digits.utils.forms import validate_required_iff @subclass class DatasetForm(Form): """ A form used to create an image processing dataset """ def validate_folder_path(form, field): if not field.data: pass else: # make sure the filesystem path exists if not os.path.exists(field.data) or not os.path.isdir(field.data): raise validators.ValidationError( 'Folder does not exist or is not reachable') else: return True def validate_file_path(form, field): if not field.data: pass else: # make sure the filesystem path exists if not os.path.exists(field.data) and not os.path.isdir(field.data): raise validators.ValidationError( 'File does not exist or is not reachable') else: return True feature_folder = utils.forms.StringField( u'Feature image folder', validators=[ validators.DataRequired(), validate_folder_path, ], tooltip="Indicate a folder full of images." ) label_folder = utils.forms.StringField( u'Label image folder', validators=[ validators.DataRequired(), validate_folder_path, ], tooltip="Indicate a folder full of images. For each image in the feature" " image folder there must be one corresponding image in the label" " image folder. The label image must have the same filename except" " for the extension, which may differ. Label images are expected" " to be single-channel images (paletted or grayscale), or RGB" " images, in which case the color/class mappings need to be" " specified through a separate text file." ) folder_pct_val = utils.forms.IntegerField( u'% for validation', default=10, validators=[ validators.NumberRange(min=0, max=100) ], tooltip="You can choose to set apart a certain percentage of images " "from the training images for the validation set." ) has_val_folder = utils.forms.BooleanField('Separate validation images', default=False, ) validation_feature_folder = utils.forms.StringField( u'Validation feature image folder', validators=[ validate_required_iff(has_val_folder=True), validate_folder_path, ], tooltip="Indicate a folder full of images." ) validation_label_folder = utils.forms.StringField( u'Validation label image folder', validators=[ validate_required_iff(has_val_folder=True), validate_folder_path, ], tooltip="Indicate a folder full of images. For each image in the feature" " image folder there must be one corresponding image in the label" " image folder. The label image must have the same filename except" " for the extension, which may differ. Label images are expected" " to be single-channel images (paletted or grayscale), or RGB" " images, in which case the color/class mappings need to be" " specified through a separate text file." ) channel_conversion = utils.forms.SelectField( 'Channel conversion', choices=[ ('RGB', 'RGB'), ('L', 'Grayscale'), ('none', 'None'), ], default='none', tooltip="Perform selected channel conversion on feature images. Label" " images are single channel and not affected by this parameter." ) class_labels_file = utils.forms.StringField( u'Class labels (optional)', validators=[ validate_file_path, ], tooltip="The 'i'th line of the file should give the string label " "associated with the '(i-1)'th numeric label. (E.g. the " "string label for the numeric label 0 is supposed to be " "on line 1.)" ) colormap_method = utils.forms.SelectField( 'Color map specification', choices=[ ('label', 'From label image'), ('textfile', 'From text file'), ], default='label', tooltip="Specify how to map class IDs to colors. Select 'From label " "image' to use palette or grayscale from label images. For " "RGB image labels, select 'From text file' and provide " "color map in separate text file." ) colormap_text_file = utils.forms.StringField( 'Color map file', validators=[ validate_required_iff(colormap_method="textfile"), validate_file_path, ], tooltip="Specify color/class mappings through a text file. " "Each line in the file should contain three space-separated " "integer values, one for each of the Red, Green, Blue " "channels. The 'i'th line of the file should give the color " "associated with the '(i-1)'th class. (E.g. the " "color for class #0 is supposed to be on line 1.)" )
DIGITS-master
digits/extensions/data/imageSegmentation/forms.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import math import os import random import numpy as np import PIL.Image import PIL.ImagePalette from digits.utils import image, subclass, override, constants from digits.utils.constants import COLOR_PALETTE_ATTRIBUTE from ..interface import DataIngestionInterface from .forms import DatasetForm TEMPLATE = "template.html" @subclass class DataIngestion(DataIngestionInterface): """ A data ingestion extension for an image segmentation dataset """ def __init__(self, **kwargs): """ the parent __init__ method automatically populates this instance with attributes from the form """ super(DataIngestion, self).__init__(**kwargs) self.random_indices = None if 'seed' not in self.userdata: # choose random seed and add to userdata so it gets persisted self.userdata['seed'] = random.randint(0, 1000) if 'colormap_method' not in self.userdata: self.userdata['colormap_method'] = 'label' random.seed(self.userdata['seed']) if self.userdata['colormap_method'] == "label": # open first image in label folder to retrieve palette # all label images must use the same palette - this is enforced # during dataset creation filename = self.make_image_list(self.label_folder)[0] image = self.load_label(filename) self.userdata[COLOR_PALETTE_ATTRIBUTE] = image.getpalette() else: # read colormap from file with open(self.colormap_text_file) as f: palette = [] lines = f.read().splitlines() for line in lines: for val in line.split(): try: palette.append(int(val)) except: raise ValueError("Your color map file seems to " "be badly formatted: '%s' is not " "an integer" % val) # fill rest with zeros palette = palette + [0] * (256 * 3 - len(palette)) self.userdata[COLOR_PALETTE_ATTRIBUTE] = palette self.palette_img = PIL.Image.new("P", (1, 1)) self.palette_img.putpalette(palette) # get labels if those were provided if self.class_labels_file: with open(self.class_labels_file) as f: self.userdata['class_labels'] = f.read().splitlines() @override def encode_entry(self, entry): """ Return numpy.ndarray """ feature_image_file = entry[0] label_image_file = entry[1] # feature image feature_image = self.encode_PIL_Image( image.load_image(feature_image_file), self.channel_conversion) # label image label_image = self.load_label(label_image_file) if label_image.getpalette() != self.userdata[COLOR_PALETTE_ATTRIBUTE]: raise ValueError("All label images must use the same palette") label_image = self.encode_PIL_Image(label_image) return feature_image, label_image def encode_PIL_Image(self, image, channel_conversion='none'): if channel_conversion != 'none': if image.mode != channel_conversion: # convert to different image mode if necessary image = image.convert(channel_conversion) # convert to numpy array image = np.array(image) # add channel axis if input is grayscale image if image.ndim == 2: image = image[..., np.newaxis] elif image.ndim != 3: raise ValueError("Unhandled number of channels: %d" % image.ndim) # transpose to CHW image = image.transpose(2, 0, 1) return image @staticmethod @override def get_category(): return "Images" @staticmethod @override def get_id(): return "image-segmentation" @staticmethod @override def get_dataset_form(): return DatasetForm() @staticmethod @override def get_dataset_template(form): """ parameters: - form: form returned by get_dataset_form(). This may be populated with values if the job was cloned returns: - (template, context) tuple - template is a Jinja template to use for rendering dataset creation options - context is a dictionary of context variables to use for rendering the form """ extension_dir = os.path.dirname(os.path.abspath(__file__)) template = open(os.path.join(extension_dir, TEMPLATE), "r").read() context = {'form': form} return (template, context) @staticmethod @override def get_title(): return "Segmentation" @override def itemize_entries(self, stage): if stage == constants.TEST_DB: # don't retun anything for the test stage return [] if stage == constants.TRAIN_DB or (not self.has_val_folder): feature_image_list = self.make_image_list(self.feature_folder) label_image_list = self.make_image_list(self.label_folder) else: # separate validation images feature_image_list = self.make_image_list(self.validation_feature_folder) label_image_list = self.make_image_list(self.validation_label_folder) # make sure filenames match if len(feature_image_list) != len(label_image_list): raise ValueError( "Expect same number of images in feature and label folders (%d!=%d)" % (len(feature_image_list), len(label_image_list))) for idx in range(len(feature_image_list)): feature_name = os.path.splitext( os.path.split(feature_image_list[idx])[1])[0] label_name = os.path.splitext( os.path.split(label_image_list[idx])[1])[0] if feature_name != label_name: raise ValueError("No corresponding feature/label pair found for (%s,%s)" % (feature_name, label_name)) # split lists if there is no val folder if not self.has_val_folder: feature_image_list = self.split_image_list(feature_image_list, stage) label_image_list = self.split_image_list(label_image_list, stage) return zip( feature_image_list, label_image_list) def load_label(self, filename): """ Load a label image """ image = PIL.Image.open(filename) if self.userdata['colormap_method'] == "label": if image.mode not in ['P', 'L', '1']: raise ValueError("Labels are expected to be single-channel (paletted or " " grayscale) images - %s mode is '%s'. If your labels are " "RGB images then set the 'Color Map Specification' field " "to 'from text file' and provide a color map text file." % (filename, image.mode)) else: if image.mode not in ['RGB']: raise ValueError("Labels are expected to be RGB images - %s mode is '%s'. " "If your labels are palette or grayscale images then set " "the 'Color Map Specification' field to 'from label image'." % (filename, image.mode)) image = image.quantize(palette=self.palette_img) return image def make_image_list(self, folder): image_files = [] for dirpath, dirnames, filenames in os.walk(folder, followlinks=True): for filename in filenames: if filename.lower().endswith(image.SUPPORTED_EXTENSIONS): image_files.append('%s' % os.path.join(dirpath, filename)) if len(image_files) == 0: raise ValueError("Unable to find supported images in %s" % folder) return sorted(image_files) def split_image_list(self, filelist, stage): if self.random_indices is None: self.random_indices = range(len(filelist)) random.shuffle(self.random_indices) elif len(filelist) != len(self.random_indices): raise ValueError( "Expect same number of images in folders (%d!=%d)" % (len(filelist), len(self.random_indices))) filelist = [filelist[idx] for idx in self.random_indices] pct_val = int(self.folder_pct_val) n_val_entries = int(math.floor(len(filelist) * pct_val / 100)) if stage == constants.VAL_DB: return filelist[:n_val_entries] elif stage == constants.TRAIN_DB: return filelist[n_val_entries:] else: raise ValueError("Unknown stage: %s" % stage)
DIGITS-master
digits/extensions/data/imageSegmentation/data.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import from .data import DataIngestion __all__ = ['DataIngestion']
DIGITS-master
digits/extensions/data/objectDetection/__init__.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import from flask_wtf import Form import os from wtforms import validators from digits import utils from digits.utils import subclass from digits.utils.forms import validate_required_if_set @subclass class DatasetForm(Form): """ A form used to create an image processing dataset """ def validate_folder_path(form, field): if not field.data: pass else: # make sure the filesystem path exists if not os.path.exists(field.data) or not os.path.isdir(field.data): raise validators.ValidationError('Folder does not exist or is not reachable') else: return True train_image_folder = utils.forms.StringField( u'Training image folder', validators=[ validators.DataRequired(), validate_folder_path, ], tooltip="Indicate a folder of images to use for training" ) train_label_folder = utils.forms.StringField( u'Training label folder', validators=[ validators.DataRequired(), validate_folder_path, ], tooltip="Indicate a folder of training labels" ) val_image_folder = utils.forms.StringField( u'Validation image folder', validators=[ validate_required_if_set('val_label_folder'), validate_folder_path, ], tooltip="Indicate a folder of images to use for training" ) val_label_folder = utils.forms.StringField( u'Validation label folder', validators=[ validate_required_if_set('val_image_folder'), validate_folder_path, ], tooltip="Indicate a folder of validation labels" ) resize_image_width = utils.forms.IntegerField( u'Resize Image Width', validators=[ validate_required_if_set('resize_image_height'), validators.NumberRange(min=1), ], tooltip="If specified, images will be resized to that dimension after padding" ) resize_image_height = utils.forms.IntegerField( u'Resize Image Height', validators=[ validate_required_if_set('resize_image_width'), validators.NumberRange(min=1), ], tooltip="If specified, images will be resized to that dimension after padding" ) padding_image_width = utils.forms.IntegerField( u'Padding Image Width', default=1248, validators=[ validate_required_if_set('padding_image_height'), validators.NumberRange(min=1), ], tooltip="If specified, images will be padded to that dimension" ) padding_image_height = utils.forms.IntegerField( u'Padding Image Height', default=384, validators=[ validate_required_if_set('padding_image_width'), validators.NumberRange(min=1), ], tooltip="If specified, images will be padded to that dimension" ) channel_conversion = utils.forms.SelectField( u'Channel conversion', choices=[ ('RGB', 'RGB'), ('L', 'Grayscale'), ('none', 'None'), ], default='RGB', tooltip="Perform selected channel conversion." ) val_min_box_size = utils.forms.IntegerField( u'Minimum box size (in pixels) for validation set', default='25', validators=[ validators.InputRequired(), validators.NumberRange(min=0), ], tooltip="Retain only the boxes that are larger than the specified " "value in both dimensions. This only affects objects in " "the validation set. Enter 0 to disable this threshold." ) custom_classes = utils.forms.StringField( u'Custom classes', validators=[ validators.Optional(), ], tooltip="Enter a comma-separated list of class names. " "Class IDs are assigned sequentially, starting from 0. " "Unmapped class names automatically map to 0. " "Leave this field blank to use default class mappings. " "See object detection extension documentation for more " "information." )
DIGITS-master
digits/extensions/data/objectDetection/forms.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. import csv import os import numpy as np import PIL.Image class ObjectType: Dontcare, Car, Van, Truck, Bus, Pickup, VehicleWithTrailer, SpecialVehicle,\ Person, Person_fa, Person_unsure, People, Cyclist, Tram, Person_Sitting,\ Misc = range(16) def __init__(self): pass class Bbox: def __init__(self, x_left=0, y_top=0, x_right=0, y_bottom=0): self.xl = x_left self.yt = y_top self.xr = x_right self.yb = y_bottom def area(self): return (self.xr - self.xl) * (self.yb - self.yt) def width(self): return self.xr - self.xl def height(self): return self.yb - self.yt def get_array(self): return [self.xl, self.yt, self.xr, self.yb] class GroundTruthObj: """ This class is the data ground-truth #Values Name Description ---------------------------------------------------------------------------- 1 type Class ID 1 truncated Float from 0 (non-truncated) to 1 (truncated), where truncated refers to the object leaving image boundaries. -1 corresponds to a don't care region. 1 occluded Integer (-1,0,1,2) indicating occlusion state: -1 = unknown, 0 = fully visible, 1 = partly occluded, 2 = largely occluded 1 alpha Observation angle of object, ranging [-pi..pi] 4 bbox 2D bounding box of object in the image (0-based index): contains left, top, right, bottom pixel coordinates 3 dimensions 3D object dimensions: height, width, length (in meters) 3 location 3D object location x,y,z in camera coordinates (in meters) 1 rotation_y Rotation ry around Y-axis in camera coordinates [-pi..pi] 1 score Only for results: Float, indicating confidence in detection, needed for p/r curves, higher is better. Here, 'DontCare' labels denote regions in which objects have not been labeled, for example because they have been too far away from the laser scanner. """ # default class mappings OBJECT_TYPES = { 'bus': ObjectType.Bus, 'car': ObjectType.Car, 'cyclist': ObjectType.Cyclist, 'pedestrian': ObjectType.Person, 'people': ObjectType.People, 'person': ObjectType.Person, 'person_sitting': ObjectType.Person_Sitting, 'person-fa': ObjectType.Person_fa, 'person?': ObjectType.Person_unsure, 'pickup': ObjectType.Pickup, 'misc': ObjectType.Misc, 'special-vehicle': ObjectType.SpecialVehicle, 'tram': ObjectType.Tram, 'truck': ObjectType.Truck, 'van': ObjectType.Van, 'vehicle-with-trailer': ObjectType.VehicleWithTrailer} def __init__(self): self.stype = '' self.truncated = 0 self.occlusion = 0 self.angle = 0 self.height = 0 self.width = 0 self.length = 0 self.locx = 0 self.locy = 0 self.locz = 0 self.roty = 0 self.bbox = Bbox() self.object = ObjectType.Dontcare @classmethod def lmdb_format_length(cls): """ width of an LMDB datafield returned by the gt_to_lmdb_format function. :return: """ return 16 def gt_to_lmdb_format(self): """ For storage of a bbox ground truth object into a float32 LMDB. Sort-by attribute is always the last value in the array. """ result = [ # bbox in x,y,w,h format: self.bbox.xl, self.bbox.yt, self.bbox.xr - self.bbox.xl, self.bbox.yb - self.bbox.yt, # alpha angle: self.angle, # class number: self.object, 0, # Y axis rotation: self.roty, # bounding box attributes: self.truncated, self.occlusion, # object dimensions: self.length, self.width, self.height, self.locx, self.locy, # depth (sort-by attribute): self.locz, ] assert(len(result) is self.lmdb_format_length()) return result def set_type(self): self.object = self.OBJECT_TYPES.get(self.stype, ObjectType.Dontcare) class GroundTruth: """ this class loads the ground truth """ def __init__(self, label_dir, label_ext='.txt', label_delimiter=' ', min_box_size=None, class_mappings=None): self.label_dir = label_dir self.label_ext = label_ext # extension of label files self.label_delimiter = label_delimiter # space is used as delimiter in label files self._objects_all = dict() # positive bboxes across images self.min_box_size = min_box_size if class_mappings is not None: GroundTruthObj.OBJECT_TYPES = class_mappings def update_objects_all(self, _key, _bboxes): if _bboxes: self._objects_all[_key] = _bboxes else: self._objects_all[_key] = [] def load_gt_obj(self): """ load bbox ground truth from files either via the provided label directory or list of label files""" files = os.listdir(self.label_dir) files = filter(lambda x: x.endswith(self.label_ext), files) if len(files) == 0: raise RuntimeError('error: no label files found in %s' % self.label_dir) for label_file in files: objects_per_image = list() with open(os.path.join(self.label_dir, label_file), 'rb') as flabel: for row in csv.reader(flabel, delimiter=self.label_delimiter): if len(row) == 0: # This can happen when you open an empty file continue if len(row) < 15: raise ValueError('Invalid label format in "%s"' % os.path.join(self.label_dir, label_file)) # load data gt = GroundTruthObj() gt.stype = row[0].lower() gt.truncated = float(row[1]) gt.occlusion = int(row[2]) gt.angle = float(row[3]) gt.bbox.xl = float(row[4]) gt.bbox.yt = float(row[5]) gt.bbox.xr = float(row[6]) gt.bbox.yb = float(row[7]) gt.height = float(row[8]) gt.width = float(row[9]) gt.length = float(row[10]) gt.locx = float(row[11]) gt.locy = float(row[12]) gt.locz = float(row[13]) gt.roty = float(row[14]) gt.set_type() box_dimensions = [gt.bbox.xr - gt.bbox.xl, gt.bbox.yb - gt.bbox.yt] if self.min_box_size is not None: if not all(x >= self.min_box_size for x in box_dimensions): # object is smaller than threshold => set to "DontCare" gt.stype = '' gt.object = ObjectType.Dontcare objects_per_image.append(gt) key = os.path.splitext(label_file)[0] self.update_objects_all(key, objects_per_image) @property def objects_all(self): return self._objects_all # return the # of pixels remaining in a def pad_bbox(arr, max_bboxes=64, bbox_width=16): if arr.shape[0] > max_bboxes: raise ValueError( 'Too many bounding boxes (%d > %d)' % arr.shape[0], max_bboxes ) # fill remainder with zeroes: data = np.zeros((max_bboxes + 1, bbox_width), dtype='float') # number of bounding boxes: data[0][0] = arr.shape[0] # width of a bounding box: data[0][1] = bbox_width # bounding box data. Merge nothing if no bounding boxes exist. if arr.shape[0] > 0: data[1:1 + arr.shape[0]] = arr return data def bbox_to_array(arr, label=0, max_bboxes=64, bbox_width=16): """ Converts a 1-dimensional bbox array to an image-like 3-dimensional array CHW array """ arr = pad_bbox(arr, max_bboxes, bbox_width) return arr[np.newaxis, :, :] def bbox_overlap(abox, bbox): # the abox box x11 = abox[0] y11 = abox[1] x12 = abox[0] + abox[2] - 1 y12 = abox[1] + abox[3] - 1 # the closer box x21 = bbox[0] y21 = bbox[1] x22 = bbox[0] + bbox[2] - 1 y22 = bbox[1] + bbox[3] - 1 overlap_box_x2 = min(x12, x22) overlap_box_x1 = max(x11, x21) overlap_box_y2 = min(y12, y22) overlap_box_y1 = max(y11, y21) # make sure we preserve any non-bbox components overlap_box = list(bbox) overlap_box[0] = overlap_box_x1 overlap_box[1] = overlap_box_y1 overlap_box[2] = overlap_box_x2 - overlap_box_x1 + 1 overlap_box[3] = overlap_box_y2 - overlap_box_y1 + 1 xoverlap = max(0, overlap_box_x2 - overlap_box_x1) yoverlap = max(0, overlap_box_y2 - overlap_box_y1) overlap_pix = xoverlap * yoverlap return overlap_pix, overlap_box def pad_image(img, padding_image_height, padding_image_width): """ pad a single image to the specified dimensions """ src_width = img.size[0] src_height = img.size[1] if padding_image_width < src_width: raise ValueError("Source image width %d is greater than padding width %d" % (src_width, padding_image_width)) if padding_image_height < src_height: raise ValueError("Source image height %d is greater than padding height %d" % (src_height, padding_image_height)) padded_img = PIL.Image.new( img.mode, (padding_image_width, padding_image_height), "black") padded_img.paste(img, (0, 0)) # copy to top-left corner return padded_img def resize_bbox_list(bboxlist, rescale_x=1, rescale_y=1): # this is expecting x1,y1,w,h: bboxListNew = [] for bbox in bboxlist: abox = bbox abox[0] *= rescale_x abox[1] *= rescale_y abox[2] *= rescale_x abox[3] *= rescale_y bboxListNew.append(abox) return bboxListNew
DIGITS-master
digits/extensions/data/objectDetection/utils.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import csv import operator import os import random import StringIO import numpy as np import digits from digits.utils import subclass, override, constants from ..interface import DataIngestionInterface from .forms import DatasetForm from .utils import GroundTruth, GroundTruthObj from .utils import bbox_to_array, pad_image, resize_bbox_list TEMPLATE = "template.html" @subclass class DataIngestion(DataIngestionInterface): """ A data ingestion extension for an object detection dataset """ def __init__(self, **kwargs): super(DataIngestion, self).__init__(**kwargs) # this instance is automatically populated with form field # attributes by superclass constructor if hasattr(self, 'custom_classes') and self.custom_classes != '': s = StringIO.StringIO(self.custom_classes) reader = csv.reader(s) self.class_mappings = {} for idx, name in enumerate(reader.next()): self.class_mappings[name.strip().lower()] = idx else: self.class_mappings = None # this will be set when we know the phase we are encoding self.ground_truth = None @override def encode_entry(self, entry): """ Return numpy.ndarray """ image_filename = entry # (1) image part # load from file (this returns a PIL image) img = digits.utils.image.load_image(image_filename) if self.channel_conversion != 'none': if img.mode != self.channel_conversion: # convert to different image mode if necessary img = img.convert(self.channel_conversion) # note: the form validator ensured that either none # or both width/height were specified if self.padding_image_width: # pad image img = pad_image( img, self.padding_image_height, self.padding_image_width) if self.resize_image_width is not None: resize_ratio_x = float(self.resize_image_width) / img.size[0] resize_ratio_y = float(self.resize_image_height) / img.size[1] # resize and convert to numpy HWC img = digits.utils.image.resize_image( img, self.resize_image_height, self.resize_image_width) else: resize_ratio_x = 1 resize_ratio_y = 1 # convert to numpy array img = np.array(img) if img.ndim == 2: # grayscale img = img[np.newaxis, :, :] if img.dtype == 'uint16': img = img.astype(float) else: if img.ndim != 3 or img.shape[2] != 3: raise ValueError("Unsupported image shape: %s" % repr(img.shape)) # HWC -> CHW img = img.transpose(2, 0, 1) # (2) label part # make sure label exists label_id = os.path.splitext(os.path.basename(entry))[0] if label_id not in self.datasrc_annotation_dict: raise ValueError("Label key %s not found in label folder" % label_id) annotations = self.datasrc_annotation_dict[label_id] # collect bbox list into bboxList bboxList = [] for bbox in annotations: # retrieve all vars defining groundtruth, and interpret all # serialized values as float32s: np_bbox = np.array(bbox.gt_to_lmdb_format()) bboxList.append(np_bbox) bboxList = sorted( bboxList, key=operator.itemgetter(GroundTruthObj.lmdb_format_length() - 1) ) bboxList.reverse() # adjust bboxes according to image cropping bboxList = resize_bbox_list(bboxList, resize_ratio_x, resize_ratio_y) # return data feature = img label = np.asarray(bboxList) # LMDB compaction: now label (aka bbox) is the joint array label = bbox_to_array( label, 0, max_bboxes=self.max_bboxes, bbox_width=GroundTruthObj.lmdb_format_length()) return feature, label @staticmethod @override def get_category(): return "Images" @staticmethod @override def get_id(): return "image-object-detection" @staticmethod @override def get_dataset_form(): return DatasetForm() @staticmethod @override def get_dataset_template(form): """ parameters: - form: form returned by get_dataset_form(). This may be populated with values if the job was cloned return: - (template, context) tuple template is a Jinja template to use for rendering dataset creation options context is a dictionary of context variables to use for rendering the form """ extension_dir = os.path.dirname(os.path.abspath(__file__)) template = open(os.path.join(extension_dir, TEMPLATE), "r").read() context = {'form': form} return (template, context) @staticmethod @override def get_title(): return "Object Detection" @override def itemize_entries(self, stage): """ return list of image file names to encode for specified stage """ if stage == constants.TEST_DB: # don't retun anything for the test stage return [] elif stage == constants.TRAIN_DB: # load ground truth self.load_ground_truth(self.train_label_folder) # get training image file names return self.make_image_list(self.train_image_folder) elif stage == constants.VAL_DB: if self.val_image_folder != '': # load ground truth self.load_ground_truth( self.val_label_folder, self.val_min_box_size) # get validation image file names return self.make_image_list(self.val_image_folder) else: # no validation folder was specified return [] else: raise ValueError("Unknown stage: %s" % stage) def load_ground_truth(self, folder, min_box_size=None): """ load ground truth from specified folder """ datasrc = GroundTruth( folder, min_box_size=min_box_size, class_mappings=self.class_mappings) datasrc.load_gt_obj() self.datasrc_annotation_dict = datasrc.objects_all scene_files = [] for key in self.datasrc_annotation_dict: scene_files.append(key) # determine largest label height: self.max_bboxes = max([len(annotation) for annotation in self.datasrc_annotation_dict.values()]) def make_image_list(self, folder): """ find all supported images within specified folder and return list of file names """ image_files = [] for dirpath, dirnames, filenames in os.walk(folder, followlinks=True): for filename in filenames: if filename.lower().endswith(digits.utils.image.SUPPORTED_EXTENSIONS): image_files.append('%s' % os.path.join(dirpath, filename)) if len(image_files) == 0: raise ValueError("Unable to find supported images in %s" % folder) # shuffle random.shuffle(image_files) return image_files
DIGITS-master
digits/extensions/data/objectDetection/data.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import from .data import DataIngestion __all__ = ['DataIngestion']
DIGITS-master
digits/extensions/data/imageProcessing/__init__.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import os from flask_wtf import Form from wtforms import validators from digits import utils from digits.utils import subclass from digits.utils.forms import validate_required_iff @subclass class DatasetForm(Form): """ A form used to create an image processing dataset """ def validate_folder_path(form, field): if not field.data: pass else: # make sure the filesystem path exists if not os.path.exists(field.data) or not os.path.isdir(field.data): raise validators.ValidationError( 'Folder does not exist or is not reachable') else: return True feature_folder = utils.forms.StringField( u'Feature image folder', validators=[ validators.DataRequired(), validate_folder_path, ], tooltip="Indicate a folder full of images." ) label_folder = utils.forms.StringField( u'Label image folder', validators=[ validators.DataRequired(), validate_folder_path, ], tooltip="Indicate a folder full of images. For each image in the feature" " image folder there must be one corresponding image in the label" " image folder. The label image must have the same filename except" " for the extension, which may differ." ) folder_pct_val = utils.forms.IntegerField( u'% for validation', default=10, validators=[ validators.NumberRange(min=0, max=100) ], tooltip="You can choose to set apart a certain percentage of images " "from the training images for the validation set." ) has_val_folder = utils.forms.BooleanField('Separate validation images', default=False, ) validation_feature_folder = utils.forms.StringField( u'Validation feature image folder', validators=[ validate_required_iff(has_val_folder=True), validate_folder_path, ], tooltip="Indicate a folder full of images." ) validation_label_folder = utils.forms.StringField( u'Validation label image folder', validators=[ validate_required_iff(has_val_folder=True), validate_folder_path, ], tooltip="Indicate a folder full of images. For each image in the feature" " image folder there must be one corresponding image in the label" " image folder. The label image must have the same filename except" " for the extension, which may differ." ) channel_conversion = utils.forms.SelectField( 'Channel conversion', choices=[ ('RGB', 'RGB'), ('L', 'Grayscale'), ('none', 'None'), ], default='none', tooltip="Perform selected channel conversion." )
DIGITS-master
digits/extensions/data/imageProcessing/forms.py
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import math import os import random import numpy as np from digits.utils import image, subclass, override, constants from ..interface import DataIngestionInterface from .forms import DatasetForm TEMPLATE = "template.html" @subclass class DataIngestion(DataIngestionInterface): """ A data ingestion extension for an image processing dataset """ def __init__(self, **kwargs): """ the parent __init__ method automatically populates this instance with attributes from the form """ super(DataIngestion, self).__init__(**kwargs) self.random_indices = None if 'seed' not in self.userdata: # choose random seed and add to userdata so it gets persisted self.userdata['seed'] = random.randint(0, 1000) random.seed(self.userdata['seed']) @override def encode_entry(self, entry): """ Return numpy.ndarray """ feature_image_file = entry[0] label_image_file = entry[1] feature_image = self.encode_PIL_Image( image.load_image(feature_image_file)) label_image = self.encode_PIL_Image( image.load_image(label_image_file)) return feature_image, label_image def encode_PIL_Image(self, image): if self.channel_conversion != 'none': if image.mode != self.channel_conversion: # convert to different image mode if necessary image = image.convert(self.channel_conversion) # convert to numpy array image = np.array(image) # add channel axis if input is grayscale image if image.ndim == 2: image = image[..., np.newaxis] elif image.ndim != 3: raise ValueError("Unhandled number of channels: %d" % image.ndim) # transpose to CHW image = image.transpose(2, 0, 1) return image @staticmethod @override def get_category(): return "Images" @staticmethod @override def get_id(): return "image-processing" @staticmethod @override def get_dataset_form(): return DatasetForm() @staticmethod @override def get_dataset_template(form): """ parameters: - form: form returned by get_dataset_form(). This may be populated with values if the job was cloned returns: - (template, context) tuple - template is a Jinja template to use for rendering dataset creation options - context is a dictionary of context variables to use for rendering the form """ extension_dir = os.path.dirname(os.path.abspath(__file__)) template = open(os.path.join(extension_dir, TEMPLATE), "r").read() context = {'form': form} return (template, context) @staticmethod @override def get_title(): return "Processing" @override def itemize_entries(self, stage): if stage == constants.TEST_DB: # don't retun anything for the test stage return [] if stage == constants.TRAIN_DB or (not self.has_val_folder): feature_image_list = self.make_image_list(self.feature_folder) label_image_list = self.make_image_list(self.label_folder) else: # separate validation images feature_image_list = self.make_image_list(self.validation_feature_folder) label_image_list = self.make_image_list(self.validation_label_folder) # make sure filenames match if len(feature_image_list) != len(label_image_list): raise ValueError( "Expect same number of images in feature and label folders (%d!=%d)" % (len(feature_image_list), len(label_image_list))) for idx in range(len(feature_image_list)): feature_name = os.path.splitext( os.path.split(feature_image_list[idx])[1])[0] label_name = os.path.splitext( os.path.split(label_image_list[idx])[1])[0] if feature_name != label_name: raise ValueError("No corresponding feature/label pair found for (%s,%s)" % (feature_name, label_name)) # split lists if there is no val folder if not self.has_val_folder: feature_image_list = self.split_image_list(feature_image_list, stage) label_image_list = self.split_image_list(label_image_list, stage) return zip( feature_image_list, label_image_list) def make_image_list(self, folder): image_files = [] for dirpath, dirnames, filenames in os.walk(folder, followlinks=True): for filename in filenames: if filename.lower().endswith(image.SUPPORTED_EXTENSIONS): image_files.append('%s' % os.path.join(dirpath, filename)) if len(image_files) == 0: raise ValueError("Unable to find supported images in %s" % folder) return sorted(image_files) def split_image_list(self, filelist, stage): if self.random_indices is None: self.random_indices = range(len(filelist)) random.shuffle(self.random_indices) elif len(filelist) != len(self.random_indices): raise ValueError( "Expect same number of images in folders (%d!=%d)" % (len(filelist), len(self.random_indices))) filelist = [filelist[idx] for idx in self.random_indices] pct_val = int(self.folder_pct_val) n_val_entries = int(math.floor(len(filelist) * pct_val / 100)) if stage == constants.VAL_DB: return filelist[:n_val_entries] elif stage == constants.TRAIN_DB: return filelist[n_val_entries:] else: raise ValueError("Unknown stage: %s" % stage)
DIGITS-master
digits/extensions/data/imageProcessing/data.py
# Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import from . import tasks from digits.job import Job from digits.utils import override # NOTE: Increment this every time the pickled object changes PICKLE_VERSION = 1 class ModelJob(Job): """ A Job that creates a neural network model """ def __init__(self, dataset_id, **kwargs): """ Arguments: dataset_id -- the job_id of the DatasetJob that this ModelJob depends on """ super(ModelJob, self).__init__(**kwargs) self.pickver_job_dataset = PICKLE_VERSION self.dataset_id = dataset_id self.load_dataset() def __getstate__(self): state = super(ModelJob, self).__getstate__() if 'dataset' in state: del state['dataset'] return state def __setstate__(self, state): super(ModelJob, self).__setstate__(state) self.dataset = None @override def json_dict(self, verbose=False): d = super(ModelJob, self).json_dict(verbose) d['dataset_id'] = self.dataset_id if verbose: d.update({ 'snapshots': [s[1] for s in self.train_task().snapshots], }) return d def load_dataset(self): from digits.webapp import scheduler job = scheduler.get_job(self.dataset_id) assert job is not None, 'Cannot find dataset' self.dataset = job for task in self.tasks: task.dataset = job def train_task(self): """Return the first TrainTask for this job""" return [t for t in self.tasks if isinstance(t, tasks.TrainTask)][0] def download_files(self): """ Returns a list of tuples: [(path, filename)...] These files get added to an archive when this job is downloaded """ return NotImplementedError()
DIGITS-master
digits/model/job.py