<commit_before>#!/usr/bin/env python
"""
Module for feature extractor object classes and classifier functions.
"""

# Rule for methods:
# When the input is images, it might be a list of np arrays, or a list of paths
# When the input is image, it is always an np array
# The base class handles conversion from paths to images in transform
# fit(images) will need to load and preprocess each element in images


from __future__ import division

import numpy as np
import cv2
import sklearn.cluster
import six
import skimage.io
import skimage.util
import mahotas.features
import neukrill_net.image_features
from neukrill_net import image_attributes


def loadimage(obj):
    """
    Loads an image if a path is given
    Input : an image or a path
    Output: the image given or loaded from path
    """
    if isinstance(obj, np.ndarray):
        # Input is a loaded image
        return obj
    elif isinstance(obj, basestring) or isinstance(obj, six.string_types):
        # Input is a string. Assume it is a path.
        # Try to load the image from this path
        return skimage.io.imread(obj)
    else:
        # No duck typing for this function, so we will give an error
        # if we don't see the right kind of input.
        raise ValueError("Wrong kind of object given. Not a numpy array or a string.")


###############################################################################
# Base class
###############################################################################

class HighLevelFeatureBase:
    """
    Base class for high level features
    """
    
    _is_combiner = False
    _needs_fitting = False
    
    def __init__(self, preprocessing_func=None, augment_func=None, **kwargs):
        """
        Initialise the preprocessing and augmentation functions.
        
        NOTE: should not be overwritten by children.
        """
        if not preprocessing_func is None:
            self.preprocess_image = preprocessing_func
            
        if not augment_func is None:
            self.augment_image = augment_func
        
    
    def __add__(self, other):
        """
        """
        if self._is_combiner and other._is_combiner:
            # Add all the other's children to me
            for child in other.childHLFs:
                self.add_HLF(child)
            return self
            
        elif self._is_combiner:
            # Add the HLF into me
            self.add_HLF(other)
            return self
            
        elif other._is_combiner:
            # Add me HLF to the combined HLF
            self.add_HLF(other)
            return other
            
        else:
            return MultiHighLevelFeature([self, other])
        
        
    def fit(self, images, y=[]):
        """
        Fit the feature to a training set.
        Some subclasses will support this, but not all.
        Input : a list of images or image paths
        Output: None
        """
        # By default, does not need fitting
        pass
        
        
    def fit_transform(self, X, *args, **kwargs):
        """
        Fit and then transform
        Input : a list of images or image paths to fit to
        Output: the stack of features transformed from the images
        """
        self.fit(X, *args, **kwargs)
        return self.transform(X)
        
        
    def preprocess_image(self, image):
        """
        Preprocessing function
        Input : image - a 2D numpy array of an image
        Output: image - a 2D numpy array of the processed image
                        the output may not be the same size as the input
        """
        # By default, the preprocessing function does nothing to the 
        # input image
        return image
        
        
    def augment_image(self, image):
        """
        Augmentation method
        Takes an image and returns a list of augmented versions of it.
        The number of augmentations should be the same for every input.
        Input : image  - a 2D numpy array of an image
        Output: images - a list of numpy arrays of images
        """
        # By default, we do not augment and return the input image
        # on its own in a list
        return [image]
        
        
    def extract_image(self, image):
        """
        Extracts a feature vector from the image
        Input : image - a 2D numpy array of an image
        Output: features - a 1D numpy array of features extracted from the image.
        """
        # Subclasses will need to overwrite this function
        raise NotImplementedError
        
        
    def preprocess_and_extract_image(self, image):
        """
        Preprocess image and than extract features
        Input : image - a 2D numpy array of an image
        Output: features - a 1D numpy array of features extracted from the image.
        
        NOTE: Subclasses should not modify this function!
        """
        return self.preprocess_image(self.extract_image(image))
        
        
    def transform(self, images):
        """
        Extract features from a set of images.
        
        Input : images - a list of images as 2D numpy arrays
                            OR
                         a list of paths of images
        
        Output: features - a 3D numpy array of features extracted from
                           the images.
                           The size of the numpy array is
                           (num_augmentations, num_images, feature_length)
        
        NOTE: Subclasses should not modify this function!
        """
        # Probe object's other methods to see how big my output needs to be
        first_image = loadimage(images[0])
        # How many augmentations do we get from each image?
        num_augmentations = len(self.augment_image(first_image))
        # How many elements are in the feature vector from each image?
        num_feature_elements = self.preprocess_and_extract_image(first_image).size
        
        # Initialise
        X = np.zeros((num_augmentations, len(images), num_feature_elements))
        
        # Loop over list of images
        for image_index, image in enumerate(images):
            # Load the image if necessary
            image = loadimage(image)
            # Augment the image, giving a list of copies
            augmented_list = self.augment_image(image)
            # Loop over all the augmented copies
            for augment_index, augmented_image in enumerate(augmented_list):
                # Extract features and put them into the array
                X[augment_index, image_index, :] = self.preprocess_and_extract_image(augmented_image).ravel()
        
        # Return the completed arary
        return X


