seawolf2357 commited on
Commit
8d1275c
·
verified ·
1 Parent(s): 24f2e4f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +222 -245
app.py CHANGED
@@ -1,290 +1,267 @@
1
- import sys
2
- sys.path.append('../')
 
 
3
 
4
- import spaces
 
5
 
6
- import torch
7
- import random
8
- import numpy as np
9
  from PIL import Image
10
-
11
  import gradio as gr
 
12
  from huggingface_hub import hf_hub_download
13
  from transformers import AutoModelForImageSegmentation
14
  from torchvision import transforms
15
 
16
  from pipeline import InstantCharacterFluxPipeline
17
 
18
- # global variable
 
 
19
  MAX_SEED = np.iinfo(np.int32).max
20
- device = "cuda" if torch.cuda.is_available() else "cpu"
21
- dtype = torch.float16 if str(device).__contains__("cuda") else torch.float32
22
-
23
- # pre-trained weights
24
- ip_adapter_path = hf_hub_download(repo_id="tencent/InstantCharacter", filename="instantcharacter_ip-adapter.bin")
25
- base_model = 'black-forest-labs/FLUX.1-dev'
26
- image_encoder_path = 'google/siglip-so400m-patch14-384'
27
- image_encoder_2_path = 'facebook/dinov2-giant'
28
- birefnet_path = 'ZhengPeng7/BiRefNet'
29
- makoto_style_lora_path = hf_hub_download(repo_id="InstantX/FLUX.1-dev-LoRA-Makoto-Shinkai", filename="Makoto_Shinkai_style.safetensors")
30
- ghibli_style_lora_path = hf_hub_download(repo_id="InstantX/FLUX.1-dev-LoRA-Ghibli", filename="ghibli_style.safetensors")
31
-
32
- # init InstantCharacter pipeline
33
- pipe = InstantCharacterFluxPipeline.from_pretrained(base_model, torch_dtype=torch.bfloat16)
 
 
 
 
 
 
 
 
34
  pipe.to(device)
35
-
36
- # load InstantCharacter
37
  pipe.init_adapter(
38
- image_encoder_path=image_encoder_path,
39
- image_encoder_2_path=image_encoder_2_path,
40
- subject_ipadapter_cfg=dict(subject_ip_adapter_path=ip_adapter_path, nb_token=1024),
 
41
  )
42
 
43
- # load matting model
44
- birefnet = AutoModelForImageSegmentation.from_pretrained(birefnet_path, trust_remote_code=True)
45
- birefnet.to('cuda')
46
- birefnet.eval()
47
- birefnet_transform_image = transforms.Compose([
 
 
48
  transforms.Resize((1024, 1024)),
49
  transforms.ToTensor(),
50
- transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
 
51
  ])
52
 
53
-
54
- def remove_bkg(subject_image):
55
-
56
- def infer_matting(img_pil):
57
- input_images = birefnet_transform_image(img_pil).unsqueeze(0).to('cuda')
58
-
59
- with torch.no_grad():
60
- preds = birefnet(input_images)[-1].sigmoid().cpu()
61
- pred = preds[0].squeeze()
62
- pred_pil = transforms.ToPILImage()(pred)
63
- mask = pred_pil.resize(img_pil.size)
64
- mask = np.array(mask)
65
- mask = mask[..., None]
66
- return mask
67
-
68
- def get_bbox_from_mask(mask, th=128):
69
- height, width = mask.shape[:2]
70
- x1, y1, x2, y2 = 0, 0, width - 1, height - 1
71
-
72
- sample = np.max(mask, axis=0)
73
- for idx in range(width):
74
- if sample[idx] >= th:
75
- x1 = idx
76
- break
77
-
78
- sample = np.max(mask[:, ::-1], axis=0)
79
- for idx in range(width):
80
- if sample[idx] >= th:
81
- x2 = width - 1 - idx
82
- break
83
-
84
- sample = np.max(mask, axis=1)
85
- for idx in range(height):
86
- if sample[idx] >= th:
87
- y1 = idx
88
- break
89
-
90
- sample = np.max(mask[::-1], axis=1)
91
- for idx in range(height):
92
- if sample[idx] >= th:
93
- y2 = height - 1 - idx
94
- break
95
-
96
- x1 = np.clip(x1, 0, width-1).round().astype(np.int32)
97
- y1 = np.clip(y1, 0, height-1).round().astype(np.int32)
98
- x2 = np.clip(x2, 0, width-1).round().astype(np.int32)
99
- y2 = np.clip(y2, 0, height-1).round().astype(np.int32)
100
-
101
- return [x1, y1, x2, y2]
102
-
103
- def pad_to_square(image, pad_value = 255, random = False):
104
- '''
105
- image: np.array [h, w, 3]
106
- '''
107
- H,W = image.shape[0], image.shape[1]
108
- if H == W:
109
- return image
110
-
111
- padd = abs(H - W)
112
- if random:
113
- padd_1 = int(np.random.randint(0,padd))
114
- else:
115
- padd_1 = int(padd / 2)
116
- padd_2 = padd - padd_1
117
-
118
- if H > W:
119
- pad_param = ((0,0),(padd_1,padd_2),(0,0))
120
- else:
121
- pad_param = ((padd_1,padd_2),(0,0),(0,0))
122
-
123
- image = np.pad(image, pad_param, 'constant', constant_values=pad_value)
124
- return image
125
-
126
- salient_object_mask = infer_matting(subject_image)[..., 0]
127
- x1, y1, x2, y2 = get_bbox_from_mask(salient_object_mask)
128
- subject_image = np.array(subject_image)
129
- salient_object_mask[salient_object_mask > 128] = 255
130
- salient_object_mask[salient_object_mask < 128] = 0
131
- sample_mask = np.concatenate([salient_object_mask[..., None]]*3, axis=2)
132
- obj_image = sample_mask / 255 * subject_image + (1 - sample_mask / 255) * 255
133
- crop_obj_image = obj_image[y1:y2, x1:x2]
134
- crop_pad_obj_image = pad_to_square(crop_obj_image, 255)
135
- subject_image = Image.fromarray(crop_pad_obj_image.astype(np.uint8))
136
- return subject_image
137
-
138
-
139
- def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
140
- if randomize_seed:
141
- seed = random.randint(0, MAX_SEED)
142
- return seed
143
 
