File size: 33,836 Bytes
04968d8
 
 
 
 
 
 
950a189
04968d8
 
 
 
5165bea
04968d8
5165bea
78d83ec
04968d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b576ce
96c47f6
 
 
 
9b576ce
04968d8
 
 
 
 
 
 
 
 
 
 
 
5165bea
 
 
 
04968d8
 
5165bea
 
04968d8
 
 
 
 
 
 
 
 
e692863
 
 
 
 
 
 
 
 
 
 
04968d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06f88eb
04968d8
 
 
 
 
 
 
 
06f88eb
04968d8
06f88eb
04968d8
 
 
 
 
 
 
 
 
 
 
 
 
 
5165bea
 
 
 
 
 
04968d8
5165bea
e692863
 
04968d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5cc0179
a31e3c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5cc0179
04968d8
 
 
 
 
 
 
 
 
 
 
 
a31e3c6
 
 
 
 
 
04968d8
 
a31e3c6
 
 
 
 
 
 
 
 
04968d8
a31e3c6
04968d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ce5a2b
04968d8
1ce5a2b
 
04968d8
 
 
a31e3c6
04968d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a31e3c6
04968d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5cc0179
c9ab7bf
 
04968d8
5cc0179
410687f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04968d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5cc0179
c9ab7bf
ef7d498
c9ab7bf
5cc0179
2a8a127
aa72610
 
f9e27ef
aa72610
5cc0179
04968d8
 
 
 
 
 
 
 
 
 
 
5cc0179
c9ab7bf
04968d8
c9ab7bf
04968d8
 
 
 
 
5cc0179
 
 
04968d8
c9ab7bf
04968d8
5cc0179
 
 
04968d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9ab7bf
04968d8
 
1ce5a2b
04968d8
 
 
 
c9ab7bf
5cc0179
 
 
e3b3385
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b576ce
e3b3385
 
c9ab7bf
e3b3385
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04968d8
 
 
c9ab7bf
983bd2f
 
 
 
 
 
 
c9ab7bf
 
d97e4e5
 
 
 
0c76176
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9ab7bf
04968d8
 
 
 
 
 
d97e4e5
04968d8
 
9b576ce
 
 
 
 
 
04968d8
 
 
 
d97e4e5
04968d8
dc439a7
9b576ce
 
 
d97e4e5
04968d8
a85c08c
58133b1
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
import ast
import copy
import glob
import hashlib
import logging
import os
import re
import time
from pathlib import Path
from typing import List, Optional, Tuple
from urllib.parse import urlparse
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO

import requests
import concurrent.futures
import random
import gradio as gr
import PIL
from gradio import processing_utils
from gradio_client.client import DEFAULT_TEMP_DIR
from text_generation import Client
from transformers import AutoProcessor


MODELS = [
    # "HuggingFaceM4/idefics-9b-instruct",
    "HuggingFaceM4/idefics-80b-instruct",
]

API_PATHS = {
    "HuggingFaceM4/idefics-9b-instruct": (
        "https://api-inference.huggingface.co/models/HuggingFaceM4/idefics-9b-instruct"
    ),
    "HuggingFaceM4/idefics-80b-instruct": (
        "https://api-inference.huggingface.co/models/HuggingFaceM4/idefics-80b-instruct"
    ),
}

SYSTEM_PROMPT = [
    """The following is a conversation between a highly knowledgeable and intelligent visual AI assistant, called Assistant, and a human user, called User.
In the following interactions, User and Assistant will converse in natural language, and Assistant will answer in a sassy way.
Assistant's main purpose is to create funny meme texts from the images User provides.
Assistant should be funny, sassy, and impertinent, and sometimes Assistant roasts people.
Assistant should not be mean. It should not say toxic, homophobic, sexist, racist, things or any demeaning things that can make people uncomfortable.
Assistant was created by Hugging Face.

Here's a conversation example:""",
    """\nUser:""",
    "https://ichef.bbci.co.uk/news/976/cpsprodpb/7727/production/_103330503_musk3.jpg",
    "Write a meme for that image.<end_of_utterance>",
    """\nAssistant: When you're trying to quit smoking but the cravings are too strong.<end_of_utterance>""",
    "\nUser:How about this image?",
    "https://www.boredpanda.com/blog/wp-content/uploads/2017/01/image-copy-copy-587d0e7918b57-png__700.jpg",
    "Write something funny about this image.<end_of_utterance>",
    """\nAssistant: Eggcellent service!<end_of_utterance>""",
    "\nUser: Roast this person",
    "https://i.pinimg.com/564x/98/34/4b/98344b2483bd7c8b71a5c0fed6fe20b6.jpg",
    "<end_of_utterance>",
    """\nAssistant: Damn your handwritting is pretty awful. But I suppose it must be pretty hard to hold a pen, considering you are a hammerhead shark.<end_of_utterance>""",
]

