Singularity666 commited on
Commit
883703e
·
verified ·
1 Parent(s): d7e1d5b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -69
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
- MODEL_NAME = "runwayml/stable-diffusion-v1-5"
9
- OUTPUT_DIR = "/home/user/app/stable_diffusion_weights/custom_model"
 
10
 
11
- def fine_tune(instance_prompt, image1, image2=None):
12
- instance_data_dir = "/home/user/app/instance_images"
13
-
14
- try:
15
- if os.path.exists(instance_data_dir):
16
- shutil.rmtree(instance_data_dir)
17
- os.makedirs(instance_data_dir, exist_ok=True)
18
-
19
- image1.save(os.path.join(instance_data_dir, "instance_0.png"))
20
- if image2 is not None:
21
- image2.save(os.path.join(instance_data_dir, "instance_1.png"))
22
-
23
- fine_tune_model(instance_data_dir, instance_prompt, MODEL_NAME, OUTPUT_DIR)
24
- return "Model fine-tuning complete."
25
- except Exception as e:
26
- return str(e)
27
-
28
- def generate_images(prompt, num_samples, height, width, num_inference_steps, guidance_scale):
29
- try:
30
- if not os.path.exists(OUTPUT_DIR):
31
- return "The model path does not exist."
32
-
33
- pipe = StableDiffusionPipeline.from_pretrained(OUTPUT_DIR, safety_checker=None, torch_dtype=torch.float32).to("cpu")
34
- pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
35
-
36
- with torch.autocast("cpu"), torch.inference_mode():
37
- images = pipe(
38
- prompt, height=height, width=width, num_images_per_prompt=num_samples,
39
- num_inference_steps=num_inference_steps, guidance_scale=guidance_scale
40
- ).images
41
-
42
- return images
43
- except Exception as e:
44
- return str(e)
45
-
46
- def gradio_app():
47
- with gr.Blocks() as demo:
48
- with gr.Tab("Fine-Tune Model"):
49
- with gr.Row():
50
- with gr.Column():
51
- instance_prompt = gr.Textbox(label="Instance Prompt")
52
- image1 = gr.Image(label="Upload Image 1", type="pil")
53
- image2 = gr.Image(label="Upload Image 2 (Optional)", type="pil")
54
- fine_tune_button = gr.Button("Fine-Tune Model")
55
- output_text = gr.Textbox(label="Output")
56
- fine_tune_button.click(fine_tune, inputs=[instance_prompt, image1, image2], outputs=output_text)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
- with gr.Tab("Generate Images"):
59
- with gr.Row():
60
- with gr.Column():
61
- prompt = gr.Textbox(label="Prompt")
62
- num_samples = gr.Number(label="Number of Samples", value=1)
63
- guidance_scale = gr.Number(label="Guidance Scale", value=7.5)
64
- height = gr.Number(label="Height", value=512)
65
- width = gr.Number(label="Width", value=512)
66
- num_inference_steps = gr.Slider(label="Steps", value=50, minimum=1, maximum=100)
67
- generate_button = gr.Button("Generate Images")
68
- with gr.Column():
69
- gallery = gr.Gallery(label="Generated Images")
70
- generate_button.click(generate_images, inputs=[prompt, num_samples, height, width, num_inference_steps, guidance_scale], outputs=gallery)
 
 
 
 
 
71
 
72
- demo.launch()
 
 
 
 
 
 
 
 
 
73
 
74
- if __name__ == "__main__":
75
- gradio_app()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()