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
 
 
 
 
 
 
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
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
# -*- coding: utf-8 -*-
"""Virtue_Try.ipynb

Automatically generated by Colab.

Original file is located at
    https://colab.research.google.com/drive/1utsRZuiRKteQ4UBw8aZMPwVnHu62Ttzd

# Virtual Try-On System using IP-Adapters Inpainting

This notebook implements a comprehensive virtual try-on system using Stable Diffusion XL with IP-Adapters for realistic clothing transfer. The pipeline consists of several well-defined steps:

1. **Environment Setup**: Install and import required libraries
2. **Model Loading**: Initialize the inpainting pipeline with IP-Adapter
3. **Image Input**: Interactive upload interface for person and clothing images
4. **Segmentation**: Automatic body part segmentation for precise masking
5. **Generation**: Virtual try-on with customizable parameters
6. **Visualization**: Compare original and generated results

---

## Step 1: Environment Setup

First, we'll install all necessary dependencies and import required libraries.
"""

# Commented out IPython magic to ensure Python compatibility.
# %pip install diffusers accelerate transformers torch pillow opencv-python insightface onnxruntime ipywidgets

# Import core libraries
import torch
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
from diffusers import AutoPipelineForInpainting, AutoencoderKL
from diffusers.utils import load_image

# Import widgets for interactive interface
import ipywidgets as widgets
from IPython.display import display, clear_output
import io
import base64

# Import utilities
import os
import warnings
warnings.filterwarnings('ignore')

print("All libraries imported successfully!")
print(f" CUDA available: {torch.cuda.is_available()}")
if torch.cuda.is_available():
    print(f" GPU: {torch.cuda.get_device_name(0)}")

"""## Step 2: Model Loading and Pipeline Setup

We'll load the Stable Diffusion XL inpainting model with IP-Adapter for clothing transfer.
"""

def setup_pipeline():
    """
    Initialize the inpainting pipeline with IP-Adapter support.
    """
    print(" Loading VAE...")
    vae = AutoencoderKL.from_pretrained(
        "madebyollin/sdxl-vae-fp16-fix",
        torch_dtype=torch.float16
    )

    print(" Loading inpainting pipeline...")
    pipeline = AutoPipelineForInpainting.from_pretrained(
        "diffusers/stable-diffusion-xl-1.0-inpainting-0.1",
        vae=vae,
        torch_dtype=torch.float16,
        variant="fp16",
        use_safetensors=True
    ).to("cuda" if torch.cuda.is_available() else "cpu")

    print(" Loading IP-Adapter...")
    pipeline.load_ip_adapter(
        "h94/IP-Adapter",
        subfolder="sdxl_models",
        weight_name="ip-adapter_sdxl.bin",
        low_cpu_mem_usage=True
    )

    print(" Pipeline loaded successfully!")
    return pipeline

# Initialize the pipeline
pipeline = setup_pipeline()

"""## Step 3: Body Segmentation Setup

We'll set up the body segmentation tool for automatic mask generation.
"""

# Commented out IPython magic to ensure Python compatibility.
# Clone and setup body segmentation tool
if not os.path.exists('Segment-Body'):
    print(" Cloning body segmentation repository...")
    !git clone https://github.com/TonyAssi/Segment-Body.git

    # Install requirements
#     %cd Segment-Body
#     %pip install -r requirements.txt
    !cp ./SegBody.py ..
#     %cd ..
    print(" Body segmentation setup complete!")
else:
    print(" Body segmentation already available!")

# Import the segmentation function
from SegBody import segment_body

"""## Step 4: Interactive Image Upload Interface

Create user-friendly widgets for uploading person and clothing images.
"""