BAN_TOKENS = (  # For documentation puporse. We are not using this list, it is hardcoded inside `idefics_causal_lm.py` inside TGI.
    "<image>;<fake_token_around_image>"
)
EOS_STRINGS = ["<end_of_utterance>", "\nUser:"]
STOP_SUSPECT_LIST = []

API_TOKEN = os.getenv("HF_AUTH_TOKEN")
IDEFICS_LOGO = "https://huggingface.co/spaces/HuggingFaceM4/idefics_playground/resolve/main/IDEFICS_logo.png"

PROCESSOR = AutoProcessor.from_pretrained(
    "HuggingFaceM4/idefics-9b-instruct",
    token=API_TOKEN,
)

BOT_AVATAR = "IDEFICS_logo.png"
IMAGE_GALLERY_PATHS = [
    f"example_images/{image_dir}/{ex_image}"
    for image_dir in os.listdir("example_images")
    for ex_image in os.listdir(f"example_images/{image_dir}")
]
random.shuffle(IMAGE_GALLERY_PATHS)
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()


# Monkey patch adapted from gradio.components.image.Image - mostly to make the `save` step optional in `pil_to_temp_file`
def hash_bytes(bytes: bytes):
    sha1 = hashlib.sha1()
    sha1.update(bytes)
    return sha1.hexdigest()


def pil_to_temp_file(
    img: PIL.Image.Image,
    dir: str = DEFAULT_TEMP_DIR,
    format: str = "png",
    resize: bool = False,
) -> str:
    """Save a PIL image into a temp file"""
    if resize:
        img = img.resize((224, 224), Image.LANCZOS)
    bytes_data = processing_utils.encode_pil_to_bytes(img, format)
    temp_dir = Path(dir) / hash_bytes(bytes_data)
    temp_dir.mkdir(exist_ok=True, parents=True)
    filename = str(temp_dir / f"image.{format}")
    if not os.path.exists(filename):
        img.save(filename, pnginfo=processing_utils.get_pil_metadata(img))
    return filename


def pil_to_base64(
    img: PIL.Image.Image,
    resize: bool = False,
) -> str:
    """Save a PIL image into a temp file"""
    if resize:
        img = img.resize((224, 224), Image.LANCZOS)
    base64_img = processing_utils.encode_pil_to_base64(img)
    return base64_img


def add_file_gallery(selected_state: gr.SelectData, gallery_list: List[str]):
    return (
        "Write a meme about this image.",
        gallery_list[selected_state.index]["name"],
        "",
    )


def choose_gallery(gallery_type: str):
    if gallery_type == "Meme templates":
        image_gallery_list = [
            f"example_images/meme_templates/{ex_image}"
            for ex_image in os.listdir("example_images/meme_templates")
        ]
    elif gallery_type == "Funny images":
        image_gallery_list = [
            f"example_images/funny_images/{ex_image}"
            for ex_image in os.listdir("example_images/funny_images")
        ]
    elif gallery_type == "Politics":
        image_gallery_list = [
            f"example_images/politics_memes/{ex_image}"
            for ex_image in os.listdir("example_images/politics_memes")
        ]
    else:
        image_gallery_list = [
            f"example_images/{image_dir}/{ex_image}"
            for image_dir in os.listdir("example_images")
            for ex_image in os.listdir(f"example_images/{image_dir}")
        ]
    random.shuffle(image_gallery_list)
    return image_gallery_list


