File size: 31,418 Bytes
ac8d53f
 
217780a
ac8d53f
 
 
 
 
217780a
ac8d53f
 
 
 
217780a
 
ac8d53f
7df19dd
 
217780a
 
ac8d53f
 
217780a
ac8d53f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58777cc
ac8d53f
 
58777cc
217780a
 
58777cc
217780a
 
 
 
 
ac8d53f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7df19dd
 
 
ac8d53f
7df19dd
 
794d2b7
217780a
0e145dd
217780a
 
 
 
 
 
 
 
 
794d2b7
217780a
ac8d53f
217780a
 
 
 
 
 
 
 
 
7df19dd
217780a
 
ac8d53f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217780a
ac8d53f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217780a
dafb0ab
217780a
ac8d53f
7df19dd
217780a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7df19dd
ac8d53f
217780a
ac8d53f
217780a
14be3d0
217780a
7df19dd
 
217780a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e145dd
217780a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e145dd
217780a
 
7df19dd
217780a
 
0e145dd
217780a
 
 
ac8d53f
217780a
 
 
58777cc
 
 
217780a
58777cc
217780a
 
 
 
 
 
 
 
 
f10b974
58777cc
 
 
 
217780a
58777cc
217780a
4c85382
217780a
 
 
 
 
 
ac8d53f
 
217780a
 
58777cc
 
0e145dd
217780a
ac8d53f
217780a
0e145dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf12ee0
 
 
ac8d53f
 
 
cf12ee0
 
5b1ab48
cf12ee0
0e145dd
cf12ee0
0e145dd
 
 
 
 
 
 
 
 
cf142d2
 
 
 
 
0e145dd
cf142d2
0e145dd
cf142d2
0e145dd
 
 
 
58777cc
 
 
 
e3795af
0e145dd
58777cc
0e145dd
58777cc
0e145dd
 
 
 
58777cc
0e145dd
 
 
 
5167a8a
0e145dd
58777cc
0e145dd
 
 
58777cc
0e145dd
 
 
5167a8a
0e145dd
 
 
 
5167a8a
 
0e145dd
 
5167a8a
 
 
0e145dd
5167a8a
0e145dd
 
 
 
 
 
 
 
 
5167a8a
 
 
e3795af
5167a8a
e3795af
5167a8a
0e145dd
5167a8a
0e145dd
5167a8a
0e145dd
 
 
 
c586e09
217780a
 
ac8d53f
 
 
 
 
 
 
217780a
 
 
 
0e145dd
217780a
 
58777cc
ac8d53f
 
 
 
58777cc
 
f10b974
 
 
 
58777cc
217780a
 
58777cc
ac8d53f
 
 
 
58777cc
 
f10b974
 
 
 
 
58777cc
 
 
 
217780a
 
 
 
 
 
 
 
 
 
ac8d53f
217780a
ac8d53f
e3795af
cf142d2
e3795af
 
 
 
 
 
 
 
 
217780a
ac8d53f
 
217780a
 
ac8d53f
 
 
 
217780a
 
 
 
ac8d53f
7df19dd
217780a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac8d53f
 
 
 
 
 
 
 
 
 
 
217780a
dd96978
 
 
 
217780a
 
dafb0ab
 
 
ac8d53f
cf12ee0
cf142d2
dafb0ab
4932b87
 
 
 
 
 
 
 
dafb0ab
ac8d53f
217780a
 
 
dafb0ab
 
 
ac8d53f
cf12ee0
cf142d2
dafb0ab
 
 
 
 
 
 
 
 
 
 
 
ac8d53f
dafb0ab
 
217780a
 
dd96978
 
 
 
 
 
 
 
 
 
 
217780a
13f2998
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
import base64
import logging
import os
import re
from io import BytesIO
from typing import List, Optional, Tuple, Union
from urllib.parse import urlparse

import gradio as gr
import PIL
from accelerate.utils import get_max_memory
from PIL import Image
from transformers import AutoConfig, AutoProcessor, IdeficsForVisionText2Text


