File size: 26,845 Bytes
ea5352f
 
 
3864c9e
ea5352f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3864c9e
ea5352f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e75649a
ea5352f
1445130
ea5352f
 
 
 
 
 
 
 
1445130
ea5352f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e123d07
ea5352f
 
 
 
 
 
 
e123d07
1445130
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea5352f
 
 
 
 
 
 
 
 
 
 
1445130
ea5352f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6c9dad
ea5352f
 
 
 
 
 
 
 
 
9203cdf
febe935
ea5352f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
febe935
ea5352f
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781


# example of face detection with mtcnn
from __future__ import print_function, division
from matplotlib import pyplot
from PIL import Image
from numpy import asarray
from mtcnn.mtcnn import MTCNN
import cv2
from mask_the_face import *
import numpy as np

import cv2
from tensorflow.keras.regularizers import l2
import pathlib
import tensorflow 
from tensorflow import keras
from tensorflow.keras.layers import  Conv2D, MaxPooling2D, Flatten, Dense,Dropout,BatchNormalization
import tensorflow.keras 
import pathlib
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import tensorflow.keras.utils as utils
from tensorflow.keras.optimizers import Adam as adam
from tensorflow.keras.optimizers import SGD
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.optimizers import Adagrad 
from tensorflow.keras.callbacks import  EarlyStopping ,ModelCheckpoint
import tensorflow as tf
from tensorflow.keras import Model
import matplotlib.pyplot as plt
import numpy as np
from tensorflow.keras.layers import  Conv2D, MaxPooling2D, Flatten, Dense, GlobalAveragePooling2D, Dropout, Input
# import keras_tuner as kt
from tensorflow.keras.applications import InceptionResNetV2
from tensorflow.keras import layers
from  tensorflow.keras.applications.inception_resnet_v2 import preprocess_input
from matplotlib import pyplot

from numpy import asarray
import copy
import random
# from mtcnn.mtcnn import MTCNN
import glob
import gradio as gr


from tensorflow.keras.regularizers import l2
from tensorflow.keras.layers import Input, Dense, Reshape, Flatten, Dropout, multiply, GaussianNoise
from tensorflow.keras.layers import BatchNormalization, Activation, Embedding, ZeroPadding2D
from tensorflow.keras.layers import MaxPooling2D
from tensorflow.keras.layers import LeakyReLU
from tensorflow.keras.layers import UpSampling2D, Conv2D
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.optimizers import Adam
from tensorflow.keras import losses
from tensorflow.keras.utils import to_categorical
import tensorflow.keras.backend as K
from tensorflow.keras.utils import plot_model
import matplotlib.pyplot as plt
import shutil
import numpy as np
from tensorflow.keras.applications import EfficientNetB0
from tensorflow.keras.applications import VGG16

def ssim_l1_loss(gt, y_pred, max_val=2.0, l1_weight=1.0):
        """
        Computes SSIM loss with L1 normalization
        @param gt: Ground truth image
        @param y_pred: Predicted image
        @param max_val: Maximal SSIM value
        @param l1_weight: Weight of L1 normalization
        @return: SSIM L1 loss
        """
        ssim_loss = 1 - tf.reduce_mean(tf.image.ssim(gt, y_pred, max_val=max_val))
        l1 = tf.keras.metrics.mean_absolute_error(gt, y_pred)
        return ssim_loss + tf.cast(l1 * l1_weight, tf.float32)