# Utils to handle the image markdown display logic
def split_str_on_im_markdown(string: str) -> List[str]:
    """
    Extract from a string (typically the user prompt string) the potential images from markdown
    Examples:
    - `User:![](https://favurl.com/chicken_on_money.png)Describe this image.` would become `["User:", "https://favurl.com/chicken_on_money.png", "Describe this image."]`
    - `User:![](/file=/my_temp/chicken_on_money.png)Describe this image.` would become `["User:", "/my_temp/chicken_on_money.png", "Describe this image."]`
    """
    IMAGES_PATTERN = re.compile(r"!\[[^\]]*\]\((.*?)\s*(\"(?:.*[^\"])\")?\s*\)")
    parts = []
    cursor = 0
    for pattern in IMAGES_PATTERN.finditer(string):
        start = pattern.start()
        if start != cursor:
            parts.append(string[cursor:start])
        image_url = pattern.group(1)
        if image_url.startswith("/file="):
            image_url = image_url[6:]  # Remove the 'file=' prefix
        parts.append(image_url)
        cursor = pattern.end()
    if cursor != len(string):
        parts.append(string[cursor:])
    return parts


def is_image(string: str) -> bool:
    """
    There are two ways for images: local image path or url.
    """
    return is_url(string) or string.startswith(DEFAULT_TEMP_DIR)


def is_url(string: str) -> bool:
    """
    Checks if the passed string contains a valid url and nothing else. e.g. if space is included it's immediately
    invalidated the url
    """
    if " " in string:
        return False
    result = urlparse(string)
    return all([result.scheme, result.netloc])


def isolate_images_urls(prompt_list: List) -> List:
    """
    Convert a full string prompt to the list format expected by the processor.
    In particular, image urls (as delimited by <fake_token_around_image>) should be their own elements.
    From:
    ```
    [
        "bonjour<fake_token_around_image><image:IMG_URL><fake_token_around_image>hello",
        PIL.Image.Image,
        "Aurevoir",
    ]
    ```
    to:
    ```
    [
        "bonjour",
        IMG_URL,
        "hello",
        PIL.Image.Image,
        "Aurevoir",
    ]
    ```
    """
    linearized_list = []
    for prompt in prompt_list:
        # Prompt can be either a string, or a PIL image
        if isinstance(prompt, PIL.Image.Image):
            linearized_list.append(prompt)
        elif isinstance(prompt, str):
            if "<fake_token_around_image>" not in prompt:
                linearized_list.append(prompt)
            else:
                prompt_splitted = prompt.split("<fake_token_around_image>")
                for ps in prompt_splitted:
                    if ps == "":
                        continue
                    if ps.startswith("<image:"):
                        linearized_list.append(ps[7:-1])
                    else:
                        linearized_list.append(ps)
        else:
            raise TypeError(
                f"Unrecognized type for `prompt`. Got {type(type(prompt))}. Was expecting something in [`str`,"
                " `PIL.Image.Image`]"
            )
    return linearized_list


def fetch_images(url_list: str) -> PIL.Image.Image:
    """Fetching images"""
    return PROCESSOR.image_processor.fetch_images(url_list)


def handle_manual_images_in_user_prompt(user_prompt: str) -> List[str]:
    """
    Handle the case of textually manually inputted images (i.e. the `<fake_token_around_image><image:IMG_URL><fake_token_around_image>`) in the user prompt
    by fetching them, saving them locally and replacing the whole sub-sequence the image local path.
    """
    if "<fake_token_around_image>" in user_prompt:
        splitted_user_prompt = isolate_images_urls([user_prompt])
        resulting_user_prompt = []
        for u_p in splitted_user_prompt:
            if is_url(u_p):
                img = fetch_images([u_p])[0]
                tmp_file = pil_to_temp_file(img)
                resulting_user_prompt.append(tmp_file)
            else:
                resulting_user_prompt.append(u_p)
        return resulting_user_prompt
    else:
        return [user_prompt]


