VictorSanh commited on
Commit
ba10e05
1 Parent(s): f1201ed

Update visualization

Browse files
Files changed (2) hide show
  1. app_dialogue.py +104 -38
  2. images/bear.jpg +0 -0
app_dialogue.py CHANGED
@@ -1,4 +1,5 @@
1
  import base64
 
2
  import logging
3
  import os
4
  import re
@@ -21,28 +22,28 @@ MODELS = [
21
  SYSTEM_PROMPT = [
22
  """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.
23
 
24
- The conversation begins:\n""",
25
- """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""",
26
- """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""",
27
  (
28
- "User:How about this"
29
  " 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"
30
- " you describe it too?<end_of_utterance>\n"
31
  ),
32
- """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""",
33
- "User: What kind of breed is it?<end_of_utterance>\n",
34
- """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""",
35
- "User: What can you tell me about this breed of dogs?<end_of_utterance>\n",
36
- """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""",
37
- "User: ghjkhjabnufs<end_of_utterance>\n",
38
- """Assistant: That doesn’t seem to be a word. Could you ask me another way?<end_of_utterance>\n""",
39
- "User: Do you like Cavalier King Charles Spaniel?<end_of_utterance>\n",
40
- """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""",
41
  (
42
- "User: How many dogs do you see in this"
43
- " 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"
44
  ),
45
- """Assistant: There is no dogs in this image. The picture shows a tennis player jumping to volley the ball.<end_of_utterance>\n""",
46
  ]
47
 
48
  BAN_TOKENS = "<image>;<fake_token_around_image>"
@@ -56,6 +57,19 @@ logging.basicConfig(level=logging.INFO)
56
  logger = logging.getLogger()
57
 
58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  # Conversion between PIL Image <-> base64 <-> Markdown utils
60
  def pil_to_base64(pil_image):
61
  """
@@ -198,7 +212,7 @@ def user_prompt_list_to_markdown(user_prompt_list: List[Union[str, PIL.Image.Ima
198
  if isinstance(elem, str):
199
  resulting_string += elem
200
  elif isinstance(elem, PIL.Image.Image):
201
- resulting_string += pil_to_markdown_im(elem)
202
  else:
203
  raise ValueError(
204
  "Unknown type for `user_prompt_list`. Expected an element of type `str` or `PIL.Image.Image` and got"
@@ -248,7 +262,7 @@ def format_user_prompt_with_im_history_and_system_conditioning(
248
  Produces the resulting list that needs to go inside the processor.
249
  It handles the potential image box input, the history and the system conditionning.
250
  """
251
- resulting_list = SYSTEM_PROMPT
252
 
253
  # Format history
254
  for turn in history:
@@ -500,6 +514,15 @@ with gr.Blocks(title="IDEFICS", theme=gr.themes.Base()) as demo:
500
  interactive=True,
501
  label="Sampling temperature",
502
  )
 
 
 
 
 
 
 
 
 
503
  num_beams = gr.Slider(
504
  minimum=0,
505
  maximum=20,
@@ -687,18 +710,38 @@ with gr.Blocks(title="IDEFICS", theme=gr.themes.Base()) as demo:
687
 
688
  if image is None:
689
  # Case where there is no image OR the image is passed as `<fake_token_around_image><image:IMAGE_URL><fake_token_around_image>`
690
- chat_history.append((user_prompt_list_to_markdown(user_prompt_list), generated_text.strip("<end_of_utterance>")))
 
 
691
  else:
692
  # Case where the image is passed through the Image Box.
693
  # Convert the image into base64 for both passing it through the chat history and
694
  # displaying the image inside the same bubble as the text.
695
  chat_history.append(
696
- (f"{user_prompt_list_to_markdown([image] + user_prompt_list)}", generated_text.strip("<end_of_utterance>"))
 
 
 
697
  )
698
  return "", None, chat_history
699
 
700
- def process_example(message, image):
701
- clear_msg, image_value, chat = model_inference(message, [], image, "greedy", 3, 1.0, 0, 512, 16, 1.0, 1.0, 50, 0.95, 0.95)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
702
  return clear_msg, image_value, chat
703
 
704
  textbox.submit(
@@ -746,26 +789,49 @@ with gr.Blocks(title="IDEFICS", theme=gr.themes.Base()) as demo:
746
  ],
747
  )
748
 
