Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,75 +1,129 @@
|
|
1 |
-
import gradio as gr
|
2 |
import os
|
3 |
-
import shutil
|
4 |
-
from main import fine_tune_model
|
5 |
-
from diffusers import StableDiffusionPipeline, DDIMScheduler
|
6 |
-
import torch
|
7 |
|
8 |
-
|
9 |
-
|
|
|
10 |
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
|
|
|
|
|
|
|
|
|
|
71 |
|
72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
73 |
|
74 |
-
|
75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
go_mgie(np.array(Image.open('./_input/0.jpg').convert('RGB')), 'make the frame red', 13331, 7.5, 1.5)
|
111 |
+
print('--init GO--')
|
112 |
+
|
113 |
+
with gr.Blocks() as app:
|
114 |
+
gr.Markdown(
|
115 |
+
"""
|
116 |
+
# MagiX: Edit Personalized Images using Gen AI
|
117 |
+
"""
|
118 |
+
)
|
119 |
+
with gr.Row(): inp, res = [gr.Image(height=384, width=384, label='Input Image', interactive=True),
|
120 |
+
gr.Image(height=384, width=384, label='Goal Image', interactive=True)]
|
121 |
+
with gr.Row(): txt, out = [gr.Textbox(label='Instruction', interactive=True),
|
122 |
+
gr.Textbox(label='Expressive Instruction', interactive=False)]
|
123 |
+
with gr.Row(): seed, cfg_txt, cfg_img = [gr.Number(value=13331, label='Seed', interactive=True),
|
124 |
+
gr.Number(value=7.5, label='Text CFG', interactive=True),
|
125 |
+
gr.Number(value=1.5, label='Image CFG', interactive=True)]
|
126 |
+
with gr.Row(): btn_sub = gr.Button('Submit')
|
127 |
+
btn_sub.click(fn=go_mgie, inputs=[inp, txt, seed, cfg_txt, cfg_img], outputs=[res, out])
|
128 |
+
|
129 |
+
app.launch()
|