###############################################################################
# Combiner class
###############################################################################

class MultiHighLevelFeature(HighLevelFeatureBase):
    """
    Class for merging high level features together
    """
    
    _is_combiner = True
    
    def __init__(self, HLF_list, *args, **kwargs):
        """
        Initialise
        List of child high-level-features
        Input : HLF_list - List of high-level-feature objects
        """
        
        HighLevelFeatureBase.__init__(self, *args, **kwargs)
        
        self._childHLFs = HLF_list
        
        
    def add_HLF(self, HighLevelOther):
        """
        Add a new high level feature to the container
        """
        _childHLFs += [HighLevelOther]
        
        
    def fit(self, *args, **kwargs):<commit_msg>Combiner has needs fitting property<commit_after>#!/usr/bin/env python
"""
Module for feature extractor object classes and classifier functions.
"""

# Rule for methods:
# When the input is images, it might be a list of np arrays, or a list of paths
# When the input is image, it is always an np array
# The base class handles conversion from paths to images in transform
# fit(images) will need to load and preprocess each element in images


from __future__ import division

import numpy as np
import cv2
import sklearn.cluster
import six
import skimage.io
import skimage.util
import mahotas.features
import neukrill_net.image_features
from neukrill_net import image_attributes


def loadimage(obj):
    """
    Loads an image if a path is given
    Input : an image or a path
    Output: the image given or loaded from path
    """
    if isinstance(obj, np.ndarray):
        # Input is a loaded image
        return obj
    elif isinstance(obj, basestring) or isinstance(obj, six.string_types):
        # Input is a string. Assume it is a path.
        # Try to load the image from this path
        return skimage.io.imread(obj)
    else:
        # No duck typing for this function, so we will give an error
        # if we don't see the right kind of input.
        raise ValueError("Wrong kind of object given. Not a numpy array or a string.")


###############################################################################
# Base class
###############################################################################

