File size: 35,552 Bytes
d43c3c5
27c0da4
d43c3c5
 
 
 
 
 
 
 
 
 
 
 
 
3156d96
 
704a12b
b84561d
d43c3c5
 
 
 
 
 
 
 
 
 
 
 
c46710e
d43c3c5
 
 
c46710e
d43c3c5
 
 
994bd5b
 
 
 
 
62beae5
 
994bd5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d8054a
 
 
 
 
 
 
 
994bd5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b801f4
994bd5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b801f4
1d8054a
994bd5b
d43c3c5
994bd5b
d43c3c5
994bd5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d43c3c5
 
994bd5b
 
 
 
 
d43c3c5
 
994bd5b
3156d96
994bd5b
 
 
 
 
d43c3c5
994bd5b
 
 
006bdc6
994bd5b
d43c3c5
994bd5b
 
 
 
 
 
 
 
 
 
 
 
 
b83da92
 
 
994bd5b
 
 
 
 
 
 
d43c3c5
 
 
 
 
 
 
 
 
 
 
 
 
994bd5b
 
3156d96
 
994bd5b
d43c3c5
 
 
 
 
 
 
 
994bd5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3156d96
994bd5b
 
 
 
 
 
b84561d
 
 
 
 
d43c3c5
994bd5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3156d96
994bd5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3156d96
994bd5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62beae5
 
 
 
 
994bd5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b83da92
 
994bd5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b801f4
006bdc6
994bd5b
 
 
 
 
 
 
 
 
 
2b801f4
994bd5b
 
 
 
 
 
 
 
2b801f4
 
 
 
 
 
 
 
 
994bd5b
2b801f4
994bd5b
21a32f7
d43c3c5
 
 
23bda42
 
 
 
 
eddbb97
d43c3c5
 
 
 
53ae485
d43c3c5
 
 
 
 
 
 
b83da92
d43c3c5
 
 
 
 
ae51ed8
 
d43c3c5
 
 
 
 
 
 
 
994bd5b
d43c3c5
 
 
 
23bda42
 
006bdc6
d43c3c5
 
 
 
23bda42
d43c3c5
23bda42
d43c3c5
 
 
006bdc6
 
994bd5b
006bdc6
 
eddbb97
d43c3c5
 
 
 
 
 
 
 
 
994bd5b
d43c3c5
 
 
 
 
 
 
 
 
 
 
 
 
006bdc6
 
 
 
 
d43c3c5
 
 
f174699
d43c3c5
 
ae51ed8
d43c3c5
 
2b801f4
1d8054a
d43c3c5
 
006bdc6
d43c3c5
41aa245
d43c3c5
006bdc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d43c3c5
ae51ed8
006bdc6
d43c3c5
2b801f4
d43c3c5
 
 
 
 
 
2b801f4
 
006bdc6
 
d43c3c5
 
 
994bd5b
 
d43c3c5
 
 
 
994bd5b
 
d43c3c5
 
 
 
994bd5b
 
d43c3c5
 
 
 
994bd5b
 
d43c3c5
 
 
 
 
 
 
 
 
726c69b
006bdc6
2b801f4
d43c3c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
994bd5b
 
d43c3c5
 
2b801f4
 
 
 
 
 
 
 
 
 
 
 
994bd5b
 
 
 
 
 
3156d96
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
import gradio as gr
import spaces
import numpy as np
import random
from diffusers import DiffusionPipeline
import torch
from diffusers import StableDiffusionXLPipeline
import requests
import torch
from PIL import Image
from transformers import AutoProcessor, AutoModelForVision2Seq, BitsAndBytesConfig
from transformers.image_utils import load_image
from peft import PeftModel
import re
from diffusers import StableDiffusionXLPipeline, DiffusionPipeline
import anthropic
import base64
from datasets import load_dataset
from PIL import Image 

css="""
#col-container {
    margin: 0 auto;
    max-width: 520px;
}
#gen-container {
    margin: 0 auto;
    max-width: 640px;
}
#title-container {
    margin: 0 auto;
    max-width: 1340px;
}
#main-container {
    margin: 0 auto;
    max-width: 1340px;
}
"""

