johann22 commited on
Commit
9ee0176
1 Parent(s): 6bebd9e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -227
app.py CHANGED
@@ -1,236 +1,39 @@
1
- import copy
2
- import PIL
3
- import re
4
- import os
5
- import gradio as gr
6
- from gradio import processing_utils
7
- from gradio_client.client import DEFAULT_TEMP_DIR
8
 
9
- from typing import List, Optional, Tuple
10
 
11
- from huggingface_hub import InferenceClient
 
 
12
 
13
- GENERATE_PROMPT=""
 
 
 
 
 
14
 
15
- client = InferenceClient("HuggingFaceM4/idefics-9b-instruct")
16
 
17
- chat_models=[
18
- "HuggingFaceM4/idefics-9b-instruct",
19
- "HuggingFaceM4/idefics-80b-instruct",
20
- ]
21
- EOS_STRINGS = ["<end_of_utterance>", "\nUser:"]
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
- The conversation begins:""",
25
- """\nUser:""",
26
- "https://i1.pickpik.com/photos/515/906/355/kittens-cats-pet-cute-preview.jpg",
27
- "Describe this image.<end_of_utterance>",
28
- """\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>""",
29
- "\nUser:How about this image?",
30
- "https://cdn.pixabay.com/photo/2017/09/25/13/12/puppy-2785074_1280.jpg",
31
- "Can you describe it too?<end_of_utterance>",
32
- """\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>""",
33
- "\nUser: What kind of breed is it?<end_of_utterance>",
34
- """\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>""",
35
- "\nUser: What can you tell me about this breed of dogs?<end_of_utterance>",
36
- """\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>""",
37
- "\nUser: ghjkhjabnufs<end_of_utterance>",
38
- """\nAssistant: That doesn’t seem to be a word. Could you ask me another way?<end_of_utterance>""",
39
- "\nUser: Do you like Cavalier King Charles Spaniel?<end_of_utterance>",
40
- """\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>""",
41
- "\nUser: How many dogs do you see in this image?",
42
- "https://i.dailymail.co.uk/i/pix/2011/07/01/article-2010308-0CD22A8300000578-496_634x414.jpg",
43
- "<end_of_utterance>",
44
- """\nAssistant: There is no dogs in this image. The picture shows a tennis player jumping to volley the ball.<end_of_utterance>""",
45
- ]
46
- def run_gpt(in_prompt,history,model_drop=None):
47
- #client = InferenceClient(chat_models.models[int(model_drop)])
48
- print(f'history :: {history}')
49
- prompt=format_prompt(in_prompt,history)
50
- seed = random.randint(1,1111111111111111)
51
- print (seed)
52
- generate_kwargs = dict(
53
- temperature=1.0,
54
- max_new_tokens=1048,
55
- top_p=0.99,
56
- repetition_penalty=1.0,
57
- do_sample=True,
58
- seed=seed,
59
- )
60
- content = GENERATE_PROMPT + prompt
61
- print(content)
62
- stream = client.text_generation(content, **generate_kwargs, stream=True, details=True, return_full_text=False)
63
- resp = ""
64
- for response in stream:
65
- resp += response.token.text
66
- return resp
67
-
68
-
69
-
70
- def hash_bytes(bytes: bytes):
71
- sha1 = hashlib.sha1()
72
- sha1.update(bytes)
73
- return sha1.hexdigest()
74
- def pil_to_temp_file(img: PIL.Image.Image, dir: str = DEFAULT_TEMP_DIR, format: str = "png") -> str:
75
- """Save a PIL image into a temp file"""
76
- bytes_data = processing_utils.encode_pil_to_bytes(img, format)
77
- temp_dir = Path(dir) / hash_bytes(bytes_data)
78
- temp_dir.mkdir(exist_ok=True, parents=True)
79
- filename = str(temp_dir / f"image.{format}")
80
- if not os.path.exists(filename):
81
- img.save(filename, pnginfo=processing_utils.get_pil_metadata(img))
82
- return filename
83
- def add_file(file):
84
- return file.name, gr.update(label='🖼️ Uploaded!')
85
- def prompt_list_to_markdown(prompt_list: List[str]) -> str:
86
- """
87
- Convert a user prompt in the list format (i.e. elements are either a PIL image or a string) into
88
- the markdown format that is used for the chatbot history and rendering.
89
- """
90
- resulting_string = ""
91
- for elem in prompt_list:
92
- if is_image(elem):
93
- if is_url(elem):
94
- resulting_string += f"![]({elem})"
95
- else:
96
- resulting_string += f"![](/file={elem})"
97
- else:
98
- resulting_string += elem
99
- return resulting_string
100
- def prompt_list_to_tgi_input(prompt_list: List[str]) -> str:
101
- """
102
- TGI expects a string that contains both text and images in the image markdown format (i.e. the `![]()` ).
103
- The images links are parsed on TGI side
104
- """
105
- result_string_input = ""
106
- for elem in prompt_list:
107
- if is_image(elem):
108
- if is_url(elem):
109
- result_string_input += f"![]({elem})"
110
- else:
111
- result_string_input += f"![]({gradio_link(img_path=elem)})"
112
- else:
113
- result_string_input += elem
114
- return result_string_input
115
- def remove_spaces_around_token(text: str) -> str:
116
- pattern = r"\s*(<fake_token_around_image>)\s*"
117
- replacement = r"\1"
118
- result = re.sub(pattern, replacement, text)
119
- return result
120
- def format_user_prompt_with_im_history_and_system_conditioning(
121
- current_user_prompt_str: str, current_image: Optional[str], history: List[Tuple[str, str]]
122
- ) -> Tuple[List[str], List[str]]:
123
- """
124
- Produces the resulting list that needs to go inside the processor.
125
- It handles the potential image box input, the history and the system conditionning.
126
- """
127
- resulting_list = copy.deepcopy(SYSTEM_PROMPT)
128
-
129
- # Format history
130
- for turn in history:
131
- user_utterance, assistant_utterance = turn
132
- splitted_user_utterance = split_str_on_im_markdown(user_utterance)
133
-
134
- optional_space = ""
135
- if not is_image(splitted_user_utterance[0]):
136
- optional_space = " "
137
- resulting_list.append(f"\nUser:{optional_space}")
138
- resulting_list.extend(splitted_user_utterance)
139
- resulting_list.append(f"<end_of_utterance>\nAssistant: {assistant_utterance}")
140
-
141
- # Format current input
142
- current_user_prompt_str = remove_spaces_around_token(current_user_prompt_str)
143
- if current_image is None:
144
- if "![](" in current_user_prompt_str:
145
- current_user_prompt_list = split_str_on_im_markdown(current_user_prompt_str)
146
- else:
147
- current_user_prompt_list = handle_manual_images_in_user_prompt(current_user_prompt_str)
148
 
149
- optional_space = ""
150
- if not is_image(current_user_prompt_list[0]):
151
- # Check if the first element is an image (and more precisely a path to an image)
152
- optional_space = " "
153
- resulting_list.append(f"\nUser:{optional_space}")
154
- resulting_list.extend(current_user_prompt_list)
155
- resulting_list.append("<end_of_utterance>\nAssistant:")
156
- else:
157
- # Choosing to put the image first when the image is inputted through the UI, but this is an arbiratrary choice.
158
- resulting_list.extend(["\nUser:", current_image, f"{current_user_prompt_str}<end_of_utterance>\nAssistant:"])
159
- current_user_prompt_list = [current_user_prompt_str]
160
-
161
- return resulting_list, current_user_prompt_list
162
-
163
- def process_example(message, image):
164
- """
165
- Same as `model_inference` but in greedy mode and with the 80b-instruct.
166
- Specifically for pre-computing the default examples.
167
- """
168
- #model_selector="HuggingFaceM4/idefics-80b-instruct"
169
- user_prompt_str=message
170
- chat_history=[]
171
- max_new_tokens=512
172
-
173
- formated_prompt_list, user_prompt_list = format_user_prompt_with_im_history_and_system_conditioning(
174
- current_user_prompt_str=user_prompt_str.strip(),
175
- current_image=image,
176
- history=chat_history,
177
- )
178
- '''
179
- client_endpoint = API_PATHS[model_selector]
180
- client = Client(
181
- base_url=client_endpoint,
182
- headers={"x-use-cache": "0", "Authorization": f"Bearer {API_TOKEN}"},
183
- 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.
184
- )'''
185
-
186
- # Common parameters to all decoding strategies
187
- # This documentation is useful to read: https://huggingface.co/docs/transformers/main/en/generation_strategies
188
- generation_args = {
189
- "max_new_tokens": max_new_tokens,
190
- "repetition_penalty": None,
191
- "stop_sequences": EOS_STRINGS,
192
- "do_sample": False,
193
- }
194
-
195
- if image is None:
196
- # Case where there is no image OR the image is passed as `<fake_token_around_image><image:IMAGE_URL><fake_token_around_image>`
197
- chat_history.append([prompt_list_to_markdown(user_prompt_list), ''])
198
- else:
199
- # Case where the image is passed through the Image Box.
200
- # Convert the image into base64 for both passing it through the chat history and
201
- # displaying the image inside the same bubble as the text.
202
- chat_history.append(
203
- [
204
- f"{prompt_list_to_markdown([image] + user_prompt_list)}",
205
- '',
206
- ]
207
- )
208
-
209
- # Hack - see explanation in `DEFAULT_IMAGES_TMP_PATH_TO_URL`
210
- for idx, i in enumerate(formated_prompt_list):
211
- if i.startswith(DEFAULT_TEMP_DIR):
212
- for k, v in DEFAULT_IMAGES_TMP_PATH_TO_URL.items():
213
- if k == i:
214
- formated_prompt_list[idx] = v
215
- break
216
-
217
- query = prompt_list_to_tgi_input(formated_prompt_list)
218
- generated_text = client.generate(prompt=query, **generation_args).generated_text
219
- if generated_text.endswith("\nUser"):
220
- generated_text = generated_text[:-5]
221
 
222
- last_turn = chat_history.pop(-1)
223
- last_turn[-1] += generated_text
224
- chat_history.append(last_turn)
225
- return "", None, chat_history
226
 
227
- with gr.Blocks() as app:
228
- chatbot=gr.Chatbot()
229
- inp_im = gr.Image()
230
- inp_txt = gr.Textbox()
231
-
232
- sub_btn = gr.Button()
233
 
234
-
235
- sub_btn.click(process_example,[inp_txt,inp_im],[inp_txt,inp_im,chatbot])
236
- app.launch()
 
 
1
+ import torch
2
+ from transformers import IdeficsForVisionText2Text, AutoProcessor
 
 
 
 
 
3
 
4
+ device = "cuda" if torch.cuda.is_available() else "cpu"
5
 
6
+ checkpoint = "HuggingFaceM4/idefics-9b-instruct"
7
+ model = IdeficsForVisionText2Text.from_pretrained(checkpoint, torch_dtype=torch.bfloat16).to(device)
8
+ processor = AutoProcessor.from_pretrained(checkpoint)
9
 
10
+ # We feed to the model an arbitrary sequence of text strings and images. Images can be either URLs or PIL Images.
11
+ prompts = [
12
+ [
13
+ "User: What is in this image?",
14
+ "https://upload.wikimedia.org/wikipedia/commons/8/86/Id%C3%A9fix.JPG",
15
+ "<end_of_utterance>",
16
 
17
+ "\nAssistant: This picture depicts Idefix, the dog of Obelix in Asterix and Obelix. Idefix is running on the ground.<end_of_utterance>",
18
 
19
+ "\nUser:",
20
+ "https://static.wikia.nocookie.net/asterix/images/2/25/R22b.gif/revision/latest?cb=20110815073052",
21
+ "And who is that?<end_of_utterance>",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
+ "\nAssistant:",
24
+ ],
25
+ ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
+ # --batched mode
28
+ inputs = processor(prompts, add_end_of_utterance_token=False, return_tensors="pt").to(device)
29
+ # --single sample mode
30
+ # inputs = processor(prompts[0], return_tensors="pt").to(device)
31
 
32
+ # Generation args
33
+ exit_condition = processor.tokenizer("<end_of_utterance>", add_special_tokens=False).input_ids
34
+ bad_words_ids = processor.tokenizer(["<image>", "<fake_token_around_image>"], add_special_tokens=False).input_ids
 
 
 
35
 
36
+ generated_ids = model.generate(**inputs, eos_token_id=exit_condition, bad_words_ids=bad_words_ids, max_length=100)
37
+ generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)
38
+ for i, t in enumerate(generated_text):
39
+ print(f"{i}:\n{t}\n")