from realsafe.defense.jpeg_compression import jpeg_compression
from realsafe.utils import get_res_path

import inception_v3

MODEL_PATH = get_res_path('./imagenet/inception_v3.ckpt')


def load(session):
    model = InceptionV3Jpeg()
    model.load(session, MODEL_PATH)
    return model


@jpeg_compression(quality=75)
class InceptionV3Jpeg(inception_v3.InceptionV3):
    pass


if __name__ == '__main__':
    inception_v3.download(MODEL_PATH)
        indices = tf.reshape(tf.multinomial(sigma * distances, 1),
                             [batch_size])
        weights = tf.expand_dims(tf.one_hot(indices, depth=n_samples), 2)
        selected_points = tf.expand_dims(
            tf.reduce_sum(weights * samples, axis=1), 1)
        centroids.append(selected_points)
    return tf.concat(centroids, axis=1)


def rgb_clustering(images, centroids, alpha):
    _, width, height, channel = images.get_shape().as_list()
    # Gaussian mixture clustering
    cluster_num = centroids.get_shape().as_list()[1]
    reshaped_images = tf.reshape(images, [-1, width, height, 1, channel])
    reshaped_centroids = tf.reshape(centroids,
                                    [-1, 1, 1, cluster_num, channel])
    distances = tf.reduce_sum(tf.square(reshaped_centroids - reshaped_images),
                              axis=4)
    logits = tf.clip_by_value(-alpha * distances, -200, 200)
    probs = tf.expand_dims(tf.nn.softmax(logits), 4)
    new_images = tf.reduce_sum(reshaped_centroids * probs, axis=3)
    # update cluster centers
    new_centroids = tf.reduce_sum(reshaped_images * probs, axis=[1, 2]) / (
        tf.reduce_sum(probs, axis=[1, 2]) + 1e-16)
    return new_images, new_centroids


if __name__ == '__main__':
    from inception_v3 import download
    download(MODEL_PATH)