class ImageUploader:
    def __init__(self):
        self.person_image = None
        self.clothing_image = None
        self.setup_widgets()

    def setup_widgets(self):
        # Person image upload
        self.person_upload = widgets.FileUpload(
            accept='image/*',
            multiple=False,
            description=' Upload Person Image',
            style={'description_width': 'initial'}
        )

        # Clothing image upload
        self.clothing_upload = widgets.FileUpload(
            accept='image/*',
            multiple=False,
            description=' Upload Clothing Image',
            style={'description_width': 'initial'}
        )

        # URL inputs as alternative
        self.person_url = widgets.Text(
            placeholder='Or paste person image URL here',
            description='Person URL:',
            style={'description_width': 'initial'},
            layout=widgets.Layout(width='500px')
        )

        self.clothing_url = widgets.Text(
            placeholder='Or paste clothing image URL here',
            description='Clothing URL:',
            style={'description_width': 'initial'},
            layout=widgets.Layout(width='500px')
        )

        # Load button
        self.load_button = widgets.Button(
            description=' Load Images',
            button_style='primary',
            icon='upload'
        )

        # Output area
        self.output = widgets.Output()

        # Bind events
        self.load_button.on_click(self.load_images)

    def load_from_upload(self, upload_widget):
        """Load image from file upload widget"""
        if upload_widget.value:
            uploaded_file = list(upload_widget.value.values())[0]
            image = Image.open(io.BytesIO(uploaded_file['content'])).convert('RGB')
            return image.resize((512, 512))
        return None

    def load_from_url(self, url):
        """Load image from URL"""
        if url.strip():
            try:
                image = load_image(url).convert('RGB')
                return image.resize((512, 512))
            except Exception as e:
                print(f" Error loading image from URL: {e}")
        return None

    def load_images(self, button):
        """Load images from uploads or URLs"""
        with self.output:
            clear_output()

            # Load person image
            self.person_image = self.load_from_upload(self.person_upload)
            if not self.person_image:
                self.person_image = self.load_from_url(self.person_url.value)

            # Load clothing image
            self.clothing_image = self.load_from_upload(self.clothing_upload)
            if not self.clothing_image:
                self.clothing_image = self.load_from_url(self.clothing_url.value)

            # Display results
            if self.person_image and self.clothing_image:
                fig, axes = plt.subplots(1, 2, figsize=(10, 5))

                axes[0].imshow(self.person_image)
                axes[0].set_title('Person Image')
                axes[0].axis('off')

                axes[1].imshow(self.clothing_image)
                axes[1].set_title('Clothing Image')
                axes[1].axis('off')

                plt.tight_layout()
                plt.show()

                print(" Images loaded successfully!")
            else:
                print(" Please upload or provide URLs for both images")

    def display(self):
        """Display the upload interface"""
        display(widgets.VBox([
            widgets.HTML('<h3> Image Upload Interface</h3>'),
            widgets.HTML('<p>Upload images using the file selectors or paste URLs below:</p>'),

            widgets.HTML('<h4>Person Image:</h4>'),
            self.person_upload,
            self.person_url,

            widgets.HTML('<h4>Clothing Image:</h4>'),
            self.clothing_upload,
            self.clothing_url,

            self.load_button,
            self.output
        ]))

# Create and display the upload interface
uploader = ImageUploader()
uploader.display()

"""## Step 5: Virtual Try-On Pipeline

Complete pipeline function with proper error handling and parameter controls.
"""

