miaw1419 commited on
Commit
994bd5b
·
verified ·
1 Parent(s): 9296d80

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +535 -525
app.py CHANGED
@@ -18,43 +18,6 @@ import base64
18
  from datasets import load_dataset
19
  from PIL import Image
20
 
21
- device = "cuda" if torch.cuda.is_available() else "cpu"
22
-
23
- word_list_dataset = load_dataset("EPFL-VILAB/4m-wordlist", data_files="list.txt", use_auth_token=True)
24
- word_list = word_list_dataset["train"]['text']
25
-
26
- bnb_config = BitsAndBytesConfig(
27
- load_in_4bit=True,
28
- bnb_4bit_use_double_quant=True,
29
- bnb_4bit_quant_type="nf4",
30
- bnb_4bit_compute_dtype=torch.float16,
31
- llm_int8_skip_modules=["lm_head", "embed_tokens"],
32
- )
33
-
34
- processor = AutoProcessor.from_pretrained("HuggingFaceM4/idefics2-8b", size= {"longest_edge": 448, "shortest_edge": 378}, do_image_splitting=False)
35
-
36
- vpe_model = AutoModelForVision2Seq.from_pretrained(
37
- "HuggingFaceM4/idefics2-8b",
38
- torch_dtype=torch.float16,
39
- quantization_config=bnb_config,
40
- )
41
-
42
- vpe_model = PeftModel.from_pretrained(vpe_model, "VPE2").to("cuda")
43
-
44
- if torch.cuda.is_available():
45
- pipe = StableDiffusionXLPipeline.from_pretrained(
46
- "stabilityai/stable-diffusion-xl-base-1.0",
47
- torch_dtype=torch.float16
48
- ).to("cuda")
49
- else:
50
- pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", use_safetensors=True)
51
- pipe = pipe.to(device)
52
-
53
- MAX_SEED = np.iinfo(np.int32).max
54
- MAX_IMAGE_SIZE = 1024
55
-
56
- valid_api = ""
57
-
58
  css="""
59
  #col-container {
60
  margin: 0 auto;
@@ -74,323 +37,282 @@ css="""
74
  }
