Spaces:
Runtime error
Runtime error
VictorSanh
commited on
Commit
•
ec50e73
1
Parent(s):
d295fd8
working but checkpoints are weird
Browse files- IDEFICS_logo.png +3 -0
- README.md +5 -6
- app_dialogue.py +737 -0
- example_images/art_critic.png +3 -0
- example_images/baguettes_guarding_paris.png +3 -0
- example_images/bear_costume.png +3 -0
- example_images/blue_dog.png +3 -0
- example_images/can_horror.png +3 -0
- example_images/cat_sketch.png +3 -0
- example_images/chicken_on_money.png +3 -0
- example_images/concrete-eating-willsmith.jpg +0 -0
- example_images/dragons_playing.png +3 -0
- example_images/elon_smoking.jpg +0 -0
- example_images/gandhi_selfie.jpg +0 -0
- example_images/gaulois.png +3 -0
- example_images/ironman_cap.png +3 -0
- example_images/kanye.jpg +0 -0
- example_images/meme_french.jpg +0 -0
- example_images/obama-harry-potter.jpg +0 -0
- example_images/plant_bulb.webp +0 -0
- example_images/polar_bear_coke.png +3 -0
- example_images/pope_doudoune.webp +0 -0
- example_images/product_ad.jpg +0 -0
- example_images/rabbit_force.png +3 -0
- example_images/ramen.png +3 -0
- example_images/recipe_burger.webp +0 -0
- example_images/ryan-reynolds-borg.jpg +0 -0
- example_images/surfing_dog.jpg +0 -0
- example_images/tom-cruise-astronaut-pegasus.jpg +0 -0
- example_images/travel_tips.jpg +0 -0
- example_images/tree_fortress.jpg +0 -0
- requirements.txt +4 -0
- utils.py +93 -0
IDEFICS_logo.png
ADDED
Git LFS Details
|
README.md
CHANGED
@@ -1,12 +1,11 @@
|
|
1 |
---
|
2 |
-
title:
|
3 |
-
emoji:
|
4 |
-
colorFrom:
|
5 |
-
colorTo:
|
6 |
sdk: gradio
|
7 |
sdk_version: 4.21.0
|
8 |
-
app_file:
|
9 |
pinned: false
|
10 |
---
|
11 |
|
12 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
1 |
---
|
2 |
+
title: IDEFICS2 Playground
|
3 |
+
emoji: 🐨
|
4 |
+
colorFrom: green
|
5 |
+
colorTo: yellow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
+
import copy
|
2 |
+
import hashlib
|
3 |
+
import logging
|
4 |
+
import os
|
5 |
+
import re
|
6 |
+
import torch
|
7 |
+
import PIL
|
8 |
+
|
9 |
+
from pathlib import Path
|
10 |
+
from threading import Thread
|
11 |
+
from typing import List, Optional, Tuple
|
12 |
+
from urllib.parse import urlparse
|
13 |
+
from PIL import Image
|
14 |
+
|
15 |
+
import gradio as gr
|
16 |
+
from gradio import processing_utils
|
17 |
+
from gradio_client.client import DEFAULT_TEMP_DIR
|
18 |
+
from transformers import AutoProcessor, AutoModelForCausalLM, TextIteratorStreamer
|
19 |
+
|
20 |
+
from utils import create_model_inputs
|
21 |
+
|
22 |
+
|
23 |
+
DEVICE = torch.device("cuda")
|
24 |
+
MODELS = {
|
25 |
+
"HuggingFaceM4/idefics2-neftune": AutoModelForCausalLM.from_pretrained(
|
26 |
+
"HuggingFaceM4/idefics2",
|
27 |
+
trust_remote_code=True,
|
28 |
+
torch_dtype=torch.bfloat16,
|
29 |
+
token=os.environ["HF_AUTH_TOKEN"],
|
30 |
+
# revision="365283baaef60c2b1131fffdee13a0da909728c8",
|
31 |
+
).to(DEVICE),
|
32 |
+
"HuggingFaceM4/idefics2": AutoModelForCausalLM.from_pretrained(
|
33 |
+
"HuggingFaceM4/idefics2",
|
34 |
+
trust_remote_code=True,
|
35 |
+
torch_dtype=torch.bfloat16,
|
36 |
+
token=os.environ["HF_AUTH_TOKEN"],
|
37 |
+
# revision="365283baaef60c2b1131fffdee13a0da909728c8",
|
38 |
+
).to(DEVICE),
|
39 |
+
}
|
40 |
+
|
41 |
+
|
42 |
+
PROCESSOR = AutoProcessor.from_pretrained(
|
43 |
+
"HuggingFaceM4/idefics2",
|
44 |
+
token=os.environ["HF_AUTH_TOKEN"],
|
45 |
+
)
|
46 |
+
FAKE_TOK_AROUND_IMAGE = "<fake_token_around_image>"
|
47 |
+
BOS_TOKEN = PROCESSOR.tokenizer.bos_token
|
48 |
+
BAD_WORDS_IDS = PROCESSOR.tokenizer(["<image>", "<fake_token_around_image>"], add_special_tokens=False).input_ids
|
49 |
+
EOS_WORDS_IDS = PROCESSOR.tokenizer(["<end_of_utterance>", "\nUser:"], add_special_tokens=False).input_ids
|
50 |
+
IMAGE_SEQ_LEN = list(MODELS.values())[0].config.perceiver_config.resampler_n_latents
|
51 |
+
|
52 |
+
SYSTEM_PROMPT = [
|
53 |
+
# """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.
|
54 |
+
|
55 |
+
# The conversation begins:""",
|
56 |
+
# """\nUser:""",
|
57 |
+
# "https://i1.pickpik.com/photos/515/906/355/kittens-cats-pet-cute-preview.jpg",
|
58 |
+
# "Describe this image.<end_of_utterance>",
|
59 |
+
# """\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>""",
|
60 |
+
# "\nUser:How about this image?",
|
61 |
+
# "https://cdn.pixabay.com/photo/2017/09/25/13/12/puppy-2785074_1280.jpg",
|
62 |
+
# "Can you describe it too?<end_of_utterance>",
|
63 |
+
# """\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>""",
|
64 |
+
# "\nUser: What kind of breed is it?<end_of_utterance>",
|
65 |
+
# """\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>""",
|
66 |
+
# "\nUser: What can you tell me about this breed of dogs?<end_of_utterance>",
|
67 |
+
# """\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>""",
|
68 |
+
# "\nUser: ghjkhjabnufs<end_of_utterance>",
|
69 |
+
# """\nAssistant: That doesn’t seem to be a word. Could you ask me another way?<end_of_utterance>""",
|
70 |
+
# "\nUser: Do you like Cavalier King Charles Spaniel?<end_of_utterance>",
|
71 |
+
# """\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>""",
|
72 |
+
# "\nUser: How many dogs do you see in this image?",
|
73 |
+
# "https://i.dailymail.co.uk/i/pix/2011/07/01/article-2010308-0CD22A8300000578-496_634x414.jpg",
|
74 |
+
# "<end_of_utterance>",
|
75 |
+
# """\nAssistant: There is no dogs in this image. The picture shows a tennis player jumping to volley the ball.<end_of_utterance>""",
|
76 |
+
]
|
77 |
+
|
78 |
+
BAN_TOKENS = ( # For documentation puporse. We are not using this list, it is hardcoded inside `idefics_causal_lm.py` inside TGI.
|
79 |
+
"<image>;<fake_token_around_image>"
|
80 |
+
)
|
81 |
+
STOP_SUSPECT_LIST = []
|
82 |
+
|
83 |
+
API_TOKEN = os.getenv("HF_AUTH_TOKEN")
|
84 |
+
# IDEFICS_LOGO = "https://huggingface.co/spaces/HuggingFaceM4/idefics_playground/resolve/main/IDEFICS_logo.png"
|
85 |
+
|
86 |
+
PROCESSOR = AutoProcessor.from_pretrained(
|
87 |
+
"HuggingFaceM4/idefics-9b-instruct",
|
88 |
+
token=API_TOKEN,
|
89 |
+
)
|
90 |
+
|
91 |
+
BOT_AVATAR = "IDEFICS_logo.png"
|
92 |
+
|
93 |
+
logging.basicConfig(level=logging.INFO)
|
94 |
+
logger = logging.getLogger()
|
95 |
+
|
96 |
+
|
97 |
+
# Monkey patch adapted from gradio.components.image.Image - mostly to make the `save` step optional in `pil_to_temp_file`
|
98 |
+
def hash_bytes(bytes: bytes):
|
99 |
+
sha1 = hashlib.sha1()
|
100 |
+
sha1.update(bytes)
|
101 |
+
return sha1.hexdigest()
|
102 |
+
|
103 |
+
|
104 |
+
def pil_to_temp_file(img: PIL.Image.Image, dir: str = DEFAULT_TEMP_DIR, format: str = "png") -> str:
|
105 |
+
"""Save a PIL image into a temp file"""
|
106 |
+
bytes_data = processing_utils.encode_pil_to_bytes(img, format)
|
107 |
+
temp_dir = Path(dir) / hash_bytes(bytes_data)
|
108 |
+
temp_dir.mkdir(exist_ok=True, parents=True)
|
109 |
+
filename = str(temp_dir / f"image.{format}")
|
110 |
+
if not os.path.exists(filename):
|
111 |
+
img.save(filename, pnginfo=processing_utils.get_pil_metadata(img))
|
112 |
+
return filename
|
113 |
+
|
114 |
+
|
115 |
+
def add_file(file):
|
116 |
+
return file.name, gr.update(label='🖼️ Uploaded!')
|
117 |
+
|
118 |
+
|
119 |
+
# Utils to handle the image markdown display logic
|
120 |
+
def split_str_on_im_markdown(string: str) -> List[str]:
|
121 |
+
"""
|
122 |
+
Extract from a string (typically the user prompt string) the potential images from markdown
|
123 |
+
Examples:
|
124 |
+
- `User:![](/file=/my_temp/chicken_on_money.png)Describe this image.` would become `["User:", "/my_temp/chicken_on_money.png", "Describe this image."]`
|
125 |
+
"""
|
126 |
+
IMAGES_PATTERN = re.compile(r"!\[[^\]]*\]\((.*?)\s*(\"(?:.*[^\"])\")?\s*\)")
|
127 |
+
parts = []
|
128 |
+
cursor = 0
|
129 |
+
for pattern in IMAGES_PATTERN.finditer(string):
|
130 |
+
start = pattern.start()
|
131 |
+
if start != cursor:
|
132 |
+
parts.append(string[cursor:start])
|
133 |
+
image_url = pattern.group(1)
|
134 |
+
if image_url.startswith("/file="):
|
135 |
+
image_url = image_url[6:] # Remove the 'file=' prefix
|
136 |
+
parts.append(image_url)
|
137 |
+
cursor = pattern.end()
|
138 |
+
if cursor != len(string):
|
139 |
+
parts.append(string[cursor:])
|
140 |
+
return parts
|
141 |
+
|
142 |
+
|
143 |
+
def is_image(string: str) -> bool:
|
144 |
+
"""
|
145 |
+
There are two ways for images: local image path or url.
|
146 |
+
"""
|
147 |
+
return is_url(string) or string.startswith(DEFAULT_TEMP_DIR)
|
148 |
+
|
149 |
+
|
150 |
+
def is_url(string: str) -> bool:
|
151 |
+
"""
|
152 |
+
Checks if the passed string contains a valid url and nothing else. e.g. if space is included it's immediately
|
153 |
+
invalidated the url
|
154 |
+
"""
|
155 |
+
if " " in string:
|
156 |
+
return False
|
157 |
+
result = urlparse(string)
|
158 |
+
return all([result.scheme, result.netloc])
|
159 |
+
|
160 |
+
|
161 |
+
def isolate_images_urls(prompt_list: List) -> List:
|
162 |
+
"""
|
163 |
+
Convert a full string prompt to the list format expected by the processor.
|
164 |
+
In particular, image urls (as delimited by <fake_token_around_image>) should be their own elements.
|
165 |
+
From:
|
166 |
+
```
|
167 |
+
[
|
168 |
+
"bonjour<fake_token_around_image><image:IMG_URL><fake_token_around_image>hello",
|
169 |
+
PIL.Image.Image,
|
170 |
+
"Aurevoir",
|
171 |
+
]
|
172 |
+
```
|
173 |
+
to:
|
174 |
+
```
|
175 |
+
[
|
176 |
+
"bonjour",
|
177 |
+
IMG_URL,
|
178 |
+
"hello",
|
179 |
+
PIL.Image.Image,
|
180 |
+
"Aurevoir",
|
181 |
+
]
|
182 |
+
```
|
183 |
+
"""
|
184 |
+
linearized_list = []
|
185 |
+
for prompt in prompt_list:
|
186 |
+
# Prompt can be either a string, or a PIL image
|
187 |
+
if isinstance(prompt, PIL.Image.Image):
|
188 |
+
linearized_list.append(prompt)
|
189 |
+
elif isinstance(prompt, str):
|
190 |
+
if "<fake_token_around_image>" not in prompt:
|
191 |
+
linearized_list.append(prompt)
|
192 |
+
else:
|
193 |
+
prompt_splitted = prompt.split("<fake_token_around_image>")
|
194 |
+
for ps in prompt_splitted:
|
195 |
+
if ps == "":
|
196 |
+
continue
|
197 |
+
if ps.startswith("<image:"):
|
198 |
+
linearized_list.append(ps[7:-1])
|
199 |
+
else:
|
200 |
+
linearized_list.append(ps)
|
201 |
+
else:
|
202 |
+
raise TypeError(
|
203 |
+
f"Unrecognized type for `prompt`. Got {type(type(prompt))}. Was expecting something in [`str`,"
|
204 |
+
" `PIL.Image.Image`]"
|
205 |
+
)
|
206 |
+
return linearized_list
|
207 |
+
|
208 |
+
|
209 |
+
def fetch_images(url_list: str) -> PIL.Image.Image:
|
210 |
+
"""Fetching images"""
|
211 |
+
return PROCESSOR.image_processor.fetch_images(url_list)
|
212 |
+
|
213 |
+
|
214 |
+
def handle_manual_images_in_user_prompt(user_prompt: str) -> List[str]:
|
215 |
+
"""
|
216 |
+
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
|
217 |
+
by fetching them, saving them locally and replacing the whole sub-sequence the image local path.
|
218 |
+
"""
|
219 |
+
if "<fake_token_around_image>" in user_prompt:
|
220 |
+
splitted_user_prompt = isolate_images_urls([user_prompt])
|
221 |
+
resulting_user_prompt = []
|
222 |
+
for u_p in splitted_user_prompt:
|
223 |
+
if is_url(u_p):
|
224 |
+
img = fetch_images([u_p])[0]
|
225 |
+
tmp_file = pil_to_temp_file(img)
|
226 |
+
resulting_user_prompt.append(tmp_file)
|
227 |
+
else:
|
228 |
+
resulting_user_prompt.append(u_p)
|
229 |
+
return resulting_user_prompt
|
230 |
+
else:
|
231 |
+
return [user_prompt]
|
232 |
+
|
233 |
+
|
234 |
+
def prompt_list_to_markdown(prompt_list: List[str]) -> str:
|
235 |
+
"""
|
236 |
+
Convert a user prompt in the list format (i.e. elements are either a PIL image or a string) into
|
237 |
+
the markdown format that is used for the chatbot history and rendering.
|
238 |
+
"""
|
239 |
+
resulting_string = ""
|
240 |
+
for elem in prompt_list:
|
241 |
+
if is_image(elem):
|
242 |
+
if is_url(elem):
|
243 |
+
resulting_string += f"![]({elem})"
|
244 |
+
else:
|
245 |
+
resulting_string += f"![](/file={elem})"
|
246 |
+
else:
|
247 |
+
resulting_string += elem
|
248 |
+
return resulting_string
|
249 |
+
|
250 |
+
def remove_spaces_around_token(text: str) -> str:
|
251 |
+
pattern = r"\s*(<fake_token_around_image>)\s*"
|
252 |
+
replacement = r"\1"
|
253 |
+
result = re.sub(pattern, replacement, text)
|
254 |
+
return result
|
255 |
+
|
256 |
+
|
257 |
+
# Chatbot utils
|
258 |
+
def format_user_prompt_with_im_history_and_system_conditioning(
|
259 |
+
current_user_prompt_str: str, current_image: Optional[str], history: List[Tuple[str, str]]
|
260 |
+
) -> Tuple[List[str], List[str]]:
|
261 |
+
"""
|
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:
|
269 |
+
user_utterance, assistant_utterance = turn
|
270 |
+
splitted_user_utterance = split_str_on_im_markdown(user_utterance)
|
271 |
+
|
272 |
+
optional_space = ""
|
273 |
+
if not is_image(splitted_user_utterance[0]):
|
274 |
+
optional_space = " "
|
275 |
+
resulting_list.append(f"\nUser:{optional_space}")
|
276 |
+
resulting_list.extend(splitted_user_utterance)
|
277 |
+
resulting_list.append(f"<end_of_utterance>\nAssistant: {assistant_utterance}")
|
278 |
+
|
279 |
+
# Format current input
|
280 |
+
current_user_prompt_str = remove_spaces_around_token(current_user_prompt_str)
|
281 |
+
if current_image is None:
|
282 |
+
if "![](" in current_user_prompt_str:
|
283 |
+
current_user_prompt_list = split_str_on_im_markdown(current_user_prompt_str)
|
284 |
+
else:
|
285 |
+
current_user_prompt_list = handle_manual_images_in_user_prompt(current_user_prompt_str)
|
286 |
+
|
287 |
+
optional_space = ""
|
288 |
+
if not is_image(current_user_prompt_list[0]):
|
289 |
+
# Check if the first element is an image (and more precisely a path to an image)
|
290 |
+
optional_space = " "
|
291 |
+
resulting_list.append(f"\nUser:{optional_space}")
|
292 |
+
resulting_list.extend(current_user_prompt_list)
|
293 |
+
resulting_list.append("<end_of_utterance>\nAssistant:")
|
294 |
+
else:
|
295 |
+
# Choosing to put the image first when the image is inputted through the UI, but this is an arbiratrary choice.
|
296 |
+
resulting_list.extend(["\nUser:", current_image, f"{current_user_prompt_str}<end_of_utterance>\nAssistant:"])
|
297 |
+
current_user_prompt_list = [current_user_prompt_str]
|
298 |
+
|
299 |
+
return resulting_list, current_user_prompt_list
|
300 |
+
|
301 |
+
|
302 |
+
textbox = gr.Textbox(
|
303 |
+
placeholder="Upload an image and send a message",
|
304 |
+
show_label=False,
|
305 |
+
# value="Describe the battle against the fierce dragons.",
|
306 |
+
visible=True,
|
307 |
+
container=False,
|
308 |
+
label="Text input",
|
309 |
+
scale=6,
|
310 |
+
)
|
311 |
+
with gr.Blocks(title="IDEFICS Playground", theme=gr.themes.Base()) as demo:
|
312 |
+
gr.HTML("""<h1 align="center">🐶 IDEFICS Playground</h1>""")
|
313 |
+
# with gr.Row(variant="panel"):
|
314 |
+
# with gr.Column(scale=1):
|
315 |
+
# gr.Image(IDEFICS_LOGO, elem_id="banner-image", show_label=False, show_download_button=False)
|
316 |
+
# with gr.Column(scale=5):
|
317 |
+
# gr.HTML("""
|
318 |
+
# <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>
|
319 |
+
# <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>
|
320 |
+
# <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>
|
321 |
+
# <p>🅿️ <strong>Intended uses:</strong> This demo along with the <a href="https://huggingface.co/models?sort=trending&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>
|
322 |
+
# <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>
|
323 |
+
# """)
|
324 |
+
|
325 |
+
with gr.Row(elem_id="model_selector_row"):
|
326 |
+
model_selector = gr.Dropdown(
|
327 |
+
choices=MODELS.keys(),
|
328 |
+
value="HuggingFaceM4/idefics2",
|
329 |
+
interactive=True,
|
330 |
+
show_label=False,
|
331 |
+
container=False,
|
332 |
+
label="Model",
|
333 |
+
visible=True,
|
334 |
+
)
|
335 |
+
|
336 |
+
imagebox = gr.Image(type="filepath", label="Image input", visible=False)
|
337 |
+
|
338 |
+
with gr.Row():
|
339 |
+
# def prefetch_images_in_history(user_prompt_str):
|
340 |
+
# """
|
341 |
+
# Pre-fetch the images that are passed in the chatbot default history.
|
342 |
+
# """
|
343 |
+
# return prompt_list_to_markdown(handle_manual_images_in_user_prompt(user_prompt_str))
|
344 |
+
|
345 |
+
chatbot = gr.Chatbot(
|
346 |
+
elem_id="chatbot",
|
347 |
+
label="IDEFICS",
|
348 |
+
visible=True,
|
349 |
+
height=750,
|
350 |
+
avatar_images=[None, BOT_AVATAR]
|
351 |
+
)
|
352 |
+
|
353 |
+
with gr.Group():
|
354 |
+
with gr.Row():
|
355 |
+
textbox.render()
|
356 |
+
submit_btn = gr.Button(value="▶️ Submit", visible=True)
|
357 |
+
clear_btn = gr.ClearButton([textbox, imagebox, chatbot], value="🧹 Clear")
|
358 |
+
regenerate_btn = gr.Button(value="🔄 Regenerate", visible=True)
|
359 |
+
upload_btn = gr.UploadButton("📁 Upload image", file_types=["image"])
|
360 |
+
|
361 |
+
with gr.Row():
|
362 |
+
with gr.Accordion("Advanced settings", open=False, visible=True) as parameter_row:
|
363 |
+
max_new_tokens = gr.Slider(
|
364 |
+
minimum=8,
|
365 |
+
maximum=1024,
|
366 |
+
value=512,
|
367 |
+
step=1,
|
368 |
+
interactive=True,
|
369 |
+
label="Maximum number of new tokens to generate",
|
370 |
+
)
|
371 |
+
repetition_penalty = gr.Slider(
|
372 |
+
minimum=0.01,
|
373 |
+
maximum=5.0,
|
374 |
+
value=1.0,
|
375 |
+
step=0.01,
|
376 |
+
interactive=True,
|
377 |
+
label="Repetition penalty",
|
378 |
+
info="1.0 is equivalent to no penalty",
|
379 |
+
)
|
380 |
+
decoding_strategy = gr.Radio(
|
381 |
+
[
|
382 |
+
"Greedy",
|
383 |
+
"Top P Sampling",
|
384 |
+
],
|
385 |
+
value="Greedy",
|
386 |
+
label="Decoding strategy",
|
387 |
+
interactive=True,
|
388 |
+
info="Higher values is equivalent to sampling more low-probability tokens.",
|
389 |
+
)
|
390 |
+
temperature = gr.Slider(
|
391 |
+
minimum=0.0,
|
392 |
+
maximum=5.0,
|
393 |
+
value=0.4,
|
394 |
+
step=0.1,
|
395 |
+
interactive=True,
|
396 |
+
visible=False,
|
397 |
+
label="Sampling temperature",
|
398 |
+
info="Higher values will produce more diverse outputs.",
|
399 |
+
)
|
400 |
+
decoding_strategy.change(
|
401 |
+
fn=lambda selection: gr.Slider(
|
402 |
+
visible=(
|
403 |
+
selection in ["contrastive_sampling", "beam_sampling", "Top P Sampling", "sampling_top_k"]
|
404 |
+
)
|
405 |
+
),
|
406 |
+
inputs=decoding_strategy,
|
407 |
+
outputs=temperature,
|
408 |
+
)
|
409 |
+
top_p = gr.Slider(
|
410 |
+
minimum=0.01,
|
411 |
+
maximum=0.99,
|
412 |
+
value=0.8,
|
413 |
+
step=0.01,
|
414 |
+
interactive=True,
|
415 |
+
visible=False,
|
416 |
+
label="Top P",
|
417 |
+
info="Higher values is equivalent to sampling more low-probability tokens.",
|
418 |
+
)
|
419 |
+
decoding_strategy.change(
|
420 |
+
fn=lambda selection: gr.Slider(visible=(selection in ["Top P Sampling"])),
|
421 |
+
inputs=decoding_strategy,
|
422 |
+
outputs=top_p,
|
423 |
+
)
|
424 |
+
|
425 |
+
def model_inference(
|
426 |
+
model_selector,
|
427 |
+
user_prompt_str,
|
428 |
+
chat_history,
|
429 |
+
image,
|
430 |
+
decoding_strategy,
|
431 |
+
temperature,
|
432 |
+
max_new_tokens,
|
433 |
+
repetition_penalty,
|
434 |
+
top_p,
|
435 |
+
):
|
436 |
+
if user_prompt_str.strip() == "" and image is None:
|
437 |
+
return "", None, chat_history
|
438 |
+
|
439 |
+
formated_prompt_list, user_prompt_list = format_user_prompt_with_im_history_and_system_conditioning(
|
440 |
+
current_user_prompt_str=user_prompt_str.strip(),
|
441 |
+
current_image=image,
|
442 |
+
history=chat_history,
|
443 |
+
)
|
444 |
+
|
445 |
+
streamer = TextIteratorStreamer(
|
446 |
+
PROCESSOR.tokenizer,
|
447 |
+
skip_prompt=True,
|
448 |
+
)
|
449 |
+
|
450 |
+
# Common parameters to all decoding strategies
|
451 |
+
# This documentation is useful to read: https://huggingface.co/docs/transformers/main/en/generation_strategies
|
452 |
+
generation_args = {
|
453 |
+
"max_new_tokens": max_new_tokens,
|
454 |
+
"repetition_penalty": repetition_penalty,
|
455 |
+
"bad_words_ids": BAD_WORDS_IDS,
|
456 |
+
"streamer": streamer,
|
457 |
+
}
|
458 |
+
|
459 |
+
assert decoding_strategy in [
|
460 |
+
"Greedy",
|
461 |
+
"Top P Sampling",
|
462 |
+
]
|
463 |
+
if decoding_strategy == "Greedy":
|
464 |
+
generation_args["do_sample"] = False
|
465 |
+
elif decoding_strategy == "Top P Sampling":
|
466 |
+
generation_args["temperature"] = temperature
|
467 |
+
generation_args["do_sample"] = True
|
468 |
+
generation_args["top_p"] = top_p
|
469 |
+
|
470 |
+
if image is None:
|
471 |
+
# Case where there is no image OR the image is passed as `<fake_token_around_image><image:IMAGE_URL><fake_token_around_image>`
|
472 |
+
chat_history.append([prompt_list_to_markdown(user_prompt_list), ''])
|
473 |
+
else:
|
474 |
+
# Case where the image is passed through the Image Box.
|
475 |
+
# Convert the image into base64 for both passing it through the chat history and
|
476 |
+
# displaying the image inside the same bubble as the text.
|
477 |
+
chat_history.append(
|
478 |
+
[
|
479 |
+
f"{prompt_list_to_markdown([image] + user_prompt_list)}",
|
480 |
+
'',
|
481 |
+
]
|
482 |
+
)
|
483 |
+
|
484 |
+
# Creating model inputs
|
485 |
+
images = []
|
486 |
+
for idx, part in enumerate(formated_prompt_list):
|
487 |
+
if is_image(part):
|
488 |
+
if is_url(part):
|
489 |
+
images.append(fetch_images([part])[0])
|
490 |
+
else:
|
491 |
+
images.append(Image.open(part))
|
492 |
+
formated_prompt_list[idx] = f"{FAKE_TOK_AROUND_IMAGE}{'<image>' * IMAGE_SEQ_LEN}{FAKE_TOK_AROUND_IMAGE}"
|
493 |
+
input_text = "".join(formated_prompt_list)
|
494 |
+
input_text = input_text.replace(FAKE_TOK_AROUND_IMAGE * 2, FAKE_TOK_AROUND_IMAGE)
|
495 |
+
input_text = BOS_TOKEN + input_text
|
496 |
+
inputs = create_model_inputs([input_text], [images])
|
497 |
+
inputs = {k: v.to(DEVICE) for k, v in inputs.items()}
|
498 |
+
generation_args.update(inputs)
|
499 |
+
|
500 |
+
thread = Thread(
|
501 |
+
target=MODELS[model_selector].generate,
|
502 |
+
kwargs=generation_args,
|
503 |
+
)
|
504 |
+
|
505 |
+
thread.start()
|
506 |
+
acc_text = ""
|
507 |
+
for idx, text_token in enumerate(streamer):
|
508 |
+
|
509 |
+
acc_text += text_token
|
510 |
+
last_turn = chat_history.pop(-1)
|
511 |
+
last_turn[-1] += acc_text
|
512 |
+
if last_turn[-1].endswith("\nUser"):
|
513 |
+
# Safeguard: sometimes (rarely), the model won't generate the token `<end_of_utterance>` and will go directly to generating `\nUser:`
|
514 |
+
# It will thus stop the generation on `\nUser:`. But when it exits, it will have already generated `\nUser`
|
515 |
+
# This post-processing ensures that we don't have an additional `\nUser` wandering around.
|
516 |
+
last_turn[-1] = last_turn[-1][:-5]
|
517 |
+
chat_history.append(last_turn)
|
518 |
+
yield "", None, chat_history
|
519 |
+
acc_text = ""
|
520 |
+
|
521 |
+
def process_example(message, image):
|
522 |
+
"""
|
523 |
+
Same as `model_inference` but in greedy mode and with the 80b-instruct.
|
524 |
+
Specifically for pre-computing the default examples.
|
525 |
+
"""
|
526 |
+
model_selector = "HuggingFaceM4/idefics2"
|
527 |
+
user_prompt_str = message
|
528 |
+
chat_history = []
|
529 |
+
max_new_tokens = 512
|
530 |
+
|
531 |
+
formated_prompt_list, user_prompt_list = format_user_prompt_with_im_history_and_system_conditioning(
|
532 |
+
current_user_prompt_str=user_prompt_str.strip(),
|
533 |
+
current_image=image,
|
534 |
+
history=chat_history,
|
535 |
+
)
|
536 |
+
|
537 |
+
# Common parameters to all decoding strategies
|
538 |
+
# This documentation is useful to read: https://huggingface.co/docs/transformers/main/en/generation_strategies
|
539 |
+
generation_args = {
|
540 |
+
"max_new_tokens": max_new_tokens,
|
541 |
+
"repetition_penalty": None,
|
542 |
+
"bad_words_ids": BAD_WORDS_IDS,
|
543 |
+
"do_sample": False,
|
544 |
+
}
|
545 |
+
|
546 |
+
if image is None:
|
547 |
+
# Case where there is no image OR the image is passed as `<fake_token_around_image><image:IMAGE_URL><fake_token_around_image>`
|
548 |
+
chat_history.append([prompt_list_to_markdown(user_prompt_list), ''])
|
549 |
+
else:
|
550 |
+
# Case where the image is passed through the Image Box.
|
551 |
+
# Convert the image into base64 for both passing it through the chat history and
|
552 |
+
# displaying the image inside the same bubble as the text.
|
553 |
+
chat_history.append(
|
554 |
+
[
|
555 |
+
f"{prompt_list_to_markdown([image] + user_prompt_list)}",
|
556 |
+
'',
|
557 |
+
]
|
558 |
+
)
|
559 |
+
|
560 |
+
# Creating model inputs
|
561 |
+
images = []
|
562 |
+
for idx, part in enumerate(formated_prompt_list):
|
563 |
+
if is_image(part):
|
564 |
+
if is_url(part):
|
565 |
+
images.append(fetch_images([part])[0])
|
566 |
+
else:
|
567 |
+
images.append(Image.open(part))
|
568 |
+
formated_prompt_list[idx] = f"{FAKE_TOK_AROUND_IMAGE}{'<image>' * IMAGE_SEQ_LEN}{FAKE_TOK_AROUND_IMAGE}"
|
569 |
+
input_text = "".join(formated_prompt_list)
|
570 |
+
input_text = input_text.replace(FAKE_TOK_AROUND_IMAGE * 2, FAKE_TOK_AROUND_IMAGE)
|
571 |
+
input_text = BOS_TOKEN + input_text
|
572 |
+
inputs = create_model_inputs([input_text], [images])
|
573 |
+
inputs = {k: v.to(DEVICE) for k, v in inputs.items()}
|
574 |
+
generation_args.update(inputs)
|
575 |
+
|
576 |
+
generated_ids = MODELS[model_selector].generate(**generation_args)
|
577 |
+
generated_text = PROCESSOR.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
578 |
+
|
579 |
+
if generated_text.endswith("\nUser"):
|
580 |
+
generated_text = generated_text[:-5]
|
581 |
+
|
582 |
+
last_turn = chat_history.pop(-1)
|
583 |
+
last_turn[-1] += generated_text
|
584 |
+
chat_history.append(last_turn)
|
585 |
+
return "", None, chat_history
|
586 |
+
|
587 |
+
textbox.submit(
|
588 |
+
fn=model_inference,
|
589 |
+
inputs=[
|
590 |
+
model_selector,
|
591 |
+
textbox,
|
592 |
+
chatbot,
|
593 |
+
imagebox,
|
594 |
+
decoding_strategy,
|
595 |
+
temperature,
|
596 |
+
max_new_tokens,
|
597 |
+
repetition_penalty,
|
598 |
+
top_p,
|
599 |
+
],
|
600 |
+
outputs=[textbox, imagebox, chatbot],
|
601 |
+
)
|
602 |
+
submit_btn.click(
|
603 |
+
fn=model_inference,
|
604 |
+
inputs=[
|
605 |
+
model_selector,
|
606 |
+
textbox,
|
607 |
+
chatbot,
|
608 |
+
imagebox,
|
609 |
+
decoding_strategy,
|
610 |
+
temperature,
|
611 |
+
max_new_tokens,
|
612 |
+
repetition_penalty,
|
613 |
+
top_p,
|
614 |
+
],
|
615 |
+
outputs=[
|
616 |
+
textbox,
|
617 |
+
imagebox,
|
618 |
+
chatbot,
|
619 |
+
],
|
620 |
+
)
|
621 |
+
|
622 |
+
def remove_last_turn(chat_history):
|
623 |
+
if len(chat_history) == 0:
|
624 |
+
return gr.Update(), gr.Update()
|
625 |
+
last_interaction = chat_history[-1]
|
626 |
+
chat_history = chat_history[:-1]
|
627 |
+
chat_update = gr.update(value=chat_history)
|
628 |
+
text_update = gr.update(value=last_interaction[0])
|
629 |
+
return chat_update, text_update
|
630 |
+
|
631 |
+
regenerate_btn.click(fn=remove_last_turn, inputs=chatbot, outputs=[chatbot, textbox]).then(
|
632 |
+
fn=model_inference,
|
633 |
+
inputs=[
|
634 |
+
model_selector,
|
635 |
+
textbox,
|
636 |
+
chatbot,
|
637 |
+
imagebox,
|
638 |
+
decoding_strategy,
|
639 |
+
temperature,
|
640 |
+
max_new_tokens,
|
641 |
+
repetition_penalty,
|
642 |
+
top_p,
|
643 |
+
],
|
644 |
+
outputs=[
|
645 |
+
textbox,
|
646 |
+
imagebox,
|
647 |
+
chatbot,
|
648 |
+
],
|
649 |
+
)
|
650 |
+
|
651 |
+
upload_btn.upload(add_file, [upload_btn], [imagebox, upload_btn], queue=False)
|
652 |
+
submit_btn.click(lambda : gr.update(label='📁 Upload image', interactive=True), [], upload_btn)
|
653 |
+
textbox.submit(lambda : gr.update(label='📁 Upload image', interactive=True), [], upload_btn)
|
654 |
+
clear_btn.click(lambda : gr.update(label='📁 Upload image', interactive=True), [], upload_btn)
|
655 |
+
|
656 |
+
examples_path = os.path.dirname(__file__)
|
657 |
+
gr.Examples(
|
658 |
+
examples=[
|
659 |
+
[
|
660 |
+
(
|
661 |
+
"Which famous person does the person in the image look like? Could you craft an engaging narrative"
|
662 |
+
" featuring this character from the image as the main protagonist?"
|
663 |
+
),
|
664 |
+
f"{examples_path}/example_images/obama-harry-potter.jpg",
|
665 |
+
],
|
666 |
+
[
|
667 |
+
"Can you describe the image? Do you think it's real?",
|
668 |
+
f"{examples_path}/example_images/rabbit_force.png",
|
669 |
+
],
|
670 |
+
["Explain this meme to me.", f"{examples_path}/example_images/meme_french.jpg"],
|
671 |
+
["Give me a short and easy recipe for this dish.", f"{examples_path}/example_images/recipe_burger.webp"],
|
672 |
+
[
|
673 |
+
"I want to go somewhere similar to the one in the photo. Give me destinations and travel tips.",
|
674 |
+
f"{examples_path}/example_images/travel_tips.jpg",
|
675 |
+
],
|
676 |
+
[
|
677 |
+
"Can you name the characters in the image and give their French names?",
|
678 |
+
f"{examples_path}/example_images/gaulois.png",
|
679 |
+
],
|
680 |
+
["Write a complete sales ad for this product.", f"{examples_path}/example_images/product_ad.jpg"],
|
681 |
+
# [
|
682 |
+
# (
|
683 |
+
# "As an art critic AI assistant, could you describe this painting in details and make a thorough"
|
684 |
+
# " critic?"
|
685 |
+
# ),
|
686 |
+
# f"{examples_path}/example_images/art_critic.png",
|
687 |
+
# ],
|
688 |
+
# [
|
689 |
+
# "Can you tell me a very short story based on this image?",
|
690 |
+
# f"{examples_path}/example_images/chicken_on_money.png",
|
691 |
+
# ],
|
692 |
+
# ["Write 3 funny meme texts about this image.", f"{examples_path}/example_images/elon_smoking.jpg"],
|
693 |
+
# [
|
694 |
+
# "Who is in this picture? Why do people find it surprising?",
|
695 |
+
# f"{examples_path}/example_images/pope_doudoune.webp",
|
696 |
+
# ],
|
697 |
+
# ["What are the armed baguettes guarding?", f"{examples_path}/example_images/baguettes_guarding_paris.png"],
|
698 |
+
# ["What is this animal and why is it unusual?", f"{examples_path}/example_images/blue_dog.png"],
|
699 |
+
# [
|
700 |
+
# "What is this object and do you think it is horrifying?",
|
701 |
+
# f"{examples_path}/example_images/can_horror.png",
|
702 |
+
# ],
|
703 |
+
# [
|
704 |
+
# (
|
705 |
+
# "What is this sketch for? How would you make an argument to prove this sketch was made by Picasso"
|
706 |
+
# " himself?"
|
707 |
+
# ),
|
708 |
+
# f"{examples_path}/example_images/cat_sketch.png",
|
709 |
+
# ],
|
710 |
+
# ["Which celebrity does this claymation figure look like?", f"{examples_path}/example_images/kanye.jpg"],
|
711 |
+
# ["What can you tell me about the cap in this image?", f"{examples_path}/example_images/ironman_cap.png"],
|
712 |
+
# [
|
713 |
+
# "Can you write an advertisement for Coca-Cola based on this image?",
|
714 |
+
# f"{examples_path}/example_images/polar_bear_coke.png",
|
715 |
+
# ],
|
716 |
+
# [
|
717 |
+
# "What is happening in this image? Which famous personality does this person in center looks like?",
|
718 |
+
# f"{examples_path}/example_images/gandhi_selfie.jpg",
|
719 |
+
# ],
|
720 |
+
# [
|
721 |
+
# "What do you think the dog is doing and is it unusual?",
|
722 |
+
# f"{examples_path}/example_images/surfing_dog.jpg",
|
723 |
+
# ],
|
724 |
+
],
|
725 |
+
inputs=[textbox, imagebox],
|
726 |
+
outputs=[textbox, imagebox, chatbot],
|
727 |
+
fn=process_example,
|
728 |
+
cache_examples=True,
|
729 |
+
examples_per_page=6,
|
730 |
+
label=(
|
731 |
+
"Click on any example below to get started.\nFor convenience, the model generations have been"
|
732 |
+
" pre-computed with `idefics-80b-instruct`."
|
733 |
+
),
|
734 |
+
)
|
735 |
+
|
736 |
+
demo.queue(max_size=40)
|
737 |
+
demo.launch()
|
example_images/art_critic.png
ADDED
Git LFS Details
|
example_images/baguettes_guarding_paris.png
ADDED
Git LFS Details
|
example_images/bear_costume.png
ADDED
Git LFS Details
|
example_images/blue_dog.png
ADDED
Git LFS Details
|
example_images/can_horror.png
ADDED
Git LFS Details
|
example_images/cat_sketch.png
ADDED
Git LFS Details
|
example_images/chicken_on_money.png
ADDED
Git LFS Details
|
example_images/concrete-eating-willsmith.jpg
ADDED
example_images/dragons_playing.png
ADDED
Git LFS Details
|
example_images/elon_smoking.jpg
ADDED
example_images/gandhi_selfie.jpg
ADDED
example_images/gaulois.png
ADDED
Git LFS Details
|
example_images/ironman_cap.png
ADDED
Git LFS Details
|
example_images/kanye.jpg
ADDED
example_images/meme_french.jpg
ADDED
example_images/obama-harry-potter.jpg
ADDED
example_images/plant_bulb.webp
ADDED
example_images/polar_bear_coke.png
ADDED
Git LFS Details
|
example_images/pope_doudoune.webp
ADDED
example_images/product_ad.jpg
ADDED
example_images/rabbit_force.png
ADDED
Git LFS Details
|
example_images/ramen.png
ADDED
Git LFS Details
|
example_images/recipe_burger.webp
ADDED
example_images/ryan-reynolds-borg.jpg
ADDED
example_images/surfing_dog.jpg
ADDED
example_images/tom-cruise-astronaut-pegasus.jpg
ADDED
example_images/travel_tips.jpg
ADDED
example_images/tree_fortress.jpg
ADDED
requirements.txt
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
transformers
|
2 |
+
datasets
|
3 |
+
pillow
|
4 |
+
numpy
|
utils.py
ADDED
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import torch
|
3 |
+
|
4 |
+
from transformers import AutoProcessor
|
5 |
+
from transformers.image_utils import to_numpy_array, PILImageResampling, ChannelDimension
|
6 |
+
from transformers.image_transforms import resize, to_channel_dimension_format
|
7 |
+
from typing import List
|
8 |
+
from PIL import Image
|
9 |
+
|
10 |
+
|
11 |
+
PROCESSOR = AutoProcessor.from_pretrained(
|
12 |
+
"HuggingFaceM4/idefics2",
|
13 |
+
token=os.environ["HF_AUTH_TOKEN"],
|
14 |
+
)
|
15 |
+
|
16 |
+
|
17 |
+
def convert_to_rgb(image):
|
18 |
+
# `image.convert("RGB")` would only work for .jpg images, as it creates a wrong background
|
19 |
+
# for transparent images. The call to `alpha_composite` handles this case
|
20 |
+
if image.mode == "RGB":
|
21 |
+
return image
|
22 |
+
|
23 |
+
image_rgba = image.convert("RGBA")
|
24 |
+
background = Image.new("RGBA", image_rgba.size, (255, 255, 255))
|
25 |
+
alpha_composite = Image.alpha_composite(background, image_rgba)
|
26 |
+
alpha_composite = alpha_composite.convert("RGB")
|
27 |
+
return alpha_composite
|
28 |
+
|
29 |
+
|
30 |
+
def custom_transform(x):
|
31 |
+
x = convert_to_rgb(x)
|
32 |
+
x = to_numpy_array(x)
|
33 |
+
|
34 |
+
height, width = x.shape[:2]
|
35 |
+
aspect_ratio = width / height
|
36 |
+
if width >= height and width > 980:
|
37 |
+
width = 980
|
38 |
+
height = int(width / aspect_ratio)
|
39 |
+
elif height > width and height > 980:
|
40 |
+
height = 980
|
41 |
+
width = int(height * aspect_ratio)
|
42 |
+
width = max(width, 378)
|
43 |
+
height = max(height, 378)
|
44 |
+
|
45 |
+
x = resize(x, (height, width), resample=PILImageResampling.BILINEAR)
|
46 |
+
x = PROCESSOR.image_processor.rescale(x, scale=1 / 255)
|
47 |
+
x = PROCESSOR.image_processor.normalize(
|
48 |
+
x,
|
49 |
+
mean=PROCESSOR.image_processor.image_mean,
|
50 |
+
std=PROCESSOR.image_processor.image_std
|
51 |
+
)
|
52 |
+
x = to_channel_dimension_format(x, ChannelDimension.FIRST)
|
53 |
+
x = torch.tensor(x)
|
54 |
+
return x
|
55 |
+
|
56 |
+
|
57 |
+
def create_model_inputs(
|
58 |
+
input_texts: List[str],
|
59 |
+
image_lists: List[List[Image.Image]],
|
60 |
+
):
|
61 |
+
"""
|
62 |
+
All this logic will eventually be handled inside the model processor.
|
63 |
+
"""
|
64 |
+
inputs = PROCESSOR.tokenizer(
|
65 |
+
input_texts,
|
66 |
+
return_tensors="pt",
|
67 |
+
add_special_tokens=False,
|
68 |
+
padding=True,
|
69 |
+
)
|
70 |
+
|
71 |
+
output_images = [
|
72 |
+
[PROCESSOR.image_processor(img, transform=custom_transform) for img in im_list]
|
73 |
+
for im_list in image_lists
|
74 |
+
]
|
75 |
+
total_batch_size = len(output_images)
|
76 |
+
max_num_images = max([len(img_l) for img_l in output_images])
|
77 |
+
if max_num_images > 0:
|
78 |
+
max_height = max([i.size(2) for img_l in output_images for i in img_l])
|
79 |
+
max_width = max([i.size(3) for img_l in output_images for i in img_l])
|
80 |
+
padded_image_tensor = torch.zeros(total_batch_size, max_num_images, 3, max_height, max_width)
|
81 |
+
padded_pixel_attention_masks = torch.zeros(
|
82 |
+
total_batch_size, max_num_images, max_height, max_width, dtype=torch.bool
|
83 |
+
)
|
84 |
+
for batch_idx, img_l in enumerate(output_images):
|
85 |
+
for img_idx, img in enumerate(img_l):
|
86 |
+
im_height, im_width = img.size()[2:]
|
87 |
+
padded_image_tensor[batch_idx, img_idx, :, :im_height, :im_width] = img
|
88 |
+
padded_pixel_attention_masks[batch_idx, img_idx, :im_height, :im_width] = True
|
89 |
+
|
90 |
+
inputs["pixel_values"] = padded_image_tensor
|
91 |
+
inputs["pixel_attention_mask"] = padded_pixel_attention_masks
|
92 |
+
|
93 |
+
return inputs
|