def virtual_try_on_pipeline(
    person_image,
    clothing_image,
    prompt="photorealistic, perfect body, beautiful skin, realistic skin, natural skin",
    negative_prompt="ugly, bad quality, bad anatomy, deformed body, deformed hands, deformed feet, deformed face, deformed clothing, deformed skin, bad skin, leggings, tights, stockings",
    ip_scale=0.8,
    strength=0.99,
    guidance_scale=7.5,
    num_steps=50,
    show_process=True
):
    """
    Complete virtual try-on pipeline with visualization.

    Args:
        person_image: PIL Image of the person
        clothing_image: PIL Image of the clothing
        prompt: Generation prompt
        negative_prompt: Negative prompt
        ip_scale: IP-Adapter influence scale (0.0-1.0)
        strength: Inpainting strength (0.0-1.0)
        guidance_scale: CFG scale
        num_steps: Number of inference steps
        show_process: Whether to show intermediate results

    Returns:
        Generated image, mask image, segmented image
    """

    if show_process:
        print(" Step 1: Preparing images...")

    # Ensure images are the right size
    person_image = person_image.resize((512, 512))
    clothing_image = clothing_image.resize((512, 512))

    if show_process:
        print(" Step 2: Generating body segmentation mask...")

    # Generate segmentation mask
    try:
        # The segment_body function might expect different input types
        # Let's try both PIL image and file path approaches
        try:
            # First try with PIL image directly
            seg_image, mask_image = segment_body(person_image, face=False)
        except (AttributeError, TypeError):
            # If that fails, save to temp file and use path
            import tempfile
            with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as tmp_file:
                temp_person_path = tmp_file.name
                person_image.save(temp_person_path)

            seg_image, mask_image = segment_body(temp_person_path, face=False)

            # Clean up temp file
            os.unlink(temp_person_path)

        mask_image = mask_image.resize((512, 512))

    except Exception as e:
        print(f" Error in segmentation: {e}")
        return None, None, None

    if show_process:
        print(" Step 3: Running virtual try-on generation...")

        # Show intermediate results
        fig, axes = plt.subplots(1, 3, figsize=(15, 5))

        axes[0].imshow(person_image)
        axes[0].set_title('Original Person')
        axes[0].axis('off')

        axes[1].imshow(mask_image, cmap='gray')
        axes[1].set_title('Generated Mask')
        axes[1].axis('off')

        axes[2].imshow(clothing_image)
        axes[2].set_title('Target Clothing')
        axes[2].axis('off')

        plt.tight_layout()
        plt.show()

    # Set IP-Adapter scale
    pipeline.set_ip_adapter_scale(ip_scale)

    try:
        # Generate the result
        result = pipeline(
            prompt=prompt,
            negative_prompt=negative_prompt,
            image=person_image,
            mask_image=mask_image,
            ip_adapter_image=clothing_image,
            strength=strength,
            guidance_scale=guidance_scale,
            num_inference_steps=num_steps,
        )

        generated_image = result.images[0]

        if show_process:
            print(" Generation completed successfully!")

        return generated_image, mask_image, seg_image

    except Exception as e:
        print(f" Error in generation: {e}")
        return None, None, None

print(" Virtual try-on pipeline ready!")

"""## Step 6: Parameter Control Interface

Interactive controls for fine-tuning the generation parameters.
"""

class ParameterController:
    def __init__(self):
        self.setup_widgets()

    def setup_widgets(self):
        # Generation parameters
        self.prompt = widgets.Textarea(
            value="photorealistic, perfect body, beautiful skin, realistic skin, natural skin",
            description='Prompt:',
            style={'description_width': 'initial'},
            layout=widgets.Layout(width='600px', height='60px')
        )

        self.negative_prompt = widgets.Textarea(
            value="ugly, bad quality, bad anatomy, deformed body, deformed hands, deformed feet, deformed face, deformed clothing, deformed skin, bad skin, leggings, tights, stockings",
            description='Negative Prompt:',
            style={'description_width': 'initial'},
            layout=widgets.Layout(width='600px', height='80px')
        )

        self.ip_scale = widgets.FloatSlider(
            value=0.8,
            min=0.0,
            max=1.0,
            step=0.1,
            description='IP-Adapter Scale:',
            style={'description_width': 'initial'}
        )

        self.strength = widgets.FloatSlider(
            value=0.99,
            min=0.1,
            max=1.0,
            step=0.01,
            description='Inpainting Strength:',
            style={'description_width': 'initial'}
        )

        self.guidance_scale = widgets.FloatSlider(
            value=7.5,
            min=1.0,
            max=20.0,
            step=0.5,
            description='Guidance Scale:',
            style={'description_width': 'initial'}
        )

        self.num_steps = widgets.IntSlider(
            value=50,
            min=10,
            max=100,
            step=10,
            description='Inference Steps:',
            style={'description_width': 'initial'}
        )

        # Generate button
        self.generate_button = widgets.Button(
            description=' Generate Virtual Try-On',
            button_style='success',
            layout=widgets.Layout(width='300px', height='50px')
        )

        # Output area
        self.output = widgets.Output()

        # Bind events
        self.generate_button.on_click(self.generate)

    def generate(self, button):
        """Generate virtual try-on with current parameters"""
        with self.output:
            clear_output()

            if not (uploader.person_image and uploader.clothing_image):
                print(" Please upload both person and clothing images first!")
                return

            print(" Starting virtual try-on generation...")

            # Run the pipeline
            generated, mask, seg = virtual_try_on_pipeline(
                person_image=uploader.person_image,
                clothing_image=uploader.clothing_image,
                prompt=self.prompt.value,
                negative_prompt=self.negative_prompt.value,
                ip_scale=self.ip_scale.value,
                strength=self.strength.value,
                guidance_scale=self.guidance_scale.value,
                num_steps=self.num_steps.value,
                show_process=True
            )

            if generated:
                # Display final comparison
                fig, axes = plt.subplots(1, 2, figsize=(12, 6))

                axes[0].imshow(uploader.person_image)
                axes[0].set_title('Original', fontsize=14, fontweight='bold')
                axes[0].axis('off')

                axes[1].imshow(generated)
                axes[1].set_title('Virtual Try-On Result', fontsize=14, fontweight='bold')
                axes[1].axis('off')

                plt.tight_layout()
                plt.show()

                print(" Virtual try-on completed successfully!")

                # Store result for potential saving
                self.last_result = generated
            else:
                print(" Generation failed. Please try adjusting parameters.")

    def display(self):
        """Display the parameter control interface"""
        display(widgets.VBox([
            widgets.HTML('<h3> Generation Parameters</h3>'),

            widgets.HTML('<h4>Prompts:</h4>'),
            self.prompt,
            self.negative_prompt,

            widgets.HTML('<h4>Advanced Settings:</h4>'),
            widgets.HBox([self.ip_scale, self.strength]),
            widgets.HBox([self.guidance_scale, self.num_steps]),

            self.generate_button,
            self.output
        ]))