75
  """
76
 
77
- if torch.cuda.is_available():
78
- power_device = "GPU"
79
- else:
80
- power_device = "CPU"
81
-
82
- comment_images = [
83
- "comment_images/15.png",
84
- "test.png",
85
- "comment_images/0.png",
86
- "comment_images/1.png",
87
- "comment_images/2.png",
88
- "comment_images/3.png",
89
- "comment_images/4.png",
90
- "comment_images/5.png",
91
- "comment_images/6.png",
92
- "comment_images/7.png",
93
- "comment_images/8.png",
94
- "comment_images/9.png",
95
- "comment_images/10.png",
96
- "comment_images/11.png",
97
- "comment_images/12.png",
98
- "comment_images/13.png",
99
- "comment_images/14.png",
100
- "comment_images/16.png",
101
- "comment_images/17.png",
102
- "comment_images/18.png",
103
- "comment_images/19.png",
104
- "comment_images/20.png",
105
- "comment_images/21.png",
106
- "comment_images/22.png",
107
- "comment_images/23.png",
108
- "comment_images/24.png",
109
- "comment_images/25.png",
110
- "comment_images/26.png",
111
- "comment_images/27.png",
112
- "comment_images/28.png",
113
- "comment_images/29.png",
114
- "comment_images/30.png",
115
- "comment_images/31.png",
116
- "comment_images/32.png",
117
- "comment_images/33.png",
118
- "comment_images/34.png",
119
- "comment_images/35.png",
120
- "comment_images/36.png",
121
- "comment_images/37.png",
122
- "comment_images/38.png",
123
- "comment_images/39.png",
124
- "comment_images/40.png",
125
- "comment_images/41.png",
126
- "comment_images/42.jpg",
127
- "comment_images/43.png",
128
- "comment_images/44.png",
129
- "comment_images/45.png",
130
- "comment_images/46.png",
131
- "comment_images/47.png",
132
- "comment_images/48.png",
133
- "comment_images/49.png",
134
- "comment_images/50.png",
135
- "comment_images/51.png",
136
- "comment_images/52.png",
137
- "comment_images/53.png",
138
- "comment_images/54.png",
139
- "comment_images/55.png"
140
- ]
141
-
142
- example_prompts = [
143
- "Painting of a lady",
144
- "Cityscape during a thunderstorm",
145
- "Inside an abondoned train, window view",
146
- "A person reaching for stars",
147
- "Abandoned robot at the depth of the sea",
148
- "Lonely astronaut in abyss",
149
- "Human in a frame"
150
- ]
151
-
152
- examples = {
153
- "A person reaching for stars":[
154
- "examples/A person reaching fo_0.png",
155
- "examples/A person reaching fo_1.png",
156
- "examples/A person reaching fo_2.png",
157
- "examples/A person reaching fo_4.png",
158
- "examples/A person reaching fo_5.png",
159
- "examples/A person reaching fo_6.png",
160
- "examples/A person reaching fo_8.png",
161
- "examples/A person reaching fo_9.png",
162
- "examples/A person reaching fo_10.png",
163
- ],
164
- "Abandoned robot at the depth of the sea":[
165
- "examples/Abandoned robot at t_0.png",
166
- "examples/Abandoned robot at t_1.png",
167
- "examples/Abandoned robot at t_2.png",
168
- "examples/Abandoned robot at t_4.png",
169
- "examples/Abandoned robot at t_5.png",
170
- "examples/Abandoned robot at t_6.png",
171
- "examples/Abandoned robot at t_8.png",
172
- "examples/Abandoned robot at t_9.png",
173
- "examples/Abandoned robot at t_10.png",
174
- ],
175
- "Cityscape during a thunderstorm":[
176
- "examples/Cityscape during a t_0.png",
177
- "examples/Cityscape during a t_1.png",
178
- "examples/Cityscape during a t_2.png",
179
- "examples/Cityscape during a t_4.png",
180
- "examples/Cityscape during a t_5.png",
181
- "examples/Cityscape during a t_6.png",
182
- "examples/Cityscape during a t_8.png",
183
- "examples/Cityscape during a t_9.png",
184
- "examples/Cityscape during a t_10.png",
185
- ],
186
- "Human in a frame":[
187
- "examples/Human in a frame_0.png",
188
- "examples/Human in a frame_1.png",
189
- "examples/Human in a frame_2.png",
190
- "examples/Human in a frame_4.png",
191
- "examples/Human in a frame_5.png",
192
- "examples/Human in a frame_6.png",
193
- "examples/Human in a frame_8.png",
194
- "examples/Human in a frame_9.png",
195
- "examples/Human in a frame_10.png",
196
- ],
197
- "Inside an abondoned train, window view":[
198
- "examples/Inside an abondoned _0.png",
199
- "examples/Inside an abondoned _1.png",
200
- "examples/Inside an abondoned _2.png",
201
- "examples/Inside an abondoned _4.png",
202
- "examples/Inside an abondoned _5.png",
203
- "examples/Inside an abondoned _6.png",
204
- "examples/Inside an abondoned _8.png",
205
- "examples/Inside an abondoned _9.png",
206
- "examples/Inside an abondoned _10.png",
207
- ],
208
- "Lonely astronaut in abyss":[
209
- "examples/Lonely astronaut in _0.png",
210
- "examples/Lonely astronaut in _1.png",
211
- "examples/Lonely astronaut in _2.png",
212
- "examples/Lonely astronaut in _4.png",
213
- "examples/Lonely astronaut in _5.png",
214
- "examples/Lonely astronaut in _6.png",
215
- "examples/Lonely astronaut in _8.png",
216
- "examples/Lonely astronaut in _9.png",
217
- "examples/Lonely astronaut in _10.png",
218
- ],
219
- "Painting of a lady":[
220
- "examples/Painting of a lady_0.png",
221
- "examples/Painting of a lady_1.png",
222
- "examples/Painting of a lady_2.png",
223
- "examples/Painting of a lady_4.png",
224
- "examples/Painting of a lady_5.png",
225
- "examples/Painting of a lady_6.png",
226
- "examples/Painting of a lady_8.png",
227
- "examples/Painting of a lady_9.png",
228
- "examples/Painting of a lady_10.png",
229
  ]
230
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
231
 
232
- comments = {'test.png': "Not sure about the concept, it's too straightforward. Though the boy looks kinda creepy which makes it exciting. the art style is pretty to look at. I like that the colors are muted, but wish they were a bit darker to make it more eerie and add depth.", 'comment_images/0.png': "Hate this with a passion. The colors are too vibrant and don't match at all. I hate these colors in general. The patterns are too abstract and contemporary. a 5-year-old could draw this. pass.", 'comment_images/1.png': "Woah I love the art style. The texture feels like old paper which is oh so beautiful. There are so many details to focus on. I love the expressive lines and how busy the composition is. Even though orange isn't my favorite, the greenish blue color of the water is so gorgeous.", 'comment_images/2.png': "I don't like how monochromatic and muted this one is. but the paperish texture is nice and the details are so intricate.", 'comment_images/3.png': "Oh super pretty! Looks so smooth and wet. Love the details and loose lines too. Feels mystical and magical and eerie. Also dark purples and blues? deep indigo? My fav ever. I'm here for it.", 'comment_images/4.png': "Love the art style. The uncanny vibe and nightmarish horror is so cool. Like its horror but if you squint you can't tell? Love the strange. wish it had more colors though. not a fan of greyscale.", 'comment_images/5.png': 'omg I hate this haha. what the hell. everything about it disgusts me so boring and childish ew.', 'comment_images/6.png': 'yessss. give it to the texture give it to the brushstrokes give it to the style. perfect. just wish the colors were less beige and more bold. I want an active nightmare. but kisses to the surrealism.'}
233
- comments = dict()
234
 
235
- image_index = 0
236
 
237
- def submit_comment(comment):
238
- global comment_images, image_index
239
- if comment != "":
240
- comments[comment_images[0]] = comment
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
241
  comment_images.append(comment_images[0])
242
  comment_images = comment_images[1:]
 
 
 
 
 
243
  image_index = (image_index + 1) % len(comment_images)
244
 
245
- elif comment_images[0] in comments:
246
- comments.pop(comment_images[0], None)
247
-
248
- next_comment = ""
249
- if comment_images[0] in comments:
250
- next_comment = comments[comment_images[0]]
251
-
252
- clear_botton = gr.Button("Clear comments", interactive=len(comments) != 0)
253
-
254
- return (gr.Image(value=comment_images[0], label=f"image {image_index+1}/{len(comment_images)}", show_label=True),
255
- gr.Text(label="Comment", show_label=False, lines=4, max_lines=5, placeholder="Enter your comment. The more detailed the better.", value=next_comment, container=False),
256
- gr.Button(f"Extract visual preference from {len(comments)} comments", interactive=len(comments) != 0, variant="primary"),
257
- clear_botton
258
- )
259
-
260
- def next_image():
261
- global comment_images, image_index
262
- comment_images.append(comment_images[0])
263
- comment_images = comment_images[1:]
264
-
265
- next_comment = ""
266
- if comment_images[0] in comments:
267
- next_comment = comments[comment_images[0]]
268
-
269
- image_index = (image_index + 1) % len(comment_images)
270
-
271
- return gr.Image(value=comment_images[0], label=f"image {image_index+1}/{len(comment_images)}", show_label=True), gr.Text(label="Comment", show_label=False, lines=4, max_lines=5, placeholder="Enter your comment. The more detailed the better.", value=next_comment, container=False)
272
-
273
- def previous_image():
274
- global comment_images, image_index
275
- comment_images = comment_images[::-1]
276
- comment_images.append(comment_images[0])
277
- comment_images = comment_images[1:]
278
- comment_images = comment_images[::-1]
279
-
280
- next_comment = ""
281
- if comment_images[0] in comments:
282
- next_comment = comments[comment_images[0]]
283
-
284
- image_index = (image_index - 1) % len(comment_images)
285
-
286
- return gr.Image(value=comment_images[0], label=f"image {image_index+1}/{len(comment_images)}", show_label=True), gr.Text(label="Comment", show_label=False, lines=4, max_lines=5, placeholder="Enter your comment. The more detailed the better.", value=next_comment, container=False)
287
-
288
- def clear_comments():
289
- comments.clear()
290
- extract_vp_botton = gr.Button(f"Extract visual preference from {len(comments)} comments", interactive=len(comments) != 0, variant="primary")
291
- clear_botton = gr.Button("Clear comments", interactive=len(comments) != 0)
292
- return extract_vp_botton, clear_botton
293
-
294
- @spaces.GPU(duration=120)
295
- def extract_vp_from_vpe():
296
- global comments
297
- if len(comments) < 8:
298
- gr.Warning("Fewer than 8 comments may lead to errors.")
299
-
300
- prompt = """I will provide a set of artworks along with accompanying comments from a person. Analyze these artworks and the comments on them and identify artistic features such as present or mentioned colors, style, composition, mood, medium, texture, brushwork, lighting, shadow effects, perspective, and other noteworthy elements.
301
- Your task is to extract the artistic features the person likes and dislikes based on both the artworks' features and the person's comments. Focus solely on artistic aspects and refrain from considering subject matter.
302
- If the person expresses a preference for a specific aspect without clearly stating its category (e.g., appreciating the colors without specifying which colors), identify these specific features from the images directly to make the person's preference understandable without needing to see the artwork.
303
- Your output should consist of two concise lists of keywords: one listing the specific art features the person likes and another listing the specific features they dislike (specified in keyword format without using sentences).
304
- Here are the images and their corresponding comments:
305
- """
306
- messages = [
307
- {
308
- "role": "user",
309
- "content": [
310
- {"type": "text",
311
- "text": prompt},
312
- ]
313
- }
314
- ]
315
- images = []
316
- comment_number = 1
317
- for image in comments:
318
- comment = comments[image]
319
- image = Image.open(image)
320
- images.append(image)
321
-
322
- messages[0]["content"].append(
323
- {"type": "image"}
324
- )
325
 
326
- messages[0]["content"].append(
327
- {"type": "text",
328
- "text": f"Comment {comment_number}: {comment}"}
329
- )
330
- comment_number = comment_number + 1
331
-
332
- prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
333
- inputs = processor(text=prompt, images=images, return_tensors="pt")
334
- inputs = {k: v.to(device) for k, v in inputs.items()}
335
-
336
- generated_ids = vpe_model.generate(**inputs, max_new_tokens=2000, repetition_penalty=0.99, do_sample=False)
337
- generated_texts = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
338
-
339
- if re.match(r"(.|\n)*Assistant: Liked Art Features: (.|\n)*Disliked Art Features: (.|\n)*", generated_texts):
340
- positive_vp, negative_vp = re.search('.* \nAssistant: Liked Art Features: (.*)\nDisliked Art Features: (.*)', generated_texts).groups()
341
- positive_vp = positive_vp.split(", ")
342
- negative_vp = negative_vp.split(", ")
343
- common = list(set(positive_vp).intersection(negative_vp))
344
-
345
- for vp in positive_vp:
346
- if vp in common:
347
- positive_vp.remove(vp)
348
-
349
- for vp in negative_vp:
350
- if vp in common:
351
- negative_vp.remove(vp)
352
-
353
- positive_vp = ", ".join(positive_vp)
354
- negative_vp = ", ".join(negative_vp)
355
- gr.Info("Visual preference successfully extracted.")
356
- else:
357
- positive_vp = ""
358
- negative_vp = ""
359
- gr.Warning("VP extraction failed: Please comment on more images.")
360
-
361
- return positive_vp, negative_vp
362
 
363
- def extract_vp():
 
 
364
 
365
- if valid_api == "":
366
- positive_vp, negative_vp = extract_vp_from_vpe()
367
-
368
- else:
369
- client = anthropic.Anthropic(
370
- api_key=valid_api,
371
- )
372
 
373
- prompt = """**Objective:**
374
- Analyze a set of artworks and accompanying comments from a person to identify artistic features they like and dislike.
375
- **Steps:**
376
- 1. **Analyze Artworks and Comments:**
377
- - Examine each artwork for artistic features such as colors, style, composition, mood, medium, texture, brushwork, lighting, shadow effects, perspective, and other noteworthy elements.
378
- - Review the accompanying comments to understand the person's preferences and opinions on these features.
379
- 2. **Identify Preferences:**
380
- - Extract artistic features that the person likes and dislikes based on the artworks' features and the comments.
381
- - Focus solely on artistic aspects and ignore the subject matter.
382
- - Convert the art features mentioned in the comments to well-known synonyms if needed.
383
- 3. **Resolve Ambiguous Preferences:**
384
- - If the person expresses a preference without clearly stating its category (e.g., "I like the style" without specifying which style), identify these specific features from the images directly.
385
- - Make the person's preference understandable and independednt of the artworks.
386
- 4. **Output Format:**
387
- - Create two concise lists of keywords: one for features the person likes and another for features they dislike.
388
- - Ensure the lists are in keyword format, divided by commas, without using sentences.
389
- - Maintain detail and accuracy for all comments and images.
390
- **Your Task:**
391
- Follow the example format and ensure that your output consists of two lists of keywords summarizing the person's preferences based on the artworks and comments provided. Consider all comments and images comprehensively.
392
- **Example**: example START:
393
- """
 
 
394
  messages = [
395
  {
396
  "role": "user",
@@ -404,30 +326,11 @@ Follow the example format and ensure that your output consists of two lists of k
404
  comment_number = 1
405
  for image in comments:
406
  comment = comments[image]
407
- if not image.lower().endswith(".jpg"):
408
- jpg_image_path = image.replace("png", "jpg")
409
- image = Image.open(image)
410
- rgb_img = image.convert("RGB")
411
- rgb_img.save(jpg_image_path, format="JPEG")
412
- with open(jpg_image_path, "rb") as image_file:
413
- image = base64.b64encode(image_file.read()).decode("utf-8")
414
-
415
- else:
416
- with open(image_path, "rb") as image_file:
417
- image = base64.b64encode(image_file.read()).decode("utf-8")
418
 
419
  messages[0]["content"].append(
420
- {"type": "text",
421
- "text": f"Image {comment_number}:"}
422
- )
423
-
424
- messages[0]["content"].append(
425
- {"type": "image",
426
- "source": {
427
- "type": "base64",
428
- "media_type": "image/jpeg",
429
- "data": image,
430
- },}
431
  )
432
 
433
  messages[0]["content"].append(
@@ -436,111 +339,265 @@ Follow the example format and ensure that your output consists of two lists of k
436
  )
437
  comment_number = comment_number + 1
438
 
439
- message = client.messages.create(
440
- model="claude-3-5-sonnet-20240620",
441
- max_tokens=1024,
442
- messages=messages
443
- )
 
 
 
 
 
 
 
 
 
 
 
444
 
445
- generated_text = message.content[0].text
446
- if re.match(r"(.|\n)*Like.*:(.|\n)*Dislike.(.|\n)*", generated_texts):
447
- positive_vp, negative_vp = re.search('.*Like.*:\n(.*)\n*Dislike.*:\n(.*)', generated_text).groups()
 
 
 
448
  gr.Info("Visual preference successfully extracted.")
449
  else:
450
  positive_vp = ""
451
  negative_vp = ""
452
  gr.Warning("VP extraction failed: Please comment on more images.")
453
-
454
- return gr.Textbox(label="Liked visual attributes", lines=3, value=positive_vp, interactive=True), gr.Textbox(label="Disliked visual attributes", lines=1, value=negative_vp, interactive=True), gr.Button("Run personalized generation", scale=0, interactive=True, variant="primary")
455
 
456
- def api_fn(api):
457
- global valid_api
458
- client = anthropic.Anthropic(
459
- api_key=api,
460
- )
461
- try:
462
- message = client.messages.create(
463
- model="claude-3-5-sonnet-20240620",
464
- max_tokens=1024,
465
- messages=[
466
- {"role": "user", "content": "Hello, Claude"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
467
  ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
468
  )
469
- gr.Info("Valid API")
470
- valid_api = api
471
-
472
- except anthropic.AuthenticationError:
473
- gr.Warning("Invalid API!")
474
- valid_api = ""
475
-
476
- except anthropic.BadRequestError:
477
- gr.Warning("Invalid API!")
478
- valid_api = ""
479
-
480
- except anthropic.PermissionDeniedError:
481
- gr.Warning("Invalid API!")
482
- valid_api = ""
483
-
484
- except anthropic.RateLimitError:
485
- gr.Warning("Invalid API!")
486
- valid_api = ""
487
-
488
-
489
- def generate_out(prompt, vp_pos, vp_neg, slider, example_prompt, gallery, num_inference_steps, seed, randomize_seed):
490
- if vp_pos == "" and vp_neg == "":
491
- gr.Warning("Visual preference is empty.", duration=10)
492
-
493
- return generate(prompt, vp_pos, vp_neg, slider, example_prompt, gallery, num_inference_steps, seed, randomize_seed)
494
-
495
- @spaces.GPU(duration=45)
496
- def generate(prompt, vp_pos, vp_neg, slider, example_prompt, gallery, num_inference_steps, seed, randomize_seed):
497
- if vp_pos == "" and vp_neg == "":
498
- slider = 0
499
-
500
- for filter in word_list:
501
- if re.search(rf"\b{filter}\b", prompt):
502
- raise gr.Error("Please try again with a different prompt")
503
- if re.search(rf"\b{filter}\b", vp_pos) or re.search(rf"\b{filter}\b", vp_neg):
504
- raise gr.Error("Please try again with a different visual preference")
505
-
506
- if vp_pos != "":
507
- vp_pos = vp_pos.split(", ")
508
- random.shuffle(vp_pos)
509
- vp_pos = ", ".join(vp_pos)
510
-
511
- if vp_neg != "":
512
- vp_neg = vp_neg.split(", ")
513
- random.shuffle(vp_neg)
514
- vp_neg = ", ".join(vp_neg)
515
-
516
- if randomize_seed:
517
- seed = random.randint(0, MAX_SEED)
518
-
519
- generator = torch.Generator().manual_seed(seed)
520
-
521
- if prompt is None:
522
- promtpt = ""
523
-
524
- image = pipe(prompt=prompt,
525
- num_inference_steps=num_inference_steps,
526
- vp_pos=vp_pos,
527
- vp_neg=vp_neg,
528
- vp_degree_pos=slider,
529
- vp_degree_neg=slider,
530
- generator=generator
531
- ).images[0]
532
-
533
- global example_prompts, examples
534
- if prompt in example_prompts:
535
- while example_prompts[0] != prompt:
536
- example_prompts.append(example_prompts[0])
537
- example_prompts = example_prompts[1:]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
538
 
539
  example_prompt = gr.Markdown(f"Prompt: {example_prompts[0]}")
540
- if len(examples[example_prompts[0]]) == 10:
541
- examples[example_prompts[0]] = examples[example_prompts[0]][:-1]
 
 
 
 
 
 
 
 
542
 
543
- examples[example_prompts[0]].append(image)
 
 
 
 
 
 
 
544
  gallery = gr.Gallery(
545
  value=examples[example_prompts[0]],
546
  label="",
@@ -550,56 +607,9 @@ def generate(prompt, vp_pos, vp_neg, slider, example_prompt, gallery, num_infere
550
  object_fit="contain",
551
  height=500)
552
 
553
- return image, example_prompt, gallery
554
-
555
- def change_vp(extract_vp):
556
- return
557
-
558
- def upload_file(files):
559
- global comment_images, image_index
560
- file_path = [file.name for file in files][0]
561
- comment_images = [file_path] + comment_images
562
-
563
- next_comment = ""
564
- return gr.Image(value=comment_images[0], label=f"image {image_index+1}/{len(comment_images)}", show_label=True), gr.Text(label="Comment", show_label=False, lines=4, max_lines=5, placeholder="Enter your comment. The more detailed the better.", value=next_comment, container=False)
565
-
566
- def next_prompt():
567
- global example_prompts, examples
568
- example_prompts.append(example_prompts[0])
569
- example_prompts = example_prompts[1:]
570
-
571
- example_prompt = gr.Markdown(f"Prompt: {example_prompts[0]}")
572
- gallery = gr.Gallery(
573
- value=examples[example_prompts[0]],
574
- label="",
575
- show_label=False,
576
- columns=[5],
577
- rows=[2],
578
- object_fit="contain",
579
- height=500)
580
-
581
- return example_prompt, gallery
582
-
583
- def previous_prompt():
584
- global example_prompts, examples
585
- example_prompts = example_prompts[::-1]
586
- example_prompts.append(example_prompts[0])
587
- example_prompts = example_prompts[1:]
588
- example_prompts = example_prompts[::-1]
589
-
590
- example_prompt = gr.Markdown(f"Prompt: {example_prompts[0]}")
591
- gallery = gr.Gallery(
592
- value=examples[example_prompts[0]],
593
- label="",
594
- show_label=False,
595
- columns=[5],
596
- rows=[2],
597
- object_fit="contain",
598
- height=500)
599
-
600
- return example_prompt, gallery
601
 
602
- with gr.Blocks(css=css, title="ViPer Demo", theme=gr.themes.Base()) as demo:
603
  with gr.Column(elem_id="title-container"):
604
  gr.Markdown(f"""