MODELS = [
    "HuggingFaceM4/idefics-9b-instruct",
    # "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 do its best to answer User’s questions. Assistant has the ability to perceive images and reason about the content of visual inputs. Assistant was built to be respectful, polite and inclusive. It knows a lot, and always tells the truth. When prompted with an image, it does not make up facts.

The conversation begins:\n""",
    """User:<fake_token_around_image><image:https://i1.pickpik.com/photos/515/906/355/kittens-cats-pet-cute-preview.jpg><fake_token_around_image>Describe this image.<end_of_utterance>\n""",
    """Assistant: Five kittens are standing together in the center of the photograph. From the left to right, there is one orange kitten, two kittens white and black stripes, and two brown kittens with an orange head. They are in bright green grass and it looks like they are moving forward.<end_of_utterance>\n""",
    (
        "User:How about this"
        " image?<fake_token_around_image><image:https://cdn.pixabay.com/photo/2017/09/25/13/12/puppy-2785074_1280.jpg><fake_token_around_image>Can"
        " you describe it too?<end_of_utterance>\n"
    ),
    """Assistant: A dog is lying on the floor, looking at the camera. It is looking directly at you. The dog has a white body and brown patches on its face and ears. Its eyes are dark. Its nose is black, and it has long, floppy ears, white paws, long fur, big eyes.<end_of_utterance>\n""",
    "User: What kind of breed is it?<end_of_utterance>\n",
    """Assistant: It looks like a Cavalier King Charles Spaniel. These breeds are known for their gentle, affectionate nature. Their long ears and big, brown eyes give them a sweet, expressive face. Cavaliers are small dogs weighing between 13 and 20 pounds. They have a silky, medium-length coat that comes in various colors, including black and tan, tricolor, red and white, or black.<end_of_utterance>\n""",
    "User: What can you tell me about this breed of dogs?<end_of_utterance>\n",
    """Assistant: One specific characteristic of the Cavalier King Charles Spaniel is its friendly and affectionate nature. This breed is known for being extremely sociable and forming strong bonds with their owners. They are often described as "velcro dogs" because they love to be close to their human companions, whether it's sitting on their laps, cuddling on the couch, or simply following them around the house.<end_of_utterance>\n""",
    "User: ghjkhjabnufs<end_of_utterance>\n",
    """Assistant: That doesn’t seem to be a word. Could you ask me another way?<end_of_utterance>\n""",
    "User: Do you like Cavalier King Charles Spaniel?<end_of_utterance>\n",
    """Assistant: I do not have personal opinions as I’m just a computer program. However, cavaliers are known for being excellent family pets due to their gentle and patient demeanor, making them great with children and other pets. Their affectionate nature also makes them ideal therapy dogs, as they can provide comfort and emotional support to those in need.<end_of_utterance>\n""",
    (
        "User: How many dogs do you see in this"
        " image?<fake_token_around_image><image:https://i.dailymail.co.uk/i/pix/2011/07/01/article-2010308-0CD22A8300000578-496_634x414.jpg><fake_token_around_image><end_of_utterance>\n"
    ),
    """Assistant: There is no dogs in this image. The picture shows a tennis player jumping to volley the ball.<end_of_utterance>\n""",
]

BAN_TOKENS = "<image>;<fake_token_around_image>"
EOS_TOKENS = "</s>;<end_of_utterance>;User"


TOKENIZER_FAST = True
MAX_SEQ_LEN = 2048

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()


# Conversion between PIL Image <-> base64 <-> Markdown utils
def pil_to_base64(pil_image):
    """
    Convert an PIL image into base64 string representation
    """
    buffered = BytesIO()
    pil_image.save(buffered, format="JPEG")  # You can change the format as per your image type
    encoded_image = base64.b64encode(buffered.getvalue()).decode("utf-8")
    return encoded_image


def pil_to_markdown_im(image):
    """
    Convert a PIL image into markdown filled with the base64 string representation.
    """
    img_b64_str = pil_to_base64(image)
    img_str = f'<img src="data:image/png;base64,{img_b64_str}" />'
    return img_str


def base64_to_pil(encoded_image):
    decoded_image = base64.b64decode(encoded_image)
    pil_image = Image.open(BytesIO(decoded_image))
    return pil_image


