Geek7 commited on
Commit
096155b
·
verified ·
1 Parent(s): c8df413

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -148
app.py CHANGED
@@ -1,150 +1,45 @@
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()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import torch
3
+ from diffusers import AutoPipelineForImage2Image
4
+ from diffusers.utils import load_image, make_image_grid
5
+ from PIL import Image
6
+ import requests
7
+ from io import BytesIO
8
+
9
+ # Load the pipeline
10
+ pipeline = AutoPipelineForImage2Image.from_pretrained(
11
+ "stabilityai/stable-diffusion-xl-refiner-1.0",
12
+ torch_dtype=torch.float16,
13
+ variant="fp16",
14
+ use_safetensors=True
15
+ )
16
+
17
+ # Offload model to reduce memory usage
18
+ pipeline.enable_model_cpu_offload()
19
+
20
+ # Function to load the initial image from a URL
21
+ def load_init_image(url):
22
+ response = requests.get(url)
23
+ return Image.open(BytesIO(response.content))
24
+
25
+ # Gradio function for image generation
26
+ def generate_image(prompt, image_url, strength):
27
+ init_image = load_init_image(image_url) # Load the initial image from the URL
28
+ result_image = pipeline(prompt, image=init_image, strength=strength).images[0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
+ # Display both the initial and result images side by side
31
+ grid_image = make_image_grid([init_image, result_image], rows=1, cols=2)
32
+ return grid_image
33
+
34
+ # Gradio interface
35
+ gr.Interface(
36
+ fn=generate_image,
37
+ inputs=[
38
+ gr.Textbox(lines=1, label="Prompt", placeholder="Enter the image description prompt"),
39
+ gr.Textbox(lines=1, label="Image URL", placeholder="Enter the URL of the initial image"),
40
+ gr.Slider(0.0, 1.0, value=0.5, label="Strength"),
41
+ ],
42
+ outputs=gr.Image(label="Image Comparison"),
43
+ title="Stable Diffusion XL Refiner - Image to Image",
44
+ description="Generate an image transformation from an initial image and a text prompt using the Stable Diffusion XL Refiner model.",
45
+ ).launch()