Update app.py
Browse files
app.py
CHANGED
@@ -1,290 +1,267 @@
|
|
1 |
-
|
2 |
-
|
|
|
|
|
3 |
|
4 |
-
import
|
|
|
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 |
-
#
|
|
|
|
|
19 |
MAX_SEED = np.iinfo(np.int32).max
|
20 |
-
device
|
21 |
-
dtype
|
22 |
-
|
23 |
-
#
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
pipe.to(device)
|
35 |
-
|
36 |
-
# load InstantCharacter
|
37 |
pipe.init_adapter(
|
38 |
-
image_encoder_path=image_encoder_path,
|
39 |
-
image_encoder_2_path=
|
40 |
-
subject_ipadapter_cfg=dict(subject_ip_adapter_path=ip_adapter_path,
|
|
|
41 |
)
|
42 |
|
43 |
-
#
|
44 |
-
|
45 |
-
|
46 |
-
birefnet.
|
47 |
-
|
|
|
|
|
48 |
transforms.Resize((1024, 1024)),
|
49 |
transforms.ToTensor(),
|
50 |
-
transforms.Normalize([0.485, 0.456, 0.406],
|
|
|
51 |
])
|
52 |
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
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 |
-
|
146 |
-
[
|
147 |
-
|
148 |
-
|
149 |
-
|
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 |
-
|
176 |
-
|
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 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
subject_image=input_image,
|
192 |
-
subject_scale=scale,
|
193 |
-
generator=torch.manual_seed(seed),
|
194 |
-
).images
|
195 |
else:
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
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 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
#
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
226 |
"""
|
227 |
|
228 |
-
|
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.
|
240 |
-
with gr.
|
241 |
-
|
242 |
-
with gr.
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
271 |
prompt,
|
272 |
-
scale,
|
273 |
guidance_scale,
|
274 |
num_inference_steps,
|
275 |
seed,
|
276 |
style_mode,
|
277 |
-
|
278 |
-
|
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 |
-
|
|
|
|
|
|
|
|
|
|
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 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()
|