Update app.py
Browse files
app.py
CHANGED
@@ -1,53 +1,150 @@
|
|
1 |
-
import
|
2 |
-
|
3 |
-
|
4 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
import gradio as gr
|
6 |
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
|
18 |
-
|
19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
20 |
|
21 |
-
|
22 |
-
edited_image = pipe(
|
23 |
-
instruction, image=input_image, guidance_scale=text_cfg_scale,
|
24 |
-
image_guidance_scale=image_cfg_scale, num_inference_steps=steps,
|
25 |
-
generator=generator
|
26 |
-
).images[0]
|
27 |
-
|
28 |
-
return edited_image
|
29 |
-
|
30 |
-
# Gradio interface
|
31 |
-
def inference(input_image, instruction, steps=50, randomize_seed=True, seed=0, text_cfg_scale=7.5, image_cfg_scale=1.5):
|
32 |
-
edited_image = generate(input_image, instruction, steps, randomize_seed, seed, text_cfg_scale, image_cfg_scale)
|
33 |
-
return edited_image
|
34 |
-
|
35 |
-
# Gradio app setup
|
36 |
-
interface = gr.Interface(
|
37 |
-
fn=inference,
|
38 |
-
inputs=[
|
39 |
-
gr.Image(type="pil", label="Upload Image"),
|
40 |
-
gr.Textbox(lines=1, label="Instruction"),
|
41 |
-
gr.Slider(20, 100, value=50, step=1, label="Steps"),
|
42 |
-
gr.Checkbox(value=True, label="Randomize Seed"),
|
43 |
-
gr.Number(value=random.randint(0, 10000), label="Seed"),
|
44 |
-
gr.Slider(1.0, 10.0, value=7.5, step=0.1, label="Text CFG"),
|
45 |
-
gr.Slider(0.5, 2.0, value=1.5, step=0.1, label="Image CFG")
|
46 |
-
],
|
47 |
-
outputs=gr.Image(label="Edited Image"),
|
48 |
-
title="InstructPix2Pix Image Editing",
|
49 |
-
description="Upload an image and provide an instruction to edit the image using Stable Diffusion."
|
50 |
-
)
|
51 |
-
|
52 |
-
if __name__ == "__main__":
|
53 |
-
interface.launch()
|
|
|
1 |
+
import os
|
2 |
+
|
3 |
+
import huggingface_hub, spaces
|
4 |
+
huggingface_hub.snapshot_download(repo_id='tsujuifu/ml-mgie', repo_type='model', local_dir='_ckpt', local_dir_use_symlinks=False)
|
5 |
+
os.system('ls _ckpt')
|
6 |
+
|
7 |
+
from PIL import Image
|
8 |
+
|
9 |
+
import numpy as np
|
10 |
+
import torch as T
|
11 |
+
import transformers, diffusers
|
12 |
+
|
13 |
+
from conversation import conv_templates
|
14 |
+
from mgie_llava import *
|
15 |
+
|
16 |
import gradio as gr
|
17 |
|
18 |
+
def crop_resize(f, sz=512):
|
19 |
+
w, h = f.size
|
20 |
+
if w>h:
|
21 |
+
p = (w-h)//2
|
22 |
+
f = f.crop([p, 0, p+h, h])
|
23 |
+
elif h>w:
|
24 |
+
p = (h-w)//2
|
25 |
+
f = f.crop([0, p, w, p+w])
|
26 |
+
f = f.resize([sz, sz])
|
27 |
+
return f
|
28 |
+
def remove_alter(s): # hack expressive instruction
|
29 |
+
if 'ASSISTANT:' in s: s = s[s.index('ASSISTANT:')+10:].strip()
|
30 |
+
if '</s>' in s: s = s[:s.index('</s>')].strip()
|
31 |
+
if 'alternative' in s.lower(): s = s[:s.lower().index('alternative')]
|
32 |
+
if '[IMG0]' in s: s = s[:s.index('[IMG0]')]
|
33 |
+
s = '.'.join([s.strip() for s in s.split('.')[:2]])
|
34 |
+
if s[-1]!='.': s += '.'
|
35 |
+
return s.strip()
|
36 |
+
|
37 |
+
DEFAULT_IMAGE_TOKEN = '<image>'
|
38 |
+
DEFAULT_IMAGE_PATCH_TOKEN = '<im_patch>'
|
39 |
+
DEFAULT_IM_START_TOKEN = '<im_start>'
|
40 |
+
DEFAULT_IM_END_TOKEN = '<im_end>'
|
41 |
+
PATH_LLAVA = '_ckpt/LLaVA-7B-v1'
|
42 |
+
|
43 |
+
tokenizer = transformers.AutoTokenizer.from_pretrained(PATH_LLAVA)
|
44 |
+
model = LlavaLlamaForCausalLM.from_pretrained(PATH_LLAVA, low_cpu_mem_usage=True, torch_dtype=T.float16, use_cache=True).cuda()
|
45 |
+
image_processor = transformers.CLIPImageProcessor.from_pretrained(model.config.mm_vision_tower, torch_dtype=T.float16)
|
46 |
+
|
47 |
+
tokenizer.padding_side = 'left'
|
48 |
+
tokenizer.add_tokens(['[IMG0]', '[IMG1]', '[IMG2]', '[IMG3]', '[IMG4]', '[IMG5]', '[IMG6]', '[IMG7]'], special_tokens=True)
|
49 |
+
model.resize_token_embeddings(len(tokenizer))
|
50 |
+
ckpt = T.load('_ckpt/mgie_7b/mllm.pt', map_location='cpu')
|
51 |
+
model.load_state_dict(ckpt, strict=False)
|
52 |
+
|
53 |
+
mm_use_im_start_end = getattr(model.config, 'mm_use_im_start_end', False)
|
54 |
+
tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
|
55 |
+
if mm_use_im_start_end: tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
|
56 |
+
|
57 |
+
vision_tower = model.get_model().vision_tower[0]
|
58 |
+
vision_tower = transformers.CLIPVisionModel.from_pretrained(vision_tower.config._name_or_path, torch_dtype=T.float16, low_cpu_mem_usage=True).cuda()
|
59 |
+
model.get_model().vision_tower[0] = vision_tower
|
60 |
+
vision_config = vision_tower.config
|
61 |
+
vision_config.im_patch_token = tokenizer.convert_tokens_to_ids([DEFAULT_IMAGE_PATCH_TOKEN])[0]
|
62 |
+
vision_config.use_im_start_end = mm_use_im_start_end
|
63 |
+
if mm_use_im_start_end: vision_config.im_start_token, vision_config.im_end_token = tokenizer.convert_tokens_to_ids([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN])
|
64 |
+
image_token_len = (vision_config.image_size//vision_config.patch_size)**2
|
65 |
|
66 |
+
_ = model.eval()
|
67 |
+
|
68 |
+
pipe = diffusers.StableDiffusionInstructPix2PixPipeline.from_pretrained('timbrooks/instruct-pix2pix', torch_dtype=T.float16).to('cuda')
|
69 |
+
pipe.set_progress_bar_config(disable=True)
|
70 |
+
pipe.unet.load_state_dict(T.load('_ckpt/mgie_7b/unet.pt', map_location='cpu'))
|
71 |
+
print('--init MGIE--')
|
72 |
+
|
73 |
+
@spaces.GPU(enable_queue=True)
|
74 |
+
def go_mgie(img, txt, seed, cfg_txt, cfg_img):
|
75 |
+
EMB = ckpt['emb'].cuda()
|
76 |
+
with T.inference_mode(): NULL = model.edit_head(T.zeros(1, 8, 4096).half().to('cuda'), EMB)
|
77 |
+
|
78 |
+
img, seed = crop_resize(Image.fromarray(img).convert('RGB')), int(seed)
|
79 |
+
inp = img
|
80 |
+
|
81 |
+
img = image_processor.preprocess(img, return_tensors='pt')['pixel_values'][0]
|
82 |
+
txt = "what will this image be like if '%s'"%(txt)
|
83 |
+
txt = txt+'\n'+DEFAULT_IM_START_TOKEN+DEFAULT_IMAGE_PATCH_TOKEN*image_token_len+DEFAULT_IM_END_TOKEN
|
84 |
+
conv = conv_templates['vicuna_v1_1'].copy()
|
85 |
+
conv.append_message(conv.roles[0], txt), conv.append_message(conv.roles[1], None)
|
86 |
+
txt = conv.get_prompt()
|
87 |
+
txt = tokenizer(txt)
|
88 |
+
txt, mask = T.as_tensor(txt['input_ids']), T.as_tensor(txt['attention_mask'])
|
89 |
+
|
90 |
+
with T.inference_mode():
|
91 |
+
_ = model.cuda()
|
92 |
+
out = model.generate(txt.unsqueeze(dim=0).cuda(), images=img.half().unsqueeze(dim=0).cuda(), attention_mask=mask.unsqueeze(dim=0).cuda(),
|
93 |
+
do_sample=False, max_new_tokens=96, num_beams=1, no_repeat_ngram_size=3,
|
94 |
+
return_dict_in_generate=True, output_hidden_states=True)
|
95 |
+
out, hid = out['sequences'][0].tolist(), T.cat([x[-1] for x in out['hidden_states']], dim=1)[0]
|
96 |
+
|
97 |
+
if 32003 in out: p = out.index(32003)-1
|
98 |
+
else: p = len(hid)-9
|
99 |
+
p = min(p, len(hid)-9)
|
100 |
+
hid = hid[p:p+8]
|
101 |
+
|
102 |
+
out = remove_alter(tokenizer.decode(out))
|
103 |
+
_ = model.cuda()
|
104 |
+
emb = model.edit_head(hid.unsqueeze(dim=0), EMB)
|
105 |
+
res = pipe(image=inp, prompt_embeds=emb, negative_prompt_embeds=NULL,
|
106 |
+
generator=T.Generator(device='cuda').manual_seed(seed), guidance_scale=cfg_txt, image_guidance_scale=cfg_img).images[0]
|
107 |
+
|
108 |
+
return res, out
|
109 |
+
|
110 |
+
def go_example(seed, cfg_txt, cfg_img):
|
111 |
+
ins = ['make the frame red', 'turn the day into night', 'give him a beard', 'make cottage a mansion',
|
112 |
+
'remove yellow object from dogs paws', 'change the hair from red to blue', 'remove the text', 'increase the image contrast',
|
113 |
+
'remove the people in the background', 'please make this photo professional looking', 'darken the image, sharpen it', 'photoshop the girl out',
|
114 |
+
'make more brightness', 'take away the brown filter form the image', 'add more contrast to simulate more light', 'dark on rgb',
|
115 |
+
'make the face happy', 'change view as ocean', 'replace basketball with soccer ball', 'let the floor be made of wood']
|
116 |
+
i = T.randint(len(ins), (1, )).item()
|
117 |
|
118 |
+
return './_input/%d.jpg'%(i), ins[i], seed, cfg_txt, cfg_img
|
119 |
+
|
120 |
+
go_mgie(np.array(Image.open('./_input/0.jpg').convert('RGB')), 'make the frame red', 13331, 7.5, 1.5)
|
121 |
+
print('--init GO--')
|
122 |
+
|
123 |
+
with gr.Blocks() as app:
|
124 |
+
gr.Markdown(
|
125 |
+
"""
|
126 |
+
# [ICLR\'24] Guiding Instruction-based Image Editing via Multimodal Large Language Models<br>
|
127 |
+
🔔 this demo is hosted by [Tsu-Jui Fu](https://github.com/tsujuifu/pytorch_mgie)<br>
|
128 |
+
🔔 a black image means that the output did not pass the [safety checker](https://huggingface.co/CompVis/stable-diffusion-safety-checker)<br>
|
129 |
+
🔔 if the building process takes too long, please try refreshing the page
|
130 |
+
"""
|
131 |
+
)
|
132 |
+
with gr.Row(): inp, res = [gr.Image(height=384, width=384, label='Input Image', interactive=True),
|
133 |
+
gr.Image(height=384, width=384, label='Goal Image', interactive=True)]
|
134 |
+
with gr.Row(): txt, out = [gr.Textbox(label='Instruction', interactive=True),
|
135 |
+
gr.Textbox(label='Expressive Instruction', interactive=False)]
|
136 |
+
with gr.Row(): seed, cfg_txt, cfg_img = [gr.Number(value=13331, label='Seed', interactive=True),
|
137 |
+
gr.Number(value=7.5, label='Text CFG', interactive=True),
|
138 |
+
gr.Number(value=1.5, label='Image CFG', interactive=True)]
|
139 |
+
with gr.Row(): btn_exp, btn_sub = [gr.Button('More Example'), gr.Button('Submit')]
|
140 |
+
btn_exp.click(fn=go_example, inputs=[seed, cfg_txt, cfg_img], outputs=[inp, txt, seed, cfg_txt, cfg_img])
|
141 |
+
btn_sub.click(fn=go_mgie, inputs=[inp, txt, seed, cfg_txt, cfg_img], outputs=[res, out])
|
142 |
+
|
143 |
+
ins = ['make the frame red', 'turn the day into night', 'give him a beard', 'make cottage a mansion',
|
144 |
+
'remove yellow object from dogs paws', 'change the hair from red to blue', 'remove the text', 'increase the image contrast',
|
145 |
+
'remove the people in the background', 'please make this photo professional looking', 'darken the image, sharpen it', 'photoshop the girl out',
|
146 |
+
'make more brightness', 'take away the brown filter form the image', 'add more contrast to simulate more light', 'dark on rgb',
|
147 |
+
'make the face happy', 'change view as ocean', 'replace basketball with soccer ball', 'let the floor be made of wood']
|
148 |
+
gr.Examples(examples=[['./_input/%d.jpg'%(i), ins[i]] for i in [1, 5, 8, 14, 16]], inputs=[inp, txt])
|
149 |
|
150 |
+
app.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|