def im_markdown_to_pil(im_markdown_str):
    pattern = r'<img src="data:image/png;base64,([^"]+)" />'
    match = re.search(pattern, im_markdown_str)
    img_b64_str = match.group(1)
    return base64_to_pil(img_b64_str)


def split_str_on_im_markdown(string_with_potential_im_markdown):
    """
    Extract from a string (typically the user prompt string) the potentional images saved as a base64 representation
    inside a markdown.
    """
    pattern = r'<img src="data:image/png;base64,([^"]+)" />'
    parts = re.split(pattern, string_with_potential_im_markdown)
    result = []

    for i, part in enumerate(parts):
        if i % 2 == 0:
            result.append(part)
        else:
            img_tag = f'<img src="data:image/png;base64,{part.strip()}" />'
            result.append(img_tag)

    return result


# Fetching utils
def is_url(string):
    """
    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):
    """
    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


# Chatbot handling utils
def handle_manual_images_in_user_prompt(user_prompt: str) -> List[Union[str, PIL.Image.Image]]:
    """
    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 and replacing the whole sub-sequence by a PIL image.
    """
    if "<fake_token_around_image>" in user_prompt:
        splitted_user_prompt = isolate_images_urls([user_prompt])
        resulting_user_prompt = []
        for up in splitted_user_prompt:
            if is_url(up):
                img = processor.image_processor.fetch_images([up])[0]
                resulting_user_prompt.append(img)
            else:
                resulting_user_prompt.append(up)
        return resulting_user_prompt
    else:
        return [user_prompt]


def user_prompt_list_to_markdown(user_prompt_list: List[Union[str, PIL.Image.Image]]):
    """
    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 user_prompt_list:
        if isinstance(elem, str):
            resulting_string += elem
        elif isinstance(elem, PIL.Image.Image):
            resulting_string += pil_to_markdown_im(elem)
        else:
            raise ValueError(
                "Unknown type for `user_prompt_list`. Expected an element of type `str` or `PIL.Image.Image` and got"
                f" `{type(elem)}`"
            )
    return resulting_string


# Model and generation utils
def load_processor_tokenizer_model(model_name):
    processor = AutoProcessor.from_pretrained(
        model_name,
        token=os.getenv("HF_AUTH_TOKEN", True),
        truncation_side="left",
    )
    tokenizer = processor.tokenizer

    config = AutoConfig.from_pretrained(model_name, use_auth_token=os.getenv("HF_AUTH_TOKEN", True))
    max_memory_map = get_max_memory()

    for key in max_memory_map.keys():
        if key != "cpu":
            # Get this in GB
            max_memory_map[key] = max_memory_map[key] // (1024 * 1024 * 1024)
            # Decrease 2 for Pytorch overhead and 2 for the forward to be safe
            max_memory_map[key] = f"{max_memory_map[key] - 4} GiB"

    model = IdeficsForVisionText2Text.from_pretrained(
        model_name,
        token=os.getenv("HF_AUTH_TOKEN", True),
        device_map="auto",
        offload_folder="./offload",
        torch_dtype=config.torch_dtype,
        max_memory=max_memory_map,
    )
    model.eval()
    print("Current device map:", model.hf_device_map)
    print("Model default generation config:", model.generation_config)
    # TODO: the device_map looks very inefficien right now. that could be improved
    return processor, tokenizer, model


def format_user_prompt_with_im_history_and_system_conditioning(
    current_user_prompt_str: str, current_image: Optional[PIL.Image.Image], history: List[Tuple[str, str]]
) -> List[Union[str, PIL.Image.Image]]:
    """
    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 = SYSTEM_PROMPT

    # Format history
    for turn in history:
        user_utterance, assistant_utterance = turn
        splitted_user_utterance = split_str_on_im_markdown(user_utterance)
        splitted_user_utterance = [
            im_markdown_to_pil(s) if s.startswith('<img src="data:image/png;base64,') else s
            for s in splitted_user_utterance
            if s != ""
        ]
        if isinstance(splitted_user_utterance[0], str):
            resulting_list.append("\nUser: ")
        else:
            resulting_list.append("\nUser:")
        resulting_list.extend(splitted_user_utterance)
        resulting_list.append(f"<end_of_utterance>\nAssistant: {assistant_utterance}")

    # Format current input
    if current_image is None:
        if "<img src=data:image/png;base64" in current_user_prompt_str:
            raise ValueError("The UI does not support inputing via the text box an image in base64.")
        current_user_prompt_list = handle_manual_images_in_user_prompt(current_user_prompt_str)
        resulting_list.append("\nUser: ")
        resulting_list.extend(current_user_prompt_list)
        resulting_list.append("<end_of_utterance>\nAssistant:")
        return resulting_list, current_user_prompt_list
    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:"])
        return resulting_list, [current_user_prompt_str]


