""" 씬 빌더 노드 시스템 (ComfyUI Custom Nodes) - 선택지(드롭다운) 버전 설치: 이 파일을 ComfyUI/custom_nodes/ 폴더에 넣고 ComfyUI를 재시작. 메뉴: 우클릭 > Add Node > SceneBuilder 노드 구성 (배경과 배경 소품은 하나로 통합됨): [추천] Scene Builder (All-in-One) : 노드 하나에서 모든 요소를 드롭다운으로 고르고 바로 최종 프롬프트 출력 [분리형] Node 1 Shot_Angle / 2a Gender / 2b Age_Range / 2c Nationality / 3 Placement_Pose / 4 Clothing_Material / 5a Hair_Color / 5b Hair_Style / 5c Expression_Action(표정+시선+행동) / 6 Environment_Background(배경+소품) / 7 Local_Lighting / 8 Atmospheric_Mood -> Node 9 Scene Aggregator 각 항목의 선택 방식: - 목록에서 직접 고르기 (기본값은 기획서 예시) - (random) : seed 값에 따라 무작위 선택. seed가 fixed면 재현, randomize면 큐마다 새로 뽑힘 - (none) : 해당 요소를 생략 - custom_override / override_... : 직접 쓴 내용(또는 연결한 STRING)이 우선 적용 인물 문장은 [관사 + young + 국적 + 성별 + in his/her + 나이대]로, 머리는 [her + 머리색 + hair + 헤어스타일]로 조립됩니다. 성별 자동 대응: 문장 속 {their} {them} {they} {s}(동사 s)는 성별에 맞게 her/his, she/he 등으로 치환됩니다. 선택지 추가 방법: 아래 데이터 목록에 문자열 한 줄을 추가하면 됩니다. 각 목록의 첫 항목이 기본값입니다. 배경은 BACKGROUNDS에 (이름, 배경 문장, [소품 문장들]) 한 묶음을 추가하면 됩니다. """ import random import re CATEGORY = "SceneBuilder" NONE = "(none)" RANDOM = "(random)" # ===================================================================== # 선택지 데이터 # ===================================================================== # ---- 노드 1: 화각 및 카메라 눈높이 ---- SHOT_ANGLE = [ "A medium shot at eye level of", "A close-up shot at eye level of", "A medium close-up shot at eye level of", "An extreme close-up shot at eye level of", "A close-up portrait at eye level of", "A waist-up shot at eye level of", "A cowboy shot, framed from mid-thigh up at eye level, of", "A three-quarter shot at eye level of", "A full-body shot at eye level of", "A wide shot at eye level of", "A wide establishing shot at eye level of", "A medium-wide shot at eye level of", "A medium shot at chest level of", "A candid medium shot at eye level of", "A side-profile medium shot at eye level of", "A medium shot from behind, at eye level, of", "A medium shot from a slightly low angle of", "A medium shot from a slightly high angle of", "A full-body shot from a low angle of", "A full-body shot from a slightly high angle of", "A high-angle shot looking down at", "A low-angle shot looking up at", "An over-the-shoulder shot of", ] # ---- 노드 2a: 성별 ---- GENDER = [ "woman", "man", ] # ---- 노드 2b: 나이대 (성인만) ---- AGE_RANGE = [ "early twenties", "mid-twenties", "late twenties", "early thirties", "mid-thirties", "late thirties", "early forties", "mid-forties", "late forties", "early fifties", "mid-fifties", "late fifties", "sixties", "seventies", ] # ---- 노드 2c: 국적/출신 (형용사 형태 한 단어) ---- NATIONALITY = [ "Korean", "Japanese", "Chinese", "Taiwanese", "Mongolian", "Thai", "Vietnamese", "Filipino", "Indonesian", "Malaysian", "Indian", "Pakistani", "Iranian", "Turkish", "Middle Eastern", "Russian", "Ukrainian", "Polish", "German", "French", "Italian", "Spanish", "Swedish", "British", "Irish", "European", "American", "Canadian", "Australian", "Mexican", "Brazilian", "Argentinian", "Latin American", "Nigerian", "Ethiopian", "Kenyan", "South African", "Egyptian", "Moroccan", "African", "Korean-American", "Japanese-American", "mixed-race", ] # ---- 노드 3: 위치 및 포즈 ---- PLACEMENT_POSE = [ "standing just inside the open front door of {their} apartment", "standing in the center of the frame", "standing slightly off-center, toward the left of the frame", "standing slightly off-center, toward the right of the frame", "standing near a window", "standing in a doorway", "standing at a kitchen counter", "standing at a bus stop", "standing on a rooftop terrace", "standing on a subway platform", "standing at the entrance of a convenience store", "standing on a quiet residential street", "leaning against a wall", "leaning on a railing", "walking along a sidewalk", "walking down a hallway toward the camera", "sitting on the edge of a bed", "sitting on a sofa in the living room", "sitting at a small wooden cafe table", "sitting at a desk by the window", "sitting on a park bench", "sitting on a set of concrete steps", "sitting cross-legged on the floor", "crouching down near the floor", "kneeling beside a low table", ] # ---- 노드 4: 의상 및 소재 ---- CLOTHING_MATERIAL = [ "wearing a simple, sleeveless slip dress in soft beige, the fabric clinging gently to {their} form", "wearing a plain white cotton t-shirt and light blue denim jeans, the fabric slightly creased", "wearing an oversized gray knit sweater and black leggings, the wool soft and slightly bulky", "wearing a fitted black turtleneck and a pleated beige skirt, the fabric hanging neatly", "wearing a white button-up shirt with the sleeves rolled up and tailored navy trousers", "wearing a light floral summer dress with thin straps, the cotton fabric flowing loosely", "wearing a long camel trench coat over a cream blouse, the heavy wool falling past {their} knees", "wearing a gray hoodie and loose sweatpants, the cotton fleece soft and worn", "wearing a soft pink cardigan over a white camisole, the knit fabric lightly textured", "wearing a simple black dress in smooth satin, the fabric catching subtle highlights", "wearing a denim jacket over a white tee and a knee-length skirt", "wearing a crisp white oxford shirt and charcoal slacks, the cotton lightly pressed", "wearing a navy crewneck sweater over a collared shirt and beige chinos", "wearing a black leather jacket over a plain gray t-shirt and dark jeans", "wearing a loose linen shirt in off-white and light khaki shorts, the fabric softly wrinkled", "wearing a tailored dark suit with a white shirt and no tie, the wool smooth and structured", "wearing a heavy olive-green parka with a fur-lined hood, the nylon shell slightly glossy", "wearing a plain black t-shirt and dark gray joggers, the fabric soft and matte", "wearing a striped long-sleeve cotton shirt and faded blue jeans", "wearing a cream knit vest over a white shirt and brown trousers", "wearing a navy windbreaker over a hooded sweatshirt and black track pants", "wearing a loose white pajama set in soft cotton, the fabric slightly rumpled", "wearing a charcoal wool coat over a ribbed black sweater, the fabric thick and warm", "wearing a simple white tank top and light-wash denim shorts", "wearing a mustard-yellow raincoat over a gray sweater, the vinyl surface slightly shiny", ] # ---- 노드 5a: 머리색깔 ('{their} ___ hair' 자리에 들어가는 형용사) ---- HAIR_COLOR = [ "dark", "black", "jet-black", "dark brown", "chestnut brown", "light brown", "golden brown", "auburn", "honey blonde", "golden blonde", "ash blonde", "platinum blonde", "strawberry blonde", "copper red", "deep burgundy", "ash gray", "silver-gray", "ash brown", "soft pink", "pastel lavender", ] # ---- 노드 5b: 헤어스타일 ('{their} (색) hair ___' 자리에 들어가는 구) ---- HAIR_STYLE = [ "pulled back", "falling loosely past {their} shoulders", "falling straight and long down {their} back", "parted in the middle and falling straight", "swept to one side", "tucked behind {their} ears", "tied in a loose ponytail", "tied in a high ponytail", "tied in a low ponytail at the nape of {their} neck", "gathered in a low ponytail with a fabric scrunchie", "pulled into a neat low bun", "twisted into a messy top bun", "styled in a sleek high bun", "twisted up and fastened with a claw clip", "styled half-up, half-down", "braided into a single long braid over one shoulder", "styled in two loose braids", "styled in a loose fishtail braid", "tied in low pigtails", "held back with a thin headband", "styled in soft waves falling past {their} shoulders", "styled in loose curls", "styled in tight natural curls", "cut in a chin-length bob", "cut in a sleek, shoulder-length lob", "cut in a short bob with straight bangs", "cut in a layered, shoulder-length style", "styled with wispy see-through bangs framing {their} face", "cut in a short pixie style", "cut short and neatly combed", "cut short and slightly tousled", "damp and slightly tousled", ] # ---- 노드 5c: 표정, 시선, 행동 ---- EXPRESSION_ACTION = [ "{their} gaze directed slightly downward as {they} wipe{s} the threshold with a damp cloth", "{their} gaze directed at the camera with a soft, relaxed smile", "{their} eyes looking off to the side as {they} adjust{s} a sleeve", "{their} gaze lowered toward a book held in both hands", "{their} expression thoughtful as {they} look{s} out the window", "{their} head turning with a gentle smile", "{their} eyes closed and a faint smile on {their} lips as {they} take{s} a slow breath", "{their} gaze fixed on {their} phone screen as {they} scroll{s} with a thumb", "{their} eyes focused as {they} pour{s} coffee into a cup", "{their} gaze meeting the camera with a calm, neutral expression", "{their} gaze steady as {they} look{s} straight into the camera", "{their} eyes half-open as {they} rub{s} the back of {their} neck", "{their} expression serious as {they} read{s} a letter", "{their} gaze lifted toward the ceiling and {their} lips parted as {they} laugh{s} quietly", "{their} arms crossed loosely and {their} eyes looking toward something just out of frame", "{their} hands wrapped around a warm mug and {their} gaze resting on the steam rising from it", "{their} head tilted slightly and {their} brow faintly furrowed as {they} type{s} on a laptop", "{their} eyes glancing back over {their} shoulder with a small smile", "{their} hands tying a shoelace and {their} gaze directed down at {their} feet", "{their} eyes lowered as {they} pat{s} {their} neck with a towel", "{their} hands resting in {their} pockets and {their} gaze wandering across the street", "{their} fingers brushing a strand of hair back and {their} expression relaxed and unguarded", "{their} gaze following something in the distance and {their} mouth set in a quiet, neutral line", "{their} hands folding a piece of laundry and {their} eyes focused on the fabric", "{their} gaze meeting the camera with a shy, slightly embarrassed smile", "{their} brow slightly furrowed in concentration as {they} stir{s} a pot on the stove", "{their} eyes wide with surprise as {they} open{s} a small package", "{their} lips pressed together in quiet resolve as {they} tighten{s} a bag strap on {their} shoulder", ] # ---- 노드 6: 핵심 배경 + 배경 소품 (통합) ---- # (이름, 배경/건축 구조 문장, [어울리는 소품 문장 변형들]) # 드롭다운에는 '이름 1', '이름 2' ... 형태로 나오며, 선택하면 '배경 문장, 소품 문장'으로 합쳐집니다. BACKGROUNDS = [ ( "Apartment corridor", "Behind {them}, the exterior corridor of a typical Korean apartment building stretches into the distance", [ "lined with identical white doors and gray concrete walls, with a small metal handrail running along the left side", "with numbered steel doors, a row of shoe racks outside, and a fire extinguisher box on the wall", "lined with identical doors, small windows with metal bars, and a few potted plants beside the entrances", ], ), ( "Studio apartment", "Behind {them}, a small, tidy studio apartment opens up with a single bed and a window", [ "furnished with a low wooden table, a folded blanket, and a small potted plant on the windowsill", "with a neatly made bed, a small desk by the window, and clothes hanging on a rack", "with a compact kitchenette in the corner, a laundry rack, and a tiny round table", ], ), ( "Living room", "Behind {them}, a bright modern living room extends toward a large window", [ "with a light wooden floor, a beige sofa, and a few books stacked on a side table", "with a low glass coffee table, a floor lamp, and a rug in muted tones", "with a television on a low cabinet, a few potted plants, and sheer curtains at the window", ], ), ( "Residential street", "Behind {them}, a quiet residential street in a Korean neighborhood stretches into the distance", [ "lined with parked cars, small shop signs without text, and utility poles with overhead cables", "lined with low-rise buildings, a few potted plants outside the doors, and bicycles leaning against the walls", "with narrow sidewalks, tangled overhead cables, and a small neighborhood shop with its shutter half open", ], ), ( "Cafe", "Behind {them}, a cozy cafe interior fills the space", [ "with wooden tables and chairs, a ceramic mug on the counter, and shelves of books along the wall", "with a long counter, an espresso machine, and pendant lights hanging above small round tables", "with large windows, potted plants on the sills, and a small wooden stand by the door", ], ), ( "Alleyway", "Behind {them}, a narrow alleyway runs between low-rise buildings", [ "lined with low brick walls, potted plants beside the doors, and cables running overhead", "with weathered concrete walls, a few stacked crates, and a metal gas meter box on the wall", "with tiled doorsteps, a small blue plastic stool, and laundry hanging from a balcony above", ], ), ( "Kitchen", "Behind {them}, a compact kitchen runs along the wall", [ "with a stainless steel sink, a few ceramic dishes on a rack, and white tiled walls", "with wooden cabinets, a small rice cooker on the counter, and a kettle on the stove", "with open shelves of glass jars, a hanging towel, and a small window above the sink", ], ), ( "Rooftop terrace", "Behind {them}, a rooftop terrace overlooks the city skyline", [ "with a concrete railing, a few folding chairs, and strings of small lights", "with water tanks, potted plants in plastic containers, and a clothes drying line", "with a low parapet wall, a metal bench, and distant apartment towers in soft haze", ], ), ( "Subway platform", "Behind {them}, a subway platform stretches along the tracks", [ "with yellow tactile paving, a row of metal benches, and a blank digital display above", "with tiled walls, glass safety doors along the platform edge, and fluorescent tube lights overhead", "with a painted support pillar, a vending machine, and a curved ceiling with exposed ducts", ], ), ( "Park path", "Behind {them}, a quiet park path winds through the trees", [ "lined with tall trees, wooden benches, and fallen leaves scattered across the ground", "with a gravel path, a low wooden fence, and dappled shade under the branches", "with a stone-paved path, a small pond in the distance, and a lamp post beside a bench", ], ), ( "Convenience store", "Behind {them}, the interior of a convenience store fills the frame", [ "with white shelves stocked with snacks and a refrigerator along the back wall", "with a checkout counter, a rack of drinks, and bright ceiling panels", "with narrow aisles of packaged goods, a refrigerated drinks wall, and a small seating counter by the window", ], ), ( "Apartment stairwell", "Behind {them}, the stairwell of a Korean apartment building rises", [ "with gray concrete steps, a metal handrail, and a small window at the landing", "with painted walls, a row of mailboxes, and a fire door at the landing", "with bare concrete stairs, a bicycle stored under the steps, and a ceiling light in a plastic cover", ], ), ( "Office hallway", "Behind {them}, a long hallway of an office building recedes into the distance", [ "with glass-walled meeting rooms, gray carpet, and a row of identical wooden doors", "with a water dispenser, a potted plant by the elevator, and recessed ceiling lights", "with a long carpeted floor, a printer on a small table, and frosted glass partitions", ], ), ( "Bathroom", "Behind {them}, a tiled bathroom with a small window is visible", [ "with white square tiles, frosted glass in the window, and a folded towel on a rail", "with a pedestal sink, a round mirror, and a plastic basket of toiletries on a shelf", "with a glass shower partition, a wooden stool, and condensation on the tiles", ], ), ( "Bookstore", "Behind {them}, a bookstore interior fills the frame with tall shelves", [ "with wooden shelves packed with books, a ladder on rails, and a reading table near the window", "with stacked paperbacks on a display table, a hanging lamp, and narrow aisles between the shelves", "with a cashier desk, a small potted plant, and rows of colorful book spines", ], ), ( "Open-plan office", "Behind {them}, an open-plan office with rows of desks stretches back", [ "with rows of desks, dual monitors, and ergonomic chairs pushed in", "with low cubicle partitions, a whiteboard on the wall, and stacks of paper trays", "with a long window wall, a few potted plants between desks, and a printer in the corner", ], ), ( "Traditional market", "Behind {them}, a covered traditional market street stretches into the distance", [ "lined with stalls of fresh vegetables in plastic baskets, hanging awnings, and cardboard boxes stacked along the edges", "with fruit piled on wooden crates, metal shelving, and fluorescent tube lights strung overhead", "with a corrugated roof overhead, plastic stools, and steaming pots at a small food stall", ], ), ( "Riverside path", "Behind {them}, a riverside walking path runs along a concrete embankment", [ "with a paved cycling lane, a metal railing, and tall grass along the water's edge", "with wooden benches facing the river, lamp posts at regular intervals, and a bridge in the distance", "with concrete steps leading down to the water, a few reeds, and distant apartment towers across the river", ], ), ( "Bedroom", "Behind {them}, a small bedroom with a window and a wooden wardrobe fills the space", [ "with a neatly made bed, a bedside table, and a folded towel at its foot", "with a wooden wardrobe, a small desk lamp, and curtains drawn halfway across the window", "with a floor cushion, a stack of books, and a plush blanket draped over the bed", ], ), ( "Parking garage", "Behind {them}, an underground parking garage stretches back", [ "with exposed concrete pillars, painted parking lines, and a few parked cars", "with low ceiling pipes, reflective floor markings, and a yellow safety barrier", "with rows of parked cars, concrete walls with painted numbers, and fluorescent tube lights", ], ), ( "Gym", "Behind {them}, a quiet gym with rows of equipment fills the room", [ "with a rack of dumbbells, a mirrored wall, and black rubber flooring", "with treadmills in a row, a water cooler, and bright overhead lights", "with weight benches, a pull-up frame, and a stack of folded towels", ], ), ( "Train carriage", "Behind {them}, a train carriage interior with rows of seats stretches back", [ "with a worn leather seat, an overhead handrail, and a window showing blurred scenery", "with rows of padded seats, hanging hand straps, and a sliding door at the end of the carriage", "with a luggage rack above the seats and sunlight flickering through the windows", ], ), ( "Classroom", "Behind {them}, a sunlit school-style classroom with rows of desks fills the room", [ "with a chalkboard, rows of wooden desks, and sunlight-faded curtains", "with a teacher's desk, a wall clock, and plastic chairs pushed under the desks", "with tall windows, a whiteboard, and a shelf of tidy notebooks at the back", ], ), ( "Hillside neighborhood", "Behind {them}, a hillside neighborhood of low houses and narrow stairs rises", [ "with steep concrete stairs, low tiled roofs, and potted plants along the walls", "with narrow lanes, hanging laundry, and a view of the city spreading out below", "with painted brick walls, a handrail along the steps, and a few motorbikes parked by the doors", ], ), ] # ---- 노드 7: 현장 물리 광원 및 조명 ---- LOCAL_LIGHTING = [ "The scene is lit by soft, diffused daylight from a high window, casting even illumination across the floor and {their} clothing", "The scene is lit by warm golden-hour sunlight streaming through a window, casting long soft shadows across the floor", "The scene is lit by soft overcast daylight, producing even, nearly shadowless illumination", "The scene is lit by soft morning light filtering through sheer curtains, creating a gentle glow", "The scene is lit by bright midday sunlight, casting crisp shadows on the nearby surfaces", "The scene is lit by warm lamplight from a bedside lamp, creating gentle pools of amber light", "The scene is lit by cool fluorescent ceiling lights, casting flat, even illumination", "The scene is lit by a mix of natural window light and warm interior lighting", "The scene is lit by dim evening light from street lamps outside, leaving the corners softly shadowed", "The scene is lit by glowing shop signs and street lights at night, casting colored reflections on nearby surfaces", "The scene is lit by low late-afternoon sunlight entering from the side, creating warm highlights and long shadows", "The scene is lit by pale blue dawn light through the window, leaving the room cool and softly lit", "The scene is lit by overhead warm pendant lights, creating soft circles of light on the surfaces below", "The scene is lit by dappled sunlight filtering through tree leaves, scattering moving patches of light across the ground", "The scene is lit by the glow of a laptop screen and a small desk lamp in an otherwise dim room", "The scene is lit by harsh overhead light from a bare bulb, casting sharp shadows beneath {their} features", "The scene is lit by flat gray light from a rainy sky outside the window, with a muted, even tone", "The scene is lit by warm indoor lighting from recessed ceiling lights, evenly illuminating the room", ] # ---- 노드 8: 정서적 무드 및 마무리 ---- ATMOSPHERIC_MOOD = [ "The mood is quiet and domestic, with no visible text in the scene.", "The mood is warm and cozy, with no visible text in the scene.", "The mood is calm and peaceful, with no visible text in the scene.", "The mood is bright and cheerful, with no visible text in the scene.", "The mood is serene and contemplative, with no visible text in the scene.", "The mood is intimate and relaxed, with no visible text in the scene.", "The mood is nostalgic and gentle, with no visible text in the scene.", "The mood is melancholic and quiet, with no visible text in the scene.", "The mood is lonely and still, with no visible text in the scene.", "The mood is lively and energetic, with no visible text in the scene.", "The mood is ordinary and unhurried, with no visible text in the scene.", "The mood is tender and unguarded, with no visible text in the scene.", "The mood is tense and watchful, with no visible text in the scene.", "The mood is playful and light, with no visible text in the scene.", "The mood is wistful and soft, with no visible text in the scene.", "The mood is focused and quietly determined, with no visible text in the scene.", "The mood is sleepy and slow, with no visible text in the scene.", "The mood is crisp and fresh, with no visible text in the scene.", "The mood is candid and spontaneous, with no visible text in the scene.", "The mood is still and slightly eerie, with no visible text in the scene.", ] # ===================================================================== # 내부 처리 (보통 수정할 필요 없음) # ===================================================================== YOUNG_AGES = {"early twenties", "mid-twenties"} # 배경: 드롭다운 값 -> 합쳐진 문장 BACKGROUND_CHOICES = [] BACKGROUND_TEXT = {} for _name, _bg, _props in BACKGROUNDS: for _n, _prop in enumerate(_props, 1): _label = f"{_name} {_n}" BACKGROUND_CHOICES.append(_label) BACKGROUND_TEXT[_label] = f"{_bg}, {_prop}" # (키, 클래스 접미사, 표시 이름, 통합 노드 입력 이름, 선택지 목록) ATOM_SPECS = [ ("shot", "ShotAngle", "Node 1 - Shot_Angle", "Shot_Angle", SHOT_ANGLE), ("gender", "Gender", "Node 2a - Gender", "Gender", GENDER), ("age", "AgeRange", "Node 2b - Age_Range", "Age_Range", AGE_RANGE), ("nationality", "Nationality", "Node 2c - Nationality", "Nationality", NATIONALITY), ("pose", "PlacementPose", "Node 3 - Placement_Pose", "Placement_Pose", PLACEMENT_POSE), ("clothing", "ClothingMaterial", "Node 4 - Clothing_Material", "Clothing_Material", CLOTHING_MATERIAL), ("hair_color", "HairColor", "Node 5a - Hair_Color", "Hair_Color", HAIR_COLOR), ("hair_style", "HairStyle", "Node 5b - Hair_Style", "Hair_Style", HAIR_STYLE), ("expression", "ExpressionAction", "Node 5c - Expression_Action", "Expression_Action", EXPRESSION_ACTION), ("background", "EnvironmentBackground", "Node 6 - Environment_Background (배경+소품)", "Environment_Background", BACKGROUND_CHOICES), ("lighting", "LocalLighting", "Node 7 - Local_Lighting", "Local_Lighting", LOCAL_LIGHTING), ("mood", "AtmosphericMood", "Node 8 - Atmospheric_Mood", "Atmospheric_Mood", ATMOSPHERIC_MOOD), ] def _norm(text): """중복 공백 제거 + 양끝 공백 제거.""" return re.sub(r"\s+", " ", (text or "")).strip() def _strip_tail(text): """끝에 이미 붙어 있는 구두점(, . ;)을 제거해 중복 부호 방지.""" return _norm(text).rstrip(" ,.;") def _resolve(key, value): """드롭다운 값을 실제 문장으로 변환 (배경만 이름 -> 합쳐진 문장).""" value = _norm(value) if key == "background": return BACKGROUND_TEXT.get(value, value) return value _FEMALE = re.compile(r"\b(woman|women|girl|female|lady)\b", re.I) _MALE = re.compile(r"\b(man|men|boy|male|guy|gentleman)\b", re.I) def _pronouns(gender_text): """성별 텍스트에서 대명사 세트 판별.""" if _FEMALE.search(gender_text or ""): return {"their": "her", "them": "her", "they": "she", "s": "s"} if _MALE.search(gender_text or ""): return {"their": "his", "them": "him", "they": "he", "s": "s"} return {"their": "their", "them": "them", "they": "they", "s": ""} def _fill(text, pron): for key, val in pron.items(): text = text.replace("{" + key + "}", val) return text def _article(word): w = word.lower() if w[:1] in "aeiou" and not w.startswith(("eu", "uni", "uk")): return "an" return "a" def _compose_subject(gender, age, nationality, pron): """성별/나이대/국적으로 인물 문구 조립.""" noun = gender or "person" core = " ".join(x for x in [nationality, noun] if x) lead = "a young" if age in YOUNG_AGES else _article(core) text = f"{lead} {core}" if age: text += f" in {pron['their']} {age}" return text def _assemble(shot, gender, age, nationality, pose, clothing, hair_color, hair_style, expression, background, lighting, mood): """요소 텍스트를 규칙대로 1단락으로 결합 (분리형/올인원 공용).""" pron = _pronouns(gender) def clean(text): return _strip_tail(_fill(text, pron)) def join(parts, sep): return sep.join(p for p in parts if p) subject = _compose_subject(clean(gender), clean(age), clean(nationality), pron) # 문장 1: [화각 + 인물 + 포즈], [의상], [표정/행동]. s1 = join([clean(shot), subject, clean(pose)], " ") # 머리 문구: "her dark hair pulled back" (색/스타일 중 있는 것만 사용), 표정/행동과 "and"로 연결 hc, hs = clean(hair_color), clean(hair_style) hair = join([pron["their"], hc, "hair", hs], " ") if (hc or hs) else "" expr = clean(expression) # 표정/행동 문구 안에 이미 "and"가 있으면 쉼표로 이어서 "and"가 연달아 나오지 않게 함 s2 = join([hair, expr], ", " if " and " in expr else " and ") clothing_text = clean(clothing) sentence1 = join([s1 + "," if s1 else "", clothing_text + "," if clothing_text else "", s2], " ").rstrip(",") if sentence1: sentence1 += "." # 문장 2: [배경 + 소품]. s4 = clean(background) sentence2 = s4 + "." if s4 else "" # 문장 3: [조명]. s5 = clean(lighting) sentence3 = s5 + "." if s5 else "" # 문장 4: [무드] (끝에 종결 부호 없으면 온점 보충) s6 = _norm(_fill(mood, pron)) if s6 and s6[-1] not in ".!?": s6 += "." return _norm(" ".join(p for p in [sentence1, sentence2, sentence3, s6] if p)) def _make_atom_node(key, suffix, opts): """분리형 노드: 드롭다운 선택 / 랜덤 / 없음 / 직접 입력 -> STRING 출력.""" opts = list(opts) class AtomNode: CATEGORY = CATEGORY RETURN_TYPES = ("STRING",) RETURN_NAMES = ("text",) FUNCTION = "run" @classmethod def INPUT_TYPES(cls): return { "required": { "choice": ([RANDOM, NONE] + opts, {"default": opts[0]}), "seed": ("INT", {"default": 0, "min": 0, "max": 0xFFFFFFFFFFFFFFFF}), }, "optional": { "custom_override": ("STRING", {"multiline": True, "default": ""}), }, } def run(self, choice, seed=0, custom_override=""): custom = _norm(custom_override) if custom: return (custom,) if choice == NONE: return ("",) if choice == RANDOM: rng = random.Random(f"{suffix}:{seed}") return (_resolve(key, rng.choice(opts)),) return (_resolve(key, choice),) return AtomNode class SceneAggregator: """Node 9 (분리형): 노드들의 출력을 받아 1단락으로 통합.""" CATEGORY = CATEGORY RETURN_TYPES = ("STRING",) RETURN_NAMES = ("scene_prompt",) FUNCTION = "aggregate" @classmethod def INPUT_TYPES(cls): return {"required": {spec[3]: ("STRING", {"forceInput": True}) for spec in ATOM_SPECS}} def aggregate(self, Shot_Angle, Gender, Age_Range, Nationality, Placement_Pose, Clothing_Material, Hair_Color, Hair_Style, Expression_Action, Environment_Background, Local_Lighting, Atmospheric_Mood): return (_assemble(Shot_Angle, Gender, Age_Range, Nationality, Placement_Pose, Clothing_Material, Hair_Color, Hair_Style, Expression_Action, Environment_Background, Local_Lighting, Atmospheric_Mood),) class SceneBuilderAll: """올인원: 한 노드에서 모든 요소를 고르고 최종 프롬프트까지 출력.""" CATEGORY = CATEGORY RETURN_TYPES = ("STRING",) RETURN_NAMES = ("scene_prompt",) FUNCTION = "build" @classmethod def INPUT_TYPES(cls): required = {} optional = {} for _key, _suffix, _display, inp, opts in ATOM_SPECS: required[inp] = ([RANDOM, NONE] + list(opts), {"default": opts[0]}) required["all_random"] = ("BOOLEAN", {"default": False}) required["seed"] = ("INT", {"default": 0, "min": 0, "max": 0xFFFFFFFFFFFFFFFF}) # 필요할 때만 다른 노드의 STRING을 연결해 해당 요소를 덮어쓰기 (소켓 전용, 위젯 없음) for _key, _suffix, _display, inp, _opts in ATOM_SPECS: optional["override_" + inp] = ("STRING", {"forceInput": True}) return {"required": required, "optional": optional} def build(self, all_random=False, seed=0, **kwargs): values = [] for key, suffix, _display, inp, opts in ATOM_SPECS: override = _norm(kwargs.get("override_" + inp, "")) choice = kwargs.get(inp) rng = random.Random(f"{suffix}:{seed}") if override: v = override elif choice == NONE and not all_random: v = "" elif choice == RANDOM or all_random: v = _resolve(key, rng.choice(list(opts))) else: v = _resolve(key, choice) values.append(v) return (_assemble(*values),) NODE_CLASS_MAPPINGS = {} NODE_DISPLAY_NAME_MAPPINGS = {} for _k, _suffix, _display, _inp, _opts in ATOM_SPECS: _cls = _make_atom_node(_k, _suffix, _opts) _key = f"SceneBuilder_{_suffix}" _cls.__name__ = _key NODE_CLASS_MAPPINGS[_key] = _cls NODE_DISPLAY_NAME_MAPPINGS[_key] = _display NODE_CLASS_MAPPINGS["SceneBuilder_Aggregator"] = SceneAggregator NODE_DISPLAY_NAME_MAPPINGS["SceneBuilder_Aggregator"] = "Node 9 - Scene Aggregator" NODE_CLASS_MAPPINGS["SceneBuilder_All"] = SceneBuilderAll NODE_DISPLAY_NAME_MAPPINGS["SceneBuilder_All"] = "Scene Builder (All-in-One)"