# Create parameter controller
controller = ParameterController()
controller.display()

def run_sample_demo():
    """Run a quick demo with sample images from URLs"""
    print(" Running sample demo...")

    # Sample image URLs
    person_url = 'https://thumbs.dreamstime.com/b/confident-full-body-casual-happy-woman-standing-wearing-jeans-isolated-white-background-37963228.jpg'
    clothing_url = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTv9q5PDBc7nD_eqy-PvMQjO9x7QCwzVKW7x3t7rG4NIBCpWzk8jOxphs7c_3tlBIWuurs&usqp=CAU'

    try:
        # Load sample images
        person_img = load_image(person_url).convert('RGB').resize((512, 512))
        clothing_img = load_image(clothing_url).convert('RGB').resize((512, 512))

        print(" Sample images loaded successfully!")

        # Run pipeline
        generated, mask, seg = virtual_try_on_pipeline(
            person_image=person_img,
            clothing_image=clothing_img,
            show_process=True
        )

        if generated:
            # Final comparison
            fig, axes = plt.subplots(1, 3, figsize=(18, 6))

            axes[0].imshow(person_img)
            axes[0].set_title('Original Person', fontsize=16, fontweight='bold')
            axes[0].axis('off')

            axes[1].imshow(clothing_img)
            axes[1].set_title('Target Clothing', fontsize=16, fontweight='bold')
            axes[1].axis('off')

            axes[2].imshow(generated)
            axes[2].set_title('Virtual Try-On Result', fontsize=16, fontweight='bold')
            axes[2].axis('off')

            plt.tight_layout()
            plt.show()

            print(" Sample demo completed successfully!")

    except Exception as e:
        print(f" Demo failed: {e}")

# Create demo button
demo_button = widgets.Button(
    description=' Run Sample Demo',
    button_style='info',
    layout=widgets.Layout(width='200px', height='40px')
)

demo_output = widgets.Output()

def on_demo_click(button):
    with demo_output:
        clear_output()
        run_sample_demo()

demo_button.on_click(on_demo_click)

display(widgets.VBox([
    widgets.HTML('<h3> Quick Demo</h3>'),
    widgets.HTML('<p>Click below to run a demo with sample images:</p>'),
    demo_button,
    demo_output
]))

def save_result(image, filename="virtual_tryon_result.png"):
    """Save generated image to file"""
    try:
        image.save(filename)
        print(f" Image saved as {filename}")
    except Exception as e:
        print(f" Error saving image: {e}")