def prompt_list_to_markdown(prompt_list: List[str]) -> str:
    """
    Convert a user prompt in the list format (i.e. elements are either a PIL image or a string) into
    the markdown format that is used for the chatbot history and rendering.
    """
    resulting_string = ""
    for elem in prompt_list:
        if is_image(elem):
            if is_url(elem):
                resulting_string += f"![]({elem})"
            else:
                resulting_string += f"![](/file={elem})"
        else:
            resulting_string += elem
    return resulting_string


def prompt_list_to_tgi_input(prompt_list: List[str]) -> str:
    """
    TGI expects a string that contains both text and images in the image markdown format (i.e. the `![]()` ).
    The images links are parsed on TGI side
    """
    result_string_input = ""
    for elem in prompt_list:
        if is_image(elem):
            if is_url(elem):
                try:
                    response = requests.get(elem)
                    if response.status_code == 200:
                        elem_pil = Image.open(BytesIO(response.content))
                except Exception:
                    print(f"Image is not loading")
            else:
                elem_pil = Image.open(elem)
            base64_img = pil_to_base64(elem_pil, resize=True)
            result_string_input += f"![]({base64_img})"
        else:
            result_string_input += elem
    return result_string_input


def remove_spaces_around_token(text: str) -> str:
    pattern = r"\s*(<fake_token_around_image>)\s*"
    replacement = r"\1"
    result = re.sub(pattern, replacement, text)
    return result


# Chatbot utils
def insert_backslash(string, max_length=50):
    # Check if the string length is less than or equal to the max_length
    if len(string) <= max_length:
        return string

    # Start from the max_length character and search for the last space character before it
    for i in range(max_length - 1, -1, -1):
        if string[i] == " ":
            # Insert a backslash before the last space character
            return string[:i] + "\n" + string[i:]

    # If no space character is found, just insert a backslash at the max_length character
    return string[:max_length] + "\n" + string[max_length:]


def resize_with_ratio(image: PIL.Image.Image, fixed_width: int) -> PIL.Image.Image:
    # Get the current width and height
    width, height = image.size

    # Calculate the new width while maintaining the aspect ratio up to 2:3 ratio
    new_width = fixed_width
    new_height = min(int(height * (new_width / width)), int(1.5 * new_width))

    # Resize the image
    resized_img = image.resize((new_width, new_height), Image.LANCZOS)

    return resized_img


def make_new_lines(draw, image, font, text_is_too_long, lines, num_lines, num_loops):
    max_len_increment = 0
    while text_is_too_long and max_len_increment < 10:
        new_lines = lines.copy()
        last_line_with_backslash = insert_backslash(
            new_lines[-1],
            max_length=(len(new_lines[-1]) + max_len_increment)
            // (num_lines - num_loops),
        )
        penultimate_line, last_line = (
            last_line_with_backslash.split("\n")[0],
            last_line_with_backslash.split("\n")[1],
        )
        new_lines.pop(-1)
        new_lines.append(penultimate_line)
        new_lines.append(last_line)
        # If the we haven't reached the last line, we split it again
        if len(new_lines) < num_lines:
            new_lines, text_width, text_is_too_long = make_new_lines(
                draw=draw,
                image=image,
                font=font,
                text_is_too_long=text_is_too_long,
                lines=new_lines,
                num_lines=num_lines,
                num_loops=num_loops + 1,
            )
        text_width = max([draw.textlength(line, font) for line in new_lines])
        text_is_too_long = text_width > image.width
        max_len_increment += 1
    if not text_is_too_long:
        lines = new_lines
    return lines, text_width, text_is_too_long


def test_font_size(
    draw,
    image,
    text,
    font,
    font_meme_text,
    num_lines=1,
    min_font=35,
    font_size_reduction=5,
):
    text_width = draw.textlength(text, font)
    text_is_too_long = True
    lines = [text]
    while font.size > min_font and text_is_too_long:
        font = ImageFont.truetype(
            f"fonts/{font_meme_text}.ttf", size=font.size - font_size_reduction
        )
        if num_lines == 1:
            text_width = draw.textlength(text, font)
            text_is_too_long = text_width > image.width
        else:
            lines, text_width, text_is_too_long = make_new_lines(
                draw=draw,
                image=image,
                font=font,
                text_is_too_long=text_is_too_long,
                lines=lines,
                num_lines=num_lines,
                num_loops=0,
            )
            temp_text = "\n".join(lines)

    if not text_is_too_long and num_lines > 1:
        text = temp_text
    return text, font, text_width, text_is_too_long


