"""
Mask R-CNN
Copyright (c) 2017 Matterport, Inc.
Licensed under the MIT License (see LICENSE for details)
Written by Waleed Abdulla
------------------------------------------------------------
Usage: import the module (see Jupyter notebooks for examples), or run from
       the command line as such:
    # Train a new model starting from pre-trained Wally weights
    To train model: python3 samples\wally\wally.py train --dataset=datasets\wally\train --model=coco
"""

import os
import numpy as np
import sys
import json
import datetime
import skimage.draw
import logging


# Root directory of the project
ROOT_DIR = os.getcwd()
if ROOT_DIR.endswith("samples/wally"):
    # Go up two levels to the repo root
    ROOT_DIR = os.path.dirname(os.path.dirname(ROOT_DIR))

# Import Mask RCNN
sys.path.append(ROOT_DIR)
from config import Config
import utils
from model import MaskRCNN

# Directory to save logs and model checkpoints, if not provided
# through the command line argument --logs
DEFAULT_LOGS_DIR = os.path.join(ROOT_DIR, "logs")

############################################################
#  Configurations
############################################################


class WallyConfig(Config):
    """Configuration for training on wally's.
    Derives from the base Config class and overrides values specific
    to the wally dataset.
    """
    # Give the configuration a recognizable name
    NAME = "wally"

    # We use a GPU with 12GB memory, which can fit two images.
    # Adjust down if you use a smaller GPU.
    IMAGES_PER_GPU = 2

    # Uncomment to train on 8 GPUs (default is 1)
    # GPU_COUNT = 8

    # Number of classes (including background)
    NUM_CLASSES = 1 + 1  # wally has 1 class
    STEPS_PER_EPOCH = 100
    DETECTION_MIN_CONFIDENCE = 0.9
    # Path to trained weights file
    COCO_WEIGHTS_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")
    MODEL_DIR = os.path.join(ROOT_DIR, "logs")
    DATA_DIR = "datasets"

    def __init__(self, predict=False) :
        if (predict) :
            self.IMAGES_PER_GPU = 1
            self.GP_COUNT = 1
        super(self.__class__, self).__init__();


############################################################
#  Dataset
############################################################
# this class extends the utils.Dataset class
class WallyDataset(utils.Dataset):
    def load_Wally(self, dataset_dir, subset):
        self.add_class("wally", "1", "wally")

        #assert subset in ["train", "val"]
        dataset_dir = os.path.join(dataset_dir, subset)

        # Load annotations
        # VGG Image Annotator (up to version 1.6) saves each image in the form:
        # { 'filename': '28503151_5b5b7ec140_b.jpg',
        #   'regions': {
        #       '0': {
        #           'region_attributes': {},
        #           'shape_attributes': {
        #               'all_points_x': [...],
        #               'all_points_y': [...],
        #               'name': 'polygon'}},
        #       ... more regions ...
        #   },
        #   'size': 100202
        # }
        # We mostly care about the x and y coordinates of each region
        # Note: In VIA 2.0, regions was changed from a dict to a list.

        annotations = json.load(open(os.path.join(dataset_dir, "via_region_data.json")))
        annotations = list(annotations.values())
        # We only want to add to the dataset images which we have annotations for (where the mask is drawn for the
        # image), we know a mask is drawn if it has a 'regions' section in the JSON
        annotations = [a for a in annotations if a['regions']]

        # Add images to the dataset
        for a in annotations:
            # Get the x, y coordinaets of points of the polygons that make up the outline of each object instance.
            # There are stores in the shape_attributes (see json format)
            polygons = [r['shape_attributes'] for r in a['regions'].values()]

            image_path = os.path.join(dataset_dir, a['filename'])
            height, width = self.getWidthHeight(image_path)
            self.add_image(
                "wally",
                image_id=a['filename'],  # use file name as a unique image id
                path=image_path,
                width=width, height=height,
                polygons=polygons)

    def getWidthHeight(self, image_path):
        image = skimage.io.imread(image_path)
        height, width = image.shape[:2]
        return height, width

    def load_mask(self, image_id):
        image_info = self.image_info[image_id]
        if image_info["source"] != "wally":
            return super(self.__class__, self).load_mask(image_id)

        info = self.image_info[image_id]
        mask = np.zeros([info["height"], info["width"], len(info["polygons"])],
                        dtype=np.uint8)
        for i, p in enumerate(info["polygons"]):
            # Get indexes of pixels inside the polygon and set them to 1
            rr, cc = skimage.draw.polygon(p['all_points_y'], p['all_points_x'])
            mask[rr, cc, i] = 1

        # Return mask, and array of class IDs of each instance. Since we have
        # one class ID only, we return an array of 1s
        return mask, np.ones([mask.shape[-1]], dtype=np.int32)

    def image_reference(self, image_id):
        info = self.image_info[image_id]
        if info["source"] == "wally":
            return info["path"]
        else:
            super(self.__class__, self).image_reference(image_id)