def compare_results(original, generated, clothing=None):
    """Create a comparison visualization"""
    if clothing is not None:
        fig, axes = plt.subplots(1, 3, figsize=(18, 6))
        images = [original, clothing, generated]
        titles = ['Original Person', 'Target Clothing', 'Virtual Try-On Result']
    else:
        fig, axes = plt.subplots(1, 2, figsize=(12, 6))
        images = [original, generated]
        titles = ['Original', 'Generated']
        axes = [axes] if len(images) == 2 else axes

    for i, (img, title) in enumerate(zip(images, titles)):
        axes[i].imshow(img)
        axes[i].set_title(title, fontsize=14, fontweight='bold')
        axes[i].axis('off')

    plt.tight_layout()
    plt.show()

# Save button for last result
save_button = widgets.Button(
    description=' Save Last Result',
    button_style='warning',
    layout=widgets.Layout(width='200px')
)

filename_input = widgets.Text(
    value='virtual_tryon_result.png',
    description='Filename:',
    style={'description_width': 'initial'},
    layout=widgets.Layout(width='300px')
)

save_output = widgets.Output()

def on_save_click(button):
    with save_output:
        clear_output()
        if hasattr(controller, 'last_result') and controller.last_result:
            save_result(controller.last_result, filename_input.value)
        else:
            print(" No result to save. Generate an image first!")

save_button.on_click(on_save_click)

display(widgets.VBox([
    widgets.HTML('<h3> Save Results</h3>'),
    widgets.HBox([filename_input, save_button]),
    save_output
]))

print(" All utilities ready!")

"""**Next Steps:**
- Scale up training with larger dataset samples
- Experiment with different LoRA configurations
- Deploy model for production inference
"""



"""# Task
Generate virtual try-on images using the `virtual_try_on_pipeline` function with sample person and clothing images. Calculate and display the SSIM, PSNR, FID, and processing time for the generated images. Present the results in a clear format, including visualizations if possible.

## Generate sample images

### Subtask:
Use the existing `virtual_try_on_pipeline` function to generate a set of virtual try-on images using sample person and clothing images.

**Reasoning**:
The subtask requires loading sample images and running the virtual try-on pipeline. The existing `run_sample_demo` function in the notebook already performs these steps. I can extract the relevant code from that function to fulfill the current subtask.
"""

# Sample image URLs
person_url = 'https://thumbs.dreamstime.com/b/confident-full-body-casual-happy-woman-standing-wearing-jeans-isolated-white-background-37963228.jpg'
clothing_url = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTv9q5PDBc7nD_eqy-PvMQjO9x7QCwzVKW7x3t7rG4NIBCpWzk8jOxphs7c_3tlBIWuurs&usqp=CAU'

# Load sample images
person_img = load_image(person_url).convert('RGB').resize((512, 512))
clothing_img = load_image(clothing_url).convert('RGB').resize((512, 512))

print(" Sample images loaded successfully!")

# Run pipeline
generated_image, mask_image, seg_image = virtual_try_on_pipeline(
    person_image=person_img,
    clothing_image=clothing_img,
    show_process=True
)

if generated_image:
    print(" Virtual try-on generation completed.")
else:
    print(" Virtual try-on generation failed.")

"""## Calculate metrics

### Subtask:
Implement functions to calculate SSIM, PSNR, and FID between the original person images and the generated images. Also, measure the processing time for each generation.

**Reasoning**:
Implement functions to calculate SSIM, PSNR, and FID, and measure processing time. Then, apply these functions to the generated image and print the results.
"""

import time
import torchmetrics.functional as tm_functional
import torchvision.transforms as T

def calculate_ssim(img1, img2):
    """Calculates SSIM between two PIL images."""
    transform = T.ToTensor()
    img1_tensor = transform(img1).unsqueeze(0)
    img2_tensor = transform(img2).unsqueeze(0)
    # SSIM requires images to be on the same device
    if img1_tensor.device != img2_tensor.device:
        img2_tensor = img2_tensor.to(img1_tensor.device)
    return tm_functional.structural_similarity_index_measure(img1_tensor, img2_tensor)

def calculate_psnr(img1, img2):
    """Calculates PSNR between two PIL images."""
    transform = T.ToTensor()
    img1_tensor = transform(img1).unsqueeze(0)
    img2_tensor = transform(img2).unsqueeze(0)
    # PSNR requires images to be on the same device
    if img1_tensor.device != img2_tensor.device:
        img2_tensor = img2_tensor.to(img1_tensor.device)
    return tm_functional.peak_signal_noise_ratio(img1_tensor, img2_tensor)