class GAN():
    def __init__(self,Xpointers,Ypointers,valX,valY,BigBatchSize,BinaryEnabled=False,BigBatchEnable=False,loading=True,printModel=False):
        self.Xpoint=  Xpointers
        self.Ypoint=  Ypointers
        self.X=''
        self.Y=''
        self.Binary=''
        self.DataSize=BigBatchSize
        self.genEnable=BigBatchEnable
        self.loading=loading
        self.PrintOut=printModel
        if self.loading:
          self.valX=self.get_all_images(valX)
          self.valY=self.get_all_images(valY)
        self.BestValLoss=1000        
        self.BinaryEnabled=BinaryEnabled
        if self.loading:
          if self.BinaryEnabled:
            self.Binary=self.GetBinary(self.valY,self.valX)
            self.ChangeToGreen('val')
        optimizer = Adam(0.0010,)

        # # Build and compile the discriminator
        
        self.discriminator_glo = self.build_discriminator()
        self.discriminator_glo.compile(loss='binary_crossentropy',
            optimizer=optimizer,
            metrics=['accuracy'])
        self.discriminator_loc = self.build_local_discriminator()
        self.discriminator_loc.compile(loss='binary_crossentropy',
            optimizer=optimizer,
            metrics=['accuracy'])
      

        self.generator,self.predictor = self.build_generator()
       
       

        GenOut = self.generator.output
        

      
        valid = self.discriminator_glo(GenOut[0])
        self.discriminator_glo.trainable = False

        valid2 = self.discriminator_loc(GenOut)
        self.discriminator_loc.trainable = False
        
        self.combined = Model(self.generator.input , [self.generator.output[0], valid,valid2])
        self.combined.compile(loss=[ssim_l1_loss, 'binary_crossentropy','binary_crossentropy'],
            loss_weights=[0.35, 0.50,1],
            optimizer=optimizer)
        if self.PrintOut:
          self.generator.summary()
          self.discriminator_loc.summary()
          self.discriminator_glo.summary()    
          self.combined.summary() 
        
        if self.loading:
          self.getBigBatch()

    def GetBinary(self,Org,Masked):
      allBinary=[]
      for i,x in enumerate(Masked):
        
        diff = cv2.absdiff(Org[i], Masked[i])
        gray=cv2.cvtColor(diff,cv2.COLOR_BGR2GRAY)
        _, diff2 = cv2.threshold(gray, 9, 255, cv2.THRESH_BINARY)
        img_median = cv2.medianBlur(diff2, 3)
        img_median = img_median/255
        allBinary.append(img_median)
      return np.array(allBinary)

    
    def get_all_images(self,classes):

      allImages=[]
      
      
      for  i,sample in enumerate(classes[:]):
      
          org_img = cv2.imread(sample)
          #org_img = org_img.astype('float32')
          org_img = cv2.resize(org_img, (256, 256))
          org_img=cv2.cvtColor(org_img,cv2.COLOR_BGR2RGB)
          # org_img= org_img/127.5 - 1
          # np.append(allImages, org_img)
          allImages.append(org_img)
          
      
      return np.array(allImages)

    def ChangeToGreen(self,data='train'):
      if data=='train':
        for i,x in enumerate(self.X):
          self.X[i][self.Binary[i]!=0]=(1,255,1)
      else:
        for i,x in enumerate(self.valX):
          self.valX[i][self.Binary[i]!=0]=(1,255,1)
      
    def getBigBatch(self):
      del self.X
      del self.Y
      del self.Binary
      if self.genEnable:
        idx = np.random.randint(0, self.Xpoint.shape[0], self.DataSize)
        currentX=self.Xpoint[idx]
        currentY=self.Ypoint[idx]
        self.X=self.get_all_images(currentX)
        self.Y=self.get_all_images(currentY)
      else:
        self.X=self.get_all_images(self.Xpoint)
        self.Y=self.get_all_images(self.Ypoint)
      if self.BinaryEnabled:
       
        self.Binary=self.GetBinary(self.Y,self.X)
        self.ChangeToGreen('train')
        self.Binary=self.Binary.reshape(self.Binary.shape[0],256,256,1)



    def downsample(self,filters, size, apply_batchnorm=True):    
       

        result = tf.keras.Sequential()
        result.add(
            tf.keras.layers.Conv2D(filters, size, strides=2, padding='same',))
        result.add(tf.keras.layers.ReLU())
        result.add(
            tf.keras.layers.Conv2D(filters, size, padding='same',))
        result.add(tf.keras.layers.ReLU())
      
        if apply_batchnorm:
          result.add(tf.keras.layers.BatchNormalization())

        return result




    def upsample(self,filters, size, apply_dropout=False):
   

      result = tf.keras.Sequential()
      result.add(
        tf.keras.layers.Conv2DTranspose(filters, size, strides=2,
                                   padding='same'))
      result.add(tf.keras.layers.ReLU())
      result.add(
        tf.keras.layers.Conv2DTranspose(filters, size,
                                        padding='same'))
     

    

      result.add(tf.keras.layers.ReLU())
      result.add(tf.keras.layers.BatchNormalization())
      if apply_dropout:
        result.add(tf.keras.layers.Dropout(0.2))
      return result       
    


    def build_generator(self):
        inputs = tf.keras.layers.Input(shape=[256, 256, 3])
        binary= tf.keras.layers.Input(shape=[256, 256, 1])
        down_stack = [
            self.downsample(128, 3, apply_batchnorm=False),  # (batch_size, 128, 128, 64)
            self.downsample(256, 3),  # (batch_size, 64, 64, 128)
            self.downsample(256, 3),  # (batch_size, 64, 64, 128)
            self.downsample(256, 3),  # (batch_size, 64, 64, 128)
            self.downsample(256, 3),  # (batch_size, 32, 32, 256)
            self.downsample(512, 3),  # (batch_size, 32, 32, 256)
            self.downsample(512, 3),  # (batch_size, 8, 8, 512)
          ]
        
        up_stack = [
          self.upsample(512, 3, apply_dropout=True),  # (batch_size, 8, 8, 1024)
          self.upsample(512, 3),  # (batch_size, 64, 64, 256)
          self.upsample(256, 3,apply_dropout=True),  # (batch_size, 64, 64, 256)
          self.upsample(256, 3),  # (batch_size, 64, 64, 256)
          self.upsample(256, 3,),  # (batch_size, 64, 64, 256)
          self.upsample(256, 3),  # (batch_size, 64, 64, 256)
          self.upsample(128, 3,),  # (batch_size, 128, 128, 128)
        ]
        down_stack2 = [
          self.downsample(128, 5, apply_batchnorm=False),  # (batch_size, 128, 128, 64)
          self.downsample(128, 5),  # (batch_size, 64, 64, 128)
          self.downsample(256, 5),  # (batch_size, 32, 32, 256)
          self.downsample(256, 5),  # (batch_size, 32, 32, 256)
          self.downsample(256, 5),  # (batch_size, 32, 32, 256)
          self.downsample(512, 5),  # (batch_size, 8, 8, 512)
        ]
      

        up_stack2 = [
          self.upsample(512, 5, apply_dropout=True),  # (batch_size, 8, 8, 1024)
          self.upsample(256, 5),  # (batch_size, 64, 64, 256)
          self.upsample(256, 5,apply_dropout=True),  # (batch_size, 64, 64, 256)
          self.upsample(256, 5),  # (batch_size, 64, 64, 256)
          self.upsample(128, 5,),  # (batch_size, 64, 64, 256)
          self.upsample(128, 5),  # (batch_size, 128, 128, 128)
        ]

        
        initializer = tf.random_normal_initializer(0., 0.02)
        last = tf.keras.layers.Conv2DTranspose(3, 3,
                                              strides=2,
                                              padding='same',
                                              name='GenOut',
                                              activation='tanh')  # (batch_size, 256, 256, 3)
        last2 = tf.keras.layers.Conv2DTranspose(3, 3,
                                              strides=2,
                                              padding='same',
                                              name='GenOut2',
                                              activation='tanh')  # (batch_size, 256, 256, 3)

        x = inputs

        # Downsampling through the model
        skips = []
        for down in down_stack:
          x = down(x)
          skips.append(x)

        skips = reversed(skips[:-1])

        # Upsampling and establishing the skip connections
        for up, skip in zip(up_stack, skips):
          x = up(x)
          x = tf.keras.layers.Concatenate()([x, skip])

        x = last(x)


        y = inputs

        # Downsampling through the model
        skips = []
        for down in down_stack2:
          y = down(y)
          skips.append(y)

        skips = reversed(skips[:-1])

        # Upsampling and establishing the skip connections
        for up, skip in zip(up_stack2, skips):
          y= up(y)
          y = tf.keras.layers.Concatenate()([y, skip])

        y = last2(y)

        z= tf.keras.layers.Average()([x,y])
        model1=tf.keras.Model(inputs=[inputs,binary], outputs=[z,binary])
        model2=tf.keras.Model(inputs=inputs, outputs=z)
        return model1,model2

        



    def build_discriminator(self):
        inputs = Input(shape=[256, 256, 3])

        facenetmodel = Flatten()
        # facenetmodel.load_weights('/content/drive/MyDrive/facenet_keras_weights.h5')
        # for layer in facenetmodel.layers[:-50]:
        #   layer.trainable = False
        
          # Augment data.
        augmented = keras.Sequential([layers.Resizing(160, 160),],name="data_augmentation",)(inputs)
        # This is 'bootstrapping' a new top_model onto the pretrained layers.
        top_model = facenetmodel(augmented)
        top_model = Dropout(0.5)(top_model)
        top_model = BatchNormalization()(top_model)
        # top_model = Flatten(name="flatten")(top_model)
        
        output_layer = Dense(1, activation='sigmoid')(top_model)
    
 

      

        return Model(inputs=inputs,  outputs=output_layer,name='Discriminator')
    
    def build_local_discriminator(self):
        img = Input(shape=[256, 256, 3])
        binary = Input(shape=[256, 256, 1])
        bitAND=tf.keras.layers.Lambda(lambda x: tf.math.multiply(x[0], x[1]))([img,binary])
        facenetmodel = Flatten()
        # facenetmodel.load_weights('/content/drive/MyDrive/facenet_keras_weights.h5')
        # for layer in facenetmodel.layers[:-50]:
        #   layer.trainable = False
        
          # Augment data.
        augmented = keras.Sequential([layers.Resizing(160, 160),],name="data_augmentation",)(bitAND)
        # This is 'bootstrapping' a new top_model onto the pretrained layers.
        top_model = facenetmodel(augmented)
        top_model = Dropout(0.5)(top_model)
        top_model = BatchNormalization()(top_model)
        # top_model = Flatten(name="flatten")(top_model)
        
        output_layer = Dense(1, activation='sigmoid')(top_model)
    
  

      

        return Model(inputs=[img,binary],  outputs=output_layer,name='Discriminator_local')

    

     



    def train(self,epochs,batch_size,imagesSavePath,modelPath, sample_interval=50,BigBatchInterval=1000,modelInterval=50):

      
        
        xVal=self.valX/127.5 - 1
        yVal=self.valY/127.5 - 1
        # Adversarial ground truths
        valid = np.ones((batch_size, 1))
        fake = np.zeros((batch_size, 1))
        valid = np.ones((batch_size, 1))
        for epoch in range(epochs):

      

            # Select a random batch of images
            idx = np.random.randint(0, self.X.shape[0], batch_size)
          
            masked_imgs = self.X[idx]
            org_imgs= self.Y[idx]
            
            masked_imgs = masked_imgs /127.5 - 1.
            org_imgs= org_imgs /127.5 - 1.
            if self.BinaryEnabled:
              binary= self.Binary[idx]
            org_local= tf.math.multiply(org_imgs, binary)
            
            gen_missing = self.generator.predict([masked_imgs,binary])
            
            # Train the discriminator
            d_loss_real_glo = self.discriminator_glo.train_on_batch(org_imgs, valid)
            d_loss_fake_glo = self.discriminator_glo.train_on_batch(gen_missing[0], fake)
            d_loss_glo = 0.5 * np.add(d_loss_real_glo, d_loss_fake_glo)

            d_loss_real_loc = self.discriminator_loc.train_on_batch([org_imgs,binary], valid)
            d_loss_fake_loc = self.discriminator_loc.train_on_batch(gen_missing, fake)
            d_loss_loc = 0.5 * np.add(d_loss_real_loc, d_loss_fake_loc)


            # ---------------------
            #  Train Generator
            # ---------------------
            # self.combined.layers[-1].trainable = False
            g_loss = self.combined.train_on_batch([masked_imgs,binary], [org_imgs, valid,valid])
            
            validx = np.random.randint(0, 500, 3)
            val_pred = self.predictor.predict(xVal[validx])
            val_loss=ssim_l1_loss(yVal[validx].astype('float32'),val_pred)
            val_loss=np.average(val_loss)
            # Plot the progress
            print ("%d  [G loss: %f,mse:%f] [val_loss:%f]" % (epoch, g_loss[0], g_loss[1],val_loss))



            
            
            # Plot the progress
          
            if epoch!=0:

              if epoch % 100 == 0:

                self.combined.save_weights('/content/drive/MyDrive/combinedModel_loc12.h5')
            # If at save interval => save generator weights
            # if epoch!=0:
            #   if epoch % modelInterval == 0:
            #      if val_loss<self.BestValLoss:
            #        self.generator.save_weights(modelPath+'GeneratorWeights_local5.h5')
            #        self.BestValLoss=val_loss 


            # If at save interval => save generated image samples
            if epoch % sample_interval == 0:
                idx = np.random.randint(0, self.X.shape[0], 6)
                val_idx = np.random.randint(0, 499, 2)
                val_reals= self.valY[val_idx]
                val_imgs = self.valX[val_idx]
                reals= self.Y[idx]
                imgs = self.X[idx]
                
                self.sample_images(epoch, imgs,reals,imagesSavePath,val_reals,val_imgs)


            #Big Batch Gen
            if self.genEnable:
              if epoch!=0:
                if epoch %  BigBatchInterval == 0:
                    self.getBigBatch()

    def sample_images(self, epoch, imgs,reals,savepath,val_reals,val_imgs):
        r, c = 3, 8

        imgs=imgs/127.5 -1.
        val_imgs=val_imgs/127.5 -1.
        gen_missing = self.predictor.predict(imgs)
        val_missing = self.predictor.predict(val_imgs)
        imgs = 0.5 * imgs + 0.5
        val_imgs = 0.5 * val_imgs + 0.5
        # reals= 0.5* reals +0.5
        gen_missing=0.5*gen_missing+0.5
        val_missing=0.5*val_missing+0.5 

        imgs=np.concatenate((imgs,val_imgs), axis=0)
        gen_missing=np.concatenate((gen_missing,val_missing), axis=0)
        reals=np.concatenate((reals,val_reals), axis=0)
        fig, axs = plt.subplots(r, c,figsize=(50,50))
        for i in range(c):
            axs[0,i].imshow(imgs[i, :,:])
            axs[0,i].axis('off')
            axs[1,i].imshow(reals[i, :,:])
            axs[1,i].axis('off')

            axs[2,i].imshow(gen_missing[i, :,:])
            axs[2,i].axis('off')
        fig.savefig(savepath+"%d.png" % epoch)
        plt.close()

