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