class HighLevelFeatureBase:
    """
    Base class for high level features
    """
    
    _is_combiner = False
    _needs_fitting = False
    
    def __init__(self, preprocessing_func=None, augment_func=None, **kwargs):
        """
        Initialise the preprocessing and augmentation functions.
        
        NOTE: should not be overwritten by children.
        """
        if not preprocessing_func is None:
            self.preprocess_image = preprocessing_func
            
        if not augment_func is None:
            self.augment_image = augment_func
        
    
    def __add__(self, other):
        """
        """
        if self._is_combiner and other._is_combiner:
            # Add all the other's children to me
            for child in other.childHLFs:
                self.add_HLF(child)
            return self
            
        elif self._is_combiner:
            # Add the HLF into me
            self.add_HLF(other)
            return self
            
        elif other._is_combiner:
            # Add me HLF to the combined HLF
            self.add_HLF(other)
            return other
            
        else:
            return MultiHighLevelFeature([self, other])
        
        
    def fit(self, images, y=[]):
        """
        Fit the feature to a training set.
        Some subclasses will support this, but not all.
        Input : a list of images or image paths
        Output: None
        """
        # By default, does not need fitting
        pass
        
        
    def fit_transform(self, X, *args, **kwargs):
        """
        Fit and then transform
        Input : a list of images or image paths to fit to
        Output: the stack of features transformed from the images
        """
        self.fit(X, *args, **kwargs)
        return self.transform(X)
        
        
    def preprocess_image(self, image):
        """
        Preprocessing function
        Input : image - a 2D numpy array of an image
        Output: image - a 2D numpy array of the processed image
                        the output may not be the same size as the input
        """
        # By default, the preprocessing function does nothing to the 
        # input image
        return image
        
        
    def augment_image(self, image):
        """
        Augmentation method
        Takes an image and returns a list of augmented versions of it.
        The number of augmentations should be the same for every input.
        Input : image  - a 2D numpy array of an image
        Output: images - a list of numpy arrays of images
        """
        # By default, we do not augment and return the input image
        # on its own in a list
        return [image]
        
        
    def extract_image(self, image):
        """
        Extracts a feature vector from the image
        Input : image - a 2D numpy array of an image
        Output: features - a 1D numpy array of features extracted from the image.
        """
        # Subclasses will need to overwrite this function
        raise NotImplementedError
        
        
    def preprocess_and_extract_image(self, image):
        """
        Preprocess image and than extract features
        Input : image - a 2D numpy array of an image
        Output: features - a 1D numpy array of features extracted from the image.
        
        NOTE: Subclasses should not modify this function!
        """
        return self.preprocess_image(self.extract_image(image))
        
        
    def transform(self, images):
        """
        Extract features from a set of images.
        
        Input : images - a list of images as 2D numpy arrays
                            OR
                         a list of paths of images
        
        Output: features - a 3D numpy array of features extracted from
                           the images.
                           The size of the numpy array is
                           (num_augmentations, num_images, feature_length)
        
        NOTE: Subclasses should not modify this function!
        """
        # Probe object's other methods to see how big my output needs to be
        first_image = loadimage(images[0])
        # How many augmentations do we get from each image?
        num_augmentations = len(self.augment_image(first_image))
        # How many elements are in the feature vector from each image?
        num_feature_elements = self.preprocess_and_extract_image(first_image).size
        
        # Initialise
        X = np.zeros((num_augmentations, len(images), num_feature_elements))
        
        # Loop over list of images
        for image_index, image in enumerate(images):
            # Load the image if necessary
            image = loadimage(image)
            # Augment the image, giving a list of copies
            augmented_list = self.augment_image(image)
            # Loop over all the augmented copies
            for augment_index, augmented_image in enumerate(augmented_list):
                # Extract features and put them into the array
                X[augment_index, image_index, :] = self.preprocess_and_extract_image(augmented_image).ravel()
        
        # Return the completed arary
        return X


###############################################################################
# Combiner class
###############################################################################

class MultiHighLevelFeature(HighLevelFeatureBase):
    """
    Class for merging high level features together
    """
    
    _is_combiner = True
    
    @property
    def _needs_fitting(self):
        return any([child._needs_fitting for child in self._childHLFs])
        
        
    def __init__(self, HLF_list, *args, **kwargs):
        """
        Initialise
        List of child high-level-features
        Input : HLF_list - List of high-level-feature objects
        """
        
        HighLevelFeatureBase.__init__(self, *args, **kwargs)
        
        self._childHLFs = HLF_list
        
        
    def add_HLF(self, HighLevelOther):
        """
        Add a new high level feature to the container
        """
        _childHLFs += [HighLevelOther]
        
        
    def fit(self, *args, **kwargs):
{'fraction_non_alphanumeric': 0.09746258945998698, 'fraction_numerical': 0.001431359791802212, 'mean_word_length': 1.9616570327552987, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2210944', 'n_tokens_mistral': 3892, 'n_tokens_neox': 3765, 'n_words': 1506}