144
  def get_example():
145
- case = [
146
- [
147
- "./assets/girl.jpg",
148
- "A girl is playing a guitar in street",
149
- 0.9,
150
- 'Makoto Shinkai style',
151
- ],
152
- [
153
- "./assets/boy.jpg",
154
- "A boy is riding a bike in snow",
155
- 0.9,
156
- 'Makoto Shinkai style',
157
- ],
158
  ]
159
- return case
160
-
161
- def run_for_examples(source_image, prompt, scale, style_mode):
162
-
163
- return create_image(
164
- input_image=source_image,
165
- prompt=prompt,
166
- scale=scale,
167
- guidance_scale=3.5,
168
- num_inference_steps=28,
169
- seed=123456,
170
- style_mode=style_mode,
171
- )
172
 
173
  @spaces.GPU
174
- def create_image(input_image,
175
- prompt,
176
- scale,
177
- guidance_scale,
178
- num_inference_steps,
179
- seed,
180
- style_mode=None):
181
-
182
  input_image = remove_bkg(input_image)
 
183
 
184
  if style_mode is None:
185
- images = pipe(
186
- prompt=prompt,
187
- num_inference_steps=num_inference_steps,
188
- guidance_scale=guidance_scale,
189
- width=1024,
190
- height=1024,
191
- subject_image=input_image,
192
- subject_scale=scale,
193
- generator=torch.manual_seed(seed),
194
- ).images
195
  else:
196
- if style_mode == 'Makoto Shinkai style':
197
- lora_file_path = makoto_style_lora_path
198
- trigger = 'Makoto Shinkai style'
199
- elif style_mode == 'Ghibli style':
200
- lora_file_path = ghibli_style_lora_path
201
- trigger = 'ghibli style'
202
-
203
- images = pipe.with_style_lora(
204
- lora_file_path=lora_file_path,
205
- trigger=trigger,
206
- prompt=prompt,
207
- num_inference_steps=num_inference_steps,
208
  guidance_scale=guidance_scale,
209
- width=1024,
210
- height=1024,
211
- subject_image=input_image,
212
- subject_scale=scale,
213
- generator=torch.manual_seed(seed),
214
- ).images
215
-
216
-
217
- return images
218
-
219
- # Description
220
- title = r"""
221
- <h1 align="center">InstantCharacter PLUS</h1>
222
- """
223
-
224
- description = r"""
225
- <b>Official 🤗 Gradio demo</b> for <a href='https://instantcharacter.github.io/' target='_blank'><b>InstantCharacter : Personalize Any Characters with a Scalable Diffusion Transformer Framework</b></a>.<br>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
226
  """
227
 
228
- article = r"""
229
- """
 
 
 
 
 
 
 
 
230
 