GAN_Model = GAN(Xpointers=None,Ypointers=None,valX=None,valY=None,
                BigBatchSize=50,BigBatchEnable=True,BinaryEnabled=True,loading=False)

GAN_Model.predictor.load_weights('DemoPredictor2.h5')

def extract_face(photo, required_size=(256, 256),incr=110):
  # load image from file
  pixels = photo
  print(pixels.shape)
  maxH=(pixels.shape[0])
  maxW=(pixels.shape[1])
  if (pixels.shape[-1])>3 or (pixels.shape[-1])<3:
    image = Image.fromarray(pixels)
    return image
  
  # create the detector, using default weights
  detector = MTCNN()
  # detect faces in the image
  results = detector.detect_faces(pixels)
  if not results:
    image = Image.fromarray(pixels)
    image = image.resize(required_size)
    return image
  # extract the bounding box from the first face
  x1, y1, width, height = results[0]['box']
  x2, y2 = x1 + width, y1 + height
  if y1-incr<=0:
    y1=0
  else :
    y1=y1-incr
  if x1-incr<=0:
    x1=0
  else :
    x1=x1-incr

  if y2+incr>=maxH:
    y2=maxH
  else :
    y2=y2+incr
  if x2+incr>=maxW:
    x2=maxW
  else :
    x2=x2+incr
  # extract the face
  face = pixels[y1:int(y2), int(x1):int(x2)]
  # resize pixels to the model size
  image = Image.fromarray(face)
  image = image.resize(required_size)

  return image