def make_meme_image(
    image: str,
    text: str,
    font_meme_text: str,
    all_caps_meme_text: bool = False,
    text_at_the_top: bool = False,
) -> PIL.Image.Image:
    """
    Takes an image and a text and returns a meme image.
    """
    text = text.replace("\nUser", " ").replace("\n", " ").strip().rstrip(".")
    if all_caps_meme_text:
        text = text.upper()
    # Resize image
    fixed_width = 700
    image = Image.open(image)
    image = resize_with_ratio(image, fixed_width)
    image_width, image_height = image.size
    height_width_ratio = image_height / image_width

    draw = ImageDraw.Draw(image)
    min_font = 35
    initial_font_size = 60
    if height_width_ratio >= 1:
        min_font = 45
        initial_font_size = 80
    text_is_too_long = True
    num_lines = 0
    while text_is_too_long and num_lines < 8:
        num_lines += 1
        font = ImageFont.truetype(f"fonts/{font_meme_text}.ttf", size=initial_font_size)
        text, font, text_width, text_is_too_long = test_font_size(
            draw,
            image,
            text,
            font,
            font_meme_text,
            num_lines=num_lines,
            min_font=min_font,
            font_size_reduction=5,
        )

    if text_is_too_long:
        text = f"Text is too long to fit the image"
        if all_caps_meme_text:
            text = text.upper()
        font = ImageFont.truetype(f"fonts/{font_meme_text}.ttf", size=font.size)
        text_width = draw.textlength(text, font)

    outline_width = 2
    text_x = (image_width - text_width) / 2
    text_y = image_height - num_lines * font.size - 10 - 2 * num_lines
    if text_at_the_top:
        text_y = 0

    for i in range(-outline_width, outline_width + 1):
        for j in range(-outline_width, outline_width + 1):
            draw.multiline_text(
                (text_x + i, text_y + j), text, fill="black", align="center", font=font
            )
    draw.multiline_text((text_x, text_y), text, fill="white", align="center", font=font)

    return image


def format_user_prompt_with_im_history_and_system_conditioning(
    system_prompt: List[str],
    current_user_prompt_str: str,
    current_image: Optional[str],
    history: List[Tuple[str, str]],
) -> Tuple[List[str], List[str]]:
    """
    Produces the resulting list that needs to go inside the processor.
    It handles the potential image box input, the history and the system conditionning.
    """
    # resulting_list = copy.deepcopy(SYSTEM_PROMPT)
    resulting_list = system_prompt

    # Format history
    for turn in history:
        user_utterance, assistant_utterance = turn
        splitted_user_utterance = split_str_on_im_markdown(user_utterance)

        optional_space = ""
        if not is_image(splitted_user_utterance[0]):
            optional_space = " "
        resulting_list.append(f"\nUser:{optional_space}")
        resulting_list.extend(splitted_user_utterance)
        resulting_list.append(f"<end_of_utterance>\nAssistant: {assistant_utterance}")

    # Format current input
    current_user_prompt_str = remove_spaces_around_token(current_user_prompt_str)
    if current_image is None:
        if "![](" in current_user_prompt_str:
            current_user_prompt_list = split_str_on_im_markdown(current_user_prompt_str)
        else:
            current_user_prompt_list = handle_manual_images_in_user_prompt(
                current_user_prompt_str
            )

        optional_space = ""
        if not is_image(current_user_prompt_list[0]):
            # Check if the first element is an image (and more precisely a path to an image)
            optional_space = " "
        resulting_list.append(f"\nUser:{optional_space}")
        resulting_list.extend(current_user_prompt_list)
        resulting_list.append("<end_of_utterance>\nAssistant:")
    else:
        # Choosing to put the image first when the image is inputted through the UI, but this is an arbiratrary choice.
        resulting_list.extend(
            [
                "\nUser:",
                current_image,
                f"{current_user_prompt_str}<end_of_utterance>\nAssistant:",
            ]
        )
        current_user_prompt_list = [current_user_prompt_str]

    return resulting_list, current_user_prompt_list