231
- block = gr.Blocks(css="footer {visibility: hidden}").queue(max_size=10, api_open=False)
232
- with block:
233
-
234
- # description
235
- gr.Markdown(title)
236
- gr.Markdown(description)
237
-
238
  with gr.Tabs():
239
- with gr.Row():
240
- with gr.Column():
241
-
242
- with gr.Row():
243
- with gr.Column():
244
- image_pil = gr.Image(label="Source Image", type='pil')
245
-
246
- prompt = gr.Textbox(label="Prompt", value="a character is riding a bike in snow")
247
-
248
- scale = gr.Slider(minimum=0, maximum=1.5, step=0.01,value=1.0, label="Scale")
249
- style_mode = gr.Dropdown(label='Style', choices=[None, 'Makoto Shinkai style', 'Ghibli style'], value='Makoto Shinkai style')
250
-
251
- with gr.Accordion(open=False, label="Advanced Options"):
252
- guidance_scale = gr.Slider(minimum=1,maximum=7.0, step=0.01,value=3.5, label="guidance scale")
253
- num_inference_steps = gr.Slider(minimum=5,maximum=50.0, step=1.0,value=28, label="num inference steps")
254
- seed = gr.Slider(minimum=-1000000, maximum=1000000, value=123456, step=1, label="Seed Value")
255
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
256
-
257
- generate_button = gr.Button("Generate Image")
258
-
259
- with gr.Column():
260
- generated_image = gr.Gallery(label="Generated Image")
261
-
262
- generate_button.click(
263
- fn=randomize_seed_fn,
264
- inputs=[seed, randomize_seed],
265
- outputs=seed,
266
- queue=False,
267
- api_name=False,
268
- ).then(
269
- fn=create_image,
270
- inputs=[image_pil,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
271
  prompt,
272
- scale,
273
  guidance_scale,
274
  num_inference_steps,
275
  seed,
276
  style_mode,
277
- ],
278
- outputs=[generated_image])
279
-
 
 
 
280
  gr.Examples(
281
  examples=get_example(),
282
  inputs=[image_pil, prompt, scale, style_mode],
 
283
  fn=run_for_examples,
284
- outputs=[generated_image],
285
  cache_examples=True,
286
  )
287
-
288
- gr.Markdown(article)
289
 
290
- block.launch()
 
 
 
 
 
1
+ # ==========================================================
2
+ # InstantCharacter PLUS – Stylish Gradio UI
3
+ # (기존 기능은 그대로, 테마 · 카드 레이아웃 · 그라데이션 배경 등 시각 강화)
4
+ # ==========================================================
5
 
6
+ import sys, os, random, numpy as np, torch
7
+ sys.path.append("../")
8
 
 
 
 
9
  from PIL import Image
10
+ import spaces
11
  import gradio as gr
12
+ from gradio.themes import Soft # ★ NEW
13
  from huggingface_hub import hf_hub_download
14
  from transformers import AutoModelForImageSegmentation
15
  from torchvision import transforms
16
 
17
  from pipeline import InstantCharacterFluxPipeline
18
 
19
+ # ─────────────────────────────
20
+ # 1 · Runtime / device
21
+ # ─────────────────────────────
22
  MAX_SEED = np.iinfo(np.int32).max
23
+ device = "cuda" if torch.cuda.is_available() else "cpu"
24
+ dtype = torch.float16 if device == "cuda" else torch.float32
25
+
26
+ # ─────────────────────────────
27
+ # 2 · Pre-trained weights
28
+ # ─────────────────────────────
29
+ ip_adapter_path = hf_hub_download("tencent/InstantCharacter",
30
+ "instantcharacter_ip-adapter.bin")
31
+ base_model = "black-forest-labs/FLUX.1-dev"
32
+ image_encoder_path = "google/siglip-so400m-patch14-384"
33
+ image_encoder2_path = "facebook/dinov2-giant"
34
+ birefnet_path = "ZhengPeng7/BiRefNet"
35
+ makoto_style_path = hf_hub_download("InstantX/FLUX.1-dev-LoRA-Makoto-Shinkai",
36
+ "Makoto_Shinkai_style.safetensors")
37
+ ghibli_style_path = hf_hub_download("InstantX/FLUX.1-dev-LoRA-Ghibli",
38
+ "ghibli_style.safetensors")
39
+
40
+ # ─────────────────────────────
41
+ # 3 · Pipeline init
42
+ # ─────────────────────────────
43
+ pipe = InstantCharacterFluxPipeline.from_pretrained(base_model,
44
+ torch_dtype=torch.bfloat16)
45
  pipe.to(device)
 
 