749
- gr.Examples(examples=[
750
- ["What are the armed baguettes guarding?", "./example_images/baguettes_guarding_paris.png"],
751
- ["Can you describe the image?", "example_images/bear_costume.png"],
752
- ["What is this object and do you think it is horrifying?", "example_images/can_horror.png"],
753
- ["Can you tell me a very short story based on this image?", "example_images/chicken_on_money.png"],
754
- ["Can you describe this image in details please?", "example_images/dragons_playing.png"],
755
- ["Can you tell me what is unique about this image?", "example_images/ironman_cap.png"],
756
- ["Can you write an advertisement for Coca-Cola based on this image?", "example_images/polar_bear_coke.png"],
757
- ["What is the rabbit doing in this image? Do you think this image is real?", "example_images/rabbit_force.png"],
758
- ["What is happening in this image and why is it unusual?", "example_images/ramen.png"],
759
- ["What I should look most forward to when I visit this place?", "example_images/tree_fortress.jpg"],
760
- ["<fake_token_around_image><image:https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/stable-diffusion-xl-coreml/a_high_quality_photo_of_a_surfing_dog.7667.final_float16_original.jpg><fake_token_around_image>What do you think the dog is doing and is it unusual?", None],
761
- ],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
762
  inputs=[textbox, imagebox],
763
  outputs=[textbox, imagebox, chatbot],
764
  fn=process_example,
765
- cache_examples=True,
766
  examples_per_page=5,
767
  label="Click on any example below to get started",
768
- )
769
 
770
  demo.queue()
771
  demo.launch()
 
1
  import base64
2
+ import copy
3
  import logging
4
  import os
5
  import re
 
22
  SYSTEM_PROMPT = [
23
  """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.
24
 
25
+ The conversation begins:""",
26
+ """\nUser:<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>""",
27
+ """\nAssistant: 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>""",
28
  (
29
+ "\nUser:How about this"
30
  " 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"
31
+ " you describe it too?<end_of_utterance>"
32
  ),
33
+ """\nAssistant: 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>""",
34
+ "\nUser: What kind of breed is it?<end_of_utterance>",
35
+ """\nAssistant: 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>""",
36
+ "\nUser: What can you tell me about this breed of dogs?<end_of_utterance>",
37
+ """\nAssistant: 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>""",
38
+ "\nUser: ghjkhjabnufs<end_of_utterance>",
39
+ """\nAssistant: That doesn’t seem to be a word. Could you ask me another way?<end_of_utterance>""",
40
+ "\nUser: Do you like Cavalier King Charles Spaniel?<end_of_utterance>\n",
41
+ """\nAssistant: 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>""",
42
  (
43
+ "\nUser: How many dogs do you see in this"
44
+ " 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>"
45
  ),
46
+ """\nAssistant: There is no dogs in this image. The picture shows a tennis player jumping to volley the ball.<end_of_utterance>""",
47
  ]
48
 
49
  BAN_TOKENS = "<image>;<fake_token_around_image>"
 
57
  logger = logging.getLogger()
58
 
59
 
60
+ def convert_to_rgb(image):
61
+ # `image.convert("RGB")` would only work for .jpg images, as it creates a wrong background
62
+ # for transparent images. The call to `alpha_composite` handles this case
63
+ if image.mode == "RGB":
64
+ return image
65
+
66
+ image_rgba = image.convert("RGBA")
67
+ background = Image.new("RGBA", image_rgba.size, (255, 255, 255))
68
+ alpha_composite = Image.alpha_composite(background, image_rgba)
69
+ alpha_composite = alpha_composite.convert("RGB")
70
+ return alpha_composite
71
+
72
+
73
  # Conversion between PIL Image <-> base64 <-> Markdown utils
74
  def pil_to_base64(pil_image):
75
  """
 
212
  if isinstance(elem, str):
213
  resulting_string += elem
214
  elif isinstance(elem, PIL.Image.Image):
215
+ resulting_string += pil_to_markdown_im(convert_to_rgb(elem))
216
  else:
217
  raise ValueError(
218
  "Unknown type for `user_prompt_list`. Expected an element of type `str` or `PIL.Image.Image` and got"
 
262
  Produces the resulting list that needs to go inside the processor.
263
  It handles the potential image box input, the history and the system conditionning.
264
  """
265
+ resulting_list = copy.deepcopy(SYSTEM_PROMPT)
266
 
