Upload mgie.py with huggingface_hub
Browse files
mgie.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
from tqdm.auto import tqdm
|
| 4 |
+
|
| 5 |
+
from PIL import Image
|
| 6 |
+
|
| 7 |
+
import torch as T
|
| 8 |
+
import transformers, diffusers
|
| 9 |
+
|
| 10 |
+
from llava.conversation import conv_templates
|
| 11 |
+
from llava.model import *
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def read_json(file_path):
|
| 15 |
+
with open(file_path, 'r', encoding='utf-8') as file:
|
| 16 |
+
data = json.load(file)
|
| 17 |
+
return data
|
| 18 |
+
|
| 19 |
+
def write_json(file_path, data):
|
| 20 |
+
with open(file_path, 'w', encoding='utf-8') as file:
|
| 21 |
+
json.dump(data, file, ensure_ascii=False, indent=4)
|
| 22 |
+
|
| 23 |
+
def crop_resize(f, sz=512):
|
| 24 |
+
w, h = f.size
|
| 25 |
+
if w>h:
|
| 26 |
+
p = (w-h)//2
|
| 27 |
+
f = f.crop([p, 0, p+h, h])
|
| 28 |
+
elif h>w:
|
| 29 |
+
p = (h-w)//2
|
| 30 |
+
f = f.crop([0, p, w, p+w])
|
| 31 |
+
f = f.resize([sz, sz])
|
| 32 |
+
return f
|
| 33 |
+
def remove_alter(s): # hack expressive instruction
|
| 34 |
+
if 'ASSISTANT:' in s: s = s[s.index('ASSISTANT:')+10:].strip()
|
| 35 |
+
if '</s>' in s: s = s[:s.index('</s>')].strip()
|
| 36 |
+
if 'alternative' in s.lower(): s = s[:s.lower().index('alternative')]
|
| 37 |
+
if '[IMG0]' in s: s = s[:s.index('[IMG0]')]
|
| 38 |
+
s = '.'.join([s.strip() for s in s.split('.')[:2]])
|
| 39 |
+
if s[-1]!='.': s += '.'
|
| 40 |
+
return s.strip()
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
DEFAULT_IMAGE_TOKEN = '<image>'
|
| 44 |
+
DEFAULT_IMAGE_PATCH_TOKEN = '<im_patch>'
|
| 45 |
+
DEFAULT_IM_START_TOKEN = '<im_start>'
|
| 46 |
+
DEFAULT_IM_END_TOKEN = '<im_end>'
|
| 47 |
+
PATH_LLAVA = './_ckpt/LLaVA-7B-v1'
|
| 48 |
+
|
| 49 |
+
tokenizer = transformers.AutoTokenizer.from_pretrained(PATH_LLAVA)
|
| 50 |
+
model = LlavaLlamaForCausalLM.from_pretrained(PATH_LLAVA, low_cpu_mem_usage=True, torch_dtype=T.float16, use_cache=True).cuda()
|
| 51 |
+
image_processor = transformers.CLIPImageProcessor.from_pretrained(model.config.mm_vision_tower, torch_dtype=T.float16)
|
| 52 |
+
|
| 53 |
+
tokenizer.padding_side = 'left'
|
| 54 |
+
tokenizer.add_tokens(['[IMG0]', '[IMG1]', '[IMG2]', '[IMG3]', '[IMG4]', '[IMG5]', '[IMG6]', '[IMG7]'], special_tokens=True)
|
| 55 |
+
model.resize_token_embeddings(len(tokenizer))
|
| 56 |
+
ckpt = T.load('./_ckpt/mgie_7b/mllm.pt', map_location='cpu')
|
| 57 |
+
model.load_state_dict(ckpt, strict=False)
|
| 58 |
+
|
| 59 |
+
mm_use_im_start_end = getattr(model.config, 'mm_use_im_start_end', False)
|
| 60 |
+
tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
|
| 61 |
+
if mm_use_im_start_end: tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
|
| 62 |
+
|
| 63 |
+
vision_tower = model.get_model().vision_tower[0]
|
| 64 |
+
vision_tower = transformers.CLIPVisionModel.from_pretrained(vision_tower.config._name_or_path, torch_dtype=T.float16, low_cpu_mem_usage=True).cuda()
|
| 65 |
+
model.get_model().vision_tower[0] = vision_tower
|
| 66 |
+
vision_config = vision_tower.config
|
| 67 |
+
vision_config.im_patch_token = tokenizer.convert_tokens_to_ids([DEFAULT_IMAGE_PATCH_TOKEN])[0]
|
| 68 |
+
vision_config.use_im_start_end = mm_use_im_start_end
|
| 69 |
+
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])
|
| 70 |
+
image_token_len = (vision_config.image_size//vision_config.patch_size)**2
|
| 71 |
+
|
| 72 |
+
_ = model.eval()
|
| 73 |
+
EMB = ckpt['emb'].cuda()
|
| 74 |
+
with T.inference_mode(): NULL = model.edit_head(T.zeros(1, 8, 4096).half().to('cuda'), EMB)
|
| 75 |
+
print('NULL:', NULL.shape)
|
| 76 |
+
|
| 77 |
+
pipe = diffusers.StableDiffusionInstructPix2PixPipeline.from_pretrained('timbrooks/instruct-pix2pix', torch_dtype=T.float16, safety_checker=None).to('cuda')
|
| 78 |
+
pipe.set_progress_bar_config(disable=True)
|
| 79 |
+
pipe.unet.load_state_dict(T.load('./_ckpt/mgie_7b/unet.pt', map_location='cpu'))
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
SEED = 13331
|
| 83 |
+
|
| 84 |
+
# ins = ['make the frame red', 'turn the day into night', 'give him a beard', 'make cottage a mansion',
|
| 85 |
+
# 'remove yellow object from dogs paws', 'change the hair from red to blue', 'remove the text', 'increase the image contrast',
|
| 86 |
+
# 'remove the people in the background', 'please make this photo professional looking', 'darken the image, sharpen it', 'photoshop the girl out',
|
| 87 |
+
# 'make more brightness', 'take away the brown filter form the image', 'add more contrast to simulate more light', 'dark on rgb',
|
| 88 |
+
# 'make the face happy', 'change view as ocean', 'replace basketball with soccer ball', 'let the floor be made of wood']
|
| 89 |
+
|
| 90 |
+
data_path = '/home/zbz5349/WorkSpace/aigeeks/Qwen2.5-VL/magicbrush_dataset/gen_new.json'
|
| 91 |
+
save_image = '/home/zbz5349/WorkSpace/aigeeks/Qwen2.5-VL/magicbrush_dataset/result_images'
|
| 92 |
+
data = read_json(data_path)
|
| 93 |
+
for i in tqdm(range(2)):
|
| 94 |
+
img_path = data[i]["content"][0]["image"]
|
| 95 |
+
txt = data[i]["result"]
|
| 96 |
+
img = Image.open(img_path)
|
| 97 |
+
img, txt = Image.open('_input/%d.jpg'%(i)).convert('RGB'), ins[i]
|
| 98 |
+
|
| 99 |
+
#img = image_processor.preprocess(img, return_tensors='pt')['pixel_values'][0]
|
| 100 |
+
txt = "what will this image be like if '%s'"%(txt)
|
| 101 |
+
txt = txt+'\n'+DEFAULT_IM_START_TOKEN+DEFAULT_IMAGE_PATCH_TOKEN*image_token_len+DEFAULT_IM_END_TOKEN
|
| 102 |
+
conv = conv_templates['vicuna_v1_1'].copy()
|
| 103 |
+
conv.append_message(conv.roles[0], txt), conv.append_message(conv.roles[1], None)
|
| 104 |
+
txt = conv.get_prompt()
|
| 105 |
+
txt = tokenizer(txt)
|
| 106 |
+
txt, mask = T.as_tensor(txt['input_ids']), T.as_tensor(txt['attention_mask'])
|
| 107 |
+
|
| 108 |
+
with T.inference_mode():
|
| 109 |
+
out = model.generate(txt.unsqueeze(dim=0).cuda(), images=img.half().unsqueeze(dim=0).cuda(), attention_mask=mask.unsqueeze(dim=0).cuda(),
|
| 110 |
+
do_sample=False, max_new_tokens=96, num_beams=1, no_repeat_ngram_size=3,
|
| 111 |
+
return_dict_in_generate=True, output_hidden_states=True)
|
| 112 |
+
out, hid = out['sequences'][0].tolist(), T.cat([x[-1] for x in out['hidden_states']], dim=1)[0]
|
| 113 |
+
|
| 114 |
+
p = min(out.index(32003)-1 if 32003 in out else len(hid)-9, len(hid)-9)
|
| 115 |
+
hid = hid[p:p+8]
|
| 116 |
+
|
| 117 |
+
out = remove_alter(tokenizer.decode(out))
|
| 118 |
+
emb = model.edit_head(hid.unsqueeze(dim=0), EMB)
|
| 119 |
+
res = pipe(image=Image.open('_input/%d.jpg'%(i)).convert('RGB'), prompt_embeds=emb, negative_prompt_embeds=NULL, generator=T.Generator(device='cuda').manual_seed(SEED)).images[0]
|
| 120 |
+
save_img_path = os.path.join(save_image, f{i}.png)
|
| 121 |
+
Image.save(save_img_path)
|