steadilyai commited on
Commit
b3a031d
β€’
1 Parent(s): cbe11bf

Upload 2 files

Browse files
Files changed (2) hide show
  1. Dockerfile +72 -0
  2. app_dialogue.py +879 -0
Dockerfile ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ARG PYTHON_VERSION=3.9
2
+ # Download LFS content while building in order to make this step cacheable
3
+ #===== LFS =====
4
+ FROM alpine/git:2.36.2 AS lfs
5
+ WORKDIR /app
6
+
7
+ FROM python:${PYTHON_VERSION}
8
+ ENV DEBIAN_FRONTEND=noninteractive \
9
+ TZ=Europe/Paris
10
+
11
+ # BEGIN Static Part
12
+ RUN apt-get update && apt-get install -y \
13
+ git \
14
+ git-lfs \
15
+ ffmpeg \
16
+ libsm6 \
17
+ libxext6 \
18
+ cmake \
19
+ libgl1-mesa-glx \
20
+ && rm -rf /var/lib/apt/lists/* \
21
+ && git lfs install
22
+
23
+ # User
24
+ RUN useradd -m -u 1000 user
25
+ USER user
26
+ ENV HOME=/home/user \
27
+ PATH=/home/user/.local/bin:$PATH
28
+ WORKDIR /home/user/app
29
+
30
+ ARG PIP_VERSION=22.3.1
31
+ RUN pip install --no-cache-dir pip==${PIP_VERSION} && \
32
+ pip install --no-cache-dir \
33
+ datasets \
34
+ "huggingface-hub>=0.12.1" "protobuf<4" "click<8.1" "pydantic~=1.0"
35
+
36
+ #^ Waiting for https://github.com/huggingface/huggingface_hub/pull/1345/files to be merge
37
+
38
+ # END Static Part
39
+
40
+ # BEGIN Dynamic Part
41
+ USER root
42
+ # User Debian packages
43
+
44
+
45
+ USER user
46
+
47
+ # Pre requirements (e.g. upgrading pip)
48
+ RUN --mount=target=pre-requirements.txt,source=pre-requirements.txt \
49
+ pip install --no-cache-dir -r pre-requirements.txt
50
+
51
+ # Python packages
52
+ RUN --mount=target=requirements.txt,source=requirements.txt \
53
+ pip install --no-cache-dir -r requirements.txt
54
+
55
+ # Streamlit and Gradio
56
+ ARG SDK= \
57
+ SDK_VERSION=
58
+ RUN pip install --no-cache-dir \
59
+ ${SDK}==${SDK_VERSION}
60
+
61
+ # App
62
+ COPY --link --chown=1000 --from=lfs /app /home/user/app
63
+ COPY --link --chown=1000 ./ /home/user/app
64
+ ENV PYTHONPATH=$HOME/app \
65
+ PYTHONUNBUFFERED=1 \
66
+ GRADIO_ALLOW_FLAGGING=never \
67
+ GRADIO_NUM_PORTS=1 \
68
+ GRADIO_SERVER_NAME=0.0.0.0 \
69
+ GRADIO_THEME=huggingface \
70
+ SYSTEM=spaces
71
+
72
+ #END Dynamic
app_dialogue.py ADDED
@@ -0,0 +1,879 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import glob
3
+ import hashlib
4
+ import logging
5
+ import os
6
+ import re
7
+ from pathlib import Path
8
+ from typing import List, Optional, Tuple
9
+ from urllib.parse import urlparse
10
+
11
+ import gradio as gr
12
+ import PIL
13
+ from gradio import processing_utils
14
+ from gradio_client.client import DEFAULT_TEMP_DIR
15
+ from text_generation import Client
16
+ from transformers import AutoProcessor
17
+
18
+
19
+ MODELS = [
20
+ # "HuggingFaceM4/idefics-9b-instruct",
21
+ "HuggingFaceM4/idefics-80b-instruct",
22
+ ]
23
+
24
+ API_PATHS = {
25
+ "HuggingFaceM4/idefics-9b-instruct": (
26
+ "http://34.106.61.22:8080"
27
+ ),
28
+ "HuggingFaceM4/idefics-80b-instruct": (
29
+ "http://34.106.61.22:8080"
30
+ ),
31
+ }
32
+
33
+ SYSTEM_PROMPT = [
34
+ """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.
35
+
36
+ The conversation begins:""",
37
+ """\nUser:""",
38
+ "https://i1.pickpik.com/photos/515/906/355/kittens-cats-pet-cute-preview.jpg",
39
+ "Describe this image.<end_of_utterance>",
40
+ """\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>""",
41
+ "\nUser:How about this image?",
42
+ "https://cdn.pixabay.com/photo/2017/09/25/13/12/puppy-2785074_1280.jpg",
43
+ "Can you describe it too?<end_of_utterance>",
44
+ """\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>""",
45
+ "\nUser: What kind of breed is it?<end_of_utterance>",
46
+ """\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>""",
47
+ "\nUser: What can you tell me about this breed of dogs?<end_of_utterance>",
48
+ """\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>""",
49
+ "\nUser: ghjkhjabnufs<end_of_utterance>",
50
+ """\nAssistant: That doesn’t seem to be a word. Could you ask me another way?<end_of_utterance>""",
51
+ "\nUser: Do you like Cavalier King Charles Spaniel?<end_of_utterance>",
52
+ """\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>""",
53
+ "\nUser: How many dogs do you see in this image?",
54
+ "https://i.dailymail.co.uk/i/pix/2011/07/01/article-2010308-0CD22A8300000578-496_634x414.jpg",
55
+ "<end_of_utterance>",
56
+ """\nAssistant: There is no dogs in this image. The picture shows a tennis player jumping to volley the ball.<end_of_utterance>""",
57
+ ]
58
+
59
+ BAN_TOKENS = ( # For documentation puporse. We are not using this list, it is hardcoded inside `idefics_causal_lm.py` inside TGI.
60
+ "<image>;<fake_token_around_image>"
61
+ )
62
+ EOS_STRINGS = ["<end_of_utterance>", "\nUser:"]
63
+ STOP_SUSPECT_LIST = []
64
+
65
+ GRADIO_LINK = "http://localhost:7860"
66
+ API_TOKEN = os.getenv("HF_AUTH_TOKEN")
67
+ IDEFICS_LOGO = "https://huggingface.co/spaces/HuggingFaceM4/idefics_playground/resolve/main/IDEFICS_logo.png"
68
+
69
+ PROCESSOR = AutoProcessor.from_pretrained(
70
+ "HuggingFaceM4/idefics-9b-instruct",
71
+ token=API_TOKEN,
72
+ )
73
+
74
+ BOT_AVATAR = "IDEFICS_logo.png"
75
+
76
+ logging.basicConfig(level=logging.INFO)
77
+ logger = logging.getLogger()
78
+
79
+
80
+ # Monkey patch adapted from gradio.components.image.Image - mostly to make the `save` step optional in `pil_to_temp_file`
81
+ def hash_bytes(bytes: bytes):
82
+ sha1 = hashlib.sha1()
83
+ sha1.update(bytes)
84
+ return sha1.hexdigest()
85
+
86
+
87
+ def pil_to_temp_file(img: PIL.Image.Image, dir: str = DEFAULT_TEMP_DIR, format: str = "png") -> str:
88
+ """Save a PIL image into a temp file"""
89
+ bytes_data = processing_utils.encode_pil_to_bytes(img, format)
90
+ temp_dir = Path(dir) / hash_bytes(bytes_data)
91
+ temp_dir.mkdir(exist_ok=True, parents=True)
92
+ filename = str(temp_dir / f"image.{format}")
93
+ if not os.path.exists(filename):
94
+ img.save(filename, pnginfo=processing_utils.get_pil_metadata(img))
95
+ return filename
96
+
97
+
98
+ def add_file(file):
99
+ return file.name, gr.update(label='πŸ–ΌοΈ Uploaded!')
100
+
101
+
102
+ # This is a hack to make pre-computing the default examples work.
103
+ # During normal inference, we pass images as url to a local file using the method `gradio_link`
104
+ # which allows the tgi server to fetch the local image from the frontend server.
105
+ # however, we are building the space (and pre-computing is part of building the space), the frontend is not available
106
+ # and won't answer. So tgi server will try to fetch an image that is not available yet, which will result in a timeout error
107
+ # because tgi will never be able to return the generation.
108
+ # To bypass that, we pass instead the images URLs from the spaces repo.
109
+ all_images = glob.glob(f"{os.path.dirname(__file__)}/example_images/*")
110
+ DEFAULT_IMAGES_TMP_PATH_TO_URL = {}
111
+ for im_path in all_images:
112
+ H = gr.Image(im_path, visible=False, type="filepath")
113
+ tmp_filename = H.preprocess(H.value)
114
+ DEFAULT_IMAGES_TMP_PATH_TO_URL[tmp_filename] = f"https://huggingface.co/spaces/HuggingFaceM4/idefics_playground/resolve/main/example_images/{os.path.basename(im_path)}"
115
+
116
+
117
+ # Utils to handle the image markdown display logic
118
+ def split_str_on_im_markdown(string: str) -> List[str]:
119
+ """
120
+ Extract from a string (typically the user prompt string) the potential images from markdown
121
+ Examples:
122
+ - `User:![](https://favurl.com/chicken_on_money.png)Describe this image.` would become `["User:", "https://favurl.com/chicken_on_money.png", "Describe this image."]`
123
+ - `User:![](/file=/my_temp/chicken_on_money.png)Describe this image.` would become `["User:", "/my_temp/chicken_on_money.png", "Describe this image."]`
124
+ """
125
+ IMAGES_PATTERN = re.compile(r"!\[[^\]]*\]\((.*?)\s*(\"(?:.*[^\"])\")?\s*\)")
126
+ parts = []
127
+ cursor = 0
128
+ for pattern in IMAGES_PATTERN.finditer(string):
129
+ start = pattern.start()
130
+ if start != cursor:
131
+ parts.append(string[cursor:start])
132
+ image_url = pattern.group(1)
133
+ if image_url.startswith("/file="):
134
+ image_url = image_url[6:] # Remove the 'file=' prefix
135
+ parts.append(image_url)
136
+ cursor = pattern.end()
137
+ if cursor != len(string):
138
+ parts.append(string[cursor:])
139
+ return parts
140
+
141
+
142
+ def is_image(string: str) -> bool:
143
+ """
144
+ There are two ways for images: local image path or url.
145
+ """
146
+ return is_url(string) or string.startswith(DEFAULT_TEMP_DIR)
147
+
148
+
149
+ def is_url(string: str) -> bool:
150
+ """
151
+ Checks if the passed string contains a valid url and nothing else. e.g. if space is included it's immediately
152
+ invalidated the url
153
+ """
154
+ if " " in string:
155
+ return False
156
+ result = urlparse(string)
157
+ return all([result.scheme, result.netloc])
158
+
159
+
160
+ def isolate_images_urls(prompt_list: List) -> List:
161
+ """
162
+ Convert a full string prompt to the list format expected by the processor.
163
+ In particular, image urls (as delimited by <fake_token_around_image>) should be their own elements.
164
+ From:
165
+ ```
166
+ [
167
+ "bonjour<fake_token_around_image><image:IMG_URL><fake_token_around_image>hello",
168
+ PIL.Image.Image,
169
+ "Aurevoir",
170
+ ]
171
+ ```
172
+ to:
173
+ ```
174
+ [
175
+ "bonjour",
176
+ IMG_URL,
177
+ "hello",
178
+ PIL.Image.Image,
179
+ "Aurevoir",
180
+ ]
181
+ ```
182
+ """
183
+ linearized_list = []
184
+ for prompt in prompt_list:
185
+ # Prompt can be either a string, or a PIL image
186
+ if isinstance(prompt, PIL.Image.Image):
187
+ linearized_list.append(prompt)
188
+ elif isinstance(prompt, str):
189
+ if "<fake_token_around_image>" not in prompt:
190
+ linearized_list.append(prompt)
191
+ else:
192
+ prompt_splitted = prompt.split("<fake_token_around_image>")
193
+ for ps in prompt_splitted:
194
+ if ps == "":
195
+ continue
196
+ if ps.startswith("<image:"):
197
+ linearized_list.append(ps[7:-1])
198
+ else:
199
+ linearized_list.append(ps)
200
+ else:
201
+ raise TypeError(
202
+ f"Unrecognized type for `prompt`. Got {type(type(prompt))}. Was expecting something in [`str`,"
203
+ " `PIL.Image.Image`]"
204
+ )
205
+ return linearized_list
206
+
207
+
208
+ def fetch_images(url_list: str) -> PIL.Image.Image:
209
+ """Fetching images"""
210
+ return PROCESSOR.image_processor.fetch_images(url_list)
211
+
212
+
213
+ def handle_manual_images_in_user_prompt(user_prompt: str) -> List[str]:
214
+ """
215
+ 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
216
+ by fetching them, saving them locally and replacing the whole sub-sequence the image local path.
217
+ """
218
+ if "<fake_token_around_image>" in user_prompt:
219
+ splitted_user_prompt = isolate_images_urls([user_prompt])
220
+ resulting_user_prompt = []
221
+ for u_p in splitted_user_prompt:
222
+ if is_url(u_p):
223
+ img = fetch_images([u_p])[0]
224
+ tmp_file = pil_to_temp_file(img)
225
+ resulting_user_prompt.append(tmp_file)
226
+ else:
227
+ resulting_user_prompt.append(u_p)
228
+ return resulting_user_prompt
229
+ else:
230
+ return [user_prompt]
231
+
232
+
233
+ def gradio_link(img_path: str) -> str:
234
+ url = f"{GRADIO_LINK}/file={img_path}"
235
+ return url
236
+
237
+
238
+ def prompt_list_to_markdown(prompt_list: List[str]) -> str:
239
+ """
240
+ Convert a user prompt in the list format (i.e. elements are either a PIL image or a string) into
241
+ the markdown format that is used for the chatbot history and rendering.
242
+ """
243
+ resulting_string = ""
244
+ for elem in prompt_list:
245
+ if is_image(elem):
246
+ if is_url(elem):
247
+ resulting_string += f"![]({elem})"
248
+ else:
249
+ resulting_string += f"![](/file={elem})"
250
+ else:
251
+ resulting_string += elem
252
+ return resulting_string
253
+
254
+
255
+ def prompt_list_to_tgi_input(prompt_list: List[str]) -> str:
256
+ """
257
+ TGI expects a string that contains both text and images in the image markdown format (i.e. the `![]()` ).
258
+ The images links are parsed on TGI side
259
+ """
260
+ result_string_input = ""
261
+ for elem in prompt_list:
262
+ if is_image(elem):
263
+ if is_url(elem):
264
+ result_string_input += f"![]({elem})"
265
+ else:
266
+ result_string_input += f"![]({gradio_link(img_path=elem)})"
267
+ else:
268
+ result_string_input += elem
269
+ return result_string_input
270
+
271
+
272
+ def remove_spaces_around_token(text: str) -> str:
273
+ pattern = r"\s*(<fake_token_around_image>)\s*"
274
+ replacement = r"\1"
275
+ result = re.sub(pattern, replacement, text)
276
+ return result
277
+
278
+
279
+ # Chatbot utils
280
+ def format_user_prompt_with_im_history_and_system_conditioning(
281
+ current_user_prompt_str: str, current_image: Optional[str], history: List[Tuple[str, str]]
282
+ ) -> Tuple[List[str], List[str]]:
283
+ """
284
+ Produces the resulting list that needs to go inside the processor.
285
+ It handles the potential image box input, the history and the system conditionning.
286
+ """
287
+ resulting_list = copy.deepcopy(SYSTEM_PROMPT)
288
+
289
+ # Format history
290
+ for turn in history:
291
+ user_utterance, assistant_utterance = turn
292
+ splitted_user_utterance = split_str_on_im_markdown(user_utterance)
293
+
294
+ optional_space = ""
295
+ if not is_image(splitted_user_utterance[0]):
296
+ optional_space = " "
297
+ resulting_list.append(f"\nUser:{optional_space}")
298
+ resulting_list.extend(splitted_user_utterance)
299
+ resulting_list.append(f"<end_of_utterance>\nAssistant: {assistant_utterance}")
300
+
301
+ # Format current input
302
+ current_user_prompt_str = remove_spaces_around_token(current_user_prompt_str)
303
+ if current_image is None:
304
+ if "![](" in current_user_prompt_str:
305
+ current_user_prompt_list = split_str_on_im_markdown(current_user_prompt_str)
306
+ else:
307
+ current_user_prompt_list = handle_manual_images_in_user_prompt(current_user_prompt_str)
308
+
309
+ optional_space = ""
310
+ if not is_image(current_user_prompt_list[0]):
311
+ # Check if the first element is an image (and more precisely a path to an image)
312
+ optional_space = " "
313
+ resulting_list.append(f"\nUser:{optional_space}")
314
+ resulting_list.extend(current_user_prompt_list)
315
+ resulting_list.append("<end_of_utterance>\nAssistant:")
316
+ else:
317
+ # Choosing to put the image first when the image is inputted through the UI, but this is an arbiratrary choice.
318
+ resulting_list.extend(["\nUser:", current_image, f"{current_user_prompt_str}<end_of_utterance>\nAssistant:"])
319
+ current_user_prompt_list = [current_user_prompt_str]
320
+
321
+ return resulting_list, current_user_prompt_list
322
+
323
+
324
+ # dope_callback = gr.CSVLogger()
325
+ # problematic_callback = gr.CSVLogger()
326
+
327
+ textbox = gr.Textbox(
328
+ placeholder="Upload an image and send a message",
329
+ show_label=False,
330
+ # value="Describe the battle against the fierce dragons.",
331
+ visible=True,
332
+ container=False,
333
+ label="Text input",
334
+ scale=6,
335
+ )
336
+ with gr.Blocks(title="IDEFICS Playground", theme=gr.themes.Base()) as demo:
337
+ gr.HTML("""<h1 align="center">🐢 IDEFICS Playground</h1>""")
338
+ with gr.Row(variant="panel"):
339
+ with gr.Column(scale=1):
340
+ gr.Image(IDEFICS_LOGO, elem_id="banner-image", show_label=False, show_download_button=False)
341
+ with gr.Column(scale=5):
342
+ gr.HTML("""
343
+ <p>This demo showcases <strong>IDEFICS</strong>, a open-access large visual language model. 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>
344
+ <p>IDEFICS (which stands for <strong>I</strong>mage-aware <strong>D</strong>ecoder <strong>E</strong>nhanced Γ  la <strong>F</strong>lamingo with <strong>I</strong>nterleaved <strong>C</strong>ross-attention<strong>S</strong>) is an open-access reproduction of <a href="https://huggingface.co/papers/2204.14198">Flamingo</a>, a closed-source visual language model developed by Deepmind. IDEFICS was built solely on publicly available data and models. It is currently the only visual language model of this scale (80 billion parameters) that is available in open-access.</p>
345
+ <p>πŸ“š The variants available in this demo were fine-tuned on a mixture of supervised and instruction fine-tuning datasets to make the models more suitable in conversational settings. For more details, we refer to our <a href="https://huggingface.co/blog/idefics">blog post</a>.</p>
346
+ <p>πŸ…ΏοΈ <strong>Intended uses:</strong> This demo along with the <a href="https://huggingface.co/models?sort=trending&amp;search=HuggingFaceM4%2Fidefics">supporting models</a> are provided as research artifacts to the community. We detail misuses and out-of-scope uses <a href="https://huggingface.co/HuggingFaceM4/idefics-80b#misuse-and-out-of-scope-use">here</a>.</p>
347
+ <p>⛔️ <strong>Limitations:</strong> The model can produce factually incorrect texts, hallucinate facts (with or without an image) and will struggle with small details in images. While the model 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. We encourage users to read our findings from evaluating the model for potential biases in the <a href="https://huggingface.co/HuggingFaceM4/idefics-80b#bias-evaluation">model card</a>.</p>
348
+ """)
349
+
350
+ # with gr.Row():
351
+ # with gr.Column(scale=2):
352
+ with gr.Row(elem_id="model_selector_row"):
353
+ model_selector = gr.Dropdown(
354
+ choices=MODELS,
355
+ value="HuggingFaceM4/idefics-80b-instruct",
356
+ interactive=True,
357
+ show_label=False,
358
+ container=False,
359
+ label="Model",
360
+ visible=False,
361
+ )
362
+
363
+ imagebox = gr.Image(type="filepath", label="Image input", visible=False)
364
+
365
+ with gr.Row():
366
+ # def prefetch_images_in_history(user_prompt_str):
367
+ # """
368
+ # Pre-fetch the images that are passed in the chatbot default history.
369
+ # """
370
+ # return prompt_list_to_markdown(handle_manual_images_in_user_prompt(user_prompt_str))
371
+
372
+ chatbot = gr.Chatbot(
373
+ elem_id="chatbot",
374
+ label="IDEFICS",
375
+ visible=True,
376
+ height=750,
377
+ avatar_images=[None, BOT_AVATAR]
378
+ # value=[
379
+ # [
380
+ # (
381
+ # prefetch_images_in_history(
382
+ # """Write a funny story including the following characters.
383
+ # There should be drama and most importantly romance.
384
+ # Character 1:<fake_token_around_image><image:https://m.media-amazon.com/images/M/MV5BODg1OTczMWEtNTU3MS00OTUzLThjODEtNDg1MWQwZmExYmFlXkEyXkFqcGdeQWFybm8@._V1_QL75_UX500_CR0,0,500,281_.jpg><fake_token_around_image>
385
+ # Character 2:<fake_token_around_image><image:https://static.wikia.nocookie.net/dreamworks/images/0/09/Shrek_dreamworks.png/revision/latest?cb=20170921225439><fake_token_around_image>
386
+ # Character 3:<fake_token_around_image><image:https://upload.wikimedia.org/wikipedia/en/e/ef/Marsupilami_1.jpg><fake_token_around_image>
387
+ # The plot should take place in the world pictured here:<fake_token_around_image><image:https://www.astronomy.com/wp-content/uploads/sites/2/2021/09/ON1.jpg><fake_token_around_image>"""
388
+ # )
389
+ # ),
390
+ # """Once upon a time, in a world where the sky was a dome and the ground was covered in grass, there lived a beautiful princess named Mulan. She was kind, brave, and always ready to help others. One day, while walking through the forest, she stumbled upon a strange creature. It was a green ogre named Shrek, who was lost and looking for his way back home.
391
+ # Mulan, being the kind-hearted person she was, decided to help Shrek find his way back. As they traveled together, they began to develop a strong bond. Shrek was impressed by Mulan's bravery and determination, while Mulan admired Shrek's loyalty and sense of humor.
392
+ # However, their journey was not without obstacles. They encountered a mischievous cat named Hoboua, who was always causing trouble and getting into fights. Despite his troublemaking ways, Hoboua had a good heart and eventually became a valuable ally to Mulan and Shrek.
393
+ # As they traveled, they faced many challenges, including battling fierce dragons and navigating treacherous mountains. Through it all, Mulan and Shrek grew closer, and their feelings for each other deepened.
394
+ # Finally, they reached Shrek's home, and he was reunited with his family and friends. Mulan, however, was sad to leave him behind. But Shrek had a surprise for her. He had fallen in love with her and wanted to be with her forever.
395
+ # Mulan was overjoyed, and they shared a passionate kiss. From that day on, they lived happily ever after, exploring the world together and facing any challenges that came their way.
396
+ # And so, the story of Mulan and Shrek's romance came to an end, leaving a lasting impression on all who heard it.""",
397
+ # ],
398
+ # ],
399
+ )
400
+
401
+ with gr.Group():
402
+ with gr.Row():
403
+ textbox.render()
404
+ submit_btn = gr.Button(value="▢️ Submit", visible=True)
405
+ clear_btn = gr.ClearButton([textbox, imagebox, chatbot], value="🧹 Clear")
406
+ regenerate_btn = gr.Button(value="πŸ”„ Regenerate", visible=True)
407
+ upload_btn = gr.UploadButton("πŸ“ Upload image", file_types=["image"])
408
+ # with gr.Group():
409
+ # with gr.Row():
410
+ # with gr.Column(scale=1, min_width=50):
411
+ # dope_bttn = gr.Button("DopeπŸ”₯")
412
+ # with gr.Column(scale=1, min_width=50):
413
+ # problematic_bttn = gr.Button("Problematic😬")
414
+
415
+ with gr.Row():
416
+ with gr.Accordion("Advanced settings", open=False, visible=True) as parameter_row:
417
+ max_new_tokens = gr.Slider(
418
+ minimum=8,
419
+ maximum=1024,
420
+ value=512,
421
+ step=1,
422
+ interactive=True,
423
+ label="Maximum number of new tokens to generate",
424
+ )
425
+ repetition_penalty = gr.Slider(
426
+ minimum=0.01,
427
+ maximum=5.0,
428
+ value=1.0,
429
+ step=0.01,
430
+ interactive=True,
431
+ label="Repetition penalty",
432
+ info="1.0 is equivalent to no penalty",
433
+ )
434
+ decoding_strategy = gr.Radio(
435
+ [
436
+ "Greedy",
437
+ "Top P Sampling",
438
+ ],
439
+ value="Greedy",
440
+ label="Decoding strategy",
441
+ interactive=True,
442
+ info="Higher values is equivalent to sampling more low-probability tokens.",
443
+ )
444
+ temperature = gr.Slider(
445
+ minimum=0.0,
446
+ maximum=5.0,
447
+ value=0.4,
448
+ step=0.1,
449
+ interactive=True,
450
+ visible=False,
451
+ label="Sampling temperature",
452
+ info="Higher values will produce more diverse outputs.",
453
+ )
454
+ decoding_strategy.change(
455
+ fn=lambda selection: gr.Slider.update(
456
+ visible=(
457
+ selection in ["contrastive_sampling", "beam_sampling", "Top P Sampling", "sampling_top_k"]
458
+ )
459
+ ),
460
+ inputs=decoding_strategy,
461
+ outputs=temperature,
462
+ )
463
+ top_p = gr.Slider(
464
+ minimum=0.01,
465
+ maximum=0.99,
466
+ value=0.8,
467
+ step=0.01,
468
+ interactive=True,
469
+ visible=False,
470
+ label="Top P",
471
+ info="Higher values is equivalent to sampling more low-probability tokens.",
472
+ )
473
+ decoding_strategy.change(
474
+ fn=lambda selection: gr.Slider.update(visible=(selection in ["Top P Sampling"])),
475
+ inputs=decoding_strategy,
476
+ outputs=top_p,
477
+ )
478
+ gr.Markdown(
479
+ """<p><strong>πŸ’‘ Pro tip</strong>:<br>
480
+ You can input an arbitrary number of images at arbitrary positions in the same query.<br>
481
+ You will need to input each image with its URL with the syntax <code>&lt;fake_token_around_image&gt;&lt;image:IMAGE_URL&gt;&lt;fake_token_around_image&gt;</code>.<br>
482
+ For example, for two images, you could input <code>TEXT_1&lt;fake_token_around_image&gt;&lt;image:IMAGE_URL_1&gt;&lt;fake_token_around_image&gt;TEXT_2&lt;fake_token_around_image&gt;&lt;image:IMAGE_URL_2&gt;&lt;fake_token_around_image&gt;TEXT_3</code>.<br>
483
+ In the particular case where two images are consecutive, it is not necessary to add an additional separator: <code>&lt;fake_token_around_image&gt;&lt;image:IMAGE_URL_1&gt;&lt;fake_token_around_image&gt;&lt;image:IMAGE_URL_2&gt;&lt;fake_token_around_image&gt;</code>.</p>"""
484
+ )
485
+
486
+ def model_inference(
487
+ model_selector,
488
+ user_prompt_str,
489
+ chat_history,
490
+ image,
491
+ decoding_strategy,
492
+ temperature,
493
+ max_new_tokens,
494
+ repetition_penalty,
495
+ top_p,
496
+ ):
497
+ if user_prompt_str.strip() == "" and image is None:
498
+ return "", None, chat_history
499
+
500
+ formated_prompt_list, user_prompt_list = format_user_prompt_with_im_history_and_system_conditioning(
501
+ current_user_prompt_str=user_prompt_str.strip(),
502
+ current_image=image,
503
+ history=chat_history,
504
+ )
505
+
506
+ client_endpoint = API_PATHS[model_selector]
507
+ client = Client(
508
+ base_url=client_endpoint,
509
+ headers={"x-use-cache": "0", "Authorization": f"Bearer {API_TOKEN}"},
510
+ )
511
+
512
+ # Common parameters to all decoding strategies
513
+ # This documentation is useful to read: https://huggingface.co/docs/transformers/main/en/generation_strategies
514
+ generation_args = {
515
+ "max_new_tokens": max_new_tokens,
516
+ "repetition_penalty": repetition_penalty,
517
+ "stop_sequences": EOS_STRINGS,
518
+ }
519
+
520
+ assert decoding_strategy in [
521
+ "Greedy",
522
+ "Top P Sampling",
523
+ ]
524
+ if decoding_strategy == "Greedy":
525
+ generation_args["do_sample"] = False
526
+ elif decoding_strategy == "Top P Sampling":
527
+ generation_args["temperature"] = temperature
528
+ generation_args["do_sample"] = True
529
+ generation_args["top_p"] = top_p
530
+
531
+ if image is None:
532
+ # Case where there is no image OR the image is passed as `<fake_token_around_image><image:IMAGE_URL><fake_token_around_image>`
533
+ chat_history.append([prompt_list_to_markdown(user_prompt_list), ''])
534
+ else:
535
+ # Case where the image is passed through the Image Box.
536
+ # Convert the image into base64 for both passing it through the chat history and
537
+ # displaying the image inside the same bubble as the text.
538
+ chat_history.append(
539
+ [
540
+ f"{prompt_list_to_markdown([image] + user_prompt_list)}",
541
+ '',
542
+ ]
543
+ )
544
+
545
+ query = prompt_list_to_tgi_input(formated_prompt_list)
546
+ stream = client.generate_stream(prompt=query, **generation_args)
547
+
548
+ acc_text = ""
549
+ for idx, response in enumerate(stream):
550
+ text_token = response.token.text
551
+
552
+ if response.details:
553
+ # That's the exit condition
554
+ return
555
+
556
+ if text_token in STOP_SUSPECT_LIST:
557
+ acc_text += text_token
558
+ continue
559
+
560
+ if idx == 0 and text_token.startswith(" "):
561
+ text_token = text_token.lstrip()
562
+
563
+ acc_text += text_token
564
+ last_turn = chat_history.pop(-1)
565
+ last_turn[-1] += acc_text
566
+ if last_turn[-1].endswith("\nUser"):
567
+ # Safeguard: sometimes (rarely), the model won't generate the token `<end_of_utterance>` and will go directly to generating `\nUser:`
568
+ # It will thus stop the generation on `\nUser:`. But when it exits, it will have already generated `\nUser`
569
+ # This post-processing ensures that we don't have an additional `\nUser` wandering around.
570
+ last_turn[-1] = last_turn[-1][:-5]
571
+ chat_history.append(last_turn)
572
+ yield "", None, chat_history
573
+ acc_text = ""
574
+
575
+ def process_example(message, image):
576
+ """
577
+ Same as `model_inference` but in greedy mode and with the 80b-instruct.
578
+ Specifically for pre-computing the default examples.
579
+ """
580
+ model_selector="HuggingFaceM4/idefics-80b-instruct"
581
+ user_prompt_str=message
582
+ chat_history=[]
583
+ max_new_tokens=512
584
+
585
+ formated_prompt_list, user_prompt_list = format_user_prompt_with_im_history_and_system_conditioning(
586
+ current_user_prompt_str=user_prompt_str.strip(),
587
+ current_image=image,
588
+ history=chat_history,
589
+ )
590
+
591
+ client_endpoint = API_PATHS[model_selector]
592
+ client = Client(
593
+ base_url=client_endpoint,
594
+ headers={"x-use-cache": "0", "Authorization": f"Bearer {API_TOKEN}"},
595
+ timeout=240, # Generous time out just in case because we are in greedy. All examples should be computed in less than 30secs with the 80b-instruct.
596
+ )
597
+
598
+ # Common parameters to all decoding strategies
599
+ # This documentation is useful to read: https://huggingface.co/docs/transformers/main/en/generation_strategies
600
+ generation_args = {
601
+ "max_new_tokens": max_new_tokens,
602
+ "repetition_penalty": None,
603
+ "stop_sequences": EOS_STRINGS,
604
+ "do_sample": False,
605
+ }
606
+
607
+ if image is None:
608
+ # Case where there is no image OR the image is passed as `<fake_token_around_image><image:IMAGE_URL><fake_token_around_image>`
609
+ chat_history.append([prompt_list_to_markdown(user_prompt_list), ''])
610
+ else:
611
+ # Case where the image is passed through the Image Box.
612
+ # Convert the image into base64 for both passing it through the chat history and
613
+ # displaying the image inside the same bubble as the text.
614
+ chat_history.append(
615
+ [
616
+ f"{prompt_list_to_markdown([image] + user_prompt_list)}",
617
+ '',
618
+ ]
619
+ )
620
+
621
+ # Hack - see explanation in `DEFAULT_IMAGES_TMP_PATH_TO_URL`
622
+ for idx, i in enumerate(formated_prompt_list):
623
+ if i.startswith(DEFAULT_TEMP_DIR):
624
+ for k, v in DEFAULT_IMAGES_TMP_PATH_TO_URL.items():
625
+ if k == i:
626
+ formated_prompt_list[idx] = v
627
+ break
628
+
629
+ query = prompt_list_to_tgi_input(formated_prompt_list)
630
+ generated_text = client.generate(prompt=query, **generation_args).generated_text
631
+ if generated_text.endswith("\nUser"):
632
+ generated_text = generated_text[:-5]
633
+
634
+ last_turn = chat_history.pop(-1)
635
+ last_turn[-1] += generated_text
636
+ chat_history.append(last_turn)
637
+ return "", None, chat_history
638
+
639
+ textbox.submit(
640
+ fn=model_inference,
641
+ inputs=[
642
+ model_selector,
643
+ textbox,
644
+ chatbot,
645
+ imagebox,
646
+ decoding_strategy,
647
+ temperature,
648
+ max_new_tokens,
649
+ repetition_penalty,
650
+ top_p,
651
+ ],
652
+ outputs=[textbox, imagebox, chatbot],
653
+ )
654
+ submit_btn.click(
655
+ fn=model_inference,
656
+ inputs=[
657
+ model_selector,
658
+ textbox,
659
+ chatbot,
660
+ imagebox,
661
+ decoding_strategy,
662
+ temperature,
663
+ max_new_tokens,
664
+ repetition_penalty,
665
+ top_p,
666
+ ],
667
+ outputs=[
668
+ textbox,
669
+ imagebox,
670
+ chatbot,
671
+ ],
672
+ )
673
+
674
+ def remove_last_turn(chat_history):
675
+ if len(chat_history) == 0:
676
+ return gr.Update(), gr.Update()
677
+ last_interaction = chat_history[-1]
678
+ chat_history = chat_history[:-1]
679
+ chat_update = gr.update(value=chat_history)
680
+ text_update = gr.update(value=last_interaction[0])
681
+ return chat_update, text_update
682
+
683
+ regenerate_btn.click(fn=remove_last_turn, inputs=chatbot, outputs=[chatbot, textbox]).then(
684
+ fn=model_inference,
685
+ inputs=[
686
+ model_selector,
687
+ textbox,
688
+ chatbot,
689
+ imagebox,
690
+ decoding_strategy,
691
+ temperature,
692
+ max_new_tokens,
693
+ repetition_penalty,
694
+ top_p,
695
+ ],
696
+ outputs=[
697
+ textbox,
698
+ imagebox,
699
+ chatbot,
700
+ ],
701
+ )
702
+
703
+ upload_btn.upload(add_file, [upload_btn], [imagebox, upload_btn], queue=False)
704
+ submit_btn.click(lambda : gr.update(label='πŸ“ Upload image', interactive=True), [], upload_btn)
705
+ textbox.submit(lambda : gr.update(label='πŸ“ Upload image', interactive=True), [], upload_btn)
706
+ clear_btn.click(lambda : gr.update(label='πŸ“ Upload image', interactive=True), [], upload_btn)
707
+
708
+ # Using Flagging for saving dope and problematic examples
709
+ # Dope examples flagging
710
+ # dope_callback.setup(
711
+ # [
712
+ # model_selector,
713
+ # textbox,
714
+ # chatbot,
715
+ # imagebox,
716
+ # decoding_strategy,
717
+ # temperature,
718
+ # max_new_tokens,
719
+ # repetition_penalty,
720
+ # top_p,
721
+ # ],
722
+ # "gradio_dope_data_points",
723
+ # )
724
+ # dope_bttn.click(
725
+ # lambda *args: dope_callback.flag(args),
726
+ # [
727
+ # model_selector,
728
+ # textbox,
729
+ # chatbot,
730
+ # imagebox,
731
+ # decoding_strategy,
732
+ # temperature,
733
+ # max_new_tokens,
734
+ # repetition_penalty,
735
+ # top_p,
736
+ # ],
737
+ # None,
738
+ # preprocess=False,
739
+ # )
740
+ # # Problematic examples flagging
741
+ # problematic_callback.setup(
742
+ # [
743
+ # model_selector,
744
+ # textbox,
745
+ # chatbot,
746
+ # imagebox,
747
+ # decoding_strategy,
748
+ # temperature,
749
+ # max_new_tokens,
750
+ # repetition_penalty,
751
+ # top_p,
752
+ # ],
753
+ # "gradio_problematic_data_points",
754
+ # )
755
+ # problematic_bttn.click(
756
+ # lambda *args: problematic_callback.flag(args),
757
+ # [
758
+ # model_selector,
759
+ # textbox,
760
+ # chatbot,
761
+ # imagebox,
762
+ # decoding_strategy,
763
+ # temperature,
764
+ # max_new_tokens,
765
+ # repetition_penalty,
766
+ # top_p,
767
+ # ],
768
+ # None,
769
+ # preprocess=False,
770
+ # )
771
+
772
+ # gr.Markdown("""## How to use?
773
+
774
+ # There are two ways to provide image inputs:
775
+ # - Using the image box on the left panel
776
+ # - Using the inline syntax: `text<fake_token_around_image><image:URL_IMAGE><fake_token_around_image>text`
777
+
778
+ # The second syntax allows inputting an arbitrary number of images.""")
779
+
780
+ examples_path = os.path.dirname(__file__)
781
+ gr.Examples(
782
+ examples=[
783
+ [
784
+ (
785
+ "Which famous person does the person in the image look like? Could you craft an engaging narrative"
786
+ " featuring this character from the image as the main protagonist?"
787
+ ),
788
+ f"{examples_path}/example_images/obama-harry-potter.jpg",
789
+ ],
790
+ [
791
+ "Can you describe the image? Do you think it's real?",
792
+ f"{examples_path}/example_images/rabbit_force.png",
793
+ ],
794
+ ["Explain this meme to me.", f"{examples_path}/example_images/meme_french.jpg"],
795
+ ["Give me a short and easy recipe for this dish.", f"{examples_path}/example_images/recipe_burger.webp"],
796
+ [
797
+ "I want to go somewhere similar to the one in the photo. Give me destinations and travel tips.",
798
+ f"{examples_path}/example_images/travel_tips.jpg",
799
+ ],
800
+ [
801
+ "Can you name the characters in the image and give their French names?",
802
+ f"{examples_path}/example_images/gaulois.png",
803
+ ],
804
+ # ["Describe this image in detail.", f"{examples_path}/example_images/plant_bulb.webp"],
805
+ ["Write a complete sales ad for this product.", f"{examples_path}/example_images/product_ad.jpg"],
806
+ [
807
+ (
808
+ "As an art critic AI assistant, could you describe this painting in details and make a thorough"
809
+ " critic?"
810
+ ),
811
+ f"{examples_path}/example_images/art_critic.png",
812
+ ],
813
+ [
814
+ "Can you tell me a very short story based on this image?",
815
+ f"{examples_path}/example_images/chicken_on_money.png",
816
+ ],
817
+ ["Write 3 funny meme texts about this image.", f"{examples_path}/example_images/elon_smoking.jpg"],
818
+ [
819
+ "Who is in this picture? Why do people find it surprising?",
820
+ f"{examples_path}/example_images/pope_doudoune.webp",
821
+ ],
822
+ # ["<fake_token_around_image><image:https://assets.stickpng.com/images/6308b83261b3e2a522f01467.png><fake_token_around_image>Make a poem about the company in the image<fake_token_around_image><image:https://miro.medium.com/v2/resize:fit:1400/0*jvDu2oQreHn63-fJ><fake_token_around_image>organizing the Woodstock of AI event,<fake_token_around_image><image:https://nationaltoday.com/wp-content/uploads/2019/12/national-llama-day-1200x834.jpg><fake_token_around_image>and the fact they brought those to the event.", None],
823
+ ["What are the armed baguettes guarding?", f"{examples_path}/example_images/baguettes_guarding_paris.png"],
824
+ # ["Can you describe the image?", f"{examples_path}/example_images/bear_costume.png"],
825
+ ["What is this animal and why is it unusual?", f"{examples_path}/example_images/blue_dog.png"],
826
+ [
827
+ "What is this object and do you think it is horrifying?",
828
+ f"{examples_path}/example_images/can_horror.png",
829
+ ],
830
+ [
831
+ (
832
+ "What is this sketch for? How would you make an argument to prove this sketch was made by Picasso"
833
+ " himself?"
834
+ ),
835
+ f"{examples_path}/example_images/cat_sketch.png",
836
+ ],
837
+ ["Which celebrity does this claymation figure look like?", f"{examples_path}/example_images/kanye.jpg"],
838
+ # [
839
+ # "Is there a celebrity look-alike in this image? What is happening to the person?",
840
+ # f"{examples_path}/example_images/ryan-reynolds-borg.jpg",
841
+ # ],
842
+ # ["Can you describe this image in details please?", f"{examples_path}/example_images/dragons_playing.png"],
843
+ ["What can you tell me about the cap in this image?", f"{examples_path}/example_images/ironman_cap.png"],
844
+ [
845
+ "Can you write an advertisement for Coca-Cola based on this image?",
846
+ f"{examples_path}/example_images/polar_bear_coke.png",
847
+ ],
848
+ # [
849
+ # "What is the rabbit doing in this image? Do you think this image is real?",
850
+ # f"{examples_path}/example_images/rabbit_force.png",
851
+ # ],
852
+ # ["What is happening in this image and why is it unusual?", f"{examples_path}/example_images/ramen.png"],
853
+ # [
854
+ # "What I should look most forward to when I visit this place?",
855
+ # f"{examples_path}/example_images/tree_fortress.jpg",
856
+ # ],
857
+ # ["Who is the person in the image and what is he doing?", f"{examples_path}/example_images/tom-cruise-astronaut-pegasus.jpg"],
858
+ [
859
+ "What is happening in this image? Which famous personality does this person in center looks like?",
860
+ f"{examples_path}/example_images/gandhi_selfie.jpg",
861
+ ],
862
+ [
863
+ "What do you think the dog is doing and is it unusual?",
864
+ f"{examples_path}/example_images/surfing_dog.jpg",
865
+ ],
866
+ ],
867
+ inputs=[textbox, imagebox],
868
+ outputs=[textbox, imagebox, chatbot],
869
+ fn=process_example,
870
+ cache_examples=True,
871
+ examples_per_page=6,
872
+ label=(
873
+ "Click on any example below to get started.\nFor convenience, the model generations have been"
874
+ " pre-computed with `idefics-80b-instruct`."
875
+ ),
876
+ )
877
+
878
+ demo.queue(concurrency_count=40, max_size=40)
879
+ demo.launch()