def expand_layout():
    return gr.Column(scale=2), gr.Gallery(height=682)


def generate_meme(
    client,
    query,
    image,
    font_meme_text,
    all_caps_meme_text,
    text_at_the_top,
    generation_args,
):
    try:
        text = client.generate(prompt=query, **generation_args).generated_text
    except Exception as e:
        logger.error(f"Error {e} while generating meme text")
        text = ""
    if image is not None and text != "":
        meme_image = make_meme_image(
            image=image,
            text=text,
            font_meme_text=font_meme_text,
            all_caps_meme_text=all_caps_meme_text,
            text_at_the_top=text_at_the_top,
        )
        return meme_image
    else:
        return None


def model_inference(
    model_selector,
    system_prompt,
    user_prompt_str,
    chat_history,
    image,
    decoding_strategy,
    temperature,
    max_new_tokens,
    repetition_penalty,
    top_p,
    all_caps_meme_text,
    text_at_the_top,
    font_meme_text,
):
    chat_history = []
    if user_prompt_str.strip() == "" and image is None:
        return "", None, chat_history

    system_prompt = ast.literal_eval(system_prompt)
    (
        formated_prompt_list,
        user_prompt_list,
    ) = format_user_prompt_with_im_history_and_system_conditioning(
        system_prompt=system_prompt,
        current_user_prompt_str=user_prompt_str.strip(),
        current_image=image,
        history=chat_history,
    )

    client_endpoint = API_PATHS[model_selector]
    client = Client(
        base_url=client_endpoint,
        headers={"x-use-cache": "0", "Authorization": f"Bearer {API_TOKEN}"},
        timeout=45,
    )

    # Common parameters to all decoding strategies
    # This documentation is useful to read: https://huggingface.co/docs/transformers/main/en/generation_strategies
    generation_args = {
        "max_new_tokens": max_new_tokens,
        "repetition_penalty": repetition_penalty,
        "stop_sequences": EOS_STRINGS,
    }

    assert decoding_strategy in [
        "Greedy",
        "Top P Sampling",
    ]
    if decoding_strategy == "Greedy":
        generation_args["do_sample"] = False
    elif decoding_strategy == "Top P Sampling":
        generation_args["temperature"] = temperature
        generation_args["do_sample"] = True
        generation_args["top_p"] = top_p

    chat_history.append([prompt_list_to_markdown(user_prompt_list), ""])

    query = prompt_list_to_tgi_input(formated_prompt_list)
    all_meme_images = []
    with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
        futures = [
            executor.submit(
                generate_meme,
                client,
                query,
                image,
                font_meme_text,
                all_caps_meme_text,
                text_at_the_top,
                generation_args,
            )
            for i in range(4)
        ]

        for future in concurrent.futures.as_completed(futures):
            meme_image = future.result(timeout=45)
            if meme_image:
                all_meme_images.append(meme_image)
    return user_prompt_str, all_meme_images, chat_history


def remove_last_turn(chat_history):
    if len(chat_history) == 0:
        return chat_history, "", ""
    last_interaction = chat_history[-1]
    chat_history = chat_history[:-1]
    chat_update = chat_history
    text_update = last_interaction[0]
    return chat_update, text_update, ""