with gr.Blocks(css=css, title="ViPer Demo", theme=gr.themes.Base()) as demo:

    device = "cuda" if torch.cuda.is_available() else "cpu"


    #word_list_dataset = load_dataset("EPFL-VILAB/4m-wordlist", data_files="list.txt", use_auth_token=True)
    #word_list = word_list_dataset["train"]['text']

    bnb_config = BitsAndBytesConfig(
        load_in_4bit=True,
        bnb_4bit_use_double_quant=True,
        bnb_4bit_quant_type="nf4",
        bnb_4bit_compute_dtype=torch.float16,
        llm_int8_skip_modules=["lm_head", "embed_tokens"],
    )

    processor = AutoProcessor.from_pretrained("HuggingFaceM4/idefics2-8b", size= {"longest_edge": 448, "shortest_edge": 378}, do_image_splitting=False)

    vpe_model = AutoModelForVision2Seq.from_pretrained(
        "HuggingFaceM4/idefics2-8b",
        torch_dtype=torch.float16,    
        quantization_config=bnb_config,
    )

    vpe_model = PeftModel.from_pretrained(vpe_model, "EPFL-VILAB/VPE-ViPer").to("cuda")
    
    vpe_model = AutoModelForVision2Seq.from_pretrained(
        "HuggingFaceM4/idefics2-8b",
        torch_dtype=torch.float16,    
        quantization_config=bnb_config,
    )

    vpe_model = PeftModel.from_pretrained(vpe_model, "VPE2").to("cuda")

    if torch.cuda.is_available():
        pipe = StableDiffusionXLPipeline.from_pretrained(
            "stabilityai/stable-diffusion-xl-base-1.0", 
            torch_dtype=torch.float16
        ).to("cuda")
    else: 
        pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", use_safetensors=True)
        pipe = pipe.to(device)

    MAX_SEED = np.iinfo(np.int32).max
    MAX_IMAGE_SIZE = 1024

    valid_api = ""

    if torch.cuda.is_available():
        power_device = "GPU"
    else:
        power_device = "CPU"

    mioo = [
        "comment_images/15.png",
        "test.png",
        "comment_images/0.png",
        "comment_images/1.png",
        "comment_images/2.png",
        "comment_images/3.png",
        "comment_images/4.png",
        "comment_images/5.png",
        "comment_images/6.png",
        "comment_images/7.png",
        "comment_images/8.png",
        "comment_images/9.png",
        "comment_images/10.png",
        "comment_images/11.png",
        "comment_images/12.png",
        "comment_images/13.png",
        "comment_images/14.png",
        "comment_images/16.png",
        "comment_images/17.png",
        "comment_images/18.png",
        "comment_images/19.png",
        "comment_images/20.png",
        "comment_images/21.png",
        "comment_images/22.png",
        "comment_images/23.png",
        "comment_images/24.png",
        "comment_images/25.png",
        "comment_images/26.png",
        "comment_images/27.png",
        "comment_images/28.png",
        "comment_images/29.png",
        "comment_images/30.png",
        "comment_images/31.png",
        "comment_images/32.png",
        "comment_images/33.png",
        "comment_images/34.png",
        "comment_images/35.png",
        "comment_images/36.png",
        "comment_images/37.png",
        "comment_images/38.png",
        "comment_images/39.png",
        "comment_images/40.png",
        "comment_images/41.png",
        "comment_images/42.jpg",
        "comment_images/43.png",
        "comment_images/44.png",
        "comment_images/45.png",
        "comment_images/46.png",
        "comment_images/47.png",
        "comment_images/48.png",
        "comment_images/49.png",
        "comment_images/50.png",
        "comment_images/51.png",
        "comment_images/52.png",
        "comment_images/53.png",
        "comment_images/54.png",
        "comment_images/55.png"
    ]
    
    comment_images = gr.State(mioo)

    example_prompts = [
        "Painting of a lady",
        "Cityscape during a thunderstorm",
        "Inside an abondoned train, window view",
        "A person reaching for stars",
        "Abandoned robot at the depth of the sea",
        "Lonely astronaut in abyss",
        "Human in a frame"
    ]

    examples = {
        "A person reaching for stars":[
            "examples/A person reaching fo_0.png",
            "examples/A person reaching fo_1.png",
            "examples/A person reaching fo_2.png",
            "examples/A person reaching fo_4.png",
            "examples/A person reaching fo_5.png",
            "examples/A person reaching fo_6.png",
            "examples/A person reaching fo_8.png",
            "examples/A person reaching fo_9.png",
            "examples/A person reaching fo_10.png",
        ],
        "Abandoned robot at the depth of the sea":[
            "examples/Abandoned robot at t_0.png",
            "examples/Abandoned robot at t_1.png",
            "examples/Abandoned robot at t_2.png",
            "examples/Abandoned robot at t_4.png",
            "examples/Abandoned robot at t_5.png",
            "examples/Abandoned robot at t_6.png",
            "examples/Abandoned robot at t_8.png",
            "examples/Abandoned robot at t_9.png",
            "examples/Abandoned robot at t_10.png",
        ],
        "Cityscape during a thunderstorm":[
            "examples/Cityscape during a t_0.png",
            "examples/Cityscape during a t_1.png",
            "examples/Cityscape during a t_2.png",
            "examples/Cityscape during a t_4.png",
            "examples/Cityscape during a t_5.png",
            "examples/Cityscape during a t_6.png",
            "examples/Cityscape during a t_8.png",
            "examples/Cityscape during a t_9.png",
            "examples/Cityscape during a t_10.png",
        ],
        "Human in a frame":[
            "examples/Human in a frame_0.png",
            "examples/Human in a frame_1.png",
            "examples/Human in a frame_2.png",
            "examples/Human in a frame_4.png",
            "examples/Human in a frame_5.png",
            "examples/Human in a frame_6.png",
            "examples/Human in a frame_8.png",
            "examples/Human in a frame_9.png",
            "examples/Human in a frame_10.png",
        ],
        "Inside an abondoned train, window view":[
            "examples/Inside an abondoned _0.png",
            "examples/Inside an abondoned _1.png",
            "examples/Inside an abondoned _2.png",
            "examples/Inside an abondoned _4.png",
            "examples/Inside an abondoned _5.png",
            "examples/Inside an abondoned _6.png",
            "examples/Inside an abondoned _8.png",
            "examples/Inside an abondoned _9.png",
            "examples/Inside an abondoned _10.png",
        ],
        "Lonely astronaut in abyss":[
            "examples/Lonely astronaut in _0.png",
            "examples/Lonely astronaut in _1.png",
            "examples/Lonely astronaut in _2.png",
            "examples/Lonely astronaut in _4.png",
            "examples/Lonely astronaut in _5.png",
            "examples/Lonely astronaut in _6.png",
            "examples/Lonely astronaut in _8.png",
            "examples/Lonely astronaut in _9.png",
            "examples/Lonely astronaut in _10.png",
        ],
        "Painting of a lady":[
            "examples/Painting of a lady_0.png",
            "examples/Painting of a lady_1.png",
            "examples/Painting of a lady_2.png",
            "examples/Painting of a lady_4.png",
            "examples/Painting of a lady_5.png",
            "examples/Painting of a lady_6.png",
            "examples/Painting of a lady_8.png",
            "examples/Painting of a lady_9.png",
            "examples/Painting of a lady_10.png",
        ]
    }

    #comments = {'test.png': "Not sure about the concept, it's too straightforward. Though the boy looks kinda creepy which makes it exciting. the art style is pretty to look at. I like that the colors are muted, but wish they were a bit darker to make it more eerie and add depth.", 'comment_images/0.png': "Hate this with a passion. The colors are too vibrant and don't match at all. I hate these colors in general. The patterns are too abstract and contemporary. a 5-year-old could draw this. pass.", 'comment_images/1.png': "Woah I love the art style. The texture feels like old paper which is oh so beautiful. There are so many details to focus on. I love the expressive lines and how busy the composition is. Even though orange isn't my favorite, the greenish blue color of the water is so gorgeous.", 'comment_images/2.png': "I don't like how monochromatic and muted this one is. but the paperish texture is nice and the details are so intricate.", 'comment_images/3.png': "Oh super pretty! Looks so smooth and wet. Love the details and loose lines too. Feels mystical and magical and eerie. Also dark purples and blues? deep indigo? My fav ever. I'm here for it.", 'comment_images/4.png': "Love the art style. The uncanny vibe and nightmarish horror is so cool. Like its horror but if you squint you can't tell? Love the strange. wish it had more colors though. not a fan of greyscale.", 'comment_images/5.png': 'omg I hate this haha. what the hell. everything about it disgusts me so boring and childish ew.', 'comment_images/6.png': 'yessss. give it to the texture give it to the brushstrokes give it to the style. perfect. just wish the colors were less beige and more bold. I want an active nightmare. but kisses to the surrealism.'}
    comments = gr.State(dict())

    image_index = gr.State(0)

    def submit_comment(comment, comments, comment_images, image_index):
        if comment != "":
            comments[comment_images[0]] = comment
            comment_images.append(comment_images[0])
            comment_images = comment_images[1:]
            image_index = (image_index + 1) % len(comment_images)

        elif comment_images[0] in comments:
            comments.pop(comment_images[0], None)

        next_comment = ""
        if comment_images[0] in comments:
            next_comment = comments[comment_images[0]]

        clear_botton = gr.Button("Clear comments", interactive=len(comments) != 0)

        return (gr.Image(value=comment_images[0], label=f"image {image_index+1}/{len(comment_images)}", show_label=True),
                gr.Text(label="Comment", show_label=False, lines=4, max_lines=5, placeholder="Enter your comment. The more detailed the better.", value=next_comment, container=False),
                gr.Button(f"Extract visual preference from {len(comments)} comments", interactive=len(comments) >= 5, variant="primary"),
                clear_botton,
                comments,
                comment_images,
                image_index
               )

    def next_image(comments, comment_images, image_index):
        comment_images.append(comment_images[0])
        comment_images = comment_images[1:]

        next_comment = ""
        if comment_images[0] in comments:
            next_comment = comments[comment_images[0]]

        image_index = (image_index + 1) % len(comment_images)

        return gr.Image(value=comment_images[0], label=f"image {image_index+1}/{len(comment_images)}", show_label=True), gr.Text(label="Comment", show_label=False, lines=4, max_lines=5, placeholder="Enter your comment. The more detailed the better.", value=next_comment, container=False), comments, comment_images, image_index

    def previous_image(comments, comment_images, image_index):
        comment_images = comment_images[::-1]
        comment_images.append(comment_images[0])
        comment_images = comment_images[1:]
        comment_images = comment_images[::-1]

        next_comment = ""
        if comment_images[0] in comments:
            next_comment = comments[comment_images[0]]

        image_index = (image_index - 1) % len(comment_images)

        return gr.Image(value=comment_images[0], label=f"image {image_index+1}/{len(comment_images)}", show_label=True), gr.Text(label="Comment", show_label=False, lines=4, max_lines=5, placeholder="Enter your comment. The more detailed the better.", value=next_comment, container=False), comments, comment_images, image_index

    def clear_comments(comments):
        comments.clear()
        extract_vp_botton = gr.Button(f"Extract visual preference from {len(comments)} comments", interactive=len(comments) >= 5, variant="primary")
        clear_botton = gr.Button("Clear comments", interactive=len(comments) != 0)
        return extract_vp_botton, clear_botton, comments

    @spaces.GPU(duration=120)
    def extract_vp_from_vpe(comments):
        if len(comments) < 8:
            gr.Warning("Fewer than 8 comments may lead to errors.")

        keys =  list(comments.keys())
        random.shuffle(keys)
        comments = dict([(key, comments[key]) for key in keys])

        prompt = """I will provide a set of artworks along with accompanying comments from a person. Analyze these artworks and the comments on them and identify artistic features such as present or mentioned colors, style, composition, mood, medium, texture, brushwork, lighting, shadow effects, perspective, and other noteworthy elements.
    Your task is to extract the artistic features the person likes and dislikes based on both the artworks' features and the person's comments. Focus solely on artistic aspects and refrain from considering subject matter.
    If the person expresses a preference for a specific aspect without clearly stating its category (e.g., appreciating the colors without specifying which colors), identify these specific features from the images directly to make the person's preference understandable without needing to see the artwork.
    Your output should consist of two concise lists of keywords: one listing the specific art features the person likes and another listing the specific features they dislike (specified in keyword format without using sentences).
    Here are the images and their corresponding comments:
    """
        messages = [
            {
                "role": "user",
                "content": [
                    {"type": "text", 
                    "text": prompt},
                ]
            }
        ]
        images = []
        comment_number = 1
        for image in comments:
            comment = comments[image]
            image = Image.open(image)
            images.append(image)

            messages[0]["content"].append(
                {"type": "image"}
            )

            messages[0]["content"].append(
                {"type": "text", 
                 "text": f"Comment {comment_number}: {comment}"}
            )
            comment_number = comment_number + 1

        prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
        inputs = processor(text=prompt, images=images, return_tensors="pt")
        inputs = {k: v.to(device) for k, v in inputs.items()}

        generated_ids = vpe_model.generate(**inputs, max_new_tokens=2000, repetition_penalty=0.99, do_sample=False)
        generated_texts = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]

        if re.match(r"(.|\n)*Assistant: Liked Art Features: (.|\n)*Disliked Art Features: (.|\n)*", generated_texts):
            positive_vp, negative_vp = re.search('.* \nAssistant: Liked Art Features: (.*)\nDisliked Art Features: (.*)', generated_texts).groups()
            positive_vp = positive_vp.split(", ")
            negative_vp = negative_vp.split(", ")
            common = list(set(positive_vp).intersection(negative_vp))

            for vp in positive_vp:
                if vp in common:
                    positive_vp.remove(vp)

            for vp in negative_vp:
                if vp in common:
                    negative_vp.remove(vp)

            positive_vp = ", ".join(positive_vp)
            negative_vp = ", ".join(negative_vp)
            gr.Info("Visual preference successfully extracted.")
        else:
            positive_vp = ""
            negative_vp = ""
            gr.Warning("VP extraction failed: Please comment on more images.")

        return positive_vp, negative_vp

    def extract_vp(comments):

        if valid_api == "":
            positive_vp, negative_vp = extract_vp_from_vpe(comments)

        else:
            client = anthropic.Anthropic(
                api_key=valid_api,
            )

            prompt = """**Objective:**
    Analyze a set of artworks and accompanying comments from a person to identify artistic features they like and dislike.
    **Steps:**
    1. **Analyze Artworks and Comments:**
       - Examine each artwork for artistic features such as colors, style, composition, mood, medium, texture, brushwork, lighting, shadow effects, perspective, and other noteworthy elements.
       - Review the accompanying comments to understand the person's preferences and opinions on these features.
    2. **Identify Preferences:**
       - Extract artistic features that the person likes and dislikes based on the artworks' features and the comments.
       - Focus solely on artistic aspects and ignore the subject matter.
       - Convert the art features mentioned in the comments to well-known synonyms if needed.
    3. **Resolve Ambiguous Preferences:**
       - If the person expresses a preference without clearly stating its category (e.g., "I like the style" without specifying which style), identify these specific features from the images directly.
       - Make the person's preference understandable and independednt of the artworks.
    4. **Output Format:**
       - Create two concise lists of keywords: one for features the person likes and another for features they dislike.
       - Ensure the lists are in keyword format, divided by commas, without using sentences.
       - Maintain detail and accuracy for all comments and images.
    **Your Task:**
    Follow the example format and ensure that your output consists of two lists of keywords summarizing the person's preferences based on the artworks and comments provided. Consider all comments and images comprehensively.
    **Example**: example START:
    """
            messages = [
                {
                    "role": "user",
                    "content": [
                        {"type": "text", 
                        "text": prompt},
                    ]
                }
            ]
            images = []
            comment_number = 1
            for image in comments:
                comment = comments[image]
                if not image.lower().endswith(".jpg"):
                    jpg_image_path = image.replace("png", "jpg")
                    image = Image.open(image)
                    rgb_img = image.convert("RGB")
                    rgb_img.save(jpg_image_path, format="JPEG")
                    with open(jpg_image_path, "rb") as image_file:
                        image = base64.b64encode(image_file.read()).decode("utf-8")

                else:
                    with open(image_path, "rb") as image_file:
                        image = base64.b64encode(image_file.read()).decode("utf-8")

                messages[0]["content"].append(
                    {"type": "text",
                    "text": f"Image {comment_number}:"}
                )

                messages[0]["content"].append(
                    {"type": "image",
                    "source": {
                            "type": "base64",
                            "media_type": "image/jpeg",
                            "data": image,
                        },}
                )

                messages[0]["content"].append(
                    {"type": "text", 
                     "text": f"Comment {comment_number}: {comment}"}
                )
                comment_number = comment_number + 1

            message = client.messages.create(
                model="claude-3-5-sonnet-20240620",
                max_tokens=1024,
                messages=messages
            )

            generated_text = message.content[0].text
            if re.match(r"(.|\n)*Like.*:(.|\n)*Dislike.(.|\n)*", generated_texts):
                positive_vp, negative_vp = re.search('.*Like.*:\n(.*)\n*Dislike.*:\n(.*)', generated_text).groups()
                gr.Info("Visual preference successfully extracted.")
            else:
                positive_vp = ""
                negative_vp = ""
                gr.Warning("VP extraction failed: Please comment on more images.")

        return gr.Textbox(label="Liked visual attributes", lines=3, value=positive_vp, interactive=True), gr.Textbox(label="Disliked visual attributes", lines=1, value=negative_vp, interactive=True), gr.Button("Run personalized generation", scale=0, interactive=True, variant="primary"), comments

    def api_fn(api):
        global valid_api
        client = anthropic.Anthropic(
            api_key=api,
        )
        try:
            message = client.messages.create(
                model="claude-3-5-sonnet-20240620",
                max_tokens=1024,
                messages=[
                    {"role": "user", "content": "Hello, Claude"}
                ]
            )
            gr.Info("Valid API")
            valid_api = api

        except anthropic.AuthenticationError:
            gr.Warning("Invalid API!")
            valid_api = ""

        except anthropic.BadRequestError:
            gr.Warning("Invalid API!")
            valid_api = ""

        except anthropic.PermissionDeniedError:
            gr.Warning("Invalid API!")
            valid_api = ""

        except anthropic.RateLimitError:
            gr.Warning("Invalid API!")
            valid_api = ""


    def generate_out(prompt, vp_pos, vp_neg, slider, example_prompt, gallery, num_inference_steps, seed, randomize_seed):
        if vp_pos == "" and vp_neg == "":
            gr.Warning("Visual preference is empty.", duration=10)

        return generate(prompt, vp_pos, vp_neg, slider, example_prompt, gallery, num_inference_steps, seed, randomize_seed)

    @spaces.GPU(duration=45)
    def generate(prompt, vp_pos, vp_neg, slider, example_prompt, gallery, num_inference_steps, seed, randomize_seed):
        if vp_pos == "" and vp_neg == "":
            slider = 0

        #for filter in word_list:
        #    if re.search(rf"\b{filter}\b", prompt):
        #        raise gr.Error("Please try again with a different prompt")
        #    if re.search(rf"\b{filter}\b", vp_pos) or re.search(rf"\b{filter}\b", vp_neg):
        #        raise gr.Error("Please try again with a different visual preference")

        if vp_pos != "":
            vp_pos = vp_pos.split(", ")
            random.shuffle(vp_pos)
            vp_pos = ", ".join(vp_pos)

        if vp_neg != "":
            vp_neg = vp_neg.split(", ")
            random.shuffle(vp_neg)
            vp_neg = ", ".join(vp_neg)

        if randomize_seed:
            seed = random.randint(0, MAX_SEED)

        generator = torch.Generator().manual_seed(seed)

        if prompt is None:
            gr.Warning("Prompt is empty: a random image will be generated.")
            prompt = ""

        image = pipe(prompt=prompt, 
                    num_inference_steps=num_inference_steps, 
                    vp_pos=vp_pos, 
                    vp_neg=vp_neg, 
                    vp_degree_pos=slider,
                    vp_degree_neg=slider,
                    generator=generator
        ).images[0]

        global example_prompts, examples
        if prompt in example_prompts:
            while example_prompts[0] != prompt:
                example_prompts.append(example_prompts[0])
                example_prompts = example_prompts[1:]

            example_prompt = gr.Markdown(f"Prompt: {example_prompts[0]}")
            if len(examples[example_prompts[0]]) == 10:
                examples[example_prompts[0]] = examples[example_prompts[0]][:-1]

            examples[example_prompts[0]].append(image)
            gallery = gr.Gallery(
                value=examples[example_prompts[0]],
                label="", 
                show_label=False,
                columns=[5],
                rows=[2], 
                object_fit="contain", 
                height=500)

        return image, example_prompt, gallery

    def change_vp(extract_vp):
        return

    def upload_file(files):
        global mioo
        file_path = [file.name for file in files][0]
        comment_images = [file_path] + comment_images

        next_comment = ""
        return gr.Image(value=mioo[0], label=f"image {0+1}/{len(mioo)}", show_label=True), gr.Text(label="Comment", show_label=False, lines=4, max_lines=5, placeholder="Enter your comment. The more detailed the better.", value=next_comment, container=False)

    def next_prompt():
        global example_prompts, examples
        example_prompts.append(example_prompts[0])
        example_prompts = example_prompts[1:]

        example_prompt = gr.Markdown(f"Prompt: {example_prompts[0]}")
        gallery = gr.Gallery(
            value=examples[example_prompts[0]],
            label="", 
            show_label=False,
            columns=[5],
            rows=[2], 
            object_fit="contain", 
            height=500)

        return example_prompt, gallery

    def previous_prompt():
        global example_prompts, examples
        example_prompts = example_prompts[::-1]
        example_prompts.append(example_prompts[0])
        example_prompts = example_prompts[1:]
        example_prompts = example_prompts[::-1]

        example_prompt = gr.Markdown(f"Prompt: {example_prompts[0]}")
        gallery = gr.Gallery(
            value=examples[example_prompts[0]],
            label="", 
            show_label=False,
            columns=[5],
            rows=[2], 
            object_fit="contain", 
            height=500)

        return example_prompt, gallery

    ###############################################
    with gr.Column(elem_id="title-container"):
        gr.Markdown(f"""
                # **ViPer: Visual Personalization of Generative Models via Individual Preference Learning**
                \n
                \n
                \n
                """)
        gr.Markdown(f"""
                \nViPer is a personalization method that extracts individual preferences by asking users to comment on a few images, explaining their likes and dislikes. These preferences then guide a text-to-image model to produce images tailored to the individual's tastes.
                \n
                \n
                \n
                """)
    with gr.Row(elem_id="main-container"):
            
        with gr.Column(elem_id="col-container"):
    
            gr.Markdown(f"""
                ## Step 1: Extracting visual preference from comments on images
            """
            )

            gr.Markdown("Please write your comments on the images below, explaining why you like or dislike each one from an artistic perspective. Comment on a mix of images: some that you like and some that you dislike. Focus on images that evoke strong reactions, whether positive or negative, and skip those that don't affect you much. More detailed comments will help us provide more personalized results. We recommend commenting on at least 8 images. If none of the provided images interest you, you can upload your own images.")


            with gr.Accordion("Examples of Effective Comments", open=False):
                example_comment_1 = gr.Textbox(
                    label="Example 1",
                    lines=2,
                    value="I don't like this at all. The beige colors bother me. It's so minimal and boring. The texture feels too shallow.",
                )

                example_comment_2 = gr.Textbox(
                    label="Example 2",
                    lines=4,
                    value="I adore the blue and greenish-blue palette, blue Dianne, and dark colors of this image. I also appreciate the Hergé inspiration in this artwork. However, I would have preferred a more complex and adventurous concept rather than a simple landscape. I wish it was more surreal and creepy.",
                )
    
            comment_image = gr.Image(value=mioo[0], label=f"image {0+1}/{len(mioo)}", show_label=True)
                      
            comment = gr.Text(
                label="Comment",
                show_label=False,
                lines=4,
                max_lines=5,
                placeholder="Enter your comment. The more detailed the better.",
                container=False,
            )
    
            with gr.Row():
                previous_image_botton = gr.Button("⬅ Previous image", scale=0)
                submit_comment_button = gr.Button("Submit comment", scale=0)
                next_image_botton = gr.Button("Skip image ➡", scale=0)

            file_output = gr.File(visible=False)

            with gr.Row():
                upload_button = gr.UploadButton("Click to upload images 📤", file_types=["image"], file_count="multiple")
                clear_botton = gr.Button("Clear comments 🗑", interactive=False)

            with gr.Accordion("Enter Claude API (optional)", open=False):
                gr.Markdown("By default, we extract visual preferences from user comments using a fine-tuned HuggingFaceM4/idefics2-8b model. Optionally, you can experiment with using claude-3-5-sonnet for visual preference extraction by entering your API key below.")
                with gr.Row():
                    api = gr.Text(
                        max_lines=1,
                        placeholder="Enter your API",
                        container=False,
                    )
                    
                    api_button = gr.Button("Enter", scale=0)
    
            extract_vp_botton = gr.Button(f"Extract visual preference from {0} comments", interactive=False, variant="primary")

        with gr.Column(elem_id="gen-container"):
            positive_extracted_vp = gr.Textbox(
                label="Liked visual attributes",
                lines=3,
                value="",
            )

            negative_extracted_vp = gr.Textbox(
                label="Disliked visual attributes",
                lines=1,
                value="",
            )

            gr.Markdown(f"""
                Hint: You can edit your visual preference in case of hallucinations.
            """
            )
    
            gr.Markdown(f"""
                ## Step 2: Personalized image generation (using Stable Diffusion XL)
                Generate personalized images using the visual preference extracted from your comments by entering a prompt below! You can adjust the personalization degree to generate results that are more or less personalized and diverse.
                """)

            slider = gr.Slider(value=0.85, minimum=0, maximum=1, label="Personalization degree", interactive=True)
    
            with gr.Row():
                prompt = gr.Dropdown(
                    example_prompts, label="Prompt", info="Enter your prompt or choose an example prompt from the dropdown.", allow_custom_value=True, multiselect=False, show_label=False
                )
                
                run_button = gr.Button("Run personalized generation", scale=0, interactive=True, variant="primary")

            result = gr.Image(label="Result", show_label=False, interactive=False)

            with gr.Accordion("Advanced Settings", open=False):
                
                with gr.Row():
                    seed = gr.Slider(
                        label="Seed",
                        minimum=0,
                        maximum=1000,
                        step=1,
                        value=0,
                    )

                    num_inference_steps = gr.Slider(
                        label="Number of inference steps",
                        minimum=1,
                        maximum=50,
                        step=1,
                        value=40,
                    )

                randomize_seed = gr.Checkbox(label="Randomize seed", value=True)

    with gr.Row(elem_id="main-container"):
        with gr.Accordion("Images generated from the example prompts, but with different extracted preferences. The first image shows the non-personalized baseline generation.", open=True): 
            example_prompt = gr.Markdown(f"Prompt: {example_prompts[0]}")
            gallery = gr.Gallery(
                value=examples[example_prompts[0]],
                label="", 
                show_label=False,
                columns=[5],
                rows=[2], 
                object_fit="contain", 
                height=500)

            with gr.Row():
                pre_prompt_button = gr.Button("⬅ Previous prompt", scale=1, interactive=True)
                next_prompt_button = gr.Button("Next prompt ➡", scale=1, interactive=True)
            
    submit_comment_button.click(
        fn = submit_comment,
        inputs = [comment, comments, comment_images, image_index],
        outputs = [comment_image, comment, extract_vp_botton, clear_botton, comments, comment_images, image_index]
    )

    previous_image_botton.click(
        fn = previous_image,
        inputs = [comments, comment_images, image_index],
        outputs = [comment_image, comment, comments, comment_images, image_index]
    )

    next_image_botton.click( 
        fn = next_image,
        inputs = [comments, comment_images, image_index],
        outputs = [comment_image, comment, comments, comment_images, image_index]
    )

    extract_vp_botton.click(
        fn = extract_vp,
        inputs = [comments],
        outputs = [positive_extracted_vp, negative_extracted_vp, run_button, comments]
    )

    api_button.click(
        fn = api_fn,
        inputs = [api],
        outputs = [],
    )

    run_button.click(
        fn = generate_out,
        inputs = [prompt, positive_extracted_vp, negative_extracted_vp, slider, example_prompt, gallery, num_inference_steps, seed, randomize_seed],
        outputs = [result, example_prompt, gallery],
    )

    positive_extracted_vp.change(
        fn = change_vp,
        inputs = [positive_extracted_vp],
        outputs = [],
    )
    
    negative_extracted_vp.change(
        fn = change_vp,
        inputs = [negative_extracted_vp],
        outputs = [],
    )

    clear_botton.click(
        fn = clear_comments,
        inputs = [comments],
        outputs = [extract_vp_botton, clear_botton, comments]
    )

    next_prompt_button.click(
        fn = next_prompt,
        inputs = [],
        outputs = [example_prompt, gallery]
    )

    pre_prompt_button.click(
        fn = previous_prompt,
        inputs = [],
        outputs = [example_prompt, gallery]
    )

    upload_button.upload(
        upload_file, 
        upload_button, 
        [comment_image, comment]
    )

demo.launch(share=True)