46
  pipe.init_adapter(
47
+ image_encoder_path=image_encoder_path,
48
+ image_encoder_2_path=image_encoder2_path,
49
+ subject_ipadapter_cfg=dict(subject_ip_adapter_path=ip_adapter_path,
50
+ nb_token=1024),
51
  )
52
 
53
+ # ─────────────────────────────
54
+ # 4 · BiRefNet (matting)
55
+ # ─────────────────────────────
56
+ birefnet = AutoModelForImageSegmentation.from_pretrained(birefnet_path,
57
+ trust_remote_code=True)
58
+ birefnet.to(device).eval()
59
+ birefnet_tf = transforms.Compose([
60
  transforms.Resize((1024, 1024)),
61
  transforms.ToTensor(),
62
+ transforms.Normalize([0.485, 0.456, 0.406],
63
+ [0.229, 0.224, 0.225]),
64
  ])
65
 
66
+ # ─────────────────────────────
67
+ # 5 · Helper utils
68
+ # ─────────────────────────────
69
+ def randomize_seed_fn(seed: int, randomize: bool) -> int:
70
+ return random.randint(0, MAX_SEED) if randomize else seed
71
+
72
+ def _infer_matting(img_pil):
73
+ with torch.no_grad():
74
+ inp = birefnet_tf(img_pil).unsqueeze(0).to(device)
75
+ mask = birefnet(inp)[-1].sigmoid().cpu()[0, 0].numpy()
76
+ return (mask * 255).astype(np.uint8)
77
+
78
+ def _bbox_from_mask(mask, th=128):
79
+ ys, xs = np.where(mask >= th)
80
+ if not len(xs):
81
+ return [0, 0, mask.shape[1]-1, mask.shape[0]-1]
82
+ return [xs.min(), ys.min(), xs.max(), ys.max()]
83
+
84
+ def _pad_square(arr, pad_val=255):
85
+ h, w = arr.shape[:2]
86
+ if h == w:
87
+ return arr
88
+ diff = abs(h - w)
89
+ pad_1 = diff // 2
90
+ pad_2 = diff - pad_1
91
+ if h > w:
92
+ pad = ((0, 0), (pad_1, pad_2), (0, 0))
93
+ else:
94
+ pad = ((pad_1, pad_2), (0, 0), (0, 0))
95
+ return np.pad(arr, pad, constant_values=pad_val)
96
+
97
+ def remove_bkg(img_pil: Image.Image) -> Image.Image:
98
+ mask = _infer_matting(img_pil)
99
+ x1, y1, x2, y2 = _bbox_from_mask(mask)
100
+ mask_bin = (mask >= 128).astype(np.uint8)[..., None]
101
+ img_np = np.array(img_pil)
102
+ obj = mask_bin * img_np + (1 - mask_bin) * 255
103
+ crop = obj[y1:y2+1, x1:x2+1]
104
+ return Image.fromarray(_pad_square(crop).astype(np.uint8))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
 
106
  def get_example():
107
+ return [
108
+ ["./assets/girl.jpg",
109
+ "A girl is playing a guitar in street", 0.9, "Makoto Shinkai style"],
110
+ ["./assets/boy.jpg",
111
+ "A boy is riding a bike in snow", 0.9, "Makoto Shinkai style"],
 
 
 
 
 
 
 
 
112
  ]
 
 
 
 
 
 
 
 
 
 
 
 
 
113
 
114
  @spaces.GPU
115
+ def create_image(input_image, prompt, scale,
116
+ guidance_scale, num_inference_steps,
117
+ seed, style_mode):
 
 
 
 
 
118
  input_image = remove_bkg(input_image)
119
+ gen = torch.manual_seed(seed)
120
 
121
  if style_mode is None:
122
+ imgs = pipe(prompt=prompt,
123
+ num_inference_steps=num_inference_steps,
124
+ guidance_scale=guidance_scale,
125
+ width=1024, height=1024,
126
+ subject_image=input_image, subject_scale=scale,
127
+ generator=gen).images
 
 
 
 
128
  else:
