BurningTimesAi/공유/기획/FirstRising/아이템/comfy_inspy.py

84 lines
4.6 KiB
Python
Raw Permalink Normal View History

# 2차 생성물 배경 제거 — InspyrenetRembg 노드(2026-09-23 세션에서 RMBG-2.0 대신 쓰던 우회) → 비교표 갱신
import json, os, sys, time, uuid, glob, urllib.request, urllib.parse
from PIL import Image, ImageDraw, ImageFont
HOST = "http://127.0.0.1:8000"
S = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(S, "comfy_out2")
def get(path):
return json.load(urllib.request.urlopen(HOST + path, timeout=120))
def upload(path):
boundary = "----bt25" + uuid.uuid4().hex
with open(path, "rb") as f:
data = f.read()
body = (f"--{boundary}\r\nContent-Disposition: form-data; name=\"image\"; filename=\"{os.path.basename(path)}\"\r\nContent-Type: image/png\r\n\r\n").encode() + data + (f"\r\n--{boundary}\r\nContent-Disposition: form-data; name=\"overwrite\"\r\n\r\ntrue\r\n--{boundary}--\r\n").encode()
req = urllib.request.Request(HOST + "/upload/image", data=body, headers={"Content-Type": f"multipart/form-data; boundary={boundary}"})
return json.load(urllib.request.urlopen(req, timeout=120))["name"]
def run(wf):
req = urllib.request.Request(HOST + "/prompt", data=json.dumps({"prompt": wf, "client_id": str(uuid.uuid4())}).encode(), headers={"Content-Type": "application/json"})
try:
r = json.load(urllib.request.urlopen(req, timeout=60))
except urllib.error.HTTPError as e:
return None, e.read().decode(errors="replace")[:300]
pid = r["prompt_id"]
for _ in range(150):
time.sleep(2)
h = get(f"/history/{pid}")
if pid in h:
if h[pid].get("status", {}).get("status_str") == "error":
msgs = [m for m in h[pid]["status"].get("messages", []) if m[0] == "execution_error"]
return None, (msgs[0][1].get("exception_message", "")[:300] if msgs else "error")
for nid, o in h[pid]["outputs"].items():
for im in o.get("images", []):
q = urllib.parse.urlencode({"filename": im["filename"], "subfolder": im.get("subfolder", ""), "type": im.get("type", "output")})
return urllib.request.urlopen(HOST + "/view?" + q, timeout=120).read(), None
return None, "timeout"
ok = 0
for p in sorted(glob.glob(os.path.join(OUT, "*.png"))):
if p.endswith("_alpha.png") or p.endswith("_inspy.png"):
continue
name = upload(p)
wf = {"1": {"class_type": "LoadImage", "inputs": {"image": name}},
"2": {"class_type": "InspyrenetRembg", "inputs": {"image": ["1", 0], "torchscript_jit": "default"}},
"3": {"class_type": "SaveImage", "inputs": {"images": ["2", 0], "filename_prefix": "bt25_inspy"}}}
data, err = run(wf)
if data is None:
print(os.path.basename(p), "inspyrenet failed:", err); continue
outp = p[:-4] + "_inspy.png"
with open(outp, "wb") as f:
f.write(data)
a = Image.open(outp)
print(os.path.basename(outp), "ok", a.mode, ("alpha min " + str(a.getextrema()[3][0])) if a.mode == "RGBA" else "")
ok += 1
print("inspyrenet done", ok)
# 비교표(기존 FR · 2차 Inspyrenet 결과)
u = r"C:\BurningTimes\FirstRising\Assets\GameAssets\UI\EquipmentItemIcon"
ref = [(os.path.join(u, n + ".png"), t) for n, t in [("1001", "FR 검"), ("1015", "FR 둔기"), ("1085", "FR 목걸이"), ("1155", "FR 장갑"), ("1225", "FR 갑옷"), ("1295", "FR 벨트"), ("1365", "FR 신발"), ("1043", "FR 단검")]]
ko = {"helmet_knight": "투구(기사)", "helmet_horned": "투구(뿔)", "ring_ruby": "반지", "shield_kite": "방패", "orb_arcane": "오브", "grimoire": "마도서", "quiver": "화살통", "amulet": "목걸이"}
order = ["helmet_knight", "helmet_horned", "ring_ruby", "shield_kite", "orb_arcane", "grimoire", "quiver", "amulet"]
gen = []
for k in order:
for suf in ("_inspy.png", "_alpha.png", ".png"):
p = os.path.join(OUT, k + suf)
if os.path.exists(p):
gen.append((p, "2차 " + ko[k] + ("" if suf == "_inspy.png" else "(키잉)" if suf == "_alpha.png" else "(원본)"))); break
cell, cols = 190, 8
sheet = Image.new("RGB", (cols * cell, 2 * (cell + 26)), (58, 58, 58)); d = ImageDraw.Draw(sheet)
font = ImageFont.truetype("C:/Windows/Fonts/malgunbd.ttf", 13)
for row, items in enumerate((ref, gen)):
for i, (p, t) in enumerate(items[:cols]):
im = Image.open(p).convert("RGBA"); im.thumbnail((cell - 10, cell - 10))
bg = Image.new("RGBA", (cell, cell), (58, 58, 58, 255)); bg.paste(im, ((cell - im.width) // 2, (cell - im.height) // 2), im)
x, y = i * cell, row * (cell + 26); sheet.paste(bg.convert("RGB"), (x, y))
d.text((x + 4, y + cell + 5), t, fill=(240, 220, 160) if row else (220, 220, 220), font=font)
sheet.save(os.path.join(S, "icon_compare3.png")); print("sheet ok")