def GetBinary_test(Org,Masked):
      allBinary=[]
      for i,x in enumerate(Masked):
        
        diff = cv2.absdiff(Org, Masked)
        gray=cv2.cvtColor(diff,cv2.COLOR_RGB2GRAY)
        _, diff2 = cv2.threshold(gray, 9, 255, cv2.THRESH_BINARY)
        img_median = cv2.medianBlur(diff2, 3)
        img_median = img_median/255
        allBinary.append(img_median)
      return np.array(allBinary)
def ChangeToGreen_test(X,Binary):
      X[Binary[0]!=0]=(1,255,1)

def predictImage_masked(GANmodel,groundTruth,masked):
    TestX=masked.copy()
    Testy=groundTruth.copy()
    
    Binary=GetBinary_test(Testy,TestX)
    ChangeToGreen_test(TestX,Binary)
    
    imgs=TestX/127.5 -1.
    Testy=Testy/255
    
    gen_missing = GANmodel.predictor.predict(imgs[None,...])

    gen_missing=0.5*gen_missing+0.5
    psnr2 = tf.image.psnr(Testy.astype('float32'),gen_missing, max_val=1.0)
    ssim=tf.image.ssim(Testy.astype('float32'), gen_missing, max_val=1)
    Mssim=np.average(ssim)
    Mpsnr=np.average(psnr2)
    I = gen_missing*255 # or any coefficient
    I = I.astype(np.uint8)
    I = cv2.normalize(I, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U)
    return (I,Mpsnr,Mssim)