def train(model):
    """Train the model."""
    # Training dataset.
    dataset_train = WallyDataset()
    dataset_train.load_Wally(args.dataset, "train")
    dataset_train.prepare()

    # Validation dataset
    dataset_val = WallyDataset()
    dataset_val.load_Wally(args.dataset, "val")
    dataset_val.prepare()

    # *** This training schedule is an example. Update to your needs ***
    # Since we're using a very small dataset, and starting from
    # COCO trained weights, we don't need to train too long. Also,
    # no need to train all layers, just the heads should do it.
    print("Training network heads")
    model.train(dataset_train, dataset_val,
                learning_rate=config.LEARNING_RATE,
                epochs=30,
                layers='heads')

if __name__ == '__main__':
    import argparse

    # Parse command line arguments
    parser = argparse.ArgumentParser(
        description='Train Mask R-CNN to detect wallys.')
    parser.add_argument("command",
                        metavar="<command>",
                        help="'train'")
    parser.add_argument('--dataset', required=False,
                        metavar="/path/to/wally/dataset/",
                        help='Directory of the wally dataset')
    parser.add_argument('--weights', required=True,
                        metavar="/path/to/weights.h5",
                        help="Path to weights .h5 file or 'coco'")
    parser.add_argument('--logs', required=False,
                        default=DEFAULT_LOGS_DIR,
                        metavar="/path/to/logs/",
                        help='Logs and checkpoints directory (default=logs/)')
    parser.add_argument('--image', required=False,
                        metavar="path or URL to image")
    parser.add_argument('--video', required=False,
                        metavar="path or URL to video")
    args = parser.parse_args()

    # Validate arguments
    if args.command == "train":
        assert args.dataset, "Argument --dataset is required for training"

    print("Weights: ", args.weights)
    print("Dataset: ", args.dataset)
    print("Logs: ", args.logs)

    # Configurations
    if args.command == "train":
        config = WallyConfig()
    else:
        class InferenceConfig(WallyConfig):
            # Set batch size to 1 since we'll be running inference on
            # one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU
            GPU_COUNT = 1
            IMAGES_PER_GPU = 1
        config = InferenceConfig()
    config.display()

    # Create model
    if args.command == "train":
        model = MaskRCNN(mode="training", config=config,
                                  model_dir=config.MODEL_DIR)
    else:
        model = MaskRCNN(mode="inference", config=config,
                                  model_dir=config.MODEL_DIR)

    # Select weights file to load
    if args.weights.lower() == "coco":
        weights_path = config.COCO_WEIGHTS_PATH
        # Download weights file
        if not os.path.exists(weights_path):
            utils.download_trained_weights(weights_path)
    elif args.weights.lower() == "last":
        # Find last trained weights
        weights_path = model.find_last()[1]
    elif args.weights.lower() == "imagenet":
        # Start from ImageNet trained weights
        weights_path = model.get_imagenet_weights()
    else:
        weights_path = args.weights

    # here we load the coco weights. This is called TRANSFER LEARNING, where we use a set of weights (created for a
    # different use than our intended use) to begin training on our data, instead of using randomly assigned weights.
    # This means that we get a slightly better accuracy from the get-go, and means we can build on the already
    # produced weights.
    print("Loading weights ", weights_path)
    if args.weights.lower() == "coco":
        # Exclude the last layers because they require a matching
        # number of classes
        model.load_weights(weights_path, by_name=True, exclude=[
            "mrcnn_class_logits", "mrcnn_bbox_fc",
            "mrcnn_bbox", "mrcnn_mask"])
    else:
        model.load_weights(weights_path, by_name=True)

    # Train or evaluate
    if args.command == "train":
        train(model)
    else:
        print("'{}' is not recognized. "
              "Use 'train' or 'splash'".format(args.command))