textbox = gr.Textbox(
    placeholder="Upload an image and ask the AI to create a meme!",
    show_label=False,
    value="Write a meme about this image.",
    visible=True,
    container=False,
    label="Text input",
    scale=8,
    max_lines=5,
)
chatbot = gr.Chatbot(
    elem_id="chatbot",
    label="AI Meme Generator Chatbot",
    visible=False,
    avatar_images=[None, BOT_AVATAR],
)
css = """
.gradio-container{max-width: 1000px!important}
h1{display: flex;align-items: center;justify-content: center;gap: .25em}
*{transition: width 0.5s ease, flex-grow 0.5s ease}
"""
with gr.Blocks(title="AI Meme Generator", theme=gr.themes.Base(), css=css) as demo:
    with gr.Row(scale=0.5):
        gr.HTML(
            """<h1 align="center">AI Meme Generator <span style="font-size: 13px;">powered by <a href="https://huggingface.co/blog/idefics">IDEFICS</a></span><img width=40 height=40 src="https://cdn-uploads.huggingface.co/production/uploads/624bebf604abc7ebb01789af/v770xGti5vH1SYLBgyOO_.png" /></h1>"""
        )

    with gr.Row(elem_id="model_selector_row"):
        model_selector = gr.Dropdown(
            choices=MODELS,
            value="HuggingFaceM4/idefics-80b-instruct",
            interactive=True,
            show_label=False,
            container=False,
            label="Model",
            visible=False,
        )
    with gr.Row(equal_height=True):
        # scale=2 when expanded
        with gr.Column(scale=4, min_width=250) as upload_area:
            imagebox = gr.Image(
                type="filepath", label="Image to meme", height=272, visible=True
            )
            with gr.Group():
                with gr.Row():
                    textbox.render()
                with gr.Row():
                    submit_btn = gr.Button(
                        value="▶️ Submit", visible=True, min_width=120
                    )
                    clear_btn = gr.ClearButton(
                        [textbox, imagebox, chatbot], value="🧹 Clear", min_width=120
                    )
                    regenerate_btn = gr.Button(
                        value="🔄 Regenerate", visible=True, min_width=120
                    )
            with gr.Accordion(
                "Advanced settings", open=False, visible=True
            ) as parameter_row:
                with gr.Row():
                    with gr.Column():
                        all_caps_meme_text = gr.Checkbox(
                            value=True,
                            label="All Caps",
                            interactive=True,
                            info="",
                        )
                        text_at_the_top = gr.Checkbox(
                            value=False,
                            label="Text at the top",
                            interactive=True,
                            info="",
                        )
                    with gr.Column():
                        font_meme_text = gr.Radio(
                            [
                                "impact",
                                "Roboto-Regular",
                            ],
                            value="impact",
                            label="Font",
                            interactive=True,
                            info="",
                        )
                system_prompt = gr.Textbox(
                    value=SYSTEM_PROMPT,
                    visible=False,
                    lines=20,
                    max_lines=50,
                    interactive=True,
                )
                max_new_tokens = gr.Slider(
                    minimum=8,
                    maximum=150,
                    value=90,
                    step=1,
                    interactive=True,
                    label="Maximum number of new tokens to generate",
                )
                repetition_penalty = gr.Slider(
                    minimum=0.0,
                    maximum=5.0,
                    value=1.2,
                    step=0.01,
                    interactive=True,
                    label="Repetition penalty",
                    info="1.0 is equivalent to no penalty",
                )
                decoding_strategy = gr.Radio(
                    [
                        "Greedy",
                        "Top P Sampling",
                    ],
                    value="Top P Sampling",
                    label="Decoding strategy",
                    interactive=True,
                    info="Higher values is equivalent to sampling more low-probability tokens.",
                )
                temperature = gr.Slider(
                    minimum=0.0,
                    maximum=5.0,
                    value=0.6,
                    step=0.1,
                    interactive=True,
                    visible=True,
                    label="Sampling temperature",
                    info="Higher values will produce more diverse outputs.",
                )
                decoding_strategy.change(
                    fn=lambda selection: gr.Slider.update(
                        visible=(
                            selection
                            in [
                                "contrastive_sampling",
                                "beam_sampling",
                                "Top P Sampling",
                                "sampling_top_k",
                            ]
                        )
                    ),
                    inputs=decoding_strategy,
                    outputs=temperature,
                )
                top_p = gr.Slider(
                    minimum=0.01,
                    maximum=0.99,
                    value=0.8,
                    step=0.01,
                    interactive=True,
                    visible=True,
                    label="Top P",
                    info="Higher values is equivalent to sampling more low-probability tokens.",
                )
                decoding_strategy.change(
                    fn=lambda selection: gr.Slider.update(
                        visible=(selection in ["Top P Sampling"])
                    ),
                    inputs=decoding_strategy,
                    outputs=top_p,
                )
        with gr.Column(scale=5) as result_area:
            generated_memes_gallery = gr.Gallery(
                # value="Images generated will appear here",
                label="IDEFICS Generated Memes",
                allow_preview=True,
                elem_id="generated_memes_gallery",
                show_download_button=True,
                show_share_button=True,
                columns=[2],
                object_fit="contain",
                height=428,
            )  # height 600 when expanded
    with gr.Row(equal_height=True):
        with gr.Box(elem_id="gallery_box"):
            gallery_type_choice = gr.Radio(
                [
                    "All",
                    "Meme templates",
                    "Funny images",
                    "Politics",
                ],
                value="All",
                label="Gallery Type",
                interactive=True,
                visible=False,
                info="Choose the type of gallery you want to see.",
            )
            template_gallery = gr.Gallery(
                value=IMAGE_GALLERY_PATHS,
                label="Templates Gallery",
                allow_preview=False,
                columns=6,
                elem_id="gallery",
                show_share_button=False,
                height=400,
            )
    with gr.Row(variant="panel"):
        with gr.Column(scale=1):
            gr.Image(
                IDEFICS_LOGO,
                elem_id="banner-image",
                show_label=False,
                show_download_button=False,
                height=200,
                width=250,
            )
        with gr.Column(scale=5):
            gr.HTML(
                """
                <p><strong>AI Meme Generator</strong> is an AI system that writes humorous content inspired by images, allowing you to make the funniest memes with little effort. Upload your image and ask the Idefics chatbot to make a tailored meme.</p>
                <p>AI Meme Generator is a space inspired from <a href="https://huggingface.co/spaces/HuggingFaceM4/ai_dad_jokes">AI Dad Jokes</a> and powered by <a href="https://huggingface.co/blog/idefics">IDEFICS</a>, an open-access large visual language model developped by Hugging Face. Like GPT-4, the multimodal model accepts arbitrary sequences of image and text inputs and produces text outputs. IDEFICS can answer questions about images, describe visual content, create stories grounded in multiple images, etc.</p>

                <p>⛔️ <strong>Intended uses and limitations:</strong> This demo is provided as research artifact to the community showcasing IDEFICS'capabilities. We detail misuses and out-of-scope uses <a href="https://huggingface.co/HuggingFaceM4/idefics-80b#misuse-and-out-of-scope-use">here</a>. In particular, the system should not be used to engage in harassment, abuse and bullying. The model can produce factually incorrect texts, hallucinate facts (with or without an image) and will struggle with small details in images. While the system will tend to refuse answering questionable user requests, it can produce problematic outputs (including racist, stereotypical, and disrespectful texts), in particular when prompted to do so.</p>
            """
            )
    with gr.Row():
        chatbot.render()

    gr.on(
        triggers=[
            textbox.submit,
            imagebox.upload,
            submit_btn.click,
            template_gallery.select,
            regenerate_btn.click,
        ],
        fn=expand_layout,
        outputs=[upload_area, generated_memes_gallery],
        queue=False,
    ).then(
        fn=lambda: "", inputs=[], outputs=[generated_memes_gallery], queue=False
    ).then(
        fn=model_inference,
        inputs=[
            model_selector,
            system_prompt,
            textbox,
            chatbot,
            imagebox,
            decoding_strategy,
            temperature,
            max_new_tokens,
            repetition_penalty,
            top_p,
            all_caps_meme_text,
            text_at_the_top,
            font_meme_text,
        ],
        outputs=[textbox, generated_memes_gallery, chatbot],
    )

    regenerate_btn.click(
        fn=remove_last_turn,
        inputs=chatbot,
        outputs=[chatbot, textbox, generated_memes_gallery],
        queue=False,
    )

    # gallery_type_choice.change(
    #     fn=choose_gallery,
    #     inputs=[gallery_type_choice],
    #     outputs=[template_gallery],
    #     queue=False,
    # )
    template_gallery.select(
        fn=add_file_gallery,
        inputs=[template_gallery],
        outputs=[textbox, imagebox, generated_memes_gallery],
        queue=False,
    )
    demo.load(
        # fn=choose_gallery,
        # inputs=[gallery_type_choice],
        # outputs=[template_gallery],
        queue=False,
    )
demo.queue(concurrency_count=4, max_size=40, api_open=False)
demo.launch(max_threads=400)