def grid_display(list_of_images, list_of_titles=[], no_of_columns=2, figsize=(10,10)):

    fig = plt.figure(figsize=figsize)
    column = 0
    for i in range(len(list_of_images)):
        column += 1
        #  check for end of column and create a new figure
        if column == no_of_columns+1:
            fig = plt.figure(figsize=figsize)
            column = 1
        fig.add_subplot(1, no_of_columns, column)
        plt.imshow(list_of_images[i])
        plt.axis('off')
        if len(list_of_titles) >= len(list_of_images):
            plt.title(list_of_titles[i])

# paths = r"C:\Users\MrSin\Downloads\images\*.jpg"
# import glob

# for filepath in glob.iglob(paths):
#      print(filepath)
#      org_img = cv2.imread(filepath)

def ExecutePipline(img):
        im = Image.fromarray(img.astype('uint8'), 'RGB')
        org_img=np.array(im) 
        # plt.imshow(org_img)
        errorPNG=cv2.imread('error.jpg',)
        errorPNG=errorPNG[...,::-1]
        img2=extract_face(org_img,incr=150)
        
        
        cropped = np.array(img2) 
        
        open_cv_image = cropped[:, :, ::-1].copy() 
        masked1=maskThisImages(open_cv_image)
        if len(masked1)==0:
            img2=extract_face(org_img,incr=165)
        
        
            cropped = np.array(img2) 
            
            open_cv_image = cropped[:, :, ::-1].copy() 
            masked1=maskThisImages(open_cv_image)
            if len(masked1)==0: 
                img2=extract_face(org_img,incr=180)
        
        
                cropped = np.array(img2) 
                
                open_cv_image = cropped[:, :, ::-1].copy() 
                masked1=maskThisImages(open_cv_image)
                if len(masked1)==0: 
                    img2=extract_face(org_img,incr=200)
            
            
                    cropped = np.array(img2) 
                    
                    open_cv_image = cropped[:, :, ::-1].copy() 
                    masked1=maskThisImages(open_cv_image)
                    if len(masked1)==0: 
                         
                        img2=extract_face(org_img,incr=500)
                
                
                        cropped = np.array(img2) 
                        
                        open_cv_image = cropped[:, :, ::-1].copy() 
                        masked1=maskThisImages(open_cv_image)
                        if len(masked1)==0: 
                            return np.zeros((256,256,3)),errorPNG,np.zeros((256,256,3))
        masked2=cv2.cvtColor(masked1,cv2.COLOR_BGR2RGB)
        # output1 = masked2*255 # or any coefficient
        # output1 = output1.astype(np.uint8)
        # output1 = cv2.normalize(output1, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U)
        # plt.imshow(output1)
        # output1= Image.fromarray(output1)
    
        results,psnr,ssim=predictImage_masked(GAN_Model,cropped,masked2)
     
        return cropped,masked2,results[0] #,