def calculate_fid(img1, img2):
    """Calculates FID between two PIL images (as a proxy)."""
    # FID typically needs feature extractors and a set of images,
    # but for a simple comparison between two images, we can use a basic approach
    # using squared difference as a proxy, although this is NOT the true FID.
    # A proper FID implementation would require a pre-trained InceptionV3 model.
    # For the purpose of this task, we'll calculate the mean squared error as a proxy.
    transform = T.ToTensor()
    img1_tensor = transform(img1)
    img2_tensor = transform(img2)
    # Ensure tensors are on the same device
    if img1_tensor.device != img2_tensor.device:
        img2_tensor = img2_tensor.to(img1_tensor.device)
    return torch.mean((img1_tensor - img2_tensor)**2)


# Record start time
start_time = time.time()

# Run the pipeline again to measure time for this specific run
generated_image, mask_image, seg_image = virtual_try_on_pipeline(
    person_image=person_img,
    clothing_image=clothing_img,
    show_process=False # Set to False to avoid re-displaying intermediate steps
)

# Record end time
end_time = time.time()

# Calculate processing time
processing_time = end_time - start_time

# Calculate metrics if generation was successful
if generated_image:
    ssim_score = calculate_ssim(person_img, generated_image)
    psnr_score = calculate_psnr(person_img, generated_image)
    # Calculate proxy FID (MSE)
    fid_proxy_score = calculate_fid(person_img, generated_image)

    print("\n--- Performance Metrics ---")
    print(f" Processing Time: {processing_time:.2f} seconds")
    print(f" SSIM Score: {ssim_score:.4f}")
    print(f" PSNR Score: {psnr_score:.4f}")
    print(f" FID (Proxy - MSE) Score: {fid_proxy_score:.4f}")
    print("-------------------------")
else:
    print("\n Generation failed, metrics cannot be calculated.")

"""**Reasoning**:
The previous command failed because the `torchmetrics` library is not installed. Install the required library.


"""

# Commented out IPython magic to ensure Python compatibility.
# %pip install torchmetrics torchvision

"""**Reasoning**:
The required libraries are now installed. Re-run the code to implement the metric functions, measure processing time, calculate metrics, and print the results.


"""

import time
import torchmetrics.functional as tm_functional
import torchvision.transforms as T
import torch

def calculate_ssim(img1, img2):
    """Calculates SSIM between two PIL images."""
    transform = T.ToTensor()
    img1_tensor = transform(img1).unsqueeze(0)
    img2_tensor = transform(img2).unsqueeze(0)
    # SSIM requires images to be on the same device
    if img1_tensor.device != img2_tensor.device:
        img2_tensor = img2_tensor.to(img1_tensor.device)
    return tm_functional.structural_similarity_index_measure(img1_tensor, img2_tensor)

def calculate_psnr(img1, img2):
    """Calculates PSNR between two PIL images."""
    transform = T.ToTensor()
    img1_tensor = transform(img1).unsqueeze(0)
    img2_tensor = transform(img2).unsqueeze(0)
    # PSNR requires images to be on the same device
    if img1_tensor.device != img2_tensor.device:
        img2_tensor = img2_tensor.to(img1_tensor.device)
    return tm_functional.peak_signal_noise_ratio(img1_tensor, img2_tensor)

def calculate_fid(img1, img2):
    """Calculates FID between two PIL images (as a proxy)."""
    # FID typically needs feature extractors and a set of images,
    # but for a simple comparison between two images, we can use a basic approach
    # using squared difference as a proxy, although this is NOT the true FID.
    # A proper FID implementation would require a pre-trained InceptionV3 model.
    # For the purpose of this task, we'll calculate the mean squared error as a proxy.
    transform = T.ToTensor()
    img1_tensor = transform(img1)
    img2_tensor = transform(img2)
    # Ensure tensors are on the same device
    if img1_tensor.device != img2_tensor.device:
        img2_tensor = img2_tensor.to(img1_tensor.device)
    return torch.mean((img1_tensor - img2_tensor)**2)


