sunyoung00 commited on
Commit
fb33f67
·
verified ·
1 Parent(s): 900bcb7

Upload 3 files

Browse files
Files changed (3) hide show
  1. README (5).md +86 -0
  2. comfy_client (19).py +534 -0
  3. workflow_api (10).json +987 -0
README (5).md ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Face Swap Batch
3
+ emoji: 🪞
4
+ colorFrom: gray
5
+ colorTo: blue
6
+ sdk: docker
7
+ app_port: 7860
8
+ pinned: false
9
+ hf_oauth: true
10
+ hf_oauth_expiration_minutes: 43200
11
+ hf_oauth_authorized_org: eland-innople
12
+ ---
13
+
14
+ # 얼굴 일괄 교체
15
+
16
+ 폴더(여러 개 가능)를 올리면, 파일명에 **남자 / 여자**가 들어간 이미지마다 맞는 얼굴로 바꿔 줍니다.
17
+ Comfy Cloud 의 `workflow_api.json`(faceswap_001) 을 그대로 실행하고, 결과는 **올린 파일명·확장자·폴더 구조 그대로** 내려받습니다.
18
+
19
+ ## 배포
20
+ 1. 이 폴더의 파일을 전부 새 Space(SDK: Docker)에 올립니다. (`assets/faces/male.jpg`, `female.jpg` 포함)
21
+ 2. Space → Settings → **Secrets** 에 추가
22
+ - `COMFY_CLOUD_API_KEY` — platform.comfy.org 에서 발급 (Comfy Cloud 구독 필요)
23
+ - `HF_TOKEN` — **쓰기(write) 권한** 토큰. 결과 영구 저장용
24
+ - `HF_DATASET_REPO` — 결과를 쌓을 Dataset 이름 (예: `내계정/faceswap-results`). 없으면 **비공개**로 자동 생성됩니다.
25
+ 3. 위 맨 앞 설정의 `hf_oauth` 3줄 덕분에 **이랜드이노플 조직 멤버가 Hugging Face 로 로그인해야만** 쓸 수 있습니다(화면·결과·통계·다운로드 모두). 그래도 Space 는 **Private** 으로 두는 것을 권합니다.
26
+ 4. 열어서 상단에 빨간 안내가 없는지, `/api/health` 가 `"ok": true` 인지, 우측 상단에 **결과 영구 저장 켜짐**이 뜨는지 확인합니다.
27
+
28
+ ## 올리는 방법 (ZIP 하나)
29
+ 이미지가 든 폴더(여러 개도 가능)를 **ZIP 한 개**로 묶어 올립니다. 폴더 우클릭 → 압축(ZIP). 브라우저에서 바로 풀어 폴더 구조·한글 파일명을 그대로 읽습니다.
30
+ - 암호가 걸린 ZIP, 4GB가 넘는 ZIP은 읽을 수 없습니다.
31
+ - 회사 보안 프로그램이 폴더·여러 개 선택을 막는 환경에서도 ZIP 은 파일 한 개라 그대로 올라갑니다.
32
+ - 이 앱은 이미지를 외부 서비스(Hugging Face·Comfy Cloud)로 보냅니다. 보안 정책상 막힌 것이라면 보안팀에 이 Space 주소를 허용해 달라고 요청해 주세요.
33
+
34
+ ## 진행 상황·취소
35
+ - 카드마다 진행 막대(%)가 보이고, 위쪽에는 전체 진행 막대가 있습니다. 진행 중에는 아래·위 두 곳에 **전체 취소** 버튼이, 카드마다 **취소** 버튼이 나옵니다.
36
+ - 취소하면 아직 보내지 않은 이미지는 '시작 전'으로 돌아가고, 보낸 이미지는 Comfy Cloud 에서도 멈춥니다. 취소한 이미지는 **다시 시도**로 처음부터 합니다.
37
+ - Comfy Cloud 의 `interrupt` 는 이 계정의 **실행 중인 작업 전부**를 멈춥니다. 같은 API 키로 다른 사람·다른 앱이 돌리는 작업까지 끊기지 않도록, Cloud 에서 실행 중인 작업이 전부 이 앱의 작업일 때만 중단합니다. 그렇지 않으면 이미 실행 중인 작업은 끝까지 진행되고(크레딧 일부 사용) 결과만 버립니다. 대기 중인 작업은 대기열에서 깔끔히 빠집니다.
38
+
39
+ ## 로그인 · 통계
40
+ - **로그인**: 위 `hf_oauth` 설정이 있으면 로그인 화면이 먼저 나오고, 조직 멤버가 아니면 접근이 거부됩니다. 로그인하지 않으면 화면뿐 아니라 `/api/*` (지난 결과·이미지·다운로드·통계)도 열리지 않습니다. 로그인 없이 쓰게 하려면 Variables 에 `REQUIRE_LOGIN=false` (또는 README 의 `hf_oauth` 줄을 지움).
41
+ - **통계 탭**: 지난 결과 기록을 기간별로 집계합니다(총 생성·재생성·사용자·일자별·성별·시간대·사용자별·폴더별·최근 생성). 완료된 생성만 세고, 사용자 정보는 로그인 기능을 켠 뒤 만든 결과부터 남습니다. '대략 크레딧'은 건수 × `CREDITS_PER_IMAGE`(기본 8.6) 추정치입니다. 로그인한 사람은 누구나 통계를 볼 수 있습니다.
42
+
43
+ ## 결과 저장
44
+ - 처리가 끝난 결과는 바로 **지난 결과** 탭에 쌓입니다. 새로고침·재시작·재배포 후에도 남습니다. (작업 탭의 진행 목록은 브라우저에만 있어도, 끝난 결과는 서버가 기록합니다.)
45
+ - 날짜 → 폴더별로 묶여 보이고, 파일명·폴더 검색, 기간 필터, 선택 ZIP, 원본과 비교, 목록에서 지우기를 지원합니다.
46
+ - 지우기는 목록에서만 숨기며 Dataset 의 파일은 남습니다.
47
+ - 저장 위치(Dataset): `faceswap/index.json`, `faceswap/{id}/result.png · thumb.jpg · source.jpg`
48
+ - `result.png` 는 무손실 원본, `source.jpg` 는 비교용 축소 원본입니다. 장당 수 MB 가 쌓이니 주기적으로 용량을 확인하세요.
49
+ - `HF_TOKEN`/`HF_DATASET_REPO` 가 없으면 서버 디스크에만 저장되어 **Space 가 재시작되면 사라집니다.** (화면에 안내가 표시됩니다.)
50
+ - Dataset 커밋은 15초 단위로 묶어서 합니다 (HF 커밋 횟수 제한 때문). 결과 화면에는 즉시 보입니다.
51
+
52
+ ## 얼굴 교체 설정 (작업 탭 위쪽)
53
+ - **성별 일괄 선택** — 전체 남자 / 전체 여자 / 파일명대로(자동 판정으로 되돌리기). 건너뜀·작업 중·완료된 사진은 그대로 둬요.
54
+ - **변형 강도** — 얼굴 · 머리를 따로 0.10~1.00 으로 조절해요(기본 0.40 · 0.40). **값의 뜻은 옛 워크플로우의 denoise 와 같아요**(얼굴=머리=0.4 면 옛 `denoise 0.4` 와 결과가 동일). 낮을수록 원본이 많이 남고, 높을수록 모델 사진 쪽으로 많이 바뀌어요. 이후에 시작하는 작업부터 적용돼요.
55
+ - **페르소나 모델** — 기본은 `assets/faces/` 의 `male.jpg` · `female.jpg`. 화면에서 직접 올리면 그 얼굴을 써요(올린 사진은 이 브라우저에 기억돼요, `기본으로`로 되돌림). 머리 스타일 설명은 비워 두면 "모델 사진과 같은 머리"로만 지시해요.
56
+ - 설정 값은 브라우저(localStorage)에 저장돼요. 기본 강도를 바꾸려면 `workflow_api.json` 의 `KSampler`(노드 `781`) `denoise` 를 고치세요.
57
+
58
+ ### 워크플로우 구조 (강도를 나누는 방법)
59
+ `workflow_api.json` 의 샘플링 마스크(노드 `316` ← `909`)가 **픽셀마다 시작 시점이 다른 지도**예요: 머리카락 영역(`906`)과 나머지 얼굴·귀·목(`903`). 차등 확산(`387`)이 이 지도대로 영역별 강도를 적용해요.
60
+ 앱은 두 강도 중 **큰 값을 KSampler(`781`)의 denoise 로** 넣고, 작은 영역에는 "더 늦게 시작하라"는 **상대 마스크 값**(`903`·`906`)을 넣어요. 두 값이 같으면 마스크가 모두 1 이라 옛 워크플로우(`denoise 0.4` + 머리 마스크)와 똑같이 동작해요.
61
+ > 주의: 차등 확산은 마스크 값을 '노이즈 단계의 비율'로 읽기 때문에, 마스크에 0.4 를 그냥 넣으면(KSampler 1.0) `denoise 0.4` 보다 훨씬 약해져요. 그래서 위처럼 강도를 변환해서 넣어요. 워크플로우 파일을 ComfyUI 에서 직접 돌릴 때는 `903`·`906` 을 1 로 두고 `781` 의 denoise 로 강도를 정하세요.
62
+ 머리카락 영역은 `hairstyle · black hair · hair` 를 합쳐 인식하고(노드 `901`·`902`), 얼굴+목(노드 `936`·`937`)을 뺀 부분이에요. 앱이 값을 넣는 노드: `781`(시드·강도) · `903` `906`(영역별 상대 강도) · `111`(프롬프트) · `645` `646`(이미지).
63
+ 이 노드가 없는 옛 워크플로우를 올려도 동작해요(화면에는 "변형" 슬라이더 하나만 보이고 denoise 로 전달).
64
+
65
+ ## 쓰는 법
66
+ - **폴더별 묶음**: 사진은 *사진이 직접 들어 있는 폴더* 단위로 묶여 나옵니다. 예) `피카소테스트.zip` 안에 `피카소테스트/1_…_여자/`, `피카소테스트/32_…_남자/` 가 있으면 폴더마다 따로 묶이고(번호 순), 제목에는 위쪽 경로가 흐리게 함께 표시됩니다. 지난 결과 탭도 같은 기준입니다. `이 폴더 ZIP`은 그 폴더에 직접 든 사진만 담습니다(하위 폴더는 별도 묶음).
67
+ - **ZIP 업로드**: 가운데 영역에 사진이 든 폴더를 ZIP 한 개로 묶어 올립니다(끌어다 놓기도 가능). ZIP 안의 사진이 모두 작은 타일로 나타납니다. 올린 뒤에는 위쪽 진행 바의 **ZIP 추가**로 더 올립니다.
68
+ - 파일명에 `남자`·`여자`(또는 male/female)가 있으면 맞는 얼굴이 자동으로 정해집니다. 한 글자 표기 `남`·`여` 도 인식하지만, 앞뒤가 `_` `-` 공백 숫자 같은 구분자일 때만 인식합니다(`남_01`, `01_여` 는 되고 `여행`, `남산` 은 안 됨). 둘 다 있으면(`남_여`) 직접 고릅니다.
69
+ - 파일명에 표기가 없으면 **폴더 이름**으로 정합니다. 가까운 폴더부터 위로 올라가며 찾고(`남자/001.jpg`, `촬영/여/a.jpg`, `남자/여행/b.jpg` → 모두 인식), 마지막으로 **ZIP 파일 이름**도 봅니다(`6_SPPPG4VU10_25_여자.zip` → 안의 사진 모두 여자). 우선순위는 파일명 > 폴더 이름 > ZIP 이름입니다. 파일명에 표기가 있으면 파일명이 우선입니다(`여자/남자_x.jpg` → 남자). 폴더로 정해진 타일에는 `(폴더)`, ZIP 이름으로 정해진 타일에는 `(ZIP)`이 표시됩니다. 화면의 묶음 이름은 ZIP 파일 이름이 아니라 ZIP 안 폴더 이름입니다. 없으면 타일에서 직접 고르거나 건너뜁니다. (삽입되는 기본 얼굴은 서버의 `assets/faces/male.jpg`·`female.jpg` 입니다. 모두에게 바꾸려면 이 두 파일을 교체해 다시 올리고, 내 화면에서만 바꾸려면 **얼굴 교체 설정 → 페르소나 모델**에서 직접 올리세요.)
70
+ - **한 번에 생성**: 동시에 만드는 장수는 기본 **2장**이고, 진행 화면에 "한 번에 2장씩"으로 표시됩니다. 관리자가 바꾸려면 주소 뒤에 `?conc=3`(1~4)을 붙이세요.
71
+ - **시작** → 타일마다 진행 막대가 보이고, 끝난 타일은 결과로 바뀝니다. 타일을 누르면 원본과 비교, **받기**는 올린 파일명 그대로 받습니다.
72
+ - 받기: 타일별 **받기**, 폴더별 **이 폴더 ZIP**, 상단 **완료분 ZIP 받기**. 예전 결과는 **지난 결과** 탭에서 받습니다.
73
+ - ���형 강도(얼굴·머리)와 페르소나 모델은 화면 위쪽 **얼굴 교체 설정**에서 바꿉니다(위 설명 참고). 바꿀 범위(노드 801·802 문구)와 기본 프롬프트 문장은 `workflow_api.json` · `comfy_client.py` 의 `PROMPT_TEMPLATE` · `DEFAULT_HAIR` 를 수정하세요.
74
+
75
+ ## 파일
76
+ | 파일 | 역할 |
77
+ |---|---|
78
+ | `server.py` | FastAPI — 작업 생성·상태·다운로드·ZIP |
79
+ | `comfy_client.py` | Comfy Cloud REST (업로드·제출·폴링·다운로드) |
80
+ | `history.py` | 결과 영구 저장 — 로컬 캐시 + HF Dataset 묶음 커밋·복원 |
81
+ | `workflow_api.json` | Export (API) 로 저장한 워크플로우 |
82
+ | `index.html` | 화면 (루트 또는 `static/` 어디에 있어도 동작) |
83
+ | `assets/faces/` | 기본 삽입 얼굴 |
84
+
85
+ ## 환경변수 (선택)
86
+ `REQUIRE_LOGIN`(로그인 필수 여부, 기본 true — `hf_oauth` 가 있을 때만 적용) · `CREDITS_PER_IMAGE`(통계의 크레딧 추정 단가, 기본 8.6) · `COMFY_MAX_CONCURRENT`(서버 동시 처리, 기본 4) · `MAX_INPUT_SIDE`(업로드 긴 변 상한, 기본 4096) · `HISTORY_COMMIT_INTERVAL`(Dataset 커밋 간격 초, 기본 15) · `DATA_DIR`(로컬 저장 경로) · `HISTORY_REMOTE_DIR`(HF 대신 다른 폴더/볼륨에 미러)
comfy_client (19).py ADDED
@@ -0,0 +1,534 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ comfy_client.py — Comfy Cloud REST 클라이언트 (얼굴 교체 워크플로우 전용)
3
+
4
+ 흐름: 이미지 업로드(해시 캐시) → workflow_api.json 패치 → /api/prompt 제출
5
+ → 상태 폴링 → SaveImage(760) 출력 다운로드
6
+
7
+ 환경변수
8
+ COMFY_CLOUD_API_KEY platform.comfy.org 에서 발급한 키 (Space Secret)
9
+ COMFY_BASE_URL 기본 https://cloud.comfy.org
10
+ COMFY_WORKFLOW_PATH 기본 workflow_api.json (Export (API) 로 저장한 파일)
11
+ MAX_INPUT_SIDE 업로드 전 긴 변 상한(px), 기본 4096
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import copy
16
+ import hashlib
17
+ import io
18
+ import json
19
+ import os
20
+ import random
21
+ import threading
22
+ import time
23
+ from typing import Any, Callable, Dict, List, Optional, Tuple
24
+
25
+ import httpx
26
+ from PIL import Image, ImageOps
27
+
28
+ BASE_URL = os.environ.get("COMFY_BASE_URL", "https://cloud.comfy.org").rstrip("/")
29
+ API_KEY = os.environ.get("COMFY_CLOUD_API_KEY", "")
30
+ WORKFLOW_PATH = os.environ.get("COMFY_WORKFLOW_PATH", "workflow_api.json")
31
+ MAX_INPUT_SIDE = int(os.environ.get("MAX_INPUT_SIDE", "4096"))
32
+
33
+ # ── 워크플로우 노드 ID (faceswap_001.json 기준) ───────────────────────────────
34
+ NODE_MAIN = "645" # LoadImage "Main Image" (몸/배경 원본)
35
+ NODE_FACE = "646" # LoadImage "Reference Face Image" (삽입할 얼굴)
36
+ NODE_OUT = "760" # SaveImage "Image Save(Output)"
37
+ NODE_SAMPLER = "781" # KSampler (seed / denoise)
38
+ NODE_PROMPT = "111" # TextEncodeQwenImageEditPlus (긍정 프롬프트)
39
+ NODE_MASK_MAIN = "801" # CLIPTextEncode — 원본 이미지에서 마스킹할 대상(SAM3)
40
+ NODE_MASK_REF = "802" # CLIPTextEncode — 얼굴 이미지에서 마스킹할 대상(SAM3)
41
+ NODE_FACE_STRENGTH = "903" # SolidMask — 얼굴(머리카락 아닌 부분)의 '상대' 강도 (앱이 채운다)
42
+ NODE_HAIR_STRENGTH = "906" # SolidMask — 머리카락의 '상대' 강도 (앱이 채운다)
43
+ NODE_SHIFT = "66" # ModelSamplingAuraFlow — 노이즈 단계 곡선(shift)
44
+ REQUIRED_NODES = [NODE_MAIN, NODE_FACE, NODE_OUT, NODE_SAMPLER]
45
+
46
+ # ── 프롬프트(성별·머리 스타일 설명으로 완성) ─────────────────────────────────────
47
+ SUBJECT = {"male": "man", "female": "woman"}
48
+ PROMPT_TEMPLATE = ("Replace the head of the {subject} in the first image with the head of the {subject} in the second image: "
49
+ "the same face and the same hairstyle as the second image{hair}. "
50
+ "Keep the body, clothes, pose, head direction, lighting and background of the first image. "
51
+ "Seamless blend, natural lighting, consistent skin tone.")
52
+ # 기본(assets) 얼굴의 머리 스타일 설명. 사용자가 올린 얼굴에는 쓰지 않는다(화면에서 직접 적을 수 있다).
53
+ DEFAULT_HAIR = {
54
+ "male": "black hair with a center part and long wispy curtain bangs falling over the forehead and framing both sides of the face, straight slightly tousled strands",
55
+ "female": "long straight jet-black hair with a center part falling past the shoulders on both sides, tucked slightly behind the ears",
56
+ }
57
+ STRENGTH_MIN, STRENGTH_MAX = 0.05, 1.0
58
+
59
+ TERMINAL_OK = {"success", "succeeded", "completed", "complete"}
60
+ TERMINAL_FAIL = {"error", "failed", "non_retryable_error", "lost", "cancelled", "canceled"}
61
+ CANCELLED = {"cancelled", "canceled"}
62
+ RUNNING = {"in_progress", "running", "executing"}
63
+
64
+ _HTTP_TIMEOUT = httpx.Timeout(connect=10.0, read=120.0, write=180.0, pool=10.0)
65
+
66
+
67
+ class ComfyError(RuntimeError):
68
+ pass
69
+
70
+
71
+ class ComfyCancelled(ComfyError):
72
+ """사용자가 취소했다."""
73
+
74
+
75
+ def _headers(json_ct: bool = True) -> Dict[str, str]:
76
+ if not API_KEY:
77
+ raise ComfyError("COMFY_CLOUD_API_KEY 가 설정되지 않았습니다 (Space Settings → Secrets).")
78
+ h = {"X-API-Key": API_KEY}
79
+ if json_ct:
80
+ h["Content-Type"] = "application/json"
81
+ return h
82
+
83
+
84
+ # ── 워크플로우 템플릿 ──────────────────────────────────────────────────────────
85
+ _TEMPLATE: Optional[Dict[str, Any]] = None
86
+ _TEMPLATE_LOCK = threading.Lock()
87
+
88
+
89
+ def load_workflow_template() -> Dict[str, Any]:
90
+ global _TEMPLATE
91
+ with _TEMPLATE_LOCK:
92
+ if _TEMPLATE is not None:
93
+ return _TEMPLATE
94
+ if not os.path.exists(WORKFLOW_PATH):
95
+ raise ComfyError(f"{WORKFLOW_PATH} 파일이 없습니다. Comfy Cloud에서 Export (API)로 저장해 Space 루트에 넣어주세요.")
96
+ with open(WORKFLOW_PATH, "r", encoding="utf-8") as f:
97
+ wf = json.load(f)
98
+ if not isinstance(wf, dict) or "nodes" in wf:
99
+ raise ComfyError(f"{WORKFLOW_PATH} 는 API 포맷이 아닙니다 (canvas 저장본). Export (API)로 다시 저장해주세요.")
100
+ missing = [n for n in REQUIRED_NODES if n not in wf]
101
+ if missing:
102
+ raise ComfyError(f"workflow_api.json 에 기대한 노드 ID가 없습니다: {missing}")
103
+ _TEMPLATE = wf
104
+ print(f"[COMFY] workflow loaded: {WORKFLOW_PATH} ({len(wf)} nodes)")
105
+ return wf
106
+
107
+
108
+ def workflow_defaults() -> Dict[str, Any]:
109
+ """UI '고급 설정'의 기본값 — 워크플로우에 들어있는 값 그대로."""
110
+ wf = load_workflow_template()
111
+
112
+ def g(node: str, key: str, default: Any = None) -> Any:
113
+ v = wf.get(node, {}).get("inputs", {}).get(key, default)
114
+ return v if not isinstance(v, list) else default
115
+
116
+ graded = NODE_FACE_STRENGTH in wf and NODE_HAIR_STRENGTH in wf # 얼굴·머리 강도를 따로 줄 수 있는 워크플로우인가
117
+ return {
118
+ "graded": graded,
119
+ "face_strength": g(NODE_SAMPLER, "denoise", 0.4), # 기본 강도 = 워크플로우 KSampler 의 denoise (얼굴·머리 같은 값)
120
+ "hair_strength": g(NODE_SAMPLER, "denoise", 0.4),
121
+ "hair_desc": dict(DEFAULT_HAIR),
122
+ "strength_range": [STRENGTH_MIN, STRENGTH_MAX],
123
+ "denoise": g(NODE_SAMPLER, "denoise", 0.4),
124
+ "prompt": PROMPT_TEMPLATE,
125
+ "mask_main": g(NODE_MASK_MAIN, "text", "face:1, head:1, hair:1"),
126
+ "mask_ref": g(NODE_MASK_REF, "text", "face:1, head:1, hair:1"),
127
+ }
128
+
129
+
130
+ def status() -> Dict[str, Any]:
131
+ try:
132
+ wf = load_workflow_template()
133
+ return {"ok": bool(API_KEY), "workflow": True, "nodes": len(wf), "api_key": bool(API_KEY),
134
+ "error": None if API_KEY else "COMFY_CLOUD_API_KEY 가 설정되지 않았습니다 (Space Settings → Secrets)."}
135
+ except ComfyError as e:
136
+ return {"ok": False, "workflow": False, "api_key": bool(API_KEY), "error": str(e)}
137
+
138
+
139
+ # ── 이미지 정규화 + 업로드(내용 해시 캐시) ─────────────────────────────────────
140
+ _UPLOAD_CACHE: Dict[str, str] = {}
141
+ _UPLOAD_LOCK = threading.Lock()
142
+
143
+
144
+ def normalize_image_bytes(data: bytes, max_side: int = MAX_INPUT_SIDE) -> Tuple[bytes, Tuple[int, int]]:
145
+ """EXIF 회전 적용 · 알파는 흰 배경에 합성 · 과대 이미지는 축소 → 무손실 PNG."""
146
+ try:
147
+ img = Image.open(io.BytesIO(data))
148
+ img.load()
149
+ except Exception as e: # noqa: BLE001
150
+ raise ComfyError(f"이미지를 열 수 없습니다: {e}") from e
151
+ img = ImageOps.exif_transpose(img)
152
+ if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info):
153
+ rgba = img.convert("RGBA")
154
+ bg = Image.new("RGB", rgba.size, (255, 255, 255))
155
+ bg.paste(rgba, mask=rgba.split()[-1])
156
+ img = bg
157
+ elif img.mode != "RGB":
158
+ img = img.convert("RGB")
159
+ w, h = img.size
160
+ if max(w, h) > max_side:
161
+ s = max_side / max(w, h)
162
+ img = img.resize((max(1, round(w * s)), max(1, round(h * s))), Image.LANCZOS)
163
+ out = io.BytesIO()
164
+ img.save(out, format="PNG", compress_level=3)
165
+ return out.getvalue(), img.size
166
+
167
+
168
+ def ensure_uploaded(data: bytes, label: str = "") -> str:
169
+ """같은 바이트는 한 번만 올린다. Comfy Cloud 가 돌려준 파일명(해시 기반)을 그대로 사용해야 한다."""
170
+ norm, _ = normalize_image_bytes(data)
171
+ digest = hashlib.sha256(norm).hexdigest()
172
+ with _UPLOAD_LOCK:
173
+ cached = _UPLOAD_CACHE.get(digest)
174
+ if cached:
175
+ return cached
176
+ filename = f"{digest}.png"
177
+ with httpx.Client(timeout=_HTTP_TIMEOUT) as client:
178
+ r = client.post(
179
+ f"{BASE_URL}/api/upload/image",
180
+ headers=_headers(json_ct=False),
181
+ files={"image": (filename, norm, "image/png")},
182
+ data={"type": "input", "overwrite": "true"},
183
+ )
184
+ if r.status_code >= 400:
185
+ raise ComfyError(f"이미지 업로드 실패({label or filename}): HTTP {r.status_code} {r.text[:200]}")
186
+ name = r.json().get("name") or filename
187
+ with _UPLOAD_LOCK:
188
+ _UPLOAD_CACHE[digest] = name
189
+ print(f"[COMFY] uploaded {label or ''} → {name[:16]}… ({len(norm):,} bytes)")
190
+ return name
191
+
192
+
193
+ # ── 워크플로우 패치 ────────────────────────────────────────────────────────────
194
+ def _strength(v: Any) -> Optional[float]:
195
+ """화면에서 온 강도 값을 0.05~1.0 으로 정리. 숫자가 아니면 None(= 워크플로우 기본값 유지)."""
196
+ try:
197
+ f = float(v)
198
+ except (TypeError, ValueError):
199
+ return None
200
+ if f != f: # NaN
201
+ return None
202
+ return round(min(STRENGTH_MAX, max(STRENGTH_MIN, f)), 3)
203
+
204
+
205
+ def compose_prompt(gender: str, hair_desc: str = "") -> str:
206
+ """성별(남자=man, 여자=woman)과 머리 스타일 설명으로 긍정 프롬프트를 만든다. 설명이 비면 '레퍼런스와 같은 머리'만 지시한다."""
207
+ desc = " ".join((hair_desc or "").split()).strip(" ,.")
208
+ return PROMPT_TEMPLATE.format(subject=SUBJECT.get(gender, "person"), hair=(", " + desc) if desc else "")
209
+
210
+
211
+ def _sigma_start(v: float, shift: float) -> float:
212
+ """강도 v 로 만들 때 첫 단계의 노이즈 크기(시그마). KSampler denoise=v 는 이 값에서 시작한다."""
213
+ return shift * v / (1.0 + (shift - 1.0) * v)
214
+
215
+
216
+ def build_workflow(main_name: str, face_name: str, settings: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
217
+ """settings: face_strength / hair_strength(0.05~1) · denoise(옛 방식, 하나의 강도) · prompt(통째로 바꿀 때) ·
218
+ gender + hair_desc(프롬프트 자동 구성) · mask_main / mask_ref
219
+
220
+ 강도의 뜻은 옛 워크플로우의 denoise 와 같다: 얼굴·머리가 같은 값 v 면 `KSampler denoise = v` 와 똑같이 동작한다.
221
+ 영역마다 값이 다르면 KSampler denoise 는 둘 중 큰 값으로 두고, 작은 영역은 차등 확산 마스크(상대값)로 더 늦게 시작시킨다.
222
+ (마스크 값은 '노이즈 단계의 비율'로 해석되므로, 강도→시작 노이즈 크기로 바꿔 비율을 구한다. 그냥 0.4 를 넣으면 훨씬 약해진다.)"""
223
+ s = settings or {}
224
+ wf = copy.deepcopy(load_workflow_template())
225
+ wf[NODE_MAIN]["inputs"]["image"] = main_name
226
+ wf[NODE_FACE]["inputs"]["image"] = face_name
227
+ wf[NODE_SAMPLER]["inputs"]["seed"] = random.randint(0, 2**53 - 1)
228
+
229
+ graded = NODE_FACE_STRENGTH in wf and NODE_HAIR_STRENGTH in wf
230
+ face_s, hair_s, legacy = _strength(s.get("face_strength")), _strength(s.get("hair_strength")), _strength(s.get("denoise"))
231
+ if graded: # 영역별 강도(얼굴/머리)를 쓰는 워크플로우
232
+ base = _strength(wf[NODE_SAMPLER]["inputs"].get("denoise")) or 0.4 # 값을 안 받았을 때의 기본 강도
233
+ if legacy is not None: # 옛 방식(denoise 하나)으로 온 값은 얼굴·머리 둘 다에
234
+ face_s = legacy if face_s is None else face_s
235
+ hair_s = legacy if hair_s is None else hair_s
236
+ face_v = face_s if face_s is not None else base
237
+ hair_v = hair_s if hair_s is not None else base
238
+ top = max(face_v, hair_v)
239
+ shift = float(wf.get(NODE_SHIFT, {}).get("inputs", {}).get("shift") or 3)
240
+ wf[NODE_SAMPLER]["inputs"]["denoise"] = top
241
+ denom = _sigma_start(top, shift)
242
+ wf[NODE_FACE_STRENGTH]["inputs"]["value"] = round(min(1.0, _sigma_start(face_v, shift) / denom), 4)
243
+ wf[NODE_HAIR_STRENGTH]["inputs"]["value"] = round(min(1.0, _sigma_start(hair_v, shift) / denom), 4)
244
+ else: # 옛 워크플로우: 하나의 denoise (얼굴 강도 값을 쓴다)
245
+ one = legacy if legacy is not None else face_s
246
+ if one is not None:
247
+ wf[NODE_SAMPLER]["inputs"]["denoise"] = one
248
+
249
+ prompt = s.get("prompt")
250
+ if not (isinstance(prompt, str) and prompt.strip()) and s.get("gender") in SUBJECT:
251
+ prompt = compose_prompt(s["gender"], s.get("hair_desc") or "")
252
+ if isinstance(prompt, str) and prompt.strip() and NODE_PROMPT in wf:
253
+ wf[NODE_PROMPT]["inputs"]["prompt"] = prompt.strip()
254
+ for key, node in (("mask_main", NODE_MASK_MAIN), ("mask_ref", NODE_MASK_REF)):
255
+ v = s.get(key)
256
+ if isinstance(v, str) and v.strip() and node in wf:
257
+ wf[node]["inputs"]["text"] = v.strip()
258
+ return wf
259
+
260
+
261
+ # ── 제출 / 상태 / 다운로드 ─────────────────────────────────────────────────────
262
+ def submit(wf: Dict[str, Any]) -> str:
263
+ payload = {"prompt": wf, "extra_data": {"api_key_comfy_org": API_KEY}}
264
+ with httpx.Client(timeout=_HTTP_TIMEOUT) as client:
265
+ r = client.post(f"{BASE_URL}/api/prompt", headers=_headers(), json=payload)
266
+ if r.status_code >= 400:
267
+ detail = r.text[:500]
268
+ try:
269
+ j = r.json()
270
+ errs = j.get("node_errors") or j.get("error")
271
+ if errs:
272
+ detail = json.dumps(errs, ensure_ascii=False)[:700]
273
+ except Exception: # noqa: BLE001
274
+ pass
275
+ hint = {401: "API 키가 잘못되었습니다.", 402: "Comfy 크레딧이 부족합니다.",
276
+ 429: "Comfy Cloud 구독/동시 실행 한도를 확인해주세요."}.get(r.status_code, "")
277
+ raise ComfyError(f"워크플로우 제출 실패 (HTTP {r.status_code}) {hint} {detail}".strip())
278
+ j = r.json()
279
+ if j.get("error") or not j.get("prompt_id"):
280
+ raise ComfyError(f"워크플로우 검증 오류: {json.dumps(j.get('node_errors') or j.get('error') or j, ensure_ascii=False)[:700]}")
281
+ return j["prompt_id"]
282
+
283
+
284
+ def job_status(prompt_id: str) -> str:
285
+ with httpx.Client(timeout=_HTTP_TIMEOUT) as client:
286
+ r = client.get(f"{BASE_URL}/api/job/{prompt_id}/status", headers=_headers(False))
287
+ if r.status_code == 404: # 경로가 다른 환�� 대비
288
+ r = client.get(f"{BASE_URL}/api/jobs/{prompt_id}", headers=_headers(False))
289
+ if r.status_code >= 400:
290
+ raise ComfyError(f"상태 조회 실패: HTTP {r.status_code} {r.text[:200]}")
291
+ return str(r.json().get("status", "")).lower()
292
+
293
+
294
+ def _collect_image_refs(obj: Any, acc: List[Dict[str, Any]]) -> None:
295
+ """응답 어디에 있든 {filename, subfolder, type} 형태의 파일 참조를 모은다."""
296
+ if isinstance(obj, dict):
297
+ if isinstance(obj.get("filename"), str):
298
+ acc.append(obj)
299
+ for v in obj.values():
300
+ _collect_image_refs(v, acc)
301
+ elif isinstance(obj, list):
302
+ for v in obj:
303
+ _collect_image_refs(v, acc)
304
+
305
+
306
+ def _outputs_of(data: Any) -> Optional[Dict[str, Any]]:
307
+ """응답에서 '결과(outputs)' 부분만 꺼낸다.
308
+
309
+ /api/jobs/{id} 는 결과(outputs) 외에 전체 워크플로우(workflow)도 함께 돌려주는데, 거기에도 노드 ID("760")가
310
+ 키로 들어 있다. 응답 전체에서 키를 찾으면 워크플로우의 노드 정의를 잡아 버리므로, outputs 만 정확히 집는다.
311
+ """
312
+ if not isinstance(data, dict):
313
+ return None
314
+ if isinstance(data.get("outputs"), dict):
315
+ return data["outputs"]
316
+ hist = data.get("history") # /api/history_v2: {"history": [ {...} ]}
317
+ if isinstance(hist, list):
318
+ for e in hist:
319
+ o = _outputs_of(e)
320
+ if o:
321
+ return o
322
+ for v in data.values(): # /api/history_v2/{id}: {prompt_id: {outputs: ...}}
323
+ if isinstance(v, dict) and isinstance(v.get("outputs"), dict):
324
+ return v["outputs"]
325
+ return None
326
+
327
+
328
+ def _only_outputs(refs: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
329
+ return [x for x in refs if x.get("type", "output") == "output"] # temp(MaskPreview 등) 제외
330
+
331
+
332
+ def job_outputs(prompt_id: str) -> List[Dict[str, Any]]:
333
+ """SaveImage 노드(760)의 결과 우선. 없으면 outputs 안의 아무 최종(output) 이미지."""
334
+ seen: List[Any] = []
335
+ with httpx.Client(timeout=_HTTP_TIMEOUT) as client:
336
+ for url in (f"{BASE_URL}/api/jobs/{prompt_id}",
337
+ f"{BASE_URL}/api/history_v2/{prompt_id}",
338
+ f"{BASE_URL}/api/history/{prompt_id}"):
339
+ try:
340
+ r = client.get(url, headers=_headers(False))
341
+ except Exception: # noqa: BLE001
342
+ continue
343
+ if r.status_code >= 400:
344
+ continue
345
+ try:
346
+ data = r.json()
347
+ except ValueError:
348
+ continue
349
+ outs = _outputs_of(data)
350
+ if outs:
351
+ seen.append(sorted(outs.keys()))
352
+ refs: List[Dict[str, Any]] = []
353
+ if outs.get(NODE_OUT) is not None:
354
+ _collect_image_refs(outs[NODE_OUT], refs)
355
+ refs = _only_outputs(refs)
356
+ if not refs: # 저장 노드 번호가 달라진 경우 대비
357
+ _collect_image_refs(outs, refs)
358
+ refs = _only_outputs(refs)
359
+ if refs:
360
+ return refs
361
+ pv = data.get("preview_output") if isinstance(data, dict) else None
362
+ if pv:
363
+ refs = []
364
+ _collect_image_refs(pv, refs)
365
+ refs = _only_outputs(refs)
366
+ if refs:
367
+ return refs
368
+ print(f"[COMFY] {prompt_id}: 출력 이미지를 찾지 못함 (outputs 에 있던 노드: {seen or '없음'})")
369
+ return []
370
+
371
+
372
+ def job_error_detail(prompt_id: str) -> str:
373
+ try:
374
+ with httpx.Client(timeout=_HTTP_TIMEOUT) as client:
375
+ r = client.get(f"{BASE_URL}/api/jobs/{prompt_id}", headers=_headers(False))
376
+ if r.status_code >= 400:
377
+ return ""
378
+ j = r.json()
379
+ for key in ("error", "execution_error", "exception_message", "message"):
380
+ v = j.get(key)
381
+ if v:
382
+ return json.dumps(v, ensure_ascii=False)[:500] if not isinstance(v, str) else v[:500]
383
+ except Exception: # noqa: BLE001
384
+ pass
385
+ return ""
386
+
387
+
388
+ def _post(path: str, payload: Optional[Dict[str, Any]] = None) -> httpx.Response:
389
+ with httpx.Client(timeout=_HTTP_TIMEOUT) as client:
390
+ if payload is None:
391
+ return client.post(f"{BASE_URL}{path}", headers=_headers(json_ct=False))
392
+ return client.post(f"{BASE_URL}{path}", headers=_headers(), json=payload)
393
+
394
+
395
+ def running_prompt_ids() -> Optional[set]:
396
+ """Comfy Cloud 에서 지금 실행 중인 작업 ID 모음. 알 수 없으면 None."""
397
+ try:
398
+ with httpx.Client(timeout=_HTTP_TIMEOUT) as client:
399
+ r = client.get(f"{BASE_URL}/api/queue", headers=_headers(False))
400
+ if r.status_code >= 400:
401
+ return None
402
+ j = r.json()
403
+ except Exception: # noqa: BLE001
404
+ return None
405
+ running = j.get("queue_running") if isinstance(j, dict) else None
406
+ if not isinstance(running, list):
407
+ return None
408
+ ids = set()
409
+ for e in running:
410
+ if isinstance(e, (list, tuple)) and len(e) > 1: # [번호, prompt_id, ...]
411
+ ids.add(str(e[1]))
412
+ elif isinstance(e, dict):
413
+ pid = e.get("prompt_id") or e.get("id")
414
+ if pid:
415
+ ids.add(str(pid))
416
+ return ids
417
+
418
+
419
+ def _safe_status(prompt_id: str) -> str:
420
+ try:
421
+ return job_status(prompt_id)
422
+ except Exception: # noqa: BLE001
423
+ return ""
424
+
425
+
426
+ def cancel_job(prompt_id: str, allowed_running: Optional[set] = None) -> str:
427
+ """Comfy Cloud 작업을 취소한다.
428
+
429
+ - 대기 중: POST /api/queue {"delete":[id]} 로 대기열에서 뺀다.
430
+ - 실행 중: POST /api/interrupt 는 이 계정의 '실행 중인 작업 전부'를 멈춘다.
431
+ 같은 API 키로 다른 사람·다른 앱이 돌리는 작업까지 끊길 수 있으므로, Cloud 에서 실행 중인 작업이
432
+ 전부 '지금 취소하려는 우리 작업'일 때만 쓴다. 아니면 중단하지 않고 결과만 버린다('soft').
433
+
434
+ 반환: 'removed' | 'interrupted' | 'soft' | 'finished'
435
+ """
436
+ try:
437
+ _post("/api/queue", {"delete": [prompt_id]})
438
+ except Exception: # noqa: BLE001
439
+ pass
440
+ st = _safe_status(prompt_id)
441
+ if st in TERMINAL_OK:
442
+ return "finished"
443
+ if st in TERMINAL_FAIL:
444
+ return "removed"
445
+ if st in RUNNING:
446
+ running = running_prompt_ids()
447
+ allowed = set(allowed_running or ()) | {prompt_id}
448
+ if running is not None and running <= allowed:
449
+ try:
450
+ _post("/api/interrupt")
451
+ return "interrupted"
452
+ except Exception: # noqa: BLE001
453
+ return "soft"
454
+ return "soft"
455
+ try: # 아직 대기 중이면 한 번 더 확실히
456
+ _post("/api/queue", {"delete": [prompt_id]})
457
+ except Exception: # noqa: BLE001
458
+ pass
459
+ return "removed"
460
+
461
+
462
+ def _get_following(client: httpx.Client, url: str, params: Optional[dict] = None, auth: bool = True) -> Optional[bytes]:
463
+ """302 로 넘어가는 signed URL 은 인증 헤더 없이 따라간다."""
464
+ r = client.get(url, headers=_headers(False) if auth else None, params=params, follow_redirects=False)
465
+ if r.status_code in (301, 302, 303, 307, 308):
466
+ loc = r.headers.get("location")
467
+ if not loc:
468
+ return None
469
+ r2 = httpx.get(loc, follow_redirects=True, timeout=_HTTP_TIMEOUT)
470
+ return r2.content if r2.status_code == 200 else None
471
+ return r.content if r.status_code == 200 and r.content else None
472
+
473
+
474
+ def download_output(ref: Dict[str, Any]) -> bytes:
475
+ params = {"filename": ref["filename"], "subfolder": ref.get("subfolder", ""), "type": ref.get("type", "output")}
476
+ with httpx.Client(timeout=_HTTP_TIMEOUT) as client:
477
+ data = _get_following(client, f"{BASE_URL}/api/view", params)
478
+ if data:
479
+ return data
480
+ asset_id = ref.get("asset_id") or ref.get("assetId")
481
+ if asset_id:
482
+ data = _get_following(client, f"{BASE_URL}/api/assets/{asset_id}/content")
483
+ if data:
484
+ return data
485
+ raise ComfyError("결과 이미지를 내려받지 못했습니다.")
486
+
487
+
488
+ def _sleep(seconds: float, should_cancel: Optional[Callable[[], bool]]) -> None:
489
+ """취소 요청에 빨리 반응하도록 잘게 쉰다."""
490
+ end = time.time() + seconds
491
+ while time.time() < end:
492
+ if should_cancel and should_cancel():
493
+ return
494
+ time.sleep(min(0.5, max(0.0, end - time.time())))
495
+
496
+
497
+ def wait_for_result(prompt_id: str, timeout_sec: int = 1500, interval: float = 3.0,
498
+ on_status: Optional[Callable[[str], None]] = None,
499
+ should_cancel: Optional[Callable[[], bool]] = None) -> bytes:
500
+ start = time.time()
501
+ last = ""
502
+ misses = 0
503
+ while time.time() - start < timeout_sec:
504
+ if should_cancel and should_cancel():
505
+ raise ComfyCancelled("취소했어요")
506
+ try:
507
+ st = job_status(prompt_id)
508
+ misses = 0
509
+ except ComfyError:
510
+ misses += 1
511
+ if misses > 8:
512
+ raise
513
+ _sleep(interval, should_cancel)
514
+ continue
515
+ if st != last and on_status:
516
+ on_status(st)
517
+ last = st
518
+ if st in CANCELLED:
519
+ raise ComfyCancelled("취소했어요")
520
+ if st in TERMINAL_OK:
521
+ refs: List[Dict[str, Any]] = []
522
+ for attempt in range(6): # 완료 표시 직후 outputs 가 늦게 채워질 수 있다
523
+ refs = job_outputs(prompt_id)
524
+ if refs:
525
+ break
526
+ time.sleep(2)
527
+ if not refs:
528
+ raise ComfyError("작업은 끝났지만 출력 이미지를 찾지 못했습니다 (SaveImage 노드 760 확인). 서버 로그의 '[COMFY] … 출력 이미지를 찾지 못함' 줄을 확인해 주세요.")
529
+ return download_output(refs[0])
530
+ if st in TERMINAL_FAIL:
531
+ detail = job_error_detail(prompt_id)
532
+ raise ComfyError(f"Comfy Cloud 작업 실패 ({st}) {detail}".strip())
533
+ _sleep(interval, should_cancel)
534
+ raise ComfyError(f"{timeout_sec}초 안에 작업이 끝나지 않았습니다.")
workflow_api (10).json ADDED
@@ -0,0 +1,987 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "38": {
3
+ "inputs": {
4
+ "clip_name": "qwen_2.5_vl_7b_fp8_scaled.safetensors",
5
+ "type": "qwen_image",
6
+ "device": "default"
7
+ },
8
+ "class_type": "CLIPLoader",
9
+ "_meta": {
10
+ "title": "CLIP 로드"
11
+ }
12
+ },
13
+ "39": {
14
+ "inputs": {
15
+ "vae_name": "qwen_image_vae.safetensors"
16
+ },
17
+ "class_type": "VAELoader",
18
+ "_meta": {
19
+ "title": "VAE 로드"
20
+ }
21
+ },
22
+ "66": {
23
+ "inputs": {
24
+ "shift": 3,
25
+ "sampling": "flow",
26
+ "model": [
27
+ "218",
28
+ 0
29
+ ]
30
+ },
31
+ "class_type": "ModelSamplingAuraFlow",
32
+ "_meta": {
33
+ "title": "모델 샘플링 (AuraFlow)"
34
+ }
35
+ },
36
+ "75": {
37
+ "inputs": {
38
+ "strength": 1,
39
+ "pre_cfg": false,
40
+ "model": [
41
+ "66",
42
+ 0
43
+ ]
44
+ },
45
+ "class_type": "CFGNorm",
46
+ "_meta": {
47
+ "title": "CFGNorm"
48
+ }
49
+ },
50
+ "88": {
51
+ "inputs": {
52
+ "pixels": [
53
+ "340",
54
+ 1
55
+ ],
56
+ "vae": [
57
+ "39",
58
+ 0
59
+ ]
60
+ },
61
+ "class_type": "VAEEncode",
62
+ "_meta": {
63
+ "title": "VAE 인코드"
64
+ }
65
+ },
66
+ "110": {
67
+ "inputs": {
68
+ "prompt": "(side-view:1.5), (looking away:1.5), (head turned:1.2)",
69
+ "clip": [
70
+ "38",
71
+ 0
72
+ ],
73
+ "vae": [
74
+ "39",
75
+ 0
76
+ ],
77
+ "image1": [
78
+ "277",
79
+ 0
80
+ ],
81
+ "image2": [
82
+ "340",
83
+ 1
84
+ ],
85
+ "image3": [
86
+ "129",
87
+ 0
88
+ ]
89
+ },
90
+ "class_type": "TextEncodeQwenImageEditPlus",
91
+ "_meta": {
92
+ "title": "TextEncodeQwenImageEditPlus(negative)"
93
+ }
94
+ },
95
+ "111": {
96
+ "inputs": {
97
+ "prompt": "Replace the head of the man in the first image with the head of the man in the second image: the same face and the same hairstyle as the second image, black hair with a center part and long wispy curtain bangs falling over the forehead and framing both sides of the face, straight slightly tousled strands. Keep the body, clothes, pose, head direction, lighting and background of the first image. Seamless blend, natural lighting, consistent skin tone.",
98
+ "clip": [
99
+ "38",
100
+ 0
101
+ ],
102
+ "vae": [
103
+ "39",
104
+ 0
105
+ ],
106
+ "image1": [
107
+ "277",
108
+ 0
109
+ ],
110
+ "image2": [
111
+ "340",
112
+ 1
113
+ ],
114
+ "image3": [
115
+ "129",
116
+ 0
117
+ ]
118
+ },
119
+ "class_type": "TextEncodeQwenImageEditPlus",
120
+ "_meta": {
121
+ "title": "텍스트 인코드 Qwen Image Edit Plus"
122
+ }
123
+ },
124
+ "129": {
125
+ "inputs": {
126
+ "detect_hand": "enable",
127
+ "detect_body": "enable",
128
+ "detect_face": "enable",
129
+ "resolution": 1024,
130
+ "bbox_detector": "yolox_l.onnx",
131
+ "pose_estimator": "dw-ll_ucoco_384_bs5.torchscript.pt",
132
+ "scale_stick_for_xinsr_cn": "disable",
133
+ "image": [
134
+ "183",
135
+ 0
136
+ ]
137
+ },
138
+ "class_type": "DWPreprocessor",
139
+ "_meta": {
140
+ "title": "DWPose Estimator"
141
+ }
142
+ },
143
+ "172": {
144
+ "inputs": {
145
+ "width": [
146
+ "183",
147
+ 1
148
+ ],
149
+ "height": [
150
+ "183",
151
+ 2
152
+ ],
153
+ "keep_proportions": true,
154
+ "upscale_method": "nearest-exact",
155
+ "crop": "disabled",
156
+ "mask": [
157
+ "177",
158
+ 2
159
+ ]
160
+ },
161
+ "class_type": "ResizeMask",
162
+ "_meta": {
163
+ "title": "Resize Mask"
164
+ }
165
+ },
166
+ "177": {
167
+ "inputs": {
168
+ "downscale_algorithm": "lanczos",
169
+ "upscale_algorithm": "lanczos",
170
+ "preresize": false,
171
+ "preresize_mode": "ensure minimum resolution",
172
+ "preresize_min_width": 1024,
173
+ "preresize_min_height": 1024,
174
+ "preresize_max_width": 16384,
175
+ "preresize_max_height": 16384,
176
+ "mask_fill_holes": true,
177
+ "mask_expand_pixels": 20,
178
+ "mask_invert": false,
179
+ "mask_blend_pixels": 5,
180
+ "mask_hipass_filter": 0.1,
181
+ "extend_for_outpainting": true,
182
+ "extend_up_factor": 1,
183
+ "extend_down_factor": 1,
184
+ "extend_left_factor": 1,
185
+ "extend_right_factor": 1,
186
+ "context_from_mask_extend_factor": 2.5,
187
+ "output_resize_to_target_size": true,
188
+ "output_target_width": 1024,
189
+ "output_target_height": 1024,
190
+ "output_padding": "128",
191
+ "image": [
192
+ "786",
193
+ 0
194
+ ],
195
+ "mask": [
196
+ "809",
197
+ 0
198
+ ]
199
+ },
200
+ "class_type": "InpaintCropImproved",
201
+ "_meta": {
202
+ "title": "✂️ Inpaint Crop (Improved)"
203
+ }
204
+ },
205
+ "183": {
206
+ "inputs": {
207
+ "width": 1024,
208
+ "height": 1024,
209
+ "interpolation": "lanczos",
210
+ "method": "keep proportion",
211
+ "condition": "downscale if bigger",
212
+ "multiple_of": 0,
213
+ "image": [
214
+ "177",
215
+ 1
216
+ ]
217
+ },
218
+ "class_type": "ImageResize+",
219
+ "_meta": {
220
+ "title": "🔧 Image Resize"
221
+ }
222
+ },
223
+ "218": {
224
+ "inputs": {
225
+ "lora_name": "Qwen-Image-Edit-2509-Lightning-8steps-V1.0-bf16.safetensors",
226
+ "strength_model": 1,
227
+ "model": [
228
+ "652",
229
+ 0
230
+ ]
231
+ },
232
+ "class_type": "LoraLoaderModelOnly",
233
+ "_meta": {
234
+ "title": "LoRA 로드 (모델 전용)"
235
+ }
236
+ },
237
+ "247": {
238
+ "inputs": {
239
+ "fill": "telea",
240
+ "falloff": 0,
241
+ "image": [
242
+ "183",
243
+ 0
244
+ ],
245
+ "mask": [
246
+ "172",
247
+ 0
248
+ ]
249
+ },
250
+ "class_type": "INPAINT_MaskedFill",
251
+ "_meta": {
252
+ "title": "Fill Masked Area"
253
+ }
254
+ },
255
+ "277": {
256
+ "inputs": {
257
+ "blur": 200,
258
+ "falloff": 0,
259
+ "image": [
260
+ "247",
261
+ 0
262
+ ],
263
+ "mask": [
264
+ "172",
265
+ 0
266
+ ]
267
+ },
268
+ "class_type": "INPAINT_MaskedBlur",
269
+ "_meta": {
270
+ "title": "Blur Masked Area"
271
+ }
272
+ },
273
+ "316": {
274
+ "inputs": {
275
+ "amount": 10,
276
+ "device": "auto",
277
+ "mask": [
278
+ "909",
279
+ 0
280
+ ]
281
+ },
282
+ "class_type": "MaskBlur+",
283
+ "_meta": {
284
+ "title": "🔧 Mask Blur"
285
+ }
286
+ },
287
+ "329": {
288
+ "inputs": {
289
+ "prompt": "place this character into the image",
290
+ "clip": [
291
+ "38",
292
+ 0
293
+ ],
294
+ "vae": [
295
+ "39",
296
+ 0
297
+ ],
298
+ "image1": [
299
+ "183",
300
+ 0
301
+ ],
302
+ "image2": [
303
+ "340",
304
+ 1
305
+ ],
306
+ "image3": [
307
+ "129",
308
+ 0
309
+ ]
310
+ },
311
+ "class_type": "TextEncodeQwenImageEditPlus",
312
+ "_meta": {
313
+ "title": "텍스트 인코드 Qwen Image Edit Plus"
314
+ }
315
+ },
316
+ "340": {
317
+ "inputs": {
318
+ "downscale_algorithm": "lanczos",
319
+ "upscale_algorithm": "lanczos",
320
+ "preresize": false,
321
+ "preresize_mode": "ensure minimum resolution",
322
+ "preresize_min_width": 1024,
323
+ "preresize_min_height": 1024,
324
+ "preresize_max_width": 16384,
325
+ "preresize_max_height": 16384,
326
+ "mask_fill_holes": true,
327
+ "mask_expand_pixels": 0,
328
+ "mask_invert": false,
329
+ "mask_blend_pixels": 0,
330
+ "mask_hipass_filter": 0.1,
331
+ "extend_for_outpainting": false,
332
+ "extend_up_factor": 1,
333
+ "extend_down_factor": 1,
334
+ "extend_left_factor": 1,
335
+ "extend_right_factor": 1,
336
+ "context_from_mask_extend_factor": 1,
337
+ "output_resize_to_target_size": true,
338
+ "output_target_width": 1024,
339
+ "output_target_height": 1024,
340
+ "output_padding": "32",
341
+ "image": [
342
+ "787",
343
+ 0
344
+ ],
345
+ "mask": [
346
+ "812",
347
+ 0
348
+ ]
349
+ },
350
+ "class_type": "InpaintCropImproved",
351
+ "_meta": {
352
+ "title": "✂️ Inpaint Crop (Improved)"
353
+ }
354
+ },
355
+ "385": {
356
+ "inputs": {
357
+ "noise_mask": true,
358
+ "positive": [
359
+ "111",
360
+ 0
361
+ ],
362
+ "negative": [
363
+ "110",
364
+ 0
365
+ ],
366
+ "vae": [
367
+ "39",
368
+ 0
369
+ ],
370
+ "pixels": [
371
+ "183",
372
+ 0
373
+ ],
374
+ "mask": [
375
+ "316",
376
+ 0
377
+ ]
378
+ },
379
+ "class_type": "InpaintModelConditioning",
380
+ "_meta": {
381
+ "title": "인페인팅 모델 조건 설정"
382
+ }
383
+ },
384
+ "387": {
385
+ "inputs": {
386
+ "strength": 1,
387
+ "model": [
388
+ "75",
389
+ 0
390
+ ]
391
+ },
392
+ "class_type": "DifferentialDiffusion",
393
+ "_meta": {
394
+ "title": "차등 확산"
395
+ }
396
+ },
397
+ "396": {
398
+ "inputs": {
399
+ "conditioning": [
400
+ "329",
401
+ 0
402
+ ],
403
+ "latent": [
404
+ "88",
405
+ 0
406
+ ]
407
+ },
408
+ "class_type": "ReferenceLatent",
409
+ "_meta": {
410
+ "title": "참조 잠재"
411
+ }
412
+ },
413
+ "494": {
414
+ "inputs": {
415
+ "samples": [
416
+ "781",
417
+ 0
418
+ ],
419
+ "vae": [
420
+ "39",
421
+ 0
422
+ ]
423
+ },
424
+ "class_type": "VAEDecode",
425
+ "_meta": {
426
+ "title": "VAE 디코드"
427
+ }
428
+ },
429
+ "518": {
430
+ "inputs": {
431
+ "stitcher": [
432
+ "177",
433
+ 0
434
+ ],
435
+ "inpainted_image": [
436
+ "494",
437
+ 0
438
+ ]
439
+ },
440
+ "class_type": "InpaintStitchImproved",
441
+ "_meta": {
442
+ "title": "✂️ Inpaint Stitch (Improved)"
443
+ }
444
+ },
445
+ "645": {
446
+ "inputs": {
447
+ "image": "3377158fc21b2b671e8917420d5dfe0245074b3a35bac6d197a30414b6b40ddf.jpeg"
448
+ },
449
+ "class_type": "LoadImage",
450
+ "_meta": {
451
+ "title": "Main Image"
452
+ }
453
+ },
454
+ "646": {
455
+ "inputs": {
456
+ "image": "2b9078b596527954e2b9713c8eff69cb1fc41cf9a36791f7fbe154b128660157.png"
457
+ },
458
+ "class_type": "LoadImage",
459
+ "_meta": {
460
+ "title": "Reference Face Image"
461
+ }
462
+ },
463
+ "652": {
464
+ "inputs": {
465
+ "unet_name": "qwen_image_edit_2509_fp8_e4m3fn.safetensors",
466
+ "weight_dtype": "fp8_e4m3fn"
467
+ },
468
+ "class_type": "UNETLoader",
469
+ "_meta": {
470
+ "title": "확산 모델 로드"
471
+ }
472
+ },
473
+ "716": {
474
+ "inputs": {
475
+ "width": [
476
+ "772",
477
+ 0
478
+ ],
479
+ "height": [
480
+ "772",
481
+ 1
482
+ ],
483
+ "interpolation": "lanczos",
484
+ "method": "keep proportion",
485
+ "condition": "always",
486
+ "multiple_of": 0,
487
+ "image": [
488
+ "518",
489
+ 0
490
+ ]
491
+ },
492
+ "class_type": "ImageResize+",
493
+ "_meta": {
494
+ "title": "🔧 Image Resize"
495
+ }
496
+ },
497
+ "760": {
498
+ "inputs": {
499
+ "filename_prefix": "ComfyUI",
500
+ "images": [
501
+ "716",
502
+ 0
503
+ ]
504
+ },
505
+ "class_type": "SaveImage",
506
+ "_meta": {
507
+ "title": "Image Save(Output)"
508
+ }
509
+ },
510
+ "772": {
511
+ "inputs": {
512
+ "image": [
513
+ "645",
514
+ 0
515
+ ]
516
+ },
517
+ "class_type": "Get Image Size",
518
+ "_meta": {
519
+ "title": "Get Image Size"
520
+ }
521
+ },
522
+ "781": {
523
+ "inputs": {
524
+ "seed": 235289200744936,
525
+ "steps": 8,
526
+ "cfg": 1,
527
+ "sampler_name": "euler",
528
+ "scheduler": "simple",
529
+ "denoise": 0.4,
530
+ "model": [
531
+ "387",
532
+ 0
533
+ ],
534
+ "positive": [
535
+ "385",
536
+ 0
537
+ ],
538
+ "negative": [
539
+ "385",
540
+ 1
541
+ ],
542
+ "latent_image": [
543
+ "385",
544
+ 2
545
+ ]
546
+ },
547
+ "class_type": "KSampler",
548
+ "_meta": {
549
+ "title": "KSampler (denoise = 가장 센 강도. 영역별 상대값은 903·906 이 정함)"
550
+ }
551
+ },
552
+ "786": {
553
+ "inputs": {
554
+ "upscale_method": "lanczos",
555
+ "largest_size": 2000,
556
+ "image": [
557
+ "645",
558
+ 0
559
+ ]
560
+ },
561
+ "class_type": "ImageScaleToMaxDimension",
562
+ "_meta": {
563
+ "title": "Scale Image to Max Dimension (2000px)"
564
+ }
565
+ },
566
+ "787": {
567
+ "inputs": {
568
+ "upscale_method": "lanczos",
569
+ "largest_size": 1000,
570
+ "image": [
571
+ "646",
572
+ 0
573
+ ]
574
+ },
575
+ "class_type": "ImageScaleToMaxDimension",
576
+ "_meta": {
577
+ "title": "Scale Image to Max Dimension (1000px)"
578
+ }
579
+ },
580
+ "800": {
581
+ "inputs": {
582
+ "ckpt_name": "sam3.1_multiplex_fp16.safetensors"
583
+ },
584
+ "class_type": "CheckpointLoaderSimple",
585
+ "_meta": {
586
+ "title": "Load SAM3 Model"
587
+ }
588
+ },
589
+ "801": {
590
+ "inputs": {
591
+ "text": "face:1, head:1, hair:1",
592
+ "clip": [
593
+ "800",
594
+ 1
595
+ ]
596
+ },
597
+ "class_type": "CLIPTextEncode",
598
+ "_meta": {
599
+ "title": "SAM3 Prompt (Main Image)"
600
+ }
601
+ },
602
+ "802": {
603
+ "inputs": {
604
+ "text": "face:1, head:1, hair:1",
605
+ "clip": [
606
+ "800",
607
+ 1
608
+ ]
609
+ },
610
+ "class_type": "CLIPTextEncode",
611
+ "_meta": {
612
+ "title": "SAM3 Prompt (Reference Face)"
613
+ }
614
+ },
615
+ "803": {
616
+ "inputs": {
617
+ "threshold": 0.3,
618
+ "refine_iterations": 2,
619
+ "individual_masks": false,
620
+ "model": [
621
+ "800",
622
+ 0
623
+ ],
624
+ "image": [
625
+ "786",
626
+ 0
627
+ ],
628
+ "conditioning": [
629
+ "801",
630
+ 0
631
+ ]
632
+ },
633
+ "class_type": "SAM3_Detect",
634
+ "_meta": {
635
+ "title": "Auto Mask - Main Image (head+hair)"
636
+ }
637
+ },
638
+ "804": {
639
+ "inputs": {
640
+ "threshold": 0.3,
641
+ "refine_iterations": 2,
642
+ "individual_masks": false,
643
+ "model": [
644
+ "800",
645
+ 0
646
+ ],
647
+ "image": [
648
+ "787",
649
+ 0
650
+ ],
651
+ "conditioning": [
652
+ "802",
653
+ 0
654
+ ]
655
+ },
656
+ "class_type": "SAM3_Detect",
657
+ "_meta": {
658
+ "title": "Auto Mask - Reference Face (head+hair)"
659
+ }
660
+ },
661
+ "805": {
662
+ "inputs": {
663
+ "mask": [
664
+ "809",
665
+ 0
666
+ ]
667
+ },
668
+ "class_type": "MaskPreview",
669
+ "_meta": {
670
+ "title": "Mask Preview (Main)"
671
+ }
672
+ },
673
+ "806": {
674
+ "inputs": {
675
+ "mask": [
676
+ "812",
677
+ 0
678
+ ]
679
+ },
680
+ "class_type": "MaskPreview",
681
+ "_meta": {
682
+ "title": "Mask Preview (Reference)"
683
+ }
684
+ },
685
+ "807": {
686
+ "inputs": {
687
+ "expand": 50,
688
+ "tapered_corners": true,
689
+ "mask": [
690
+ "803",
691
+ 0
692
+ ]
693
+ },
694
+ "class_type": "GrowMask",
695
+ "_meta": {
696
+ "title": "Main: close gaps (+50)"
697
+ }
698
+ },
699
+ "808": {
700
+ "inputs": {
701
+ "masks": [
702
+ "807",
703
+ 0
704
+ ]
705
+ },
706
+ "class_type": "Mask Fill Holes",
707
+ "_meta": {
708
+ "title": "Main: fill holes"
709
+ }
710
+ },
711
+ "809": {
712
+ "inputs": {
713
+ "expand": -50,
714
+ "tapered_corners": true,
715
+ "mask": [
716
+ "808",
717
+ 0
718
+ ]
719
+ },
720
+ "class_type": "GrowMask",
721
+ "_meta": {
722
+ "title": "Main: restore edge (-50)"
723
+ }
724
+ },
725
+ "810": {
726
+ "inputs": {
727
+ "expand": 30,
728
+ "tapered_corners": true,
729
+ "mask": [
730
+ "804",
731
+ 0
732
+ ]
733
+ },
734
+ "class_type": "GrowMask",
735
+ "_meta": {
736
+ "title": "Ref: close gaps (+30)"
737
+ }
738
+ },
739
+ "811": {
740
+ "inputs": {
741
+ "masks": [
742
+ "810",
743
+ 0
744
+ ]
745
+ },
746
+ "class_type": "Mask Fill Holes",
747
+ "_meta": {
748
+ "title": "Ref: fill holes"
749
+ }
750
+ },
751
+ "812": {
752
+ "inputs": {
753
+ "expand": -30,
754
+ "tapered_corners": true,
755
+ "mask": [
756
+ "811",
757
+ 0
758
+ ]
759
+ },
760
+ "class_type": "GrowMask",
761
+ "_meta": {
762
+ "title": "Ref: restore edge (-30)"
763
+ }
764
+ },
765
+ "901": {
766
+ "inputs": {
767
+ "text": "hairstyle:1, black hair:1, hair:1",
768
+ "clip": [
769
+ "800",
770
+ 1
771
+ ]
772
+ },
773
+ "class_type": "CLIPTextEncode",
774
+ "_meta": {
775
+ "title": "SAM3 Prompt (Hair region)"
776
+ }
777
+ },
778
+ "902": {
779
+ "inputs": {
780
+ "threshold": 0.1,
781
+ "refine_iterations": 2,
782
+ "individual_masks": false,
783
+ "model": [
784
+ "800",
785
+ 0
786
+ ],
787
+ "image": [
788
+ "183",
789
+ 0
790
+ ],
791
+ "conditioning": [
792
+ "901",
793
+ 0
794
+ ]
795
+ },
796
+ "class_type": "SAM3_Detect",
797
+ "_meta": {
798
+ "title": "Auto Mask - Hair (crop)"
799
+ }
800
+ },
801
+ "936": {
802
+ "inputs": {
803
+ "text": "face:1, neck:1",
804
+ "clip": [
805
+ "800",
806
+ 1
807
+ ]
808
+ },
809
+ "class_type": "CLIPTextEncode",
810
+ "_meta": {
811
+ "title": "SAM3 Prompt (Face + Neck)"
812
+ }
813
+ },
814
+ "937": {
815
+ "inputs": {
816
+ "threshold": 0.3,
817
+ "refine_iterations": 2,
818
+ "individual_masks": false,
819
+ "model": [
820
+ "800",
821
+ 0
822
+ ],
823
+ "image": [
824
+ "183",
825
+ 0
826
+ ],
827
+ "conditioning": [
828
+ "936",
829
+ 0
830
+ ]
831
+ },
832
+ "class_type": "SAM3_Detect",
833
+ "_meta": {
834
+ "title": "Auto Mask - Face+Neck (crop)"
835
+ }
836
+ },
837
+ "938": {
838
+ "inputs": {
839
+ "expand": 12,
840
+ "tapered_corners": true,
841
+ "mask": [
842
+ "937",
843
+ 0
844
+ ]
845
+ },
846
+ "class_type": "GrowMask",
847
+ "_meta": {
848
+ "title": "Face+Neck: margin (+12)"
849
+ }
850
+ },
851
+ "905": {
852
+ "inputs": {
853
+ "x": 0,
854
+ "y": 0,
855
+ "operation": "multiply",
856
+ "destination": [
857
+ "902",
858
+ 0
859
+ ],
860
+ "source": [
861
+ "172",
862
+ 0
863
+ ]
864
+ },
865
+ "class_type": "MaskComposite",
866
+ "_meta": {
867
+ "title": "Hair ∩ Head"
868
+ }
869
+ },
870
+ "939": {
871
+ "inputs": {
872
+ "x": 0,
873
+ "y": 0,
874
+ "operation": "subtract",
875
+ "destination": [
876
+ "905",
877
+ 0
878
+ ],
879
+ "source": [
880
+ "938",
881
+ 0
882
+ ]
883
+ },
884
+ "class_type": "MaskComposite",
885
+ "_meta": {
886
+ "title": "Hair only (Hair − Face/Neck)"
887
+ }
888
+ },
889
+ "903": {
890
+ "inputs": {
891
+ "value": 1,
892
+ "width": 1024,
893
+ "height": 1024
894
+ },
895
+ "class_type": "SolidMask",
896
+ "_meta": {
897
+ "title": "얼굴 강도 상대값 (앱이 채움: 1 = KSampler denoise 와 같음)"
898
+ }
899
+ },
900
+ "906": {
901
+ "inputs": {
902
+ "value": 1,
903
+ "width": 1024,
904
+ "height": 1024
905
+ },
906
+ "class_type": "SolidMask",
907
+ "_meta": {
908
+ "title": "머리 강도 상대값 (앱이 채움: 1 = KSampler denoise 와 같음)"
909
+ }
910
+ },
911
+ "904": {
912
+ "inputs": {
913
+ "x": 0,
914
+ "y": 0,
915
+ "operation": "multiply",
916
+ "destination": [
917
+ "903",
918
+ 0
919
+ ],
920
+ "source": [
921
+ "172",
922
+ 0
923
+ ]
924
+ },
925
+ "class_type": "MaskComposite",
926
+ "_meta": {
927
+ "title": "Face strength × Head"
928
+ }
929
+ },
930
+ "907": {
931
+ "inputs": {
932
+ "x": 0,
933
+ "y": 0,
934
+ "operation": "multiply",
935
+ "destination": [
936
+ "906",
937
+ 0
938
+ ],
939
+ "source": [
940
+ "939",
941
+ 0
942
+ ]
943
+ },
944
+ "class_type": "MaskComposite",
945
+ "_meta": {
946
+ "title": "Hair strength × Hair"
947
+ }
948
+ },
949
+ "908": {
950
+ "inputs": {
951
+ "x": 0,
952
+ "y": 0,
953
+ "operation": "subtract",
954
+ "destination": [
955
+ "904",
956
+ 0
957
+ ],
958
+ "source": [
959
+ "939",
960
+ 0
961
+ ]
962
+ },
963
+ "class_type": "MaskComposite",
964
+ "_meta": {
965
+ "title": "Face part (Head − Hair)"
966
+ }
967
+ },
968
+ "909": {
969
+ "inputs": {
970
+ "x": 0,
971
+ "y": 0,
972
+ "operation": "add",
973
+ "destination": [
974
+ "908",
975
+ 0
976
+ ],
977
+ "source": [
978
+ "907",
979
+ 0
980
+ ]
981
+ },
982
+ "class_type": "MaskComposite",
983
+ "_meta": {
984
+ "title": "Strength map (face + hair)"
985
+ }
986
+ }
987
+ }