# paths = r"C:\Users\MrSin\Downloads\images\*.jpg"
# import glob

# for filepath in glob.iglob(paths):
#      print(filepath)
#      org_img = cv2.imread(filepath)
#      org_img=cv2.cvtColor(org_img,cv2.COLOR_BGR2RGB)

#      img=extract_face(org_img)
     
#      cropped = np.array(img) 
#      #output 1^
#      open_cv_image = cropped[:, :, ::-1].copy() 
#      masked=maskThisImages(open_cv_image)
#      cv2.imwrite('mytestmasked.jpg',masked)
#      masked=cv2.cvtColor(masked,cv2.COLOR_BGR2RGB)
#      #output 2^
#      print(masked.shape)
#      results,psnr,ssim=predictImage_masked_model2(GAN_Model,cropped,masked)
#      displayResult = np.array(results[0]) 
#      #output 2 results[0]^
#      titles = ["groundtruth", 
#           "Masked", 
#           "Generated", ]
#      images = [cropped,masked,results[0]]
#      grid_display(images, titles, 3, (15,15))

# titles = ["groundtruth", 
#           "Masked", 
#           "Generated", ]
# org_img = cv2.imread('mytestmasked.jpg')
# org_img=cv2.cvtColor(org_img,cv2.COLOR_BGR2RGB)
# results=predictImageOnly(GAN_Model,org_img)
# images = [cropped,masked,results[0]]
# grid_display(images, titles, 3, (15,15))