# Record start time
start_time = time.time()

# Run the pipeline again to measure time for this specific run
generated_image, mask_image, seg_image = virtual_try_on_pipeline(
    person_image=person_img,
    clothing_image=clothing_img,
    show_process=False # Set to False to avoid re-displaying intermediate steps
)

# Record end time
end_time = time.time()

# Calculate processing time
processing_time = end_time - start_time

# Calculate metrics if generation was successful
if generated_image:
    ssim_score = calculate_ssim(person_img, generated_image)
    psnr_score = calculate_psnr(person_img, generated_image)
    # Calculate proxy FID (MSE)
    fid_proxy_score = calculate_fid(person_img, generated_image)

    print("\n--- Performance Metrics ---")
    print(f" Processing Time: {processing_time:.2f} seconds")
    print(f" SSIM Score: {ssim_score:.4f}")
    print(f" PSNR Score: {psnr_score:.4f}")
    print(f" FID (Proxy - MSE) Score: {fid_proxy_score:.4f}")
    print("-------------------------")
else:
    print("\n Generation failed, metrics cannot be calculated.")

"""**Reasoning**:
The error indicates that the SSIM and PSNR calculations are failing because the generated image is a different size (1024x1024) than the original person image (512x512). The pipeline was likely configured to output a larger image. Resize the generated image to match the size of the input person image before calculating the metrics.


"""

import time
import torchmetrics.functional as tm_functional
import torchvision.transforms as T
import torch

def calculate_ssim(img1, img2):
    """Calculates SSIM between two PIL images."""
    transform = T.ToTensor()
    img1_tensor = transform(img1).unsqueeze(0)
    img2_tensor = transform(img2).unsqueeze(0)
    # SSIM requires images to be on the same device
    if img1_tensor.device != img2_tensor.device:
        img2_tensor = img2_tensor.to(img1_tensor.device)
    return tm_functional.structural_similarity_index_measure(img1_tensor, img2_tensor)

def calculate_psnr(img1, img2):
    """Calculates PSNR between two PIL images."""
    transform = T.ToTensor()
    img1_tensor = transform(img1).unsqueeze(0)
    img2_tensor = transform(img2).unsqueeze(0)
    # PSNR requires images to be on the same device
    if img1_tensor.device != img2_tensor.device:
        img2_tensor = img2_tensor.to(img1_tensor.device)
    return tm_functional.peak_signal_noise_ratio(img1_tensor, img2_tensor)

def calculate_fid(img1, img2):
    """Calculates FID between two PIL images (as a proxy)."""
    # FID typically needs feature extractors and a set of images,
    # but for a simple comparison between two images, we can use a basic approach
    # using squared difference as a proxy, although this is NOT the true FID.
    # A proper FID implementation would require a pre-trained InceptionV3 model.
    # For the purpose of this task, we'll calculate the mean squared error as a proxy.
    transform = T.ToTensor()
    img1_tensor = transform(img1)
    img2_tensor = transform(img2)
    # Ensure tensors are on the same device
    if img1_tensor.device != img2_tensor.device:
        img2_tensor = img2_tensor.to(img1_tensor.device)
    return torch.mean((img1_tensor - img2_tensor)**2)


# Record start time
start_time = time.time()

# Run the pipeline again to measure time for this specific run
generated_image, mask_image, seg_image = virtual_try_on_pipeline(
    person_image=person_img,
    clothing_image=clothing_img,
    show_process=False # Set to False to avoid re-displaying intermediate steps
)

# Record end time
end_time = time.time()

# Calculate processing time
processing_time = end_time - start_time

# Calculate metrics if generation was successful
if generated_image:
    # Resize generated image to match person_img size before calculating metrics
    generated_image_resized = generated_image.resize(person_img.size)

    ssim_score = calculate_ssim(person_img, generated_image_resized)
    psnr_score = calculate_psnr(person_img, generated_image_resized)
    # Calculate proxy FID (MSE)
    fid_proxy_score = calculate_fid(person_img, generated_image_resized)

    print("\n--- Performance Metrics ---")
    print(f" Processing Time: {processing_time:.2f} seconds")
    print(f" SSIM Score: {ssim_score:.4f}")
    print(f" PSNR Score: {psnr_score:.4f}")
    print(f" FID (Proxy - MSE) Score: {fid_proxy_score:.4f}")
    print("-------------------------")