129
+ lora_path, trigger = (
130
+ (makoto_style_path, "Makoto Shinkai style")
131
+ if style_mode == "Makoto Shinkai style"
132
+ else (ghibli_style_path, "ghibli style")
133
+ )
134
+ imgs = pipe.with_style_lora(
135
+ lora_file_path=lora_path, trigger=trigger,
136
+ prompt=prompt, num_inference_steps=num_inference_steps,
 
 
 
 
137
  guidance_scale=guidance_scale,
138
+ width=1024, height=1024,
139
+ subject_image=input_image, subject_scale=scale,
140
+ generator=gen).images
141
+ return imgs
142
+
143
+ def run_for_examples(src, p, s, st):
144
+ return create_image(src, p, s, 3.5, 28, 123456, st)
145
+
146
+ # ─────────────────────────────
147
+ # 6 · Theme & CSS
148
+ # ─────────────────────────────
149
+ theme = Soft(primary_hue="pink",
150
+ font=[gr.themes.GoogleFont("Inter")])
151
+
152
+ css = """
153
+ body{
154
+ background:#141e30;
155
+ background:linear-gradient(135deg,#141e30,#243b55);
156
+ }
157
+ #title{
158
+ text-align:center;
159
+ font-size:2.2rem;
160
+ font-weight:700;
161
+ color:#ffffff;
162
+ padding:20px 0 6px;
163
+ }
164
+ .card{
165
+ border-radius:18px;
166
+ background:#ffffff0d;
167
+ padding:18px 22px;
168
+ backdrop-filter:blur(6px);
169
+ }
170
+ .gr-image,.gr-video{border-radius:14px}
171
+ .gr-image:hover{box-shadow:0 0 0 4px #ec4899}
172
+ footer{visibility:hidden}
173
  """
174
 
175
+ # ─────────────────────────────
176
+ # 7 · Gradio UI
177
+ # ─────────────────────────────
178
+ with gr.Blocks(css=css, theme=theme) as demo:
179
+ # Header
180
+ gr.Markdown("<div id='title'>InstantCharacter&nbsp;PLUS</div>")
181
+ gr.Markdown(
182
+ "<b>Official 🤗 Gradio demo of "
183
+ "<a href='https://instantcharacter.github.io/' target='_blank'>InstantCharacter</a></b>"
184
+ )
185
 
 
 
 
 
 
 
 
186
  with gr.Tabs():
187
+ with gr.TabItem("Generate"):
188
+ with gr.Row(equal_height=True):
189
+ # ── Inputs
190
+ with gr.Column(elem_classes="card"):
191
+ image_pil = gr.Image(label="Source Image",
192
+ type="pil", height=380)
193
+ prompt = gr.Textbox(
194
+ label="Prompt",
195
+ value="A character is riding a bike in snow",
196
+ lines=2,
197
+ )
198
+ scale = gr.Slider(0, 1.5, 1.0, step=0.01, label="Scale")
199
+ style_mode = gr.Dropdown(
200
+ ["None", "Makoto Shinkai style", "Ghibli style"],
201
+ label="Style",
202
+ value="Makoto Shinkai style",
203
+ )
204
+
205
+ with gr.Accordion("⚙️ Advanced Options", open=False):
206
+ guidance_scale = gr.Slider(
207
+ 1, 7, 3.5, step=0.01, label="Guidance scale"
208
+ )
209
+ num_inference_steps = gr.Slider(
210
+ 5, 50, 28, step=1, label="# Inference steps"
211
+ )
212
+ seed = gr.Number(123456, label="Seed", precision=0)
213
+ randomize_seed = gr.Checkbox(
214
+ label="Randomize seed", value=True
215
+ )
216
+
217
+ generate_btn = gr.Button(
218
+ "🚀 Generate",
219
+ variant="primary",
220
+ size="lg",
221
+ elem_classes="contrast",
222
+ )
223
+
224
+ # ── Outputs
225
+ with gr.Column(elem_classes="card"):
226
+ generated_image = gr.Gallery(
227
+ label="Generated Image",
228
+ show_label=True,
229
+ height="auto",
230
+ columns=[1],
231
+ )
232
+
233
+ # Connect button
234
+ generate_btn.click(
235
+ randomize_seed_fn,
236
+ [seed, randomize_seed],
237
+ seed,
238
+ queue=False,
239
+ ).then(
240
+ create_image,
241
+ [
242
+ image_pil,
243
  prompt,
244
+ scale,
245
  guidance_scale,
246
  num_inference_steps,
247
  seed,
248
  style_mode,
249
+ ],
250
+ generated_image,
251
+ )
252
+
253
+ # Examples gallery
254
+ gr.Markdown("### 🔥 Quick Examples")
255
  gr.Examples(
256
  examples=get_example(),
257
  inputs=[image_pil, prompt, scale, style_mode],
258
+ outputs=generated_image,
259
  fn=run_for_examples,
 
260
  cache_examples=True,
261
  )
 
 
262
 
263
+ # ─────────────────────────────
264
+ # 8 · Launch
265
+ # ─────────────────────────────
266
+ if __name__ == "__main__":
267
+ demo.queue(max_size=10, api_open=False).launch()