267
  # Format history
268
  for turn in history:
 
514
  interactive=True,
515
  label="Sampling temperature",
516
  )
517
+ decoding_strategy.change(
518
+ fn=lambda selection: gr.Slider.update(
519
+ visible=(
520
+ selection in ["contrastive_sampling", "beam_sampling", "sampling_top_p", "sampling_top_k"]
521
+ )
522
+ ),
523
+ inputs=decoding_strategy,
524
+ outputs=temperature,
525
+ )
526
  num_beams = gr.Slider(
527
  minimum=0,
528
  maximum=20,
 
710
 
711
  if image is None:
712
  # Case where there is no image OR the image is passed as `<fake_token_around_image><image:IMAGE_URL><fake_token_around_image>`
713
+ chat_history.append(
714
+ (user_prompt_list_to_markdown(user_prompt_list), generated_text.strip("<end_of_utterance>"))
715
+ )
716
  else:
717
  # Case where the image is passed through the Image Box.
718
  # Convert the image into base64 for both passing it through the chat history and
719
  # displaying the image inside the same bubble as the text.
720
  chat_history.append(
721
+ (
722
+ f"{user_prompt_list_to_markdown([image] + user_prompt_list)}",
723
+ generated_text.strip("<end_of_utterance>"),
724
+ )
725
  )
726
  return "", None, chat_history
727
 
728
+ def process_example(message, image):
729
+ clear_msg, image_value, chat = model_inference(
730
+ user_prompt_str=message,
731
+ chat_history=[],
732
+ image=image,
733
+ decoding_strategy="greedy",
734
+ num_beams=3,
735
+ temperature=1.0,
736
+ no_repeat_ngram_size=0,
737
+ max_new_tokens=512,
738
+ min_length=16,
739
+ repetition_penalty=1.0,
740
+ length_penalty=1.0,
741
+ top_k=50,
742
+ top_p=0.95,
743
+ penalty_alpha=0.95,
744
+ )
745
  return clear_msg, image_value, chat
746
 
747
  textbox.submit(
 
789
  ],
790
  )
791
 
792
+ examples_path = os.path.dirname(__file__)
793
+ gr.Examples(
794
+ examples=[
795
+ ["What are the armed baguettes guarding?", f"{examples_path}/example_images/baguettes_guarding_paris.png"],
796
+ ["Can you describe the image?", f"{examples_path}/example_images/bear_costume.png"],
797
+ [
798
+ "What is this object and do you think it is horrifying?",
799
+ f"{examples_path}/example_images/can_horror.png",
800
+ ],
801
+ [
802
+ "Can you tell me a very short story based on this image?",
803
+ f"{examples_path}/example_images/chicken_on_money.png",
804
+ ],
805
+ ["Can you describe this image in details please?", f"{examples_path}/example_images/dragons_playing.png"],
806
+ ["Can you tell me what is unique about this image?", f"{examples_path}/example_images/ironman_cap.png"],
807
+ [
808
+ "Can you write an advertisement for Coca-Cola based on this image?",
809
+ f"{examples_path}/example_images/polar_bear_coke.png",
810
+ ],
811
+ [
812
+ "What is the rabbit doing in this image? Do you think this image is real?",
813
+ f"{examples_path}/example_images/rabbit_force.png",
814
+ ],
815
+ ["What is happening in this image and why is it unusual?", f"{examples_path}/example_images/ramen.png"],
816
+ [
817
+ "What I should look most forward to when I visit this place?",
818
+ f"{examples_path}/example_images/tree_fortress.jpg",
819
+ ],
820
+ [
821
+ (
822
+ "<fake_token_around_image><image:https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/stable-diffusion-xl-coreml/a_high_quality_photo_of_a_surfing_dog.7667.final_float16_original.jpg><fake_token_around_image>What"
823
+ " do you think the dog is doing and is it unusual?"
824
+ ),
825
+ None,
826
+ ],
827
+ ],
828
  inputs=[textbox, imagebox],
829
  outputs=[textbox, imagebox, chatbot],
830
  fn=process_example,
831
+ cache_examples=True,
832
  examples_per_page=5,
833
  label="Click on any example below to get started",
834
+ )
835
 
836
  demo.queue()
837
  demo.launch()
images/bear.jpg DELETED
Binary file (245 kB)