605
  # **ViPer: Visual Personalization of Generative Models via Individual Preference Learning**
@@ -638,7 +648,7 @@ with gr.Blocks(css=css, title="ViPer Demo", theme=gr.themes.Base()) as demo:
638
  value="I adore the blue and greenish-blue palette, blue Dianne, and dark colors of this image. I also appreciate the Hergé inspiration in this artwork. However, I would have preferred a more complex and adventurous concept rather than a simple landscape. I wish it was more surreal and creepy.",
639
  )
640
 
641
- comment_image = gr.Image(value=comment_images[0], label=f"image {image_index+1}/{len(comment_images)}", show_label=True)
642
 
643
  comment = gr.Text(
644
  label="Comment",
@@ -658,7 +668,7 @@ with gr.Blocks(css=css, title="ViPer Demo", theme=gr.themes.Base()) as demo:
658
 
659
  with gr.Row():
660
  upload_button = gr.UploadButton("Click to upload images 📤", file_types=["image"], file_count="multiple")
661
- clear_botton = gr.Button("Clear comments 🗑", interactive=len(comments) != 0)
662
 
663
  with gr.Accordion("Enter Claude API (optional)", open=False):
664
  gr.Markdown("By default, we extract visual preferences from user comments using a fine-tuned HuggingFaceM4/idefics2-8b model. Optionally, you can experiment with using claude-3-5-sonnet for visual preference extraction by entering your API key below.")
@@ -671,7 +681,7 @@ with gr.Blocks(css=css, title="ViPer Demo", theme=gr.themes.Base()) as demo:
671
 
672
  api_button = gr.Button("Enter", scale=0)
673
 
674
- extract_vp_botton = gr.Button(f"Extract visual preference from {len(comments)} comments", interactive=len(comments) != 0, variant="primary")
675
 
676
  with gr.Column(elem_id="gen-container"):
677
  positive_extracted_vp = gr.Textbox(
@@ -746,26 +756,26 @@ with gr.Blocks(css=css, title="ViPer Demo", theme=gr.themes.Base()) as demo:
746
 
747
  submit_comment_button.click(
748
  fn = submit_comment,
749
- inputs = [comment],
750
- outputs = [comment_image, comment, extract_vp_botton, clear_botton]
751
  )
752
 
753
  previous_image_botton.click(
754
  fn = previous_image,
755
- inputs = [],
756
- outputs = [comment_image, comment]
757
  )
758
 
759
  next_image_botton.click(
760
  fn = next_image,
761
- inputs = [],
762
- outputs = [comment_image, comment]
763
  )
764
 
765
  extract_vp_botton.click(
766
  fn = extract_vp,
767
- inputs = [],
768
- outputs = [positive_extracted_vp, negative_extracted_vp, run_button]
769
  )
770
 
771
  api_button.click(
@@ -794,14 +804,8 @@ with gr.Blocks(css=css, title="ViPer Demo", theme=gr.themes.Base()) as demo:
794
 
795
  clear_botton.click(
796
  fn = clear_comments,
797
- inputs = [],
798
- outputs = [extract_vp_botton, clear_botton]
799
- )
800
-
801
- upload_button.upload(
802
- upload_file,
803
- upload_button,
804
- [comment_image, comment]
805
  )
806
 
807
  next_prompt_button.click(
@@ -816,4 +820,10 @@ with gr.Blocks(css=css, title="ViPer Demo", theme=gr.themes.Base()) as demo:
816
  outputs = [example_prompt, gallery]
817
  )
818
 
 
 
 
 
 
 
819
  demo.launch(share=True)
 
18
  from datasets import load_dataset
19
  from PIL import Image
20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  css="""
22
  #col-container {
23
  margin: 0 auto;
 
37
  }
38
  """
39
 
40
+ with gr.Blocks(css=css, title="ViPer Demo", theme=gr.themes.Base()) as demo:
41
+
42
+ device = "cuda" if torch.cuda.is_available() else "cpu"
43
+
44
+
45
+ word_list_dataset = load_dataset("EPFL-VILAB/4m-wordlist", data_files="list.txt", use_auth_token=True)
46
+ word_list = word_list_dataset["train"]['text']
47
+
48
+ bnb_config = BitsAndBytesConfig(
49
+ load_in_4bit=True,
50
+ bnb_4bit_use_double_quant=True,
51
+ bnb_4bit_quant_type="nf4",
52
+ bnb_4bit_compute_dtype=torch.float16,
53
+ llm_int8_skip_modules=["lm_head", "embed_tokens"],
54
+ )
55
+
56
+ processor = AutoProcessor.from_pretrained("HuggingFaceM4/idefics2-8b", size= {"longest_edge": 448, "shortest_edge": 378}, do_image_splitting=False)
57
+
58
+ vpe_model = AutoModelForVision2Seq.from_pretrained(
59
+ "HuggingFaceM4/idefics2-8b",
60
+ torch_dtype=torch.float16,
61
+ quantization_config=bnb_config,
62
+ )
63
+
64
+ vpe_model = PeftModel.from_pretrained(vpe_model, "VPE2").to("cuda")
65
+
66
+ if torch.cuda.is_available():
67
+ pipe = StableDiffusionXLPipeline.from_pretrained(
68
+ "stabilityai/stable-diffusion-xl-base-1.0",
69
+ torch_dtype=torch.float16
70
+ ).to("cuda")
71
+ else:
72
+ pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", use_safetensors=True)
73
+ pipe = pipe.to(device)
74
+
75
+ MAX_SEED = np.iinfo(np.int32).max
76
+ MAX_IMAGE_SIZE = 1024
77
+
78
+ valid_api = ""
79
+
80
+ if torch.cuda.is_available():
81
+ power_device = "GPU"
82
+ else:
83
+ power_device = "CPU"
84
+
85
+ mioo = [
86
+ "comment_images/15.png",
87
+ "test.png",
88
+ "comment_images/0.png",
89
+ "comment_images/1.png",
90
+ "comment_images/2.png",
91
+ "comment_images/3.png",
92
+ "comment_images/4.png",
93
+ "comment_images/5.png",
94
+ "comment_images/6.png",
95
+ "comment_images/7.png",
96
+ "comment_images/8.png",
97
+ "comment_images/9.png",
98
+ "comment_images/10.png",
99
+ "comment_images/11.png",
100
+ "comment_images/12.png",
101
+ "comment_images/13.png",
102
+ "comment_images/14.png",
103
+ "comment_images/16.png",
104
+ "comment_images/17.png",
105
+ "comment_images/18.png",
106
+ "comment_images/19.png",
107
+ "comment_images/20.png",
108
+ "comment_images/21.png",
109
+ "comment_images/22.png",
110
+ "comment_images/23.png",
111
+ "comment_images/24.png",
112
+ "comment_images/25.png",
113
+ "comment_images/26.png",
114
+ "comment_images/27.png",
115
+ "comment_images/28.png",
116
+ "comment_images/29.png",
117
+ "comment_images/30.png",
118
+ "comment_images/31.png",
119
+ "comment_images/32.png",
120
+ "comment_images/33.png",
121
+ "comment_images/34.png",
122
+ "comment_images/35.png",
123
+ "comment_images/36.png",
124
+ "comment_images/37.png",
125
+ "comment_images/38.png",
126
+ "comment_images/39.png",
127
+ "comment_images/40.png",
128
+ "comment_images/41.png",
129
+ "comment_images/42.jpg",
130
+ "comment_images/43.png",
131
+ "comment_images/44.png",
132
+ "comment_images/45.png",
133
+ "comment_images/46.png",
134
+ "comment_images/47.png",
135
+ "comment_images/48.png",
136
+ "comment_images/49.png",
137
+ "comment_images/50.png",
138
+ "comment_images/51.png",
139
+ "comment_images/52.png",
140
+ "comment_images/53.png",
141
+ "comment_images/54.png",
142
+ "comment_images/55.png"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
  ]
144
+
145
+ comment_images = gr.State(mioo)
146
+
147
+ example_prompts = [
148
+ "Painting of a lady",
149
+ "Cityscape during a thunderstorm",
150
+ "Inside an abondoned train, window view",
151
+ "A person reaching for stars",
152
+ "Abandoned robot at the depth of the sea",
153
+ "Lonely astronaut in abyss",
154
+ "Human in a frame"
155
+ ]
156
+
157
+ examples = {
158
+ "A person reaching for stars":[
159
+ "examples/A person reaching fo_0.png",
160
+ "examples/A person reaching fo_1.png",
161
+ "examples/A person reaching fo_2.png",
162
+ "examples/A person reaching fo_4.png",
163
+ "examples/A person reaching fo_5.png",
164
+ "examples/A person reaching fo_6.png",
165
+ "examples/A person reaching fo_8.png",
166
+ "examples/A person reaching fo_9.png",
167
+ "examples/A person reaching fo_10.png",
168
+ ],
169
+ "Abandoned robot at the depth of the sea":[
170
+ "examples/Abandoned robot at t_0.png",
171
+ "examples/Abandoned robot at t_1.png",
172
+ "examples/Abandoned robot at t_2.png",
173
+ "examples/Abandoned robot at t_4.png",
174
+ "examples/Abandoned robot at t_5.png",
175
+ "examples/Abandoned robot at t_6.png",
176
+ "examples/Abandoned robot at t_8.png",
177
+ "examples/Abandoned robot at t_9.png",
178
+ "examples/Abandoned robot at t_10.png",
179
+ ],
180
+ "Cityscape during a thunderstorm":[
181
+ "examples/Cityscape during a t_0.png",
182
+ "examples/Cityscape during a t_1.png",
183
+ "examples/Cityscape during a t_2.png",
184
+ "examples/Cityscape during a t_4.png",
185
+ "examples/Cityscape during a t_5.png",
186
+ "examples/Cityscape during a t_6.png",
187
+ "examples/Cityscape during a t_8.png",
188
+ "examples/Cityscape during a t_9.png",
189
+ "examples/Cityscape during a t_10.png",
190
+ ],
191
+ "Human in a frame":[
192
+ "examples/Human in a frame_0.png",
193
+ "examples/Human in a frame_1.png",
194
+ "examples/Human in a frame_2.png",
195
+ "examples/Human in a frame_4.png",
196
+ "examples/Human in a frame_5.png",
197
+ "examples/Human in a frame_6.png",
198
+ "examples/Human in a frame_8.png",
199
+ "examples/Human in a frame_9.png",
200
+ "examples/Human in a frame_10.png",
201
+ ],
202
+ "Inside an abondoned train, window view":[
203
+ "examples/Inside an abondoned _0.png",
204
+ "examples/Inside an abondoned _1.png",
205
+ "examples/Inside an abondoned _2.png",
206
+ "examples/Inside an abondoned _4.png",
207
+ "examples/Inside an abondoned _5.png",
208
+ "examples/Inside an abondoned _6.png",
209
+ "examples/Inside an abondoned _8.png",
210
+ "examples/Inside an abondoned _9.png",
211
+ "examples/Inside an abondoned _10.png",
212
+ ],
213
+ "Lonely astronaut in abyss":[
214
+ "examples/Lonely astronaut in _0.png",
215
+ "examples/Lonely astronaut in _1.png",
216
+ "examples/Lonely astronaut in _2.png",
217
+ "examples/Lonely astronaut in _4.png",
218
+ "examples/Lonely astronaut in _5.png",
219
+ "examples/Lonely astronaut in _6.png",
220
+ "examples/Lonely astronaut in _8.png",
221
+ "examples/Lonely astronaut in _9.png",
222
+ "examples/Lonely astronaut in _10.png",
223
+ ],
224
+ "Painting of a lady":[
225
+ "examples/Painting of a lady_0.png",
226
+ "examples/Painting of a lady_1.png",
227
+ "examples/Painting of a lady_2.png",
228
+ "examples/Painting of a lady_4.png",
229
+ "examples/Painting of a lady_5.png",
230
+ "examples/Painting of a lady_6.png",
231
+ "examples/Painting of a lady_8.png",
232
+ "examples/Painting of a lady_9.png",
233
+ "examples/Painting of a lady_10.png",
234
+ ]
235
+ }
236
 
237
+ comments = {'test.png': "Not sure about the concept, it's too straightforward. Though the boy looks kinda creepy which makes it exciting. the art style is pretty to look at. I like that the colors are muted, but wish they were a bit darker to make it more eerie and add depth.", 'comment_images/0.png': "Hate this with a passion. The colors are too vibrant and don't match at all. I hate these colors in general. The patterns are too abstract and contemporary. a 5-year-old could draw this. pass.", 'comment_images/1.png': "Woah I love the art style. The texture feels like old paper which is oh so beautiful. There are so many details to focus on. I love the expressive lines and how busy the composition is. Even though orange isn't my favorite, the greenish blue color of the water is so gorgeous.", 'comment_images/2.png': "I don't like how monochromatic and muted this one is. but the paperish texture is nice and the details are so intricate.", 'comment_images/3.png': "Oh super pretty! Looks so smooth and wet. Love the details and loose lines too. Feels mystical and magical and eerie. Also dark purples and blues? deep indigo? My fav ever. I'm here for it.", 'comment_images/4.png': "Love the art style. The uncanny vibe and nightmarish horror is so cool. Like its horror but if you squint you can't tell? Love the strange. wish it had more colors though. not a fan of greyscale.", 'comment_images/5.png': 'omg I hate this haha. what the hell. everything about it disgusts me so boring and childish ew.', 'comment_images/6.png': 'yessss. give it to the texture give it to the brushstrokes give it to the style. perfect. just wish the colors were less beige and more bold. I want an active nightmare. but kisses to the surrealism.'}
238
+ comments = gr.State(dict())
239
 
240
+ image_index = gr.State(0)
241
 
242
+ def submit_comment(comment, comments, comment_images, image_index):
243
+ if comment != "":
244
+ comments[comment_images[0]] = comment
245
+ comment_images.append(comment_images[0])
246
+ comment_images = comment_images[1:]
247
+ image_index = (image_index + 1) % len(comment_images)
248
+
249
+ elif comment_images[0] in comments:
250
+ comments.pop(comment_images[0], None)
251
+
252
+ next_comment = ""
253
+ if comment_images[0] in comments:
254
+ next_comment = comments[comment_images[0]]
255
+
256
+ clear_botton = gr.Button("Clear comments", interactive=len(comments) != 0)
257
+
258
+ print(comments)
259
+
260
+ return (gr.Image(value=comment_images[0], label=f"image {image_index+1}/{len(comment_images)}", show_label=True),
261
+ gr.Text(label="Comment", show_label=False, lines=4, max_lines=5, placeholder="Enter your comment. The more detailed the better.", value=next_comment, container=False),
262
+ gr.Button(f"Extract visual preference from {len(comments)} comments", interactive=len(comments) >= 5, variant="primary"),
263
+ clear_botton,
264
+ comments,
265
+ comment_images,
266
+ image_index
267
+ )
268
+
269
+ def next_image(comments, comment_images, image_index):
270
  comment_images.append(comment_images[0])
271
  comment_images = comment_images[1:]
272
+
273
+ next_comment = ""
274
+ if comment_images[0] in comments:
275
+ next_comment = comments[comment_images[0]]
276
+
277
  image_index = (image_index + 1) % len(comment_images)
278
 
279
+ return gr.Image(value=comment_images[0], label=f"image {image_index+1}/{len(comment_images)}", show_label=True), gr.Text(label="Comment", show_label=False, lines=4, max_lines=5, placeholder="Enter your comment. The more detailed the better.", value=next_comment, container=False), comments, comment_images, image_index
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
280
 
281
+ def previous_image(comments, comment_images, image_index):
282
+ comment_images = comment_images[::-1]
283
+ comment_images.append(comment_images[0])
284
+ comment_images = comment_images[1:]
285
+ comment_images = comment_images[::-1]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
286
 
287
+ next_comment = ""
288
+ if comment_images[0] in comments:
289
+ next_comment = comments[comment_images[0]]
290
 
291
+ image_index = (image_index - 1) % len(comment_images)
 
 
 
 
 
 
292
 
293
+ return gr.Image(value=comment_images[0], label=f"image {image_index+1}/{len(comment_images)}", show_label=True), gr.Text(label="Comment", show_label=False, lines=4, max_lines=5, placeholder="Enter your comment. The more detailed the better.", value=next_comment, container=False), comments, comment_images, image_index
294
+
295
+ def clear_comments(comments):
296
+ comments.clear()
297
+ extract_vp_botton = gr.Button(f"Extract visual preference from {len(comments)} comments", interactive=len(comments) >= 5, variant="primary")
298
+ clear_botton = gr.Button("Clear comments", interactive=len(comments) != 0)
299
+ return extract_vp_botton, clear_botton, comments
300
+
301
+ @spaces.GPU(duration=120)
302
+ def extract_vp_from_vpe(comments):
303
+ if len(comments) < 8:
304
+ gr.Warning("Fewer than 8 comments may lead to errors.")
305
+
306
+ keys = list(comments.keys())
307
+ random.shuffle(keys)
308
+ comments = [(key, comments[key]) for key in keys]
309
+
310
+ prompt = """I will provide a set of artworks along with accompanying comments from a person. Analyze these artworks and the comments on them and identify artistic features such as present or mentioned colors, style, composition, mood, medium, texture, brushwork, lighting, shadow effects, perspective, and other noteworthy elements.
311
+ Your task is to extract the artistic features the person likes and dislikes based on both the artworks' features and the person's comments. Focus solely on artistic aspects and refrain from considering subject matter.
312
+ If the person expresses a preference for a specific aspect without clearly stating its category (e.g., appreciating the colors without specifying which colors), identify these specific features from the images directly to make the person's preference understandable without needing to see the artwork.
313
+ Your output should consist of two concise lists of keywords: one listing the specific art features the person likes and another listing the specific features they dislike (specified in keyword format without using sentences).
314
+ Here are the images and their corresponding comments:
315
+ """
316
  messages = [
317
  {
318
  "role": "user",
 
326
  comment_number = 1
327
  for image in comments:
328
  comment = comments[image]
329
+ image = Image.open(image)
330
+ images.append(image)
 
 
 
 
 
 
 
 
 
331
 
332
  messages[0]["content"].append(
333
+ {"type": "image"}
 
 
 
 
 
 
 
 
 
 
334
  )
335
 
336
  messages[0]["content"].append(
 
339
  )
340
  comment_number = comment_number + 1
341
 
342
+ prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
343
+ inputs = processor(text=prompt, images=images, return_tensors="pt")
344
+ inputs = {k: v.to(device) for k, v in inputs.items()}
345
+
346
+ generated_ids = vpe_model.generate(**inputs, max_new_tokens=2000, repetition_penalty=0.99, do_sample=False)
347
+ generated_texts = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
348
+
349
+ if re.match(r"(.|\n)*Assistant: Liked Art Features: (.|\n)*Disliked Art Features: (.|\n)*", generated_texts):
350
+ positive_vp, negative_vp = re.search('.* \nAssistant: Liked Art Features: (.*)\nDisliked Art Features: (.*)', generated_texts).groups()
351
+ positive_vp = positive_vp.split(", ")
352
+ negative_vp = negative_vp.split(", ")
353
+ common = list(set(positive_vp).intersection(negative_vp))
354
+
355
+ for vp in positive_vp:
356
+ if vp in common:
357
+ positive_vp.remove(vp)
358
 
359
+ for vp in negative_vp:
360
+ if vp in common:
361
+ negative_vp.remove(vp)
362
+
363
+ positive_vp = ", ".join(positive_vp)
364
+ negative_vp = ", ".join(negative_vp)
365
  gr.Info("Visual preference successfully extracted.")
366
  else:
367
  positive_vp = ""
368
  negative_vp = ""
369
  gr.Warning("VP extraction failed: Please comment on more images.")
 
 
370
 
371
+ return positive_vp, negative_vp
372
+
373
+ def extract_vp(comments):
374
+
375
+ if valid_api == "":
376
+ positive_vp, negative_vp = extract_vp_from_vpe(comments)
377
+
378
+ else:
379
+ client = anthropic.Anthropic(
380
+ api_key=valid_api,
381
+ )
382
+
383
+ prompt = """**Objective:**
384
+ Analyze a set of artworks and accompanying comments from a person to identify artistic features they like and dislike.
385
+ **Steps:**
386
+ 1. **Analyze Artworks and Comments:**
387
+ - Examine each artwork for artistic features such as colors, style, composition, mood, medium, texture, brushwork, lighting, shadow effects, perspective, and other noteworthy elements.
388
+ - Review the accompanying comments to understand the person's preferences and opinions on these features.
389
+ 2. **Identify Preferences:**
390
+ - Extract artistic features that the person likes and dislikes based on the artworks' features and the comments.
391
+ - Focus solely on artistic aspects and ignore the subject matter.
392
+ - Convert the art features mentioned in the comments to well-known synonyms if needed.
393
+ 3. **Resolve Ambiguous Preferences:**
394
+ - If the person expresses a preference without clearly stating its category (e.g., "I like the style" without specifying which style), identify these specific features from the images directly.
395
+ - Make the person's preference understandable and independednt of the artworks.
396
+ 4. **Output Format:**
397
+ - Create two concise lists of keywords: one for features the person likes and another for features they dislike.
398
+ - Ensure the lists are in keyword format, divided by commas, without using sentences.
399
+ - Maintain detail and accuracy for all comments and images.
400
+ **Your Task:**
401
+ Follow the example format and ensure that your output consists of two lists of keywords summarizing the person's preferences based on the artworks and comments provided. Consider all comments and images comprehensively.
402
+ **Example**: example START:
403
+ """
404
+ messages = [
405
+ {
406
+ "role": "user",
407
+ "content": [
408
+ {"type": "text",
409
+ "text": prompt},
410
+ ]
411
+ }
412
  ]
413
+ images = []
414
+ comment_number = 1
415
+ for image in comments:
416
+ comment = comments[image]
417
+ if not image.lower().endswith(".jpg"):
418
+ jpg_image_path = image.replace("png", "jpg")
419
+ image = Image.open(image)
420
+ rgb_img = image.convert("RGB")
421
+ rgb_img.save(jpg_image_path, format="JPEG")
422
+ with open(jpg_image_path, "rb") as image_file:
423
+ image = base64.b64encode(image_file.read()).decode("utf-8")
424
+
425
+ else:
426
+ with open(image_path, "rb") as image_file:
427
+ image = base64.b64encode(image_file.read()).decode("utf-8")
428
+
429
+ messages[0]["content"].append(
430
+ {"type": "text",
431
+ "text": f"Image {comment_number}:"}
432
+ )
433
+
434
+ messages[0]["content"].append(
435
+ {"type": "image",
436
+ "source": {
437
+ "type": "base64",
438
+ "media_type": "image/jpeg",
439
+ "data": image,
440
+ },}
441
+ )
442
+
443
+ messages[0]["content"].append(
444
+ {"type": "text",
445
+ "text": f"Comment {comment_number}: {comment}"}
446
+ )
447
+ comment_number = comment_number + 1
448
+
449
+ message = client.messages.create(
450
+ model="claude-3-5-sonnet-20240620",
451
+ max_tokens=1024,
452
+ messages=messages
453
+ )
454
+
455
+ generated_text = message.content[0].text
456
+ if re.match(r"(.|\n)*Like.*:(.|\n)*Dislike.(.|\n)*", generated_texts):
457
+ positive_vp, negative_vp = re.search('.*Like.*:\n(.*)\n*Dislike.*:\n(.*)', generated_text).groups()
458
+ gr.Info("Visual preference successfully extracted.")
459
+ else:
460
+ positive_vp = ""
461
+ negative_vp = ""
462
+ gr.Warning("VP extraction failed: Please comment on more images.")
463
+
464
+ return gr.Textbox(label="Liked visual attributes", lines=3, value=positive_vp, interactive=True), gr.Textbox(label="Disliked visual attributes", lines=1, value=negative_vp, interactive=True), gr.Button("Run personalized generation", scale=0, interactive=True, variant="primary"), comments
465
+
466
+ def api_fn(api):
467
+ global valid_api
468
+ client = anthropic.Anthropic(
469
+ api_key=api,
470
  )
471
+ try:
472
+ message = client.messages.create(
473
+ model="claude-3-5-sonnet-20240620",
474
+ max_tokens=1024,
475
+ messages=[
476
+ {"role": "user", "content": "Hello, Claude"}
477
+ ]
478
+ )
479
+ gr.Info("Valid API")
480
+ valid_api = api
481
+
482
+ except anthropic.AuthenticationError:
483
+ gr.Warning("Invalid API!")
484
+ valid_api = ""
485
+
486
+ except anthropic.BadRequestError:
487
+ gr.Warning("Invalid API!")
488
+ valid_api = ""
489
+
490
+ except anthropic.PermissionDeniedError:
491
+ gr.Warning("Invalid API!")
492
+ valid_api = ""
493
+
494
+ except anthropic.RateLimitError:
495
+ gr.Warning("Invalid API!")
496
+ valid_api = ""
497
+
498
+
499
+ def generate_out(prompt, vp_pos, vp_neg, slider, example_prompt, gallery, num_inference_steps, seed, randomize_seed):
500
+ if vp_pos == "" and vp_neg == "":
501
+ gr.Warning("Visual preference is empty.", duration=10)
502
+
503
+ return generate(prompt, vp_pos, vp_neg, slider, example_prompt, gallery, num_inference_steps, seed, randomize_seed)
504
+
505
+ @spaces.GPU(duration=45)
506
+ def generate(prompt, vp_pos, vp_neg, slider, example_prompt, gallery, num_inference_steps, seed, randomize_seed):
507
+ if vp_pos == "" and vp_neg == "":
508
+ slider = 0
509
+
510
+ for filter in word_list:
511
+ if re.search(rf"\b{filter}\b", prompt):
512
+ raise gr.Error("Please try again with a different prompt")
513
+ if re.search(rf"\b{filter}\b", vp_pos) or re.search(rf"\b{filter}\b", vp_neg):
514
+ raise gr.Error("Please try again with a different visual preference")
515
+
516
+ if vp_pos != "":
517
+ vp_pos = vp_pos.split(", ")
518
+ random.shuffle(vp_pos)
519
+ vp_pos = ", ".join(vp_pos)
520
+
521
+ if vp_neg != "":
522
+ vp_neg = vp_neg.split(", ")
523
+ random.shuffle(vp_neg)
524
+ vp_neg = ", ".join(vp_neg)
525
+
526
+ if randomize_seed:
527
+ seed = random.randint(0, MAX_SEED)
528
+
529
+ generator = torch.Generator().manual_seed(seed)
530
+
531
+ if prompt is None:
532
+ promtpt = ""
533
+
534
+ image = pipe(prompt=prompt,
535
+ num_inference_steps=num_inference_steps,
536
+ vp_pos=vp_pos,
537
+ vp_neg=vp_neg,
538
+ vp_degree_pos=slider,
539
+ vp_degree_neg=slider,
540
+ generator=generator
541
+ ).images[0]
542
+
543
+ global example_prompts, examples
544
+ if prompt in example_prompts:
545
+ while example_prompts[0] != prompt:
546
+ example_prompts.append(example_prompts[0])
547
+ example_prompts = example_prompts[1:]
548
+
549
+ example_prompt = gr.Markdown(f"Prompt: {example_prompts[0]}")
550
+ if len(examples[example_prompts[0]]) == 10:
551
+ examples[example_prompts[0]] = examples[example_prompts[0]][:-1]
552
+
553
+ examples[example_prompts[0]].append(image)
554
+ gallery = gr.Gallery(
555
+ value=examples[example_prompts[0]],
556
+ label="",
557
+ show_label=False,
558
+ columns=[5],
559
+ rows=[2],
560
+ object_fit="contain",
561
+ height=500)
562
+
563
+ return image, example_prompt, gallery
564
+
565
+ def change_vp(extract_vp):
566
+ return
567
+
568
+ def upload_file(files):
569
+ global mioo
570
+ file_path = [file.name for file in files][0]
571
+ comment_images = [file_path] + comment_images
572
+
573
+ next_comment = ""
574
+ return gr.Image(value=mioo[0], label=f"image {0+1}/{len(mioo)}", show_label=True), gr.Text(label="Comment", show_label=False, lines=4, max_lines=5, placeholder="Enter your comment. The more detailed the better.", value=next_comment, container=False)
575
+
576
+ def next_prompt():
577
+ global example_prompts, examples
578
+ example_prompts.append(example_prompts[0])
579
+ example_prompts = example_prompts[1:]
580
 
581
  example_prompt = gr.Markdown(f"Prompt: {example_prompts[0]}")
582
+ gallery = gr.Gallery(
583
+ value=examples[example_prompts[0]],
584
+ label="",
585
+ show_label=False,
586
+ columns=[5],
587
+ rows=[2],
588
+ object_fit="contain",
589
+ height=500)
590
+
591
+ return example_prompt, gallery
592
 
593
+ def previous_prompt():
594
+ global example_prompts, examples
595
+ example_prompts = example_prompts[::-1]
596
+ example_prompts.append(example_prompts[0])
597
+ example_prompts = example_prompts[1:]
598
+ example_prompts = example_prompts[::-1]
599
+
600
+ example_prompt = gr.Markdown(f"Prompt: {example_prompts[0]}")
601
  gallery = gr.Gallery(
602
  value=examples[example_prompts[0]],
603
  label="",
 
607
  object_fit="contain",
608
  height=500)
609
 
610
+ return example_prompt, gallery
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
611
 
612
+ ###############################################
613
  with gr.Column(elem_id="title-container"):
614
  gr.Markdown(f"""
615
  # **ViPer: Visual Personalization of Generative Models via Individual Preference Learning**
 
648
  value="I adore the blue and greenish-blue palette, blue Dianne, and dark colors of this image. I also appreciate the Hergé inspiration in this artwork. However, I would have preferred a more complex and adventurous concept rather than a simple landscape. I wish it was more surreal and creepy.",
649
  )
650
 
651
+ comment_image = gr.Image(value=mioo[0], label=f"image {0+1}/{len(mioo)}", show_label=True)
652
 
653
  comment = gr.Text(
654
  label="Comment",
 
668
 
669
  with gr.Row():
670
  upload_button = gr.UploadButton("Click to upload images 📤", file_types=["image"], file_count="multiple")
671
+ clear_botton = gr.Button("Clear comments 🗑", interactive=False)
672
 
673
  with gr.Accordion("Enter Claude API (optional)", open=False):
674
  gr.Markdown("By default, we extract visual preferences from user comments using a fine-tuned HuggingFaceM4/idefics2-8b model. Optionally, you can experiment with using claude-3-5-sonnet for visual preference extraction by entering your API key below.")
 
681
 
682
  api_button = gr.Button("Enter", scale=0)
683
 
684
+ extract_vp_botton = gr.Button(f"Extract visual preference from {0} comments", interactive=False, variant="primary")
685
 
686
  with gr.Column(elem_id="gen-container"):
687
  positive_extracted_vp = gr.Textbox(
 
756
 
757
  submit_comment_button.click(
758
  fn = submit_comment,
759
+ inputs = [comment, comments, comment_images, image_index],
760
+ outputs = [comment_image, comment, extract_vp_botton, clear_botton, comments, comment_images, image_index]
761
  )
762
 
763
  previous_image_botton.click(
764
  fn = previous_image,
765
+ inputs = [comments, comment_images, image_index],
766
+ outputs = [comment_image, comment, comments, comment_images, image_index]
767
  )
768
 
769
  next_image_botton.click(
770
  fn = next_image,
771
+ inputs = [comments, comment_images, image_index],
772
+ outputs = [comment_image, comment, comments, comment_images, image_index]
773
  )
774
 
775
  extract_vp_botton.click(
776
  fn = extract_vp,
777
+ inputs = [comments],
778
+ outputs = [positive_extracted_vp, negative_extracted_vp, run_button, comments]
779
  )
780
 
781
  api_button.click(
 
804
 
805
  clear_botton.click(
806
  fn = clear_comments,
807
+ inputs = [comments],
808
+ outputs = [extract_vp_botton, clear_botton, comments]
 
 
 
 
 
 
809
  )
810
 
811
  next_prompt_button.click(
 
820
  outputs = [example_prompt, gallery]
821
  )
822
 
823
+ upload_button.upload(
824
+ upload_file,
825
+ upload_button,
826
+ [comment_image, comment]
827
+ )
828
+
829
  demo.launch(share=True)