# imagein = gr.Image()
# maskedOut = gr.Image(type='numpy',label='Masked (Model-input)')
# crop = gr.Image(type='numpy',label='cropped')
# genOut= gr.Image(type='numpy',label='Unmasked Output')

# gr.Interface(
#     ExecutePipline,
#     inputs=imagein,
#     outputs=[crop,maskedOut,genOut],
#     title="Face Un-Masking",
#     description="Compare 2 state-of-the-art machine learning models",).launch(share=True)



with gr.Blocks() as demo:
    gr.HTML(
        """
            <div style="text-align: center; max-width: 650px; margin: 0 auto;">
              <div
                style="
                  display: inline-flex;
                  align-items: center;
                  gap: 0.8rem;
                  font-size: 1.75rem;
                "
              >
                
                <h1 style="font-weight: 900; margin-bottom: 7px;">
                  Face Un-Masking
                </h1>
              </div>
              <p style="margin-bottom: 10px; font-size: 94%">
                AI Model that generate area under masks! simply upload your face image without a mask, then click submit, the model will apply digital mask then send it     to the Double Context GAN to predect area under the mask.
                
              </p>
            </div>
        """
    )
    with gr.Row():
        with gr.Column():
            imagein = gr.Image(label='Input',interactive=True)
            
        with gr.Column():
            gr.Examples(['40868.jpg','08227.jpg','59028.jpg','31735.jpg','49936.jpg','21565.jpg'],inputs=imagein)
    with gr.Row():
       
        image_button = gr.Button("Submit")
        
        
        
        
    with gr.Row():
        with gr.Column():
            crop = gr.Image(type='numpy',label='Groundtruth(cropped)',)
        with gr.Column():
            maskedOut = gr.Image(type='numpy',label='Masked (Model-input)')
        with gr.Column():
            genOut= gr.Image(type='numpy',label='Unmasked Output')
    
    gr.Markdown("<p style='text-align: center'>Made  with 🖤  by  Mohammed:Me.MohammedAlsinan@gmail.com & Aseel:A9eel.7neef@gmail.com </p>")
    image_button.click(fn=ExecutePipline,inputs=imagein,outputs=[crop,maskedOut,genOut])
demo.launch()