else:
    print("\n Generation failed, metrics cannot be calculated.")

"""## Store results

### Subtask:
Store the calculated metrics and processing times in a structured format (e.g., a pandas DataFrame).

**Reasoning**:
Store the calculated metrics and processing time in a pandas DataFrame for structured presentation.
"""

import pandas as pd

# Create a dictionary to hold the calculated metrics and processing time.
metrics_data = {
    'Processing Time': processing_time,
    'SSIM Score': ssim_score.item(), # Convert tensor to scalar
    'PSNR Score': psnr_score.item(), # Convert tensor to scalar
    'FID (Proxy - MSE) Score': fid_proxy_score.item() # Convert tensor to scalar
}

# Create a list containing this dictionary.
metrics_list = [metrics_data]

# Create a pandas DataFrame from the list of dictionaries.
metrics_df = pd.DataFrame(metrics_list)

# Display the created DataFrame.
display(metrics_df)

"""## Visualize results

### Subtask:
Create visualizations (e.g., bar charts or tables) to present the evaluation metrics and compare them if possible (although comparison data is not available for this specific model).

**Reasoning**:
Create a bar chart to visualize the evaluation metrics from the metrics_df DataFrame.
"""

import matplotlib.pyplot as plt

# Create a figure and axes
fig, ax = plt.subplots(figsize=(10, 6))

# Create a bar plot of the metrics
metrics_df.plot(kind='bar', ax=ax, legend=False)

# Rotate x-axis labels for better readability
plt.xticks(rotation=45, ha='right')

# Set plot title and y-axis label
plt.title("Evaluation Metrics", fontsize=16, fontweight='bold')
plt.ylabel("Score/Time", fontsize=12)

# Add the values on top of the bars
for container in ax.containers:
    ax.bar_label(container, fmt='%.4f')

plt.tight_layout()
plt.show()

"""## Summarize findings

### Subtask:
Provide a summary of the evaluation results and key findings.

**Reasoning**:
Based on the `metrics_df` and the generated plot, provide a summary of the evaluation results as requested in the instructions.
"""

print("--- Evaluation Results Summary ---")
print(f"Processing Time: {metrics_df['Processing Time'].iloc[0]:.2f} seconds")
print(f"SSIM Score: {metrics_df['SSIM Score'].iloc[0]:.4f} (Higher is generally better, indicates structural similarity)")
print(f"PSNR Score: {metrics_df['PSNR Score'].iloc[0]:.4f} (Higher is generally better, indicates image quality)")
print(f"FID (Proxy - MSE) Score: {metrics_df['FID (Proxy - MSE) Score'].iloc[0]:.4f} (Lower is generally better, indicates difference between images - this is a simple proxy, not true FID)")
print("\nObservations:")
print("- The virtual try-on generation took approximately 47.43 seconds for a 512x512 image on the available hardware.")
print("- The SSIM score of 0.9009 suggests a relatively high structural similarity between the original and generated images.")
print("- The PSNR score of 27.9312 indicates a reasonable level of image quality, though higher values would indicate less noise/distortion.")
print("- The low FID (Proxy - MSE) score of 0.0145 suggests a small difference between the original and generated images in terms of pixel values, which is a positive indicator for this proxy metric.")
print("--------------------------------")

"""## Summary:

### Data Analysis Key Findings

*   The virtual try-on generation process for a 512x512 image took approximately 47.43 seconds.
*   The generated image achieved an SSIM score of 0.9009, indicating a high structural similarity with the original person image.
*   A PSNR score of 27.9312 was calculated, suggesting a reasonable level of image quality.
*   The FID (Proxy - MSE) score was 0.0145, where a lower score indicates less difference between the original and generated images for this specific proxy metric.

### Insights or Next Steps

*   The processing time of 47.43 seconds per image might be a bottleneck for real-time or high-throughput applications, suggesting a need to explore optimization strategies for faster generation.
*   While the SSIM and PSNR scores are reasonably good, further fine-tuning of the model could potentially improve image quality and reduce artifacts, leading to higher scores.

"""