text: # -*- coding: utf-8 -*-
  """
  Implementation of example defense.
  This defense loads inception v1 checkpoint and classifies all images using loaded checkpoint.
  """
  from __future__ import absolute_import
  from __future__ import division
  from __future__ import print_function
  import os
  import numpy as np
  import tensorflow as tf
  # from tensorflow.contrib.slim.nets import inception
  from scipy.misc import imread
  from scipy.misc import imresize
  from cleverhans.attacks import FastGradientMethod
  from cleverhans.attacks import Model
  from PIL import Image
  import inception_v1 as inception
  
  slim = tf.contrib.slim
  
  tf.flags.DEFINE_string(
      'checkpoint_path', '', 'Path to checkpoint for inception network.')
  tf.flags.DEFINE_string(
      'input_dir', '', 'Input directory with images.')
  tf.flags.DEFINE_string(
      'output_dir', '', 'Output directory with images.')
  tf.flags.DEFINE_integer(
      'image_width', 224, 'Width of each input images.')
  tf.flags.DEFINE_integer(
      'image_height', 224, 'Height of each input images.')
  tf.flags.DEFINE_integer(
      'batch_size', 16, 'How many images process at one time.')
  tf.flags.DEFINE_integer(
      'num_classes', 110, 'Number of Classes')
  FLAGS = tf.flags.FLAGS
  
  
  def load_images(input_dir, batch_shape):
      images = []
      filenames = []
      true_labels = []
      idx = 0
      batch_size = batch_shape[0]
      dev = pd.read_csv(os.path.join(input_dir, 'dev.csv'))
      filename2label = {dev.iloc[i]['filename']: dev.iloc[i]['trueLabel'] for i in range(len(dev))}
      for filename in filename2label.keys():
          raw_image = imread(os.path.join(input_dir, filename), mode='RGB')
          # image = tf.image.resize_bilinear(raw_image, [FLAGS.image_height,FLAGS.image_width],align_corners=False)
          image = imresize(raw_image, [FLAGS.image_height, FLAGS.image_width]).astype(np.float)
          image = (image / 255.0) * 2.0 - 1.0
          images.append(image)
          filenames.append(filename)
          true_labels.append(filename2label[filename])
          idx += 1
          if idx == FLAGS.batch_size:
              images = np.array(images)
              yield filenames, images, true_labels
              filenames = []
              images = []
              true_labels = []
              idx = 0
      if idx > 0:
          images = np.array(images)
          yield filenames, images, true_labels
  
  
  def save_images(images, filenames, output_dir):
      for i, filename in enumerate(filenames):
          # Images for inception classifier are normalized to be in [-1, 1] interval,
          # so rescale them back to [0, 1].
          with open(os.path.join(output_dir, filename), 'w') as f:
              img = (((images[i, :, :, :] + 1.0) * 0.5) * 255.0).astype(np.uint8)
              # resize back to [299, 299]
              r_img = imresize(img, [299, 299])
              Image.fromarray(r_img).save(f, format='PNG')
  
  
  def check_or_create_dir(directory):
      """Check if directory exists otherwise create it."""
      if not os.path.exists(directory):
          os.makedirs(directory)
  
  
  class InceptionModel(Model):
      """Model class for CleverHans library."""
  
      def __init__(self, nb_classes):
          super(InceptionModel, self).__init__(nb_classes=nb_classes,
                                               needs_dummy_fprop=True)
          self.built = False
  
      def __call__(self, x_input, return_logits=False):
          """Constructs model and return probabilities for given input."""
          reuse = True if self.built else None
          with slim.arg_scope(inception.inception_v1_arg_scope()):
              _, end_points = inception.inception_v1(
                  x_input, num_classes=self.nb_classes, is_training=False,
                  reuse=reuse)
          self.built = True
          self.logits = end_points['Logits']
          # Strip off the extra reshape op at the output
          self.probs = end_points['Predictions'].op.inputs[0]
          if return_logits:
              return self.logits
          else:
              return self.probs
  
      def get_logits(self, x_input):
          return self(x_input, return_logits=True)
  
      def get_probs(self, x_input):
          return self(x_input)
  
  
  def main(_):
      """Run the sample attack"""
      batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3]
      nb_classes = FLAGS.num_classes
      # tf.logging.set_verbosity(tf.logging.INFO)
      check_or_create_dir(FLAGS.checkpoint_path)
  
      with tf.Graph().as_default():
          # Prepare graph
          x_input = tf.placeholder(tf.float32, shape=batch_shape)
          model = InceptionModel(nb_classes)
          # Run computation
          with tf.Session(config=tf.ConfigProto(allow_soft_placement=True, log_device_placement=True)) as sess:
              fgsm_model = FastGradientMethod(model, sess=sess)
              attack_params = {"eps": 32.0 / 255.0, "clip_min": -1.0, "clip_max": 1.0}
              x_adv = fgsm_model.generate(x_input, **attack_params)
              saver = tf.train.Saver(slim.get_model_variables())
              saver.restore(sess, FLAGS.checkpoint_path)
  
              for filenames, images, true_labels in load_images(FLAGS.input_dir, batch_shape):
                  adv_images = sess.run(x_adv, feed_dict={x_input: images})
                  save_images(adv_images, filenames, FLAGS.output_dir)
  
  
  if __name__ == '__main__':
      tf.app.run()
  