Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,177 +1,235 @@
|
|
1 |
-
# app.py —
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
from huggingface_hub import hf_hub_download
|
8 |
-
import huggingface_hub as _hf
|
9 |
-
if not hasattr(_hf, "cached_download"):
|
10 |
-
_hf.cached_download = hf_hub_download
|
11 |
-
|
12 |
-
##############################################################################
|
13 |
-
# 1. ライブラリ
|
14 |
-
##############################################################################
|
15 |
-
import os, io, base64, subprocess, traceback
|
16 |
from pathlib import Path
|
17 |
-
from typing import Optional
|
18 |
-
import numpy as np
|
19 |
-
import torch, gradio as gr, spaces
|
20 |
-
from fastapi import FastAPI, UploadFile, File, Form, HTTPException
|
21 |
from PIL import Image
|
22 |
from diffusers import (
|
23 |
-
|
24 |
-
|
25 |
-
DPMSolverMultistepScheduler,
|
26 |
)
|
27 |
-
from diffusers.loaders import AttnProcsLayers
|
28 |
from insightface.app import FaceAnalysis
|
29 |
-
from realesrgan import RealESRGANer
|
30 |
|
31 |
##############################################################################
|
32 |
-
#
|
33 |
-
##############################################################################
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
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 |
-
|
93 |
-
)
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
##############################################################################
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
142 |
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
151 |
with gr.Row():
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
|
|
173 |
|
174 |
-
|
175 |
-
|
176 |
-
##############################################################################
|
177 |
-
demo.queue(default_concurrency_limit=2).launch(share=False)
|
|
|
1 |
+
# app.py — InstantID × Beautiful Realistic Asians v7 (ZeroGPU-friendly, persistent cache)
|
2 |
+
"""Persistent-cache backend for InstantID portrait generation.
|
3 |
+
- Caches model assets under /data when writable, else ~/.cache
|
4 |
+
- Robust download with retry + multiple fallback URLs per asset
|
5 |
+
"""
|
6 |
+
import os, subprocess, cv2, torch, spaces, gradio as gr, numpy as np
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
from pathlib import Path
|
|
|
|
|
|
|
|
|
8 |
from PIL import Image
|
9 |
from diffusers import (
|
10 |
+
StableDiffusionPipeline, ControlNetModel,
|
11 |
+
DPMSolverMultistepScheduler, AutoencoderKL,
|
|
|
12 |
)
|
|
|
13 |
from insightface.app import FaceAnalysis
|
|
|
14 |
|
15 |
##############################################################################
|
16 |
+
# 0. Cache dir & helpers
|
17 |
+
##############################################################################
|
18 |
+
PERSIST_BASE = Path("/data")
|
19 |
+
CACHE_ROOT = (PERSIST_BASE / "instantid_cache" if PERSIST_BASE.exists() and os.access(PERSIST_BASE, os.W_OK)
|
20 |
+
else Path.home() / ".cache" / "instantid_cache")
|
21 |
+
print("cache →", CACHE_ROOT)
|
22 |
+
|
23 |
+
MODELS_DIR = CACHE_ROOT / "models"
|
24 |
+
LORA_DIR = MODELS_DIR / "Lora"
|
25 |
+
EMB_DIR = CACHE_ROOT / "embeddings"
|
26 |
+
UPSCALE_DIR = CACHE_ROOT / "realesrgan"
|
27 |
+
for p in (MODELS_DIR, LORA_DIR, EMB_DIR, UPSCALE_DIR):
|
28 |
+
p.mkdir(parents=True, exist_ok=True)
|
29 |
+
|
30 |
+
|
31 |
+
def dl(url: str, dst: Path, attempts: int = 2):
|
32 |
+
if dst.exists():
|
33 |
+
print("✓", dst.relative_to(CACHE_ROOT)); return
|
34 |
+
for i in range(1, attempts + 1):
|
35 |
+
print(f"⬇ {dst.name} (try {i}/{attempts})")
|
36 |
+
if subprocess.call(["wget", "-q", "-O", str(dst), url]) == 0:
|
37 |
+
return
|
38 |
+
raise RuntimeError(f"download failed → {url}")
|
39 |
+
|
40 |
+
##############################################################################
|
41 |
+
# 1. Asset download
|
42 |
+
##############################################################################
|
43 |
+
print("— asset check —")
|
44 |
+
|
45 |
+
# 1-A. base ckpt
|
46 |
+
BASE_CKPT = MODELS_DIR / "beautiful_realistic_asians_v7_fp16.safetensors"
|
47 |
+
dl("https://civitai.com/api/download/models/177164?type=Model&format=SafeTensor&size=pruned&fp=fp16", BASE_CKPT)
|
48 |
+
|
49 |
+
# 1-B. IP-Adapter core + FaceID LoRA
|
50 |
+
IP_BIN_FILE = LORA_DIR / "ip-adapter-plus-face_sd15.bin"
|
51 |
+
dl("https://huggingface.co/h94/IP-Adapter/resolve/main/models/ip-adapter-plus-face_sd15.bin", IP_BIN_FILE)
|
52 |
+
|
53 |
+
LORA_FILE = LORA_DIR / "ip-adapter-faceid-plusv2_sd15_lora.safetensors"
|
54 |
+
dl("https://huggingface.co/h94/IP-Adapter-FaceID/resolve/main/ip-adapter-faceid-plusv2_sd15_lora.safetensors", LORA_FILE)
|
55 |
+
|
56 |
+
# 1-C. textual-inversion embeddings
|
57 |
+
EMB_URLS = {
|
58 |
+
"ng_deepnegative_v1_75t.pt": [
|
59 |
+
"https://huggingface.co/datasets/gsdf/EasyNegative/resolve/main/ng_deepnegative_v1_75t.pt",
|
60 |
+
"https://huggingface.co/mrpxl2/animetarotV51.safetensors/raw/cc3008c0148061896549a995cc297aef0af4ef1b/ng_deepnegative_v1_75t.pt",
|
61 |
+
],
|
62 |
+
"badhandv4.pt": [
|
63 |
+
"https://huggingface.co/datasets/gsdf/ConceptLab/resolve/main/badhandv4.pt",
|
64 |
+
"https://huggingface.co/nolanaatama/embeddings/raw/main/badhandv4.pt",
|
65 |
+
],
|
66 |
+
"CyberRealistic_Negative-neg.pt": [
|
67 |
+
"https://huggingface.co/datasets/gsdf/ConceptLab/resolve/main/CyberRealistic_Negative-neg.pt",
|
68 |
+
"https://huggingface.co/wsj1995/embeddings/raw/main/CyberRealistic_Negative-neg.civitai.info",
|
69 |
+
],
|
70 |
+
"UnrealisticDream.pt": [
|
71 |
+
"https://huggingface.co/datasets/gsdf/ConceptLab/resolve/main/UnrealisticDream.pt",
|
72 |
+
"https://huggingface.co/imagepipeline/UnrealisticDream/raw/main/f84133b4-aad8-44be-b9ce-7e7e3a8c111f.pt",
|
73 |
+
],
|
74 |
+
}
|
75 |
+
for fname, urls in EMB_URLS.items():
|
76 |
+
dst = EMB_DIR / fname
|
77 |
+
for idx, u in enumerate(urls, 1):
|
78 |
+
try:
|
79 |
+
dl(u, dst); break
|
80 |
+
except RuntimeError:
|
81 |
+
if idx == len(urls): raise
|
82 |
+
print(" ↳ fallback URL …")
|
83 |
+
|
84 |
+
# 1-D. Real-ESRGAN weights 8×
|
85 |
+
RRG_WEIGHTS = UPSCALE_DIR / "RealESRGAN_x8plus.pth"
|
86 |
+
RRG_URLS = [
|
87 |
+
"https://huggingface.co/NoCrypt/Superscale_RealESRGAN/resolve/main/RealESRGAN_x8plus.pth",
|
88 |
+
"https://huggingface.co/ai-forever/Real-ESRGAN/raw/main/RealESRGAN_x8.pth",
|
89 |
+
"https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/8x_NMKD-Superscale_100k.pth",
|
90 |
+
]
|
91 |
+
for idx, link in enumerate(RRG_URLS, 1):
|
92 |
+
try:
|
93 |
+
dl(link, RRG_WEIGHTS); break
|
94 |
+
except RuntimeError:
|
95 |
+
if idx == len(RRG_URLS): raise
|
96 |
+
print(" ↳ fallback URL …")
|
97 |
+
|
98 |
+
##############################################################################
|
99 |
+
# 2. Runtime init
|
100 |
+
##############################################################################
|
101 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
102 |
+
dtype = torch.float16 if torch.cuda.is_available() else torch.float32
|
103 |
+
print("device:", device, "| dtype:", dtype)
|
104 |
+
|
105 |
+
providers = ["CUDAExecutionProvider", "CPUExecutionProvider"] if torch.cuda.is_available() else ["CPUExecutionProvider"]
|
106 |
+
face_app = FaceAnalysis(name="buffalo_l", root=str(CACHE_ROOT), providers=providers)
|
107 |
+
face_app.prepare(ctx_id=(0 if torch.cuda.is_available() else -1), det_size=(640, 640))
|
108 |
+
|
109 |
+
controlnet = ControlNetModel.from_pretrained("InstantX/InstantID", subfolder="ControlNetModel", torch_dtype=dtype)
|
110 |
+
pipe = StableDiffusionPipeline.from_single_file(BASE_CKPT, torch_dtype=dtype, safety_checker=None, use_safetensors=True, clip_skip=2)
|
111 |
+
pipe.vae = AutoencoderKL.from_pretrained("stabilityai/sd-vae-ft-mse", torch_dtype=dtype).to(device)
|
112 |
+
pipe.controlnet = controlnet
|
113 |
+
pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config, use_karras_sigmas=True, algorithm_type="sde-dpmsolver++")
|
114 |
+
|
115 |
+
pipe.load_ip_adapter(str(LORA_DIR), subfolder="", weight_name=IP_BIN_FILE.name)
|
116 |
+
# load FaceID LoRA (Δ only LoRA weights, not full IP-Adapter)
|
117 |
+
pipe.load_lora_weights(str(LORA_DIR), weight_name=LORA_FILE.name)
|
118 |
+
pipe.set_ip_adapter_scale(0.65)
|
119 |
+
|
120 |
+
for emb in EMB_DIR.glob("*.*"):
|
121 |
+
try:
|
122 |
+
pipe.load_textual_inversion(emb, token=emb.stem)
|
123 |
+
print("emb loaded →", emb.stem)
|
124 |
+
except Exception:
|
125 |
+
print("emb skip →", emb.name)
|
126 |
+
pipe.to(device)
|
127 |
+
print("pipeline ready ✔")
|
128 |
+
|
129 |
+
##############################################################################
|
130 |
+
# 3. Upscaler
|
131 |
+
##############################################################################
|
132 |
+
try:
|
133 |
+
from basicsr.archs.rrdb_arch import RRDBNet
|
134 |
+
try:
|
135 |
+
from realesrgan import RealESRGAN
|
136 |
+
except ImportError:
|
137 |
+
from realesrgan import RealESRGANer as RealESRGAN
|
138 |
+
rrdb = RRDBNet(3, 3, 64, 23, 32, scale=8)
|
139 |
+
upsampler = RealESRGAN(device, rrdb, scale=8)
|
140 |
+
upsampler.load_weights(str(RRG_WEIGHTS))
|
141 |
+
UPSCALE_OK = True
|
142 |
+
except Exception as e:
|
143 |
+
print("Real-ESRGAN disabled →", e)
|
144 |
+
UPSCALE_OK = False
|
145 |
+
|
146 |
+
##############################################################################
|
147 |
+
# 4. Prompts & generation
|
148 |
+
##############################################################################
|
149 |
+
BASE_PROMPT = (
|
150 |
+
"(masterpiece:1.2), best quality, ultra-realistic, RAW photo, 8k,\n"
|
151 |
+
"photo of {subject},\n"
|
152 |
+
"cinematic lighting, golden hour, rim light, shallow depth of field,\n"
|
153 |
+
"textured skin, high detail, shot on Canon EOS R5, 85 mm f/1.4, ISO 200,\n"
|
154 |
+
"<lora:ip-adapter-faceid-plusv2_sd15_lora:0.65>, (face),\n"
|
155 |
+
"(aesthetic:1.1), (cinematic:0.8)"
|
156 |
+
)
|
157 |
+
# [!!] 下記のNEG_PROMPTを修正しました。不要なカンマと重複した文字列を削除し、単一の文字列になるようにしました。
|
158 |
+
NEG_PROMPT = (
|
159 |
+
"ng_deepnegative_v1_75t, CyberRealistic_Negative-neg, UnrealisticDream, "
|
160 |
+
"(worst quality:2), (low quality:1.8), lowres, (jpeg artifacts:1.2), "
|
161 |
+
"painting, sketch, illustration, drawing, cartoon, anime, cgi, render, 3d, "
|
162 |
+
"monochrome, grayscale, text, logo, watermark, signature, username, "
|
163 |
+
"(MajicNegative_V2:0.8), bad hands, extra digits, fused fingers, malformed limbs, "
|
164 |
+
"missing arms, missing legs, (badhandv4:0.7), BadNegAnatomyV1-neg, skin blemishes, acnes, age spot, glans"
|
165 |
+
)
|
166 |
|
167 |
+
@spaces.GPU(duration=90)
|
168 |
+
def generate(
|
169 |
+
face_np, subject, add_prompt, add_neg, cfg, ip_scale, steps, w, h, upscale, up_factor,
|
170 |
+
progress=gr.Progress(track_tqdm=True)
|
171 |
+
):
|
172 |
+
if face_np is None or face_np.size == 0:
|
173 |
+
raise gr.Error("顔画像をアップロードしてください。")
|
174 |
+
|
175 |
+
prompt = BASE_PROMPT.format(subject=(subject.strip() or "a beautiful 20yo woman"))
|
176 |
+
if add_prompt:
|
177 |
+
prompt += ", " + add_prompt
|
178 |
+
neg = NEG_PROMPT + (", " + add_neg if add_neg else "")
|
179 |
+
|
180 |
+
pipe.set_ip_adapter_scale(ip_scale)
|
181 |
+
img_in = Image.fromarray(face_np)
|
182 |
+
|
183 |
+
result = pipe(
|
184 |
+
prompt=prompt,
|
185 |
+
negative_prompt=neg,
|
186 |
+
ip_adapter_image=img_in,
|
187 |
+
image=img_in,
|
188 |
+
controlnet_conditioning_scale=0.9,
|
189 |
+
num_inference_steps=int(steps) + 5,
|
190 |
+
guidance_scale=cfg,
|
191 |
+
width=int(w),
|
192 |
+
height=int(h),
|
193 |
+
).images[0]
|
194 |
+
|
195 |
+
if upscale:
|
196 |
+
if UPSCALE_OK:
|
197 |
+
up, _ = upsampler.enhance(cv2.cvtColor(np.array(result), cv2.COLOR_RGB2BGR), outscale=up_factor)
|
198 |
+
result = Image.fromarray(cv2.cvtColor(up, cv2.COLOR_BGR2RGB))
|
199 |
+
else:
|
200 |
+
result = result.resize((int(result.width * up_factor), int(result.height * up_factor)), Image.LANCZOS)
|
201 |
+
|
202 |
+
return result
|
203 |
+
|
204 |
+
##############################################################################
|
205 |
+
# 5. Gradio UI
|
206 |
+
##############################################################################
|
207 |
+
|
208 |
+
with gr.Blocks() as demo:
|
209 |
+
gr.Markdown("# InstantID – Beautiful Realistic Asians v7")
|
210 |
with gr.Row():
|
211 |
+
with gr.Column():
|
212 |
+
face_in = gr.Image(label="顔写真", type="numpy")
|
213 |
+
subj_in = gr.Textbox(label="被写体説明", placeholder="e.g. woman in black suit, smiling")
|
214 |
+
add_in = gr.Textbox(label="追加プロンプト")
|
215 |
+
addneg_in = gr.Textbox(label="追加ネガティブ")
|
216 |
+
ip_sld = gr.Slider(0, 1.5, 0.65, step=0.05, label="IP-Adapter scale")
|
217 |
+
cfg_sld = gr.Slider(1, 15, 6, step=0.5, label="CFG")
|
218 |
+
step_sld = gr.Slider(10, 50, 20, step=1, label="Steps")
|
219 |
+
w_sld = gr.Slider(512, 1024, 512, step=64, label="幅")
|
220 |
+
h_sld = gr.Slider(512, 1024, 768, step=64, label="高さ")
|
221 |
+
up_ck = gr.Checkbox(label="アップスケール", value=True)
|
222 |
+
up_fac = gr.Slider(1, 8, 2, step=1, label="倍率")
|
223 |
+
btn = gr.Button("生成", variant="primary")
|
224 |
+
with gr.Column():
|
225 |
+
out_img = gr.Image(label="結果")
|
226 |
+
|
227 |
+
btn.click(
|
228 |
+
generate,
|
229 |
+
[face_in, subj_in, add_in, addneg_in, cfg_sld, ip_sld, step_sld, w_sld, h_sld, up_ck, up_fac],
|
230 |
+
out_img,
|
231 |
+
api_name="predict",
|
232 |
+
)
|
233 |
|
234 |
+
print("launching …")
|
235 |
+
demo.queue().launch(show_error=True)
|
|
|
|