def model_generation(
    prompt_list,
    processor,
    tokenizer,
    model,
    temperature,
    no_repeat_ngram_size,
    max_new_tokens,
    min_length,
    ban_tokens,
    eos_tokens,
    force_words,
    repetition_penalty,
    hide_special_tokens,
    decoding_strategy,
    num_beams,
    length_penalty,
    top_k,
    top_p,
    penalty_alpha,
):
    input_args = processor(
        isolate_images_urls(prompt_list),
        truncation=True,
        max_length=MAX_SEQ_LEN - max_new_tokens,
        padding=True,
        # add_end_of_utterance_token=False, # Already taken care of inside the prompts, so bypassing the processor's handling of this token
    )
    for k, v in input_args.items():
        input_args[k] = v.to(0)

    # Excluding some words from the generation
    bad_words_ids = None
    ban_tokens = ban_tokens.replace("\\n", "\n")
    bad_words = ban_tokens.split(";")
    if len(bad_words) > 0:
        bad_words_ids = tokenizer(bad_words, add_special_tokens=False).input_ids

    # Forcing some words in the generation
    force_words_ids = None
    if force_words != "":
        force_words = force_words.replace("\\n", "\n")
        force_words = force_words.split(";")
        if len(force_words) > 0:
            force_words_ids = tokenizer(force_words, add_special_tokens=False).input_ids

    eos_token_ids = None
    if eos_tokens != "":
        eos_tokens = eos_tokens.replace("\\n", "\n")
        eos_tokens = eos_tokens.split(";")
        if len(eos_tokens) > 0:
            eos_token_ids = []
            for eos_token in eos_tokens:
                tokenized_eos_token = tokenizer(eos_token, add_special_tokens=False).input_ids
                if len(tokenized_eos_token) > 1:
                    raise ValueError(
                        f"eos_tokens should be one token, here {eos_token} is {len(tokenized_eos_token)} tokens:"
                        f" {tokenized_eos_token}"
                    )
                eos_token_ids += tokenized_eos_token

    # Common parameters to all decoding strategies
    # This documentation is useful to read: https://huggingface.co/docs/transformers/main/en/generation_strategies
    generation_args = {
        "temperature": temperature,
        "no_repeat_ngram_size": no_repeat_ngram_size,
        "max_new_tokens": max_new_tokens,
        "min_length": min_length,
        "bad_words_ids": bad_words_ids,
        "force_words_ids": force_words_ids,
        "repetition_penalty": repetition_penalty,
        "eos_token_id": eos_token_ids,
    }

    assert decoding_strategy in [
        "greedy",
        "beam_search",
        "beam_sampling",
        "sampling_top_k",
        "sampling_top_p",
        "contrastive_sampling",
    ]
    if decoding_strategy == "greedy":
        pass
    elif decoding_strategy == "beam_search":
        generation_args["num_beams"] = num_beams
        generation_args["length_penalty"] = length_penalty
        assert generation_args["num_beams"] > 1
    elif decoding_strategy == "beam_sampling":
        generation_args["num_beams"] = num_beams
        generation_args["length_penalty"] = length_penalty
        generation_args["do_sample"] = True
        assert generation_args["num_beams"] > 1
    elif decoding_strategy == "sampling_top_k":
        generation_args["do_sample"] = True
        generation_args["top_k"] = top_k
    elif decoding_strategy == "sampling_top_p":
        generation_args["do_sample"] = True
        generation_args["top_p"] = top_p
    elif decoding_strategy == "contrastive_sampling":
        generation_args["do_sample"] = True
        generation_args["penalty_alpha"] = penalty_alpha
        generation_args["top_k"] = top_k

    generated_tokens = model.generate(
        **input_args,
        **generation_args,
    )

    tokens = tokenizer.convert_ids_to_tokens(generated_tokens[0])
    decoded_skip_special_tokens = repr(
        tokenizer.batch_decode(generated_tokens, skip_special_tokens=hide_special_tokens)[0]
    )

    actual_generated_tokens = generated_tokens[:, input_args["input_ids"].shape[-1] :]
    first_end_token = len(actual_generated_tokens[0])
    actual_generated_tokens = actual_generated_tokens[:, :first_end_token]
    generated_text = tokenizer.batch_decode(actual_generated_tokens, skip_special_tokens=hide_special_tokens)[0]

    logger.info(
        "Result: \n"
        f"----Prompt: `{prompt_list}`\n"
        f"----Tokens ids - prompt + generation: `{generated_tokens[0].tolist()}`\n"
        f"----Tokens converted - prompt + generation: `{tokens}`\n"
        f"----String decoded with skipped special tokens - prompt + generation: `{decoded_skip_special_tokens}`\n"
        f"----Total length - prompt + generation `{len(generated_tokens[0].tolist())}`\n"
        f"----Token ids - generation: `{actual_generated_tokens[0].tolist()}`\n"
        f"----Tokens converted - generation: `{tokenizer.convert_ids_to_tokens(actual_generated_tokens[0])}`\n"
        f"----String decoded with skipped special tokens - generation: `{generated_text}`\n"
        f"----Total length - generation: `{len(actual_generated_tokens[0].tolist())}`\n"
        f"----Generation mode: `{decoding_strategy}`\n"
        f"----Generation parameters: `{generation_args}`\n"
    )

    return generated_text


textbox = gr.Textbox(
    show_label=False,
    value="What color are the cat's eyes?",
    placeholder=(
        "To input images, use the following syntax:"
        " `<fake_token_around_image><image:URL_IMAGE><fake_token_around_image>textexttext`"
    ),
    visible=True,
    container=False,
)
with gr.Blocks(title="IDEFICS", theme=gr.themes.Base()) as demo:
    # state = gr.State()

    with gr.Row():
        with gr.Column(scale=3):
            with gr.Row(elem_id="model_selector_row"):
                model_selector = gr.Dropdown(
                    choices=MODELS,
                    value=MODELS[0] if len(MODELS) > 0 else "",
                    interactive=True,
                    show_label=False,
                    container=False,
                )
            processor, tokenizer, model = load_processor_tokenizer_model(model_selector.value)

            imagebox = gr.Image(type="pil", label="Image input")

            with gr.Accordion("Generation parameters", open=False, visible=True) as parameter_row:
                max_new_tokens = gr.Slider(
                    minimum=0,
                    maximum=2048,
                    value=512,
                    step=1,
                    interactive=True,
                    label="Maximum number of new tokens to generate",
                )
                min_length = gr.Slider(
                    minimum=0,
                    maximum=50,
                    value=0,
                    step=1,
                    interactive=True,
                    label="Minimum number of new tokens to generate",
                )
                repetition_penalty = gr.Slider(
                    minimum=0.0,
                    maximum=5.0,
                    value=1.0,
                    step=0.1,
                    interactive=True,
                    label="Repetition penalty",
                    info="1.0 means no penalty",
                )
                no_repeat_ngram_size = gr.Slider(
                    minimum=0,
                    maximum=10,
                    value=0,
                    step=1,
                    interactive=True,
                    label="N-gram repetition threshold",
                    info="If set to int > 0, all ngrams of that size can only occur once.",
                )
                decoding_strategy = gr.Radio(
                    [
                        "greedy",
                        # "beam_search",
                        # "beam_sampling",
                        # "sampling_top_k",
                        "sampling_top_p",
                    ],
                    value="greedy",
                    label="Decoding strategy",
                    interactive=True,
                )
                temperature = gr.Slider(
                    minimum=0.0,
                    maximum=5.0,
                    value=1.0,
                    step=0.1,
                    interactive=True,
                    label="Sampling temperature",
                )
                num_beams = gr.Slider(
                    minimum=0,
                    maximum=20,
                    value=3.0,
                    step=1.0,
                    interactive=True,
                    visible=False,
                    label="Number of beams",
                    info="Only used if `decoding_strategy` is `beam_search` or `beam_sampling`.",
                )
                decoding_strategy.change(
                    fn=lambda selection: gr.Slider.update(visible=(selection in ["beam_search", "beam_sampling"])),
                    inputs=decoding_strategy,
                    outputs=num_beams,
                )
                top_p = gr.Slider(
                    minimum=0.0,
                    maximum=1.0,
                    value=0.95,
                    step=0.01,
                    interactive=True,
                    visible=False,
                    label="Top P",
                    info=(
                        "If set to float < 1, only the smallest set of most probable tokens with probabilities that"
                        " add up to top_p or higher are kept for generation."
                    ),
                )
                decoding_strategy.change(
                    fn=lambda selection: gr.Slider.update(visible=(selection in ["sampling_top_p"])),
                    inputs=decoding_strategy,
                    outputs=top_p,
                )
                top_k = gr.Slider(
                    minimum=0,
                    maximum=500,
                    value=50,
                    step=1,
                    interactive=True,
                    visible=False,
                    label="Top K",
                    info="The number of highest probability vocabulary tokens to keep for top-k-filtering.",
                )
                decoding_strategy.change(
                    fn=lambda selection: gr.Slider.update(visible=(selection in ["sampling_top_k"])),
                    inputs=decoding_strategy,
                    outputs=top_k,
                )
                length_penalty = gr.Slider(
                    minimum=-1000.0,
                    maximum=1000.0,
                    value=1.0,
                    step=0.1,
                    interactive=True,
                    visible=False,
                    label="Length penalty",
                    info=(
                        "length_penalty > 0.0 promotes longer sequences, while length_penalty < 0.0 encourages shorter"
                        " sequences. Only used if `decoding_strategy` is `beam_search` or `beam_sampling`."
                    ),
                )
                decoding_strategy.change(
                    fn=lambda selection: gr.Slider.update(visible=(selection in ["beam_search", "beam_sampling"])),
                    inputs=decoding_strategy,
                    outputs=length_penalty,
                )
                penalty_alpha = gr.Slider(
                    minimum=0.0,
                    maximum=5.0,
                    value=0.95,
                    step=0.05,
                    interactive=True,
                    visible=False,
                    label="Penalty alpha",
                    info="Only used if `decoding_strategy` is `contrastive_sampling`.",
                )
                decoding_strategy.change(
                    fn=lambda selection: gr.Slider.update(visible=(selection in ["contrastive_sampling"])),
                    inputs=decoding_strategy,
                    outputs=penalty_alpha,
                )

        with gr.Column(scale=6):

            def prefetch_images_in_history(user_prompt_str):
                """
                Pre-fetch the images that are passed in the chatbot default history.
                """
                return user_prompt_list_to_markdown(handle_manual_images_in_user_prompt(user_prompt_str))

            chatbot = gr.Chatbot(
                elem_id="chatbot",
                label="Idefics Chatbot",
                visible=True,
                height=550,
                value=[
                    [
                        (
                            prefetch_images_in_history(
                                "What's unusual about this"
                                " image?<fake_token_around_image><image:https://i.redd.it/9nkcvbi1pp9y.jpg><fake_token_around_image>"
                            )
                        ),
                        (
                            "The unusual aspect of this image is that there is a cat lying on a bed with an orange on"
                            " its stomach. The cat is white and fluffy, and it appears to be sleeping or resting"
                            " comfortably with the orange on its belly. This is an uncommon sight, as cats typically"
                            " do not interact with fruits in such a manner."
                        ),
                    ],
                    [
                        (
                            prefetch_images_in_history(
                                "<fake_token_around_image><image:https://www.boredpanda.com/blog/wp-content/uploads/2014/02/funny-wet-cats-coverimage.jpg><fake_token_around_image>What"
                                " about this cat? Why do people find it funny?"
                            )
                        ),
                        (
                            "The cat in the image is a gray and white long-haired cat with a surprised expression on"
                            " its face. The cat's eyes are wide open, and it appears to be looking directly at the"
                            " camera. The cat's mouth is also open, which adds to its surprised and funny appearance."
                            " The combination of the cat's surprised expression and its wet fur, possibly from being"
                            " in the shower or bath, makes it an amusing and entertaining sight for many people."
                        ),
                    ],
                ],
            )
            with gr.Row():
                with gr.Column(scale=8):
                    textbox.render()
                with gr.Column(scale=1, min_width=60):
                    submit_btn = gr.Button(value="Submit", visible=True)
                with gr.Column(scale=1, min_width=20):
                    clear_btn = gr.ClearButton([textbox, chatbot])
                    cur_dir = os.path.dirname(os.path.abspath(__file__))

    def model_inference(
        user_prompt_str,
        chat_history,
        image,
        decoding_strategy,
        num_beams,
        temperature,
        no_repeat_ngram_size,
        max_new_tokens,
        min_length,
        repetition_penalty,
        length_penalty,
        top_k,
        top_p,
        penalty_alpha,
    ):
        # global processor, model, tokenizer

        force_words = ""
        hide_special_tokens = False

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

        generated_text = model_generation(
            prompt_list=formated_prompt_list,
            processor=processor,
            tokenizer=tokenizer,
            model=model,
            temperature=temperature,
            no_repeat_ngram_size=no_repeat_ngram_size,
            max_new_tokens=max_new_tokens,
            min_length=min_length,
            ban_tokens=BAN_TOKENS,
            eos_tokens=EOS_TOKENS,
            force_words=force_words,
            repetition_penalty=repetition_penalty,
            hide_special_tokens=hide_special_tokens,
            decoding_strategy=decoding_strategy,
            num_beams=num_beams,
            length_penalty=length_penalty,
            top_k=top_k,
            top_p=top_p,
            penalty_alpha=penalty_alpha,
        )

        if image is None:
            # Case where there is no image OR the image is passed as `<fake_token_around_image><image:IMAGE_URL><fake_token_around_image>`
            chat_history.append((user_prompt_list_to_markdown(user_prompt_list), generated_text.strip("<end_of_utterance>")))
        else:
            # Case where the image is passed through the Image Box.
            # Convert the image into base64 for both passing it through the chat history and
            # displaying the image inside the same bubble as the text.
            chat_history.append(
                (f"{user_prompt_list_to_markdown([image] + user_prompt_list)}", generated_text.strip("<end_of_utterance>"))
            )
        return "", None, chat_history

    def process_example(message): 
        clear_msg, image_value, chat = model_inference(message, [], None, "greedy", 3, 1.0, 0, 512, 16, 1.0, 1.0, 50, 0.95, 0.95)
        return clear_msg, image_value, chat

    textbox.submit(
        fn=model_inference,
        inputs=[
            textbox,
            chatbot,
            imagebox,
            decoding_strategy,
            num_beams,
            temperature,
            no_repeat_ngram_size,
            max_new_tokens,
            min_length,
            repetition_penalty,
            length_penalty,
            top_k,
            top_p,
            penalty_alpha,
        ],
        outputs=[textbox, imagebox, chatbot],
    )
    submit_btn.click(
        fn=model_inference,
        inputs=[
            textbox,
            chatbot,
            imagebox,
            decoding_strategy,
            num_beams,
            temperature,
            no_repeat_ngram_size,
            max_new_tokens,
            min_length,
            repetition_penalty,
            length_penalty,
            top_k,
            top_p,
            penalty_alpha,
        ],
        outputs=[
            textbox,
            imagebox,
            chatbot,
        ],
    )

    gr.Examples(examples=[
        #[f"{cur_dir}/examples/extreme_ironing.jpg", "What is unusual about this image?"], 
        #[f"{cur_dir}/examples/waterview.jpg", "What are the things I should be cautious about when I visit here?"],
        ["<fake_token_around_image><https://huggingface.co/spaces/ysharma/m4-dialogue/resolve/main/images/bear.jpg><fake_token_around_image> Describe this image"],
        ], 
        inputs=[textbox],
        outputs=[textbox, imagebox, chatbot],
        fn=process_example,
        cache_examples=True,               
    )    

demo.queue()
demo.launch()