Spaces:
Running on Zero
Running on Zero
refactor: unify prompt enhancer chains into a data-driven pipeline
Browse filesReplace the three per-architecture prompt enhancer injectors with a single
registry-driven implementation, and modernize the node it emits.
Files changed (22)
- chain_injectors/__init__.py+12
- chain_injectors/flux3_prompt_upsampler_injector.pyDeleted-304
- chain_injectors/ming_image_prompt_enhancer_injector.pyDeleted-262
- chain_injectors/prompt_enhancer_injector.pyAdded+489
- chain_injectors/qwen_image_2_1_prompt_enhancer_injector.pyDeleted-245
- core/pipelines/pipeline_input_processor.py+13-35
- core/pipelines/sd_image_pipeline.py+2-6
- core/pipelines/workflow_executor.py+86-1
- core/pipelines/workflow_recipes/_partials/conditioning/flux3.yaml+3-2
- core/pipelines/workflow_recipes/_partials/conditioning/ming-image.yaml+3-2
- core/pipelines/workflow_recipes/_partials/conditioning/qwen-image-2.1.yaml+3-2
- core/workflow_assembler.py+30-6
- mcp_tools/common.py+25-145
- ui/events/change_handlers.py+13-9
- ui/events/main.py+13-17
- ui/events/run_handlers.py+10-25
- ui/imagegen_ui.py+2-5
- ui/shared/ui_components.py+916-947
- yaml/chain_features.yaml+13-61
- yaml/model_architecture_features.yaml+3-3
- yaml/prompt_enhancer.yamlAdded+65
- yaml/task_features.yaml+5-15
41 unmodified lines42434445464741 unmodified linesfull_module_name = f"chain_injectors.{module_name}"chain_type = f"dynamic_{feature_name}_chains"features[feature_name] = {'module': full_module_name,'chain_type': chain_type41 unmodified lines42434445464748495051525354555657585941 unmodified linesfull_module_name = f"chain_injectors.{module_name}"chain_type = f"dynamic_{feature_name}_chains"# Honour an explicit CHAIN_TYPE the same way discover_injectors() does.# Without this, a module that declares CHAIN_TYPE = "foo" is registered# under "foo" by discover_injectors() but looked up here as# "dynamic_foo_chains", so the assembler silently skips it.try:module = importlib.import_module(full_module_name)declared = getattr(module, 'CHAIN_TYPE', None)if declared:chain_type = declaredexcept Exception:passfeatures[feature_name] = {'module': full_module_name,'chain_type': chain_type
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304"""FLUX.3 Prompt Upsampler Chain Injector.
This injector integrates the FLUX.3 prompt upsampler model into the generation workflow:- Uses qwen3.5_9b_flux3_prompt_upsampler_w4a8.safetensors (type: flux3).- Uses PrimitiveStringMultiline for system prompt and input prompt.- Expands user prompt into detailed generative captions using TextGenerate.- Supports reasoning mode (thinking=True) via native ComfyUI TextGenerate reasoning separation.- Supports single or multi-reference image inputs: multiple reference images are stitched into a structured grid layout via ComfyUI native ImageStitch nodes and scaled via ImageScaleToTotalPixels, then connected to the TextGenerate 'image' input.- Connects enhanced prompt directly to downstream CLIPTextEncode positive prompt."""
try: from utils.app_utils import ensure_file_downloadedexcept ImportError: ensure_file_downloaded = None
SYSTEM_PROMPTS = { "t2i": ( "You are the prompt upsampler of a text-to-image model. Expand the user's short request into ONE detailed, self-contained caption: the exact text the image model receives. Output only the caption, with no greetings, explanations, refusals, questions, Markdown, headings, JSON, coordinates, ids or angle-bracket tokens, and no quotes around it. If the input is not clearly an image request, caption a visualization of its concept. The request may begin with a \"TARGET CANVAS: W:H\" line: compose for that canvas (wide spreads content sideways, tall stacks it) and never mention the ratio or the canvas.\n\n" "Fidelity and planning: keep every explicit subject, attribute, count, spatial constraint, style cue and piece of wording; never contradict, substitute, drop or narrow the request, and keep an abstract concept abstract. Decide everything left open as ONE concrete, consistent plan; never offer alternatives or hedge. Never re-express a stated constraint through another mechanism; add camera optics (depth of field, bokeh, blur) only when asked for or implied. Without a stated style, plan an actual photograph and open with the medium convention (\"Full-color outdoor photograph, ...\", \"Full-color indoor photograph, ...\", \"Studio photograph, ...\", \"Close-up photograph, ...\"); keep \"Photorealistic\" for renders, and turn \"photorealistic\" or \"realistic\" requests for photos into the photograph convention. Give a photograph a few ordinary, non-ideal specifics drawn from the scene's own objects instead of the stock-photo ideal. Do not invent names, brands, logos or celebrities; keep user-named ones. A long request keeps its content but not its wording: drop appraisal and sales vocabulary, turn moods into observable physical facts, and add only new concrete content with positions. Time of day is lighting, not rendered text.\n\n" "Caption format: one continuous prose block in the generative voice, never \"this image shows\", \"we can see\" or \"is visible\". Lead with medium and style, then scene, lighting and camera, then the subjects with concrete colors, materials and state. Every person in focus gets an observable profile: ethnicity, gender, age range, skin tone (\"fair skin\", \"brown skin\"), hair and clothing. Make the layout reconstructable from words: frame-relative positions (frame-left, frame-right, upper, lower, foreground, midground, background), sentence-initial anchors (\"On the left, ...\", \"In the background, ...\"), relations (holds, faces, behind) and a consistent order; describe up to about ten instances one by one, beyond that give the exact count and arrangement. Out-of-focus or distant planes are shapes, colors and silhouettes, never identities or readable text, and the background takes about a sixth of the caption. Be definite: no hedging adverbs, no quality or emotion judgments, no closing sentence about mood; state negations as what is present. Rendered text: transcribe every wording verbatim inside double quotes in its original language and script, keep the line breaks of multi-line text, and give its typography, color and placement; author concrete, domain-correct wording when the request needs text it does not supply, and name canonical structures (calendar, keyboard, periodic table) exactly with their full layout. All prose is English; only quoted text keeps its language. Typical length is 100 to 350 words, more for complex scenes.\n\n" "Output only the caption." ), "i2i": ( "You are the prompt upsampler of an image-editing model. You see the reference image(s), attached in order (the first image, the second image, ...), and the user's short request. Expand it into ONE detailed, self-contained instruction: the caption the editing model receives together with the same images. Output only the instruction as one continuous English prose block, with no greetings, explanations, Markdown, JSON, coordinates, ids or angle-bracket tokens. Read a vague or conversational request as the most plausible edit of the supplied images.\n\n" "Pick the voice by task shape. When one reference stays and gets bounded changes, write an imperative editing instruction on it (\"Remove the ...\", \"Change the ... to ...\", \"Zoom in on ...\"); a whole-image transformation opens with its scope (\"Convert the entire image into ...\", \"Apply a ... filter over the entire scene\", \"Horizontally flip the entire image so that ...\", \"Shift the camera viewpoint to ...\", then where the major elements should now be). When the references are drawn into a newly composed frame (combining subjects, a new scene, a garment, object or style donor), write a generation request (\"Create a photograph of ...\", \"Create an anime-style illustration of ...\", \"Generate a new image featuring ...\") that says what to take from each image, by ordinal, and what is newly generated.\n\n" "Keep every explicit edit, constraint, count, position, style cue and piece of wording, and decide what is left open as one concrete plan. Ground everything in what is actually visible: identify each referent unambiguously by its real appearance, never mention content that is not there, and use every image the user attached. State every end state concretely (which color, how large, which pose, which material) and give new content enough appearance to be generated. Cover the knock-on effects of the change (shadows, reflections, occlusion, perspective, scale, lighting) and say what fills a removed region. A zoom-in names what stays in frame and which neighbors are cropped out; an outpainting continues the scene in the same medium. Describe the change, not the whole scene, and close an editing instruction with one compact clause naming what stays unchanged; transferred people keep their identity, face and accessories unless asked otherwise. Transcribe on-image text verbatim in its original language inside double quotes, with line breaks as \\n, and match the original font, size and color when replacing it. Name recognizable public figures, brands and landmarks you can see. Directions are frame-relative; use no evaluative or quality words. Typical length is 50 to 150 words.\n\n" "Output only the instruction." ), "t2i_bbox": ( "You are the prompt upsampler of a text-to-image model. Plan the full image the user's short request implies and output ONE structured caption on a single line: the global caption paragraph, one space, then ONE JSON array, the element table that places every cited element with a bounding box in the image to be generated. Output nothing else (no Markdown fences, commentary or refusals); visualize the concept of a non-image input. The request may begin with a \"TARGET CANVAS: W:H\" line: compose for that canvas and never mention it. Boxes live on a 0-1000 grid stretched onto the canvas: an element of physical width-to-height ratio a gets an x-span of about y-span x a x H/W.\n\n" "Planning: keep every explicit subject, attribute, count, spatial constraint, style cue and piece of wording, and decide everything left open as ONE concrete composition that the caption and the table both describe. Without a stated style plan an actual photograph and open with the medium convention (\"Full-color outdoor photograph, ...\", \"Studio photograph, ...\"); add camera optics only when asked for; do not invent names, brands, logos or celebrities; drop appraisal and sales vocabulary.\n\nThe table: one row per distinct object, person, animal, building or salient region the caption mentions and one per coherent text block; no rows for style, lighting or atmosphere. Structured layouts (tables, grids, calendars, keyboards, charts, maps, posters, pages) decompose into their regions, each row carrying that region's complete verbatim content; more than about ten interchangeable items become one collection row giving the exact count and arrangement, while items whose positions matter keep a row each. Row keys, in order: \"id\", \"bbox\", \"desc\". id: the bare class noun plus an index numbered left to right, then top to bottom, from 1 (person_1, dog_2); a text block is its two-letter language code plus _Text_ plus an index (En_Text_1); one entity is one row and ids are unique. bbox: [y_min, x_min, y_max, x_max] as integers from 0 to 1000, top-left origin, clamped at the borders, with plausible relative sizes and a small margin around text. desc: one self-contained paragraph in the generative voice that opens with the element's identity (never \"the X\"): shape, material, colors, state and markings, but no position. People in focus get the richest desc: ethnicity, gender, age range, skin tone, build, hair, face, each garment, accessories, pose and expression. A text row carries its complete wording verbatim in double quotes, with line breaks as \\n, plus its typography.\n\nThe global caption: one flowing paragraph in the generative voice (medium first, then scene, lighting, camera and frame-relative layout; no quality judgments) that names each table element at identity level at its first mention and cites it with its id in its own angle brackets: \"a wicker table <table_1> holding a tiered stand <stand_1>\". Cite every table id and no other; appearance detail and text content live in the descs; no coordinates. Text-dense documents are laid out region by region with every visible text transcribed verbatim at a readable size (cut content rather than shrink type), and a grid quotes every visible cell. All prose is English; only quoted text keeps its language.\n\nOutput only the caption and the table." ), "i2i_bbox": ( "You are the annotation system an image-editing model was trained on. You see the source image(s), attached in order as ref_image_0, ref_image_1, ..., and the user's editing instruction; the edited target image does not exist yet. Determine the edit precisely, imagine the target consistently with the source, and write the record its annotator would have written, on one line: the instruction paragraph, one space, then ONE JSON array. Output nothing else.\n\nThe paragraph: English, instruction voice (\"Change the ...\", \"Remove the ...\", or \"Create a photograph of ...\" when the references are drawn into a new frame), never observer phrasing and never a comparison with the target. Cite every involved object, person or text block at its first mention with its table id in its own angle brackets (\"remove the delivery van <van_1>\"), every table id exactly once and no other id; cite a reference image by its token when content is taken from it (\"the cup <cup_1> from <ref_image_1>\"). End states (new color, new text in quotes, pose, degree) live in the paragraph, static appearance in the descs; no coordinates. An editing instruction closes with one compact clause that everything else stays identical to the source.\n\nThe table, rows {\"id\", \"from\", \"src_bbox\", \"tgt_bbox\", \"desc\"}: one row per edited, removed, added, moved or anchoring item, plus the scene or background when it is itself changed or preserved; no rows for untouched scenery. id: a lowercase class noun plus an index (person_1, cup_2) numbered left to right, then top to bottom; text blocks are En_Text_1 and so on; ids are unique. from: \"ref_image_N\" for an item visible in reference N, \"target\" for newly created content. src_bbox is the item's box in its from-image and null for target rows; tgt_bbox is its box in the imagined result and null for removed items; moved or resized items carry both; new items are sized like similar objects in the frame. Boxes are [y_min, x_min, y_max, x_max] integers from 0 to 1000, top-left origin, tight around objects, with 5 to 15 units of margin around text. A row may also carry src_bbox_1stage and tgt_bbox_1stage, a first-pass estimate of the same boxes. desc: one English paragraph of the item's static appearance in its from-image (for target rows, its decided appearance), opening with its identity; people get the richest descs (ethnicity, gender, age range, skin tone, hair, face, garments, accessories, pose, expression); text rows quote their text verbatim.\n\nState only decided facts: visible in the source, demanded by the instruction, or a concrete default needed to realize it. Settle whether the edit targets one instance, all of a class or several; land every magnitude on a concrete value; include visible knock-on effects; added objects are new objects at real-world size; a zoom-in names the neighbors it excludes; an outpainting keeps the source whole and continues it in the same medium. Everything the instruction does not involve stays identical to the source.\n\nOutput only the paragraph and the table." )}
DEFAULT_FLUX3_SYSTEM_PROMPT = SYSTEM_PROMPTS["t2i"]
def create_node(assembler, class_type, title): """Create a workflow node dictionary with fallback template generation.""" try: node = assembler._get_node_template(class_type) except Exception: node = { "inputs": {}, "class_type": class_type, "_meta": {"title": title} } if "_meta" not in node: node["_meta"] = {} node['_meta']['title'] = title return node
def inject(assembler, chain_definition, chain_items): """Inject FLUX.3 prompt upsampler nodes into the target generation workflow.""" if not chain_items: return
is_enabled = False thinking_enabled = False bbox_mode = False max_length = 3584 custom_system_prompt = None
for item in chain_items: if isinstance(item, dict): if item.get("enable", False) or item.get("enabled", False) or item.get("value", False): is_enabled = True if item.get("thinking", False) in (True, "true", "on", "yes", "1", 1): thinking_enabled = True if item.get("bbox_mode", False) in (True, "true", "on", "yes", "1", 1): bbox_mode = True if "max_length" in item and item["max_length"]: try: max_length = int(item["max_length"]) except (ValueError, TypeError): pass if "system_prompt" in item and item["system_prompt"]: custom_system_prompt = str(item["system_prompt"]) elif item is True or str(item).lower() in ("on", "true", "yes", "1"): is_enabled = True break
if not is_enabled: return
target_node_name = chain_definition.get('target_node', 'pos_prompt') target_node_id = assembler.node_map.get(target_node_name)
if not target_node_id or target_node_id not in assembler.workflow: for node_id, node in assembler.workflow.items(): if isinstance(node, dict) and node.get('class_type') == 'CLIPTextEncode': title = node.get('_meta', {}).get('title', '').lower() if 'pos' in title or 'positive' in title: target_node_id = node_id break
if not target_node_id or target_node_id not in assembler.workflow: for node_id, node in assembler.workflow.items(): if isinstance(node, dict) and node.get('class_type') in ('CLIPTextEncode', 'TextEncodeQwenImage21', 'TextEncodeMingImageEdit'): target_node_id = node_id break
if not target_node_id or target_node_id not in assembler.workflow: print(f"Warning: Target node '{target_node_name}' not found for FLUX.3 Prompt Upsampler. Skipping.") return
target_node = assembler.workflow[target_node_id] original_prompt = target_node.get('inputs', {}).get('text') if original_prompt is None: original_prompt = target_node.get('inputs', {}).get('prompt', '')
# 1. Collect image connections for multi-image reference support load_image_nodes = [ node_id for node_id, node in assembler.workflow.items() if isinstance(node, dict) and node.get('class_type') == 'LoadImage' ] has_load_image = len(load_image_nodes) > 0 target_image_conn = None
# Auto-select official BFL system prompt template: # If loadimage is detected: i2i / i2i_bbox; otherwise t2i / t2i_bbox if custom_system_prompt: system_prompt = custom_system_prompt else: if has_load_image: template_key = "i2i_bbox" if bbox_mode else "i2i" else: template_key = "t2i_bbox" if bbox_mode else "t2i" system_prompt = SYSTEM_PROMPTS.get(template_key, DEFAULT_FLUX3_SYSTEM_PROMPT)
if has_load_image: indexed_slots = [] target_inputs = target_node.get('inputs', {}) for slot_key, slot_val in target_inputs.items(): if slot_key.startswith('images.image_') and isinstance(slot_val, (list, tuple)): try: idx = int(slot_key.split('_')[-1]) except Exception: idx = 999 indexed_slots.append((idx, slot_val))
indexed_slots.sort(key=lambda x: x[0]) ref_image_conns = [s[1] for s in indexed_slots]
if not ref_image_conns: for lid in load_image_nodes: scaled_conn = None for nid, node in assembler.workflow.items(): if isinstance(node, dict) and node.get('class_type') == 'ImageScaleToTotalPixels': img_input = node.get('inputs', {}).get('image') if isinstance(img_input, (list, tuple)) and str(img_input[0]) == str(lid): scaled_conn = [nid, 0] break if scaled_conn: ref_image_conns.append(scaled_conn) else: scale_id = assembler._get_unique_id() scale_node = create_node(assembler, "ImageScaleToTotalPixels", "Scale Input Image") scale_node['inputs'] = { "upscale_method": "nearest-exact", "megapixels": 1, "resolution_steps": 1, "image": [lid, 0] } assembler.workflow[scale_id] = scale_node ref_image_conns.append([scale_id, 0])
if len(ref_image_conns) == 1: target_image_conn = ref_image_conns[0] elif len(ref_image_conns) >= 2: num_cols = 2 if len(ref_image_conns) <= 4 else 3 rows = [] for i in range(0, len(ref_image_conns), num_cols): rows.append(ref_image_conns[i:i + num_cols])
stitched_rows = [] for r_idx, row_imgs in enumerate(rows): if len(row_imgs) == 1: stitched_rows.append(row_imgs[0]) else: curr_stitch = row_imgs[0] for c_idx in range(1, len(row_imgs)): st_id = assembler._get_unique_id() st_node = create_node(assembler, "ImageStitch", f"Stitch Images (Row {r_idx+1}-{c_idx})") st_node['inputs'] = { "direction": "right", "match_image_size": True, "spacing_width": 0, "spacing_color": "white", "image1": curr_stitch, "image2": row_imgs[c_idx] } assembler.workflow[st_id] = st_node curr_stitch = [st_id, 0] stitched_rows.append(curr_stitch)
if len(stitched_rows) == 1: final_stitched = stitched_rows[0] else: curr_vertical = stitched_rows[0] for r_idx in range(1, len(stitched_rows)): st_id = assembler._get_unique_id() st_node = create_node(assembler, "ImageStitch", f"Stitch Images (Vertical {r_idx})") st_node['inputs'] = { "direction": "down", "match_image_size": True, "spacing_width": 0, "spacing_color": "white", "image1": curr_vertical, "image2": stitched_rows[r_idx] } assembler.workflow[st_id] = st_node curr_vertical = [st_id, 0] final_stitched = curr_vertical
final_scale_id = assembler._get_unique_id() final_scale_node = create_node(assembler, "ImageScaleToTotalPixels", "Scale Stitched Image") final_scale_node['inputs'] = { "upscale_method": "nearest-exact", "megapixels": 1, "resolution_steps": 1, "image": final_stitched } assembler.workflow[final_scale_id] = final_scale_node target_image_conn = [final_scale_id, 0]
# 2. Ensure model is downloaded clip_model_name = "qwen3.5_9b_flux3_prompt_upsampler_w4a8.safetensors" if ensure_file_downloaded: try: ensure_file_downloaded(clip_model_name) except Exception as e: print(f"Warning: Failed to ensure '{clip_model_name}' downloaded: {e}")
# 3. Create CLIPLoader node (type: flux3) clip_node_id = assembler._get_unique_id() clip_node = create_node(assembler, "CLIPLoader", "Load CLIP") clip_node['inputs'] = { "clip_name": clip_model_name, "type": "flux3", "device": "default" } assembler.workflow[clip_node_id] = clip_node
# 4. Create PrimitiveStringMultiline node for System Prompt system_prompt_node_id = assembler._get_unique_id() system_prompt_node = create_node(assembler, "PrimitiveStringMultiline", "Text (System prompt)") system_prompt_node['inputs'] = { "value": system_prompt } assembler.workflow[system_prompt_node_id] = system_prompt_node
# 5. Create PrimitiveStringMultiline node for User Prompt if isinstance(original_prompt, (list, tuple)): prompt_conn = original_prompt else: prompt_node_id = assembler._get_unique_id() prompt_node = create_node(assembler, "PrimitiveStringMultiline", "Text (Multiline)") prompt_node['inputs'] = { "value": original_prompt if isinstance(original_prompt, str) else "" } assembler.workflow[prompt_node_id] = prompt_node prompt_conn = [prompt_node_id, 0]
# 6. Create TextGenerate node text_gen_node_id = assembler._get_unique_id() text_gen_node = create_node(assembler, "TextGenerate", "Generate Text") text_gen_inputs = { "prompt": prompt_conn, "max_length": max_length, "sampling_mode": "on", "sampling_mode.temperature": 1.0, "sampling_mode.top_k": 1, "sampling_mode.top_p": 0.95, "sampling_mode.min_p": 0.0, "sampling_mode.repetition_penalty": 1.05, "sampling_mode.seed": 0, "sampling_mode.presence_penalty": 1.5, "thinking": thinking_enabled, "use_default_template": True, "mtp": "auto", "clip": [clip_node_id, 0], "system_prompt": [system_prompt_node_id, 0] } if target_image_conn is not None: text_gen_inputs["image"] = target_image_conn
text_gen_node['inputs'] = text_gen_inputs assembler.workflow[text_gen_node_id] = text_gen_node
# 7. Connect TextGenerate output to positive prompt node if 'text' in target_node.get('inputs', {}): target_node['inputs']['text'] = [text_gen_node_id, 0] else: target_node['inputs']['prompt'] = [text_gen_node_id, 0]
print(f"[Injector] FLUX.3 Prompt Upsampler applied successfully (clip='{clip_model_name}', thinking={thinking_enabled}, images={has_load_image}).")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262"""Ming-Image Prompt Enhancer Chain Injector.
This injector automatically integrates the Qwen3.8-27B prompt enhancement model intothe Ming-Image generation workflow:- Detects whether the task is pure text-to-image (T2I) or involves images (I2I, inpainting, outpainting, hires.fix, or multi-reference images).- Uses the Qwen3.8-27B PE text encoder: qwen3.8_27b_w4a8.safetensors (type: qwen_image).- Handles single or multi-reference inputs: multiple reference images are stitched into a structured grid layout via ComfyUI native ImageStitch nodes and scaled via ImageScaleToTotalPixels.- Supports reasoning mode (thinking=True) leveraging ComfyUI TextGenerate native reasoning separation (output slot 0 outputs clean prompt text, while output slot 1 isolates reasoning chain)."""
try: from utils.app_utils import ensure_file_downloadedexcept ImportError: ensure_file_downloaded = None
DEFAULT_MING_IMAGE_SYSTEM_PROMPT = ( "You are a senior visual designer and image-prompt engineer. Expand the user's request into one precise, high-resolution Figma-style caption. Return only one JSON object. " "Use exactly two top-level keys. `canvas_settings` contains exactly `aspect_ratio`, `ambient_lighting`, and `image_style`. `layers` lists visible groups from background to topmost overlay. Every layer contains exactly `description`, `coordinates`, `hierarchy_and_relation`, and `color_specs`; `color_specs` is an array of hex colors. " '`coordinates` MUST be one string, never an object or array, in exactly this form: `"cx: 0.500, cy: 0.500, w: 1.000, h: 1.000"`. Values are normalized; each bbox encloses its complete owned object and stays inside the canvas. ' "A layer is one selectable visible semantic group: background, full person, coherent object, panel, card, row, or text block. Prefer the fewest groups that preserve the layout. Keep people and objects intact. Never create invisible parents, guides, placeholders, empty layers, duplicate summaries, or multiple owners for one element. " "Preserve every user-supplied rendered string character-for-character and as one contiguous string. Unless multiple visible copies are requested, it must occur exactly once across all `description` fields and zero times in `hierarchy_and_relation`. Quote it only where describing its visible rendering; refer to the related subject elsewhere with unquoted semantic wording. Enumerate intended copy, invent extra copy sparingly, and never hide content behind \"other text\", \"remaining labels\", or \"etc.\" " "Describe concrete composition, typography, materials, texture, lighting, pose, and camera treatment without literary filler. Use `hierarchy_and_relation` only for ownership, alignment, containment, stacking, and occlusion. " "Infer structured layouts first. Use one complete layer per card and state its row and column. A compact secondary table may be one layer only if every header and cell is listed; otherwise use a visible shared frame when present, one complete header, and one complete layer per body row, binding values to columns and stating blanks. Enumerate sequences, schedules, spans, gaps, and vacant tracks in visual order. Do not mistake ordinary alignment for a table. " "Silently verify schema, string coordinates, Z-order, exact-text counts, geometry, bbox validity, and completeness.")
def create_node(assembler, class_type, title): """Create a workflow node dictionary with fallback template generation.""" try: node = assembler._get_node_template(class_type) except Exception: node = { "inputs": {}, "class_type": class_type, "_meta": {"title": title} } if "_meta" not in node: node["_meta"] = {} node['_meta']['title'] = title return node
def inject(assembler, chain_definition, chain_items): """Inject Ming-Image prompt enhancer nodes into the target generation workflow.""" if not chain_items: return
is_enabled = False thinking_enabled = False max_length = 4096 system_prompt = DEFAULT_MING_IMAGE_SYSTEM_PROMPT for item in chain_items: if isinstance(item, dict): if item.get("enable", False) or item.get("enabled", False) or item.get("value", False): is_enabled = True if item.get("thinking", False) in (True, "true", "on", "yes", "1", 1): thinking_enabled = True if "max_length" in item and item["max_length"]: try: max_length = int(item["max_length"]) except (ValueError, TypeError): pass if "system_prompt" in item and item["system_prompt"]: system_prompt = str(item["system_prompt"]) elif item is True or str(item).lower() in ("on", "true", "yes", "1"): is_enabled = True break
if not is_enabled: return
target_node_name = chain_definition.get('target_node', 'prompt') target_node_id = assembler.node_map.get(target_node_name)
if not target_node_id or target_node_id not in assembler.workflow: for node_id, node in assembler.workflow.items(): if isinstance(node, dict) and node.get('class_type') == 'TextEncodeMingImageEdit': target_node_id = node_id break
if not target_node_id or target_node_id not in assembler.workflow: print(f"Warning: Target node '{target_node_name}' (TextEncodeMingImageEdit) not found for Ming-Image Prompt Enhancer. Skipping.") return
target_node = assembler.workflow[target_node_id] original_prompt = target_node.get('inputs', {}).get('prompt', '')
# 1. Check if any LoadImage nodes exist in the workflow load_image_nodes = [ node_id for node_id, node in assembler.workflow.items() if isinstance(node, dict) and node.get('class_type') == 'LoadImage' ] has_load_image = len(load_image_nodes) > 0
target_image_conn = None clip_model_name = "qwen3.8_27b_w4a8.safetensors"
if has_load_image: # Collect image connections # Prioritize extracting all images.image_* slots from target_node['inputs'] (injected by reference image injectors) indexed_slots = [] target_inputs = target_node.get('inputs', {}) for slot_key, slot_val in target_inputs.items(): if slot_key.startswith('images.image_') and isinstance(slot_val, (list, tuple)): try: idx = int(slot_key.split('_')[-1]) except Exception: idx = 999 indexed_slots.append((idx, slot_val))
indexed_slots.sort(key=lambda x: x[0]) ref_image_conns = [s[1] for s in indexed_slots]
# If no reference image slots exist (e.g. pure img2img / inpaint / outpaint), retrieve from LoadImage nodes if not ref_image_conns: for lid in load_image_nodes: scaled_conn = None for nid, node in assembler.workflow.items(): if isinstance(node, dict) and node.get('class_type') == 'ImageScaleToTotalPixels': img_input = node.get('inputs', {}).get('image') if isinstance(img_input, (list, tuple)) and str(img_input[0]) == str(lid): scaled_conn = [nid, 0] break if scaled_conn: ref_image_conns.append(scaled_conn) else: scale_id = assembler._get_unique_id() scale_node = create_node(assembler, "ImageScaleToTotalPixels", "Scale Input Image") scale_node['inputs'] = { "upscale_method": "nearest-exact", "megapixels": 1, "resolution_steps": 1, "image": [lid, 0] } assembler.workflow[scale_id] = scale_node ref_image_conns.append([scale_id, 0])
# Organize multiple reference images into grid stitching if len(ref_image_conns) == 1: target_image_conn = ref_image_conns[0] elif len(ref_image_conns) >= 2: num_cols = 2 if len(ref_image_conns) <= 4 else 3
rows = [] for i in range(0, len(ref_image_conns), num_cols): rows.append(ref_image_conns[i:i + num_cols])
# Horizontally stitch images in each row stitched_rows = [] for r_idx, row_imgs in enumerate(rows): if len(row_imgs) == 1: stitched_rows.append(row_imgs[0]) else: curr_stitch = row_imgs[0] for c_idx in range(1, len(row_imgs)): st_id = assembler._get_unique_id() st_node = create_node(assembler, "ImageStitch", f"Stitch Images (Row {r_idx+1}-{c_idx})") st_node['inputs'] = { "direction": "right", "match_image_size": True, "spacing_width": 0, "spacing_color": "white", "image1": curr_stitch, "image2": row_imgs[c_idx] } assembler.workflow[st_id] = st_node curr_stitch = [st_id, 0] stitched_rows.append(curr_stitch)
# Vertically stitch multiple rows if len(stitched_rows) == 1: final_stitched = stitched_rows[0] else: curr_vertical = stitched_rows[0] for r_idx in range(1, len(stitched_rows)): st_id = assembler._get_unique_id() st_node = create_node(assembler, "ImageStitch", f"Stitch Images (Vertical {r_idx})") st_node['inputs'] = { "direction": "down", "match_image_size": True, "spacing_width": 0, "spacing_color": "white", "image1": curr_vertical, "image2": stitched_rows[r_idx] } assembler.workflow[st_id] = st_node curr_vertical = [st_id, 0] final_stitched = curr_vertical
# Scale final stitched image to ~1024 level via ImageScaleToTotalPixels final_scale_id = assembler._get_unique_id() final_scale_node = create_node(assembler, "ImageScaleToTotalPixels", "Scale Stitched Image") final_scale_node['inputs'] = { "upscale_method": "nearest-exact", "megapixels": 1, "resolution_steps": 1, "image": final_stitched } assembler.workflow[final_scale_id] = final_scale_node target_image_conn = [final_scale_id, 0]
# 2. Ensure model is downloaded in CPU stage before workflow execution if ensure_file_downloaded: try: ensure_file_downloaded(clip_model_name) except Exception as e: print(f"Warning: Failed to ensure '{clip_model_name}' downloaded: {e}")
# 3. Create CLIPLoader node (using qwen_image type for Qwen3.8-27B PE) clip_node_id = assembler._get_unique_id() clip_node = create_node(assembler, "CLIPLoader", "Load CLIP") clip_node['inputs'] = { "clip_name": clip_model_name, "type": "qwen_image", "device": "default" } assembler.workflow[clip_node_id] = clip_node
# 4. Create PrimitiveString node for System Prompt (Text node) system_prompt_node_id = assembler._get_unique_id() system_prompt_node = create_node(assembler, "PrimitiveString", "Text") system_prompt_node['inputs'] = { "value": system_prompt } assembler.workflow[system_prompt_node_id] = system_prompt_node
# 5. Create TextGenerate node text_gen_node_id = assembler._get_unique_id() text_gen_node = create_node(assembler, "TextGenerate", "Generate Text") text_gen_inputs = { "prompt": original_prompt, "max_length": max_length, "sampling_mode": "on", "sampling_mode.temperature": 0.7, "sampling_mode.top_k": 64, "sampling_mode.top_p": 0.95, "sampling_mode.min_p": 0.05, "sampling_mode.repetition_penalty": 1.05, "sampling_mode.seed": 0, "sampling_mode.presence_penalty": 0, "thinking": thinking_enabled, "use_default_template": True, "mtp": "auto", "clip": [clip_node_id, 0], "system_prompt": [system_prompt_node_id, 0] } if target_image_conn is not None: text_gen_inputs["image"] = target_image_conn
text_gen_node['inputs'] = text_gen_inputs assembler.workflow[text_gen_node_id] = text_gen_node
# 6. Connect TextGenerate output directly to target node prompt # ComfyUI TextGenerate node natively strips reasoning tags (<think>...</think>) into output slot 1, # leaving clean enhanced prompt in output slot 0. target_node['inputs']['prompt'] = [text_gen_node_id, 0] print(f"[Injector] Ming-Image Prompt Enhancer applied successfully ({'I2I' if has_load_image else 'T2I'}, clip='{clip_model_name}', thinking={thinking_enabled}).")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489"""Prompt Enhancer Chain Injector (data-driven).
Merges the former qwen_image_2_1_prompt_enhancer / ming_image_prompt_enhancer /flux3_prompt_upsampler injectors into a single implementation driven by``yaml/prompt_enhancer.yaml``.
The YAML declares three independent modules, named after their UI labels in the"Prompt Enhancer Settings" accordion:
* ``architecture`` Model framework -> default ``clip`` (Prompt Enhancer Model) and default ``system_prompt`` (System Prompt). These are the dropdown defaults applied whenever the base model changes. A missing entry falls back to the first registry item.* ``clip`` Every name shown in the "Prompt Enhancer Model" dropdown, mapped to its checkpoint ``filename`` and ``clip_type``. Declaration order is dropdown order.* ``system_prompt`` Every name shown in the "System Prompt" dropdown, mapped to the system prompt sent to ``TextGenerateV2``. An empty value means no system prompt.
The modules are fully decoupled: any framework may pick any clip, and any clipmay be paired with any system prompt. ``clip_type`` therefore travels with theclip, not with the framework. There is no image-based or bbox auto-detection.
The injector then:
1. Resolves the target text-encode node that receives the enhanced prompt.2. Collects reference images (native ``images.image_N`` slots first, otherwise ``LoadImage`` nodes) and feeds each one into its own autogrow slot.3. Loads the selected checkpoint through ``CLIPLoader`` and, when the chosen system prompt carries text, materialises it as a primitive string node.4. Emits a ``TextGenerateV2`` node (Sampling Mode ``off``) and wires its clean ``generated_text`` output into the downstream positive prompt."""
import os
import yaml
try: from utils.app_utils import ensure_file_downloadedexcept ImportError: ensure_file_downloaded = None
CHAIN_TYPE = "prompt_enhancer"
_YAML_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "yaml")_CONFIG_PATH = os.path.join(_YAML_DIR, "prompt_enhancer.yaml")
# Node class -> (target node names to try, input keys holding the source prompt)_TARGET_HINTS = ( ("TextEncodeQwenImage21", ("prompt",), ("prompt",)), ("TextEncodeMingImageEdit", ("prompt",), ("prompt",)), ("CLIPTextEncode", ("pos_prompt",), ("text", "prompt")),)
_config_cache = None
def load_prompt_enhancer_config(): """Load and cache the prompt enhancer registry.""" global _config_cache if _config_cache is None: try: with open(_CONFIG_PATH, "r", encoding="utf-8") as f: _config_cache = yaml.safe_load(f) or {} except (OSError, yaml.YAMLError) as e: print(f"Warning: Failed to load prompt enhancer config '{_CONFIG_PATH}': {e}") _config_cache = {} return _config_cache
def get_clip_registry(): """Return the ordered ``clip name -> {filename, clip_type}`` registry.""" return load_prompt_enhancer_config().get("clip", {}) or {}
def get_system_prompt_registry(): """Return the ``system_prompt name -> text`` map (``""`` = no prompt).""" return load_prompt_enhancer_config().get("system_prompt", {}) or {}
def get_architectures(): """Return the ``model framework -> {clip, system_prompt}`` defaults map.""" return load_prompt_enhancer_config().get("architecture", {}) or {}
def get_clip_names(): """Return the selectable clip names, in declared order.""" return [str(name) for name in get_clip_registry().keys()]
def get_clip_entry(name): """Return the ``{filename, clip_type}`` registry entry for a clip name.""" entry = get_clip_registry().get(str(name)) return entry if isinstance(entry, dict) else {}
def get_system_prompt_names(): """Return the selectable system_prompt names, including empty (no-prompt) ones.""" return [str(name) for name in get_system_prompt_registry().keys()]
def get_all_system_prompt_keys(): """Return the system_prompt names that carry text (empty ones are dropped).""" return [name for name, text in get_system_prompt_registry().items() if text]
def get_architecture_defaults(framework=None): """Return ``{model, system_prompt}`` defaults for a model framework.
Reads the ``architecture`` module. Falls back to the first registry entry when the framework is unknown or omits a field, so the UI always has a usable default. """ defaults = get_architectures().get(str(framework), {}) if framework else {} if not isinstance(defaults, dict): defaults = {}
clip_names = get_clip_names() prompt_names = get_system_prompt_names()
model = defaults.get("clip") if model not in clip_names: model = clip_names[0] if clip_names else None
system_prompt = defaults.get("system_prompt") if system_prompt not in prompt_names: system_prompt = prompt_names[0] if prompt_names else None
return {"model": model, "system_prompt": system_prompt}
def create_node(assembler, class_type, title): """Create a workflow node dictionary with fallback template generation.""" try: node = assembler._get_node_template(class_type) except Exception: node = { "inputs": {}, "class_type": class_type, "_meta": {"title": title} } if "_meta" not in node: node["_meta"] = {} node['_meta']['title'] = title return node
def _as_bool(value, default=False): if isinstance(value, bool): return value if value is None: return default return str(value).strip().lower() in ("on", "true", "yes", "1")
def _parse_chain_items(chain_items): """Normalise the chain items into ``{enable, thinking, model, system_prompt, max_length}``.""" params = { "enable": False, "thinking": False, "model": None, "system_prompt": None, "max_length": None, } if isinstance(chain_items, dict): chain_items = [chain_items]
for item in chain_items or []: if isinstance(item, dict): if item.get("enable", False) or item.get("enabled", False) or item.get("value", False): params["enable"] = True params["thinking"] = _as_bool(item.get("thinking"), False) if item.get("model"): params["model"] = str(item["model"]) if item.get("system_prompt"): params["system_prompt"] = str(item["system_prompt"]) if item.get("max_length"): try: params["max_length"] = int(item["max_length"]) except (ValueError, TypeError): pass elif item is True or str(item).strip().lower() in ("on", "true", "yes", "1"): params["enable"] = True break
return params
def _infer_clip_type(clip_filename): """Best-effort ``CLIPLoader`` type when ``clip_type`` is missing from the YAML.
A wrong type silently loads the checkpoint into the wrong text encoder, so the filename is inspected before falling back to the most common type. """ name = str(clip_filename or "").lower() if "flux3" in name: print(f"Warning: 'clip_type' missing for '{clip_filename}'; inferred 'flux3' from the filename.") return "flux3" if "flux2" in name: print(f"Warning: 'clip_type' missing for '{clip_filename}'; inferred 'flux2' from the filename.") return "flux2" print(f"Warning: 'clip_type' missing for '{clip_filename}'; defaulting to 'qwen_image'. Add it to prompt_enhancer.yaml.") return "qwen_image"
def _resolve_model(params, chain_definition=None): """Pick the Prompt Enhancer Model: explicit request, then framework default, then first registered.""" available = get_clip_names() if not available: return None
requested = params.get("model") if not requested: defaults = get_architecture_defaults((chain_definition or {}).get("framework")) requested = defaults["model"]
if requested: requested = str(requested) if requested in available: return requested # Tolerate the checkpoint filename being supplied instead of the name. for name in available: if str(get_clip_entry(name).get("filename") or "") == requested: return name # Unknown name: fall through to the framework default.
defaults = get_architecture_defaults((chain_definition or {}).get("framework")) return defaults["model"] if defaults["model"] in available else available[0]
def _select_system_prompt(requested_system_prompt, framework=None): """Resolve the system prompt text from the global system_prompt registry.""" prompts = get_system_prompt_registry() if not prompts: return None
# An explicit UI choice always wins, including an empty prompt (no prompt). if requested_system_prompt and str(requested_system_prompt) in prompts: return prompts[str(requested_system_prompt)] or None
# Otherwise use the framework default, falling back to any non-empty prompt. default_prompt = get_architecture_defaults(framework)["system_prompt"] if default_prompt and str(default_prompt) in prompts: return prompts[str(default_prompt)] or None
for text in prompts.values(): if text: return text return None
def _find_target_node(assembler, chain_definition=None): """Locate the text-encode node that should receive the enhanced prompt.""" target_node_name = (chain_definition or {}).get("target_node") target_node_id = assembler.node_map.get(target_node_name) if target_node_name else None if target_node_id and target_node_id in assembler.workflow: return target_node_id, None
for class_type, node_names, input_keys in _TARGET_HINTS: return_class = (class_type, input_keys) for node_name in node_names: node_id = assembler.node_map.get(node_name) if node_id and assembler.workflow.get(node_id, {}).get('class_type') == class_type: return node_id, return_class
# Prefer a positive-prompt encode node when the class_type is shared. for node_id, node in assembler.workflow.items(): if not isinstance(node, dict) or node.get('class_type') != class_type: continue title = str(node.get('_meta', {}).get('title', '')).lower() if 'pos' in title or 'positive' in title: return node_id, return_class
for node_id, node in assembler.workflow.items(): if isinstance(node, dict) and node.get('class_type') == class_type: return node_id, return_class
return None, None
def _get_autogrow_slot_names(class_type, input_name='images'): """Resolve the per-image autogrow slot names for ``class_type.input_name``.
ComfyUI exposes two flavours of Autogrow template:
* ``TemplateNames(names=["image1", ...])`` -> explicit names * ``TemplatePrefix(prefix="image", max=N)`` -> ``prefix + range(max)``
Returns ``None`` when the node schema cannot be introspected. """ try: from comfy_integration.nodes import NODE_CLASS_MAPPINGS node_class = NODE_CLASS_MAPPINGS.get(class_type) except Exception: node_class = None
if node_class is not None: try: input_types = node_class.INPUT_TYPES() or {} except Exception: input_types = {} for category in ('required', 'optional'): spec = (input_types.get(category) or {}).get(input_name) if not spec or len(spec) < 2 or not isinstance(spec[1], dict): continue template = spec[1].get('template') if not isinstance(template, dict): continue names = template.get('names') if isinstance(names, (list, tuple)) and names: return [str(n) for n in names] prefix = template.get('prefix') if isinstance(prefix, str): max_count = template.get('max', 100) if not isinstance(max_count, int) or max_count <= 0: max_count = 100 return [f"{prefix}{i}" for i in range(max_count)]
# Fall back to the published TextGenerateV2 contract. if class_type == "TextGenerateV2": return [f"image{i}" for i in range(1, 51)] return None
def _collect_reference_images(assembler, target_node): """Collect the reference image connections feeding the prompt node.
Native autogrow slots on the target node (``images.image_N``) win; otherwise every ``LoadImage`` node is scaled and used. Each image keeps its own connection so the caller can wire them into separate autogrow slots. """ load_image_nodes = [ node_id for node_id, node in assembler.workflow.items() if isinstance(node, dict) and node.get('class_type') == 'LoadImage' ]
indexed_slots = [] for slot_key, slot_val in target_node.get('inputs', {}).items(): if slot_key.startswith('images.image_') and isinstance(slot_val, (list, tuple)): try: idx = int(slot_key.split('_')[-1]) except (ValueError, IndexError): idx = 999 indexed_slots.append((idx, slot_val))
indexed_slots.sort(key=lambda x: x[0]) if indexed_slots: return [slot[1] for slot in indexed_slots]
if not load_image_nodes: return []
scaled_conns = [] for load_id in load_image_nodes: scaled_conn = None for node_id, node in assembler.workflow.items(): if isinstance(node, dict) and node.get('class_type') == 'ImageScaleToTotalPixels': img_input = node.get('inputs', {}).get('image') if isinstance(img_input, (list, tuple)) and str(img_input[0]) == str(load_id): scaled_conn = [node_id, 0] break if scaled_conn is None: scale_id = assembler._get_unique_id() scale_node = create_node(assembler, "ImageScaleToTotalPixels", "Scale Input Image") scale_node['inputs'] = { "upscale_method": "nearest-exact", "megapixels": 1, "resolution_steps": 1, "image": [load_id, 0] } assembler.workflow[scale_id] = scale_node scaled_conn = [scale_id, 0] scaled_conns.append(scaled_conn) return scaled_conns
def inject(assembler, chain_definition, chain_items): """Inject prompt enhancer nodes into the target generation workflow.""" if not chain_items: return
params = _parse_chain_items(chain_items) if not params["enable"]: return
model_name = _resolve_model(params, chain_definition) if not model_name: print("Warning: No Prompt Enhancer Models configured in prompt_enhancer.yaml. Skipping.") return
framework = (chain_definition or {}).get("framework") entry = get_clip_entry(model_name) clip_model_name = str(entry.get("filename") or model_name) clip_type = str(entry.get("clip_type") or _infer_clip_type(clip_model_name))
target_node_id, class_hint = _find_target_node(assembler, chain_definition) if not target_node_id: print(f"Warning: Target text-encode node for prompt enhancer '{model_name}' not found. Skipping.") return
target_node = assembler.workflow[target_node_id]
# Fall back to the detected node class when the recipe gave no target_node. prompt_input_keys = (class_hint[1] if class_hint else None) or ("text", "prompt") original_prompt = None for input_key in prompt_input_keys: original_prompt = target_node.get('inputs', {}).get(input_key) if original_prompt is not None: break if original_prompt is None: original_prompt = ""
image_conns = _collect_reference_images(assembler, target_node) system_prompt_name = params["system_prompt"] if params["system_prompt"] else None if ensure_file_downloaded: try: ensure_file_downloaded(clip_model_name) except Exception as e: print(f"Warning: Failed to ensure '{clip_model_name}' downloaded: {e}")
# 1. Load the selected Prompt Enhancer Model checkpoint clip_node_id = assembler._get_unique_id() clip_node = create_node(assembler, "CLIPLoader", "Load CLIP") clip_node['inputs'] = { "clip_name": clip_model_name, "type": clip_type, "device": "default" } assembler.workflow[clip_node_id] = clip_node
# 2. Materialise the system prompt when the selected System Prompt carries text system_prompt_conn = None system_prompt = _select_system_prompt(system_prompt_name, framework) if system_prompt: system_prompt_node_id = assembler._get_unique_id() system_prompt_node = create_node(assembler, "PrimitiveStringMultiline", "Text (System prompt)") system_prompt_node['inputs'] = {"value": system_prompt} assembler.workflow[system_prompt_node_id] = system_prompt_node system_prompt_conn = [system_prompt_node_id, 0]
# 3. Emit the TextGenerateV2 node (Sampling Mode off: sampling-only sub-inputs are omitted) max_length = params["max_length"] or 4096 text_gen_node_id = assembler._get_unique_id() text_gen_node = create_node(assembler, "TextGenerateV2", "Generate Text") text_gen_inputs = { "prompt": original_prompt, "max_length": max_length, "sampling_mode": "off", "thinking": params["thinking"], "use_default_template": True, "mtp": "auto", "clip": [clip_node_id, 0] } if system_prompt_conn is not None: text_gen_inputs["system_prompt"] = system_prompt_conn
# Wire each reference image into its own autogrow slot (image1, image2, ...). if image_conns: slot_names = _get_autogrow_slot_names("TextGenerateV2", "images") if slot_names: for conn, slot_name in zip(image_conns, slot_names): text_gen_inputs[slot_name] = conn if len(image_conns) > len(slot_names): print( f"Warning: {len(image_conns)} reference images but TextGenerateV2 " f"exposes only {len(slot_names)} slots; extra images were dropped." ) else: print("Warning: could not resolve TextGenerateV2 autogrow slots; images not wired.")
text_gen_node['inputs'] = text_gen_inputs assembler.workflow[text_gen_node_id] = text_gen_node
# 4. Route the clean generated_text output into the downstream prompt input # (slot 0 carries the enhanced prompt; ComfyUI puts reasoning into slot 1) target_inputs = target_node.setdefault('inputs', {}) if 'text' in target_inputs or ('prompt' not in target_inputs and 'text' in prompt_input_keys): target_inputs['text'] = [text_gen_node_id, 0] else: target_inputs['prompt'] = [text_gen_node_id, 0]
print( f"[Injector] Prompt Enhancer '{model_name}' applied successfully " f"(clip='{clip_model_name}', type='{clip_type}', " f"system_prompt={system_prompt_name or 'auto'})." )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245"""Qwen-Image-2.1 Prompt Enhancer Chain Injector.
This injector automatically integrates the Qwen-Image-2.1 prompt enhancement model intothe generation workflow:- Detects whether the task is pure text-to-image (T2I) or involves images (I2I, inpainting, outpainting, hires.fix, or multi-reference images).- Automatically selects the appropriate prompt enhancement checkpoint: - T2I: qwen3.5_9b_qwen_image_2.1_pe_t2i.int8_convrot.safetensors - I2I / Reference: qwen3.5_9b_qwen_image_2.1_pe_i2i.int8_convrot.safetensors- Handles single or multi-reference inputs: multiple reference images are stitched into a structured grid layout via ComfyUI native ImageStitch nodes and scaled via ImageScaleToTotalPixels.- Supports reasoning mode (thinking=True) leveraging ComfyUI TextGenerate native reasoning separation (output slot 0 outputs clean prompt text, while output slot 1 isolates reasoning chain)."""
try: from utils.app_utils import ensure_file_downloadedexcept ImportError: ensure_file_downloaded = None
def create_node(assembler, class_type, title): """Create a workflow node dictionary with fallback template generation.""" try: node = assembler._get_node_template(class_type) except Exception: node = { "inputs": {}, "class_type": class_type, "_meta": {"title": title} } if "_meta" not in node: node["_meta"] = {} node['_meta']['title'] = title return node
def inject(assembler, chain_definition, chain_items): """Inject Qwen-Image-2.1 prompt enhancer nodes into the target generation workflow.""" if not chain_items: return
is_enabled = False thinking_enabled = False max_length = 4096 for item in chain_items: if isinstance(item, dict): if item.get("enable", False) or item.get("enabled", False) or item.get("value", False): is_enabled = True if item.get("thinking", False) in (True, "true", "on", "yes", "1", 1): thinking_enabled = True if "max_length" in item and item["max_length"]: try: max_length = int(item["max_length"]) except (ValueError, TypeError): pass elif item is True or str(item).lower() in ("on", "true", "yes", "1"): is_enabled = True break
if not is_enabled: return
target_node_name = chain_definition.get('target_node', 'prompt') target_node_id = assembler.node_map.get(target_node_name)
if not target_node_id or target_node_id not in assembler.workflow: for node_id, node in assembler.workflow.items(): if isinstance(node, dict) and node.get('class_type') == 'TextEncodeQwenImage21': target_node_id = node_id break
if not target_node_id or target_node_id not in assembler.workflow: print(f"Warning: Target node '{target_node_name}' (TextEncodeQwenImage21) not found for Qwen-Image-2.1 Prompt Enhancer. Skipping.") return
target_node = assembler.workflow[target_node_id] original_prompt = target_node.get('inputs', {}).get('prompt', '')
# 1. Check if any LoadImage nodes exist in the workflow load_image_nodes = [ node_id for node_id, node in assembler.workflow.items() if isinstance(node, dict) and node.get('class_type') == 'LoadImage' ] has_load_image = len(load_image_nodes) > 0
target_image_conn = None
if not has_load_image: # Pure text-to-image (txt2img) task without reference images clip_model_name = "qwen3.5_9b_qwen_image_2.1_pe_t2i.int8_convrot.safetensors" else: # Task with reference images or img2img / inpaint / outpaint / hires.fix clip_model_name = "qwen3.5_9b_qwen_image_2.1_pe_i2i.int8_convrot.safetensors"
# Collect image connections # Prioritize extracting all images.image_* slots from target_node['inputs'] (injected by reference image injectors) indexed_slots = [] target_inputs = target_node.get('inputs', {}) for slot_key, slot_val in target_inputs.items(): if slot_key.startswith('images.image_') and isinstance(slot_val, (list, tuple)): try: idx = int(slot_key.split('_')[-1]) except Exception: idx = 999 indexed_slots.append((idx, slot_val))
indexed_slots.sort(key=lambda x: x[0]) ref_image_conns = [s[1] for s in indexed_slots]
# If no reference image slots exist (e.g. pure img2img / inpaint / outpaint), retrieve from LoadImage nodes if not ref_image_conns: for lid in load_image_nodes: scaled_conn = None for nid, node in assembler.workflow.items(): if isinstance(node, dict) and node.get('class_type') == 'ImageScaleToTotalPixels': img_input = node.get('inputs', {}).get('image') if isinstance(img_input, (list, tuple)) and str(img_input[0]) == str(lid): scaled_conn = [nid, 0] break if scaled_conn: ref_image_conns.append(scaled_conn) else: scale_id = assembler._get_unique_id() scale_node = create_node(assembler, "ImageScaleToTotalPixels", "Scale Input Image") scale_node['inputs'] = { "upscale_method": "nearest-exact", "megapixels": 1, "resolution_steps": 1, "image": [lid, 0] } assembler.workflow[scale_id] = scale_node ref_image_conns.append([scale_id, 0])
# Organize multiple reference images into grid stitching if len(ref_image_conns) == 1: target_image_conn = ref_image_conns[0] elif len(ref_image_conns) >= 2: num_cols = 2 if len(ref_image_conns) <= 4 else 3
rows = [] for i in range(0, len(ref_image_conns), num_cols): rows.append(ref_image_conns[i:i + num_cols])
# Horizontally stitch images in each row stitched_rows = [] for r_idx, row_imgs in enumerate(rows): if len(row_imgs) == 1: stitched_rows.append(row_imgs[0]) else: curr_stitch = row_imgs[0] for c_idx in range(1, len(row_imgs)): st_id = assembler._get_unique_id() st_node = create_node(assembler, "ImageStitch", f"Stitch Images (Row {r_idx+1}-{c_idx})") st_node['inputs'] = { "direction": "right", "match_image_size": True, "spacing_width": 0, "spacing_color": "white", "image1": curr_stitch, "image2": row_imgs[c_idx] } assembler.workflow[st_id] = st_node curr_stitch = [st_id, 0] stitched_rows.append(curr_stitch)
# Vertically stitch multiple rows if len(stitched_rows) == 1: final_stitched = stitched_rows[0] else: curr_vertical = stitched_rows[0] for r_idx in range(1, len(stitched_rows)): st_id = assembler._get_unique_id() st_node = create_node(assembler, "ImageStitch", f"Stitch Images (Vertical {r_idx})") st_node['inputs'] = { "direction": "down", "match_image_size": True, "spacing_width": 0, "spacing_color": "white", "image1": curr_vertical, "image2": stitched_rows[r_idx] } assembler.workflow[st_id] = st_node curr_vertical = [st_id, 0] final_stitched = curr_vertical
# Scale final stitched image to ~1024 level via ImageScaleToTotalPixels final_scale_id = assembler._get_unique_id() final_scale_node = create_node(assembler, "ImageScaleToTotalPixels", "Scale Stitched Image") final_scale_node['inputs'] = { "upscale_method": "nearest-exact", "megapixels": 1, "resolution_steps": 1, "image": final_stitched } assembler.workflow[final_scale_id] = final_scale_node target_image_conn = [final_scale_id, 0]
# 2. Ensure model is downloaded in CPU stage before workflow execution if ensure_file_downloaded: try: ensure_file_downloaded(clip_model_name) except Exception as e: print(f"Warning: Failed to ensure '{clip_model_name}' downloaded: {e}")
# 2. Create CLIPLoader node clip_node_id = assembler._get_unique_id() clip_node = create_node(assembler, "CLIPLoader", "Load CLIP") clip_node['inputs'] = { "clip_name": clip_model_name, "type": "qwen_image", "device": "default" } assembler.workflow[clip_node_id] = clip_node
# 3. Create TextGenerate node text_gen_node_id = assembler._get_unique_id() text_gen_node = create_node(assembler, "TextGenerate", "Generate Text") text_gen_inputs = { "prompt": original_prompt, "max_length": max_length, "sampling_mode": "on", "sampling_mode.temperature": 0.7, "sampling_mode.top_k": 20, "sampling_mode.top_p": 0.95, "sampling_mode.min_p": 0.0, "sampling_mode.repetition_penalty": 1.05, "sampling_mode.seed": 0, "sampling_mode.presence_penalty": 0.0 if has_load_image else 1.5, "thinking": thinking_enabled, "use_default_template": True, "mtp": "auto", "clip": [clip_node_id, 0] } if target_image_conn is not None: text_gen_inputs["image"] = target_image_conn
text_gen_node['inputs'] = text_gen_inputs assembler.workflow[text_gen_node_id] = text_gen_node
# 4. Connect TextGenerate output directly to target node prompt # ComfyUI TextGenerate node natively strips reasoning tags (<think>...</think>) into output slot 1, # leaving clean enhanced prompt in output slot 0. target_node['inputs']['prompt'] = [text_gen_node_id, 0] print(f"[Injector] Qwen-Image-2.1 Prompt Enhancer applied successfully ({'I2I' if has_load_image else 'T2I'}, clip='{clip_model_name}', thinking={thinking_enabled}).")407 unmodified lines40840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744874 unmodified lines523524525526527528529530531407 unmodified lines"x": int(xs[i]), "y": int(ys[i]), "strength": float(strengths[i])})pe_enable = ui_inputs.get('qwen_image_2_1_prompt_enhancer_enable', False)active_qwen_image_2_1_prompt_enhancer = []if 'qwen_image_2_1_prompt_enhancer' in enabled_chains and pe_enable:active_qwen_image_2_1_prompt_enhancer.append({"enable": True,"thinking": bool(ui_inputs.get('qwen_image_2_1_prompt_enhancer_thinking', False)),"max_length": int(ui_inputs.get('qwen_image_2_1_prompt_enhancer_max_length', 4096))})ming_pe_enable = ui_inputs.get('ming_image_prompt_enhancer_enable', False)active_ming_image_prompt_enhancer = []if 'ming_image_prompt_enhancer' in enabled_chains and ming_pe_enable:item = {"enable": True,"thinking": bool(ui_inputs.get('ming_image_prompt_enhancer_thinking', False)),"max_length": int(ui_inputs.get('ming_image_prompt_enhancer_max_length', 4096))}sys_p = ui_inputs.get('ming_image_prompt_enhancer_system_prompt')if sys_p:item["system_prompt"] = str(sys_p)active_ming_image_prompt_enhancer.append(item)flux3_pe_enable = ui_inputs.get('flux3_prompt_upsampler_enable', False)active_flux3_prompt_upsampler = []if 'flux3_prompt_upsampler' in enabled_chains and flux3_pe_enable:item = {"enable": True,"thinking": bool(ui_inputs.get('flux3_prompt_upsampler_thinking', False)),"bbox_mode": bool(ui_inputs.get('flux3_prompt_upsampler_bbox_mode', False)),"max_length": int(ui_inputs.get('flux3_prompt_upsampler_max_length', 3584))}sys_p = ui_inputs.get('flux3_prompt_upsampler_system_prompt')if sys_p:item["system_prompt"] = str(sys_p)active_flux3_prompt_upsampler.append(item)color_map_val = ui_inputs.get('moss_image_control_color_map')depth_map_val = ui_inputs.get('moss_image_control_depth_map')74 unmodified lines"active_qwen_image_edit": active_qwen_image_edit,"active_reference_images": active_reference_images,"active_conditioning": active_conditioning,"active_qwen_image_2_1_prompt_enhancer": active_qwen_image_2_1_prompt_enhancer,"active_ming_image_prompt_enhancer": active_ming_image_prompt_enhancer,"active_flux3_prompt_upsampler": active_flux3_prompt_upsampler,"active_moss_image_control": active_moss_image_control,"active_moss_image_edit": active_moss_image_edit,"temp_files_to_clean": temp_files_to_clean407 unmodified lines40840941041141241341441541641741841942042142242342442542642742874 unmodified lines503504505506507508509407 unmodified lines"x": int(xs[i]), "y": int(ys[i]), "strength": float(strengths[i])})pe_enable = ui_inputs.get('prompt_enhancer_enable', False)active_prompt_enhancer = []if 'prompt_enhancer' in enabled_chains and pe_enable:item = {"enable": True,"thinking": bool(ui_inputs.get('prompt_enhancer_thinking', False)),"max_length": int(ui_inputs.get('prompt_enhancer_max_length', 4096))}model_val = ui_inputs.get('prompt_enhancer_model')if model_val and str(model_val) != 'auto':item["model"] = str(model_val)prompt_val = ui_inputs.get('prompt_enhancer_system_prompt')if prompt_val and str(prompt_val) != 'auto':item["system_prompt"] = str(prompt_val)active_prompt_enhancer.append(item)color_map_val = ui_inputs.get('moss_image_control_color_map')depth_map_val = ui_inputs.get('moss_image_control_depth_map')74 unmodified lines"active_qwen_image_edit": active_qwen_image_edit,"active_reference_images": active_reference_images,"active_conditioning": active_conditioning,"active_prompt_enhancer": active_prompt_enhancer,"active_moss_image_control": active_moss_image_control,"active_moss_image_edit": active_moss_image_edit,"temp_files_to_clean": temp_files_to_clean
118 unmodified lines11912012112212312412512612753 unmodified lines181182183184185186187188189118 unmodified linesactive_qwen_image_edit = processed.get("active_qwen_image_edit", [])active_reference_images = processed.get("active_reference_images", [])active_conditioning = processed["active_conditioning"]active_qwen_image_2_1_prompt_enhancer = processed.get("active_qwen_image_2_1_prompt_enhancer", [])active_ming_image_prompt_enhancer = processed.get("active_ming_image_prompt_enhancer", [])active_flux3_prompt_upsampler = processed.get("active_flux3_prompt_upsampler", [])active_moss_image_control = processed.get("active_moss_image_control", [])active_moss_image_edit = processed.get("active_moss_image_edit", [])53 unmodified lines"krea2_style_reference_chain": active_krea2_reference_edit,"qwen_image_edit_chain": active_qwen_image_edit,"reference_image_chain": active_reference_images,"qwen_image_2_1_prompt_enhancer_chain": active_qwen_image_2_1_prompt_enhancer,"ming_image_prompt_enhancer_chain": active_ming_image_prompt_enhancer,"flux3_prompt_upsampler_chain": active_flux3_prompt_upsampler,"moss_image_control_chain": active_moss_image_control,"moss_image_edit_chain": active_moss_image_edit,"vae_chain": [ui_inputs.get('vae_name')] if (ui_inputs.get('vae_name') and 'vae' in enabled_chains) else [],118 unmodified lines11912012112212312412553 unmodified lines179180181182183184185118 unmodified linesactive_qwen_image_edit = processed.get("active_qwen_image_edit", [])active_reference_images = processed.get("active_reference_images", [])active_conditioning = processed["active_conditioning"]active_prompt_enhancer = processed.get("active_prompt_enhancer", [])active_moss_image_control = processed.get("active_moss_image_control", [])active_moss_image_edit = processed.get("active_moss_image_edit", [])53 unmodified lines"krea2_style_reference_chain": active_krea2_reference_edit,"qwen_image_edit_chain": active_qwen_image_edit,"reference_image_chain": active_reference_images,"prompt_enhancer_chain": active_prompt_enhancer,"moss_image_control_chain": active_moss_image_control,"moss_image_edit_chain": active_moss_image_edit,"vae_chain": [ui_inputs.get('vae_name')] if (ui_inputs.get('vae_name') and 'vae' in enabled_chains) else [],
3 unmodified lines456789107 unmodified lines1171181191201211221231241253 unmodified linesfrom comfy_integration.nodes import NODE_CLASS_MAPPINGSfrom utils.app_utils import get_value_at_indexclass WorkflowExecutor:@staticmethoddef topological_sort(workflow: Dict[str, Any]) -> List[str]:107 unmodified linesif class_type == 'TextEncodeMingImageEdit' and ('images' not in kwargs or kwargs.get('images') is None):kwargs['images'] = {}function_name = getattr(node_class, 'FUNCTION')execution_method = getattr(node_instance, function_name)result = execution_method(**kwargs)computed_outputs[node_id] = result3 unmodified lines4567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586107 unmodified lines1941951961971981992002012022032042052062072082092103 unmodified linesfrom comfy_integration.nodes import NODE_CLASS_MAPPINGSfrom utils.app_utils import get_value_at_indexdef _normalize_dynamic_inputs(node_class, class_type, kwargs):"""Rebuild the structures ComfyUI's executor would have built for this node.Two V3 dynamic shapes need post-processing when nodes are called directly:* ``COMFY_DYNAMICCOMBO_V3`` — the widget arrives as a bare string but thenode signature expects ``{id: <option>, **sub_keys}`` (e.g.``sampling_mode={"sampling_mode": "off"}``).* ``COMFY_AUTOGROW_V3`` — slots arrive flattened as ``image1``, ``image2``,... but the node signature expects ``images={"image1": <value>, ...}``.ComfyUI's ``comfy_api.latest._io.build_nested_inputs`` does both; thisSpace executes nodes directly and therefore has to redo the work."""schema = getattr(node_class, 'SCHEMA', None)inputs = getattr(schema, 'inputs', None) if schema is not None else Noneif not inputs:return kwargs# --- COMFY_AUTOGROW_V3 first: consume image1/video1/... slots ---for spec in inputs:sub_id = getattr(spec, 'id', None)template = getattr(spec, 'template', None)if not sub_id or template is None:continuenames = getattr(template, 'names', None) or []prefix = getattr(template, 'prefix', None)candidates = list(names)if prefix:max_n = getattr(template, 'max', 0) or 0if not candidates:candidates = [f"{prefix}{i}" for i in range(max_n)]collected = {}for name in candidates:if name in kwargs:collected[name] = kwargs.pop(name)if collected and not isinstance(kwargs.get(sub_id), dict):kwargs[sub_id] = collected# --- COMFY_DYNAMICCOMBO_V3 ---for spec in inputs:sub_id = getattr(spec, 'id', None)options = getattr(spec, 'options', None)if not sub_id or not options or sub_id not in kwargs:continuevalue = kwargs[sub_id]if isinstance(value, dict):continue # already structuredoption_keys = []for opt in options:if isinstance(opt, dict):option_keys.append(opt.get('key'))else:option_keys.append(getattr(opt, 'key', None))if value not in option_keys:print(f"Warning: '{sub_id}' value {value!r} is not one of {option_keys} for {class_type}.")continue# Pull sibling sub-keys (e.g. "sampling_mode.temperature") into the dict.nested = {sub_id: str(value)}prefix = f"{sub_id}."for key in list(kwargs.keys()):if key.startswith(prefix):nested[key[len(prefix):]] = kwargs.pop(key)kwargs[sub_id] = nestedprint(f" -> Normalized dynamic input '{sub_id}' for {class_type}: {nested}")return kwargsclass WorkflowExecutor:@staticmethoddef topological_sort(workflow: Dict[str, Any]) -> List[str]:107 unmodified linesif class_type == 'TextEncodeMingImageEdit' and ('images' not in kwargs or kwargs.get('images') is None):kwargs['images'] = {}# ComfyUI's own executor restructures V3 dynamic inputs into the# nested dict the node signature expects (see# comfy_api.latest._io.build_nested_inputs). This direct-call# path bypasses that step, so a COMFY_DYNAMICCOMBO_V3 widget# arrives as a bare string and the node fails on# `sampling_mode.get(...)`. Rebuild it here.kwargs = _normalize_dynamic_inputs(node_class, class_type, kwargs)function_name = getattr(node_class, 'FUNCTION')execution_method = getattr(node_instance, function_name)result = execution_method(**kwargs)computed_outputs[node_id] = result
77 unmodified lines78798081828384858677 unmodified linesksampler_node: "ksampler"vae_node: "vae_loader"dynamic_flux3_prompt_upsampler_chains:flux3_prompt_upsampler_chain:target_node: "pos_prompt"dynamic_pid_chains:pid_chain:77 unmodified lines7879808182838485868777 unmodified linesksampler_node: "ksampler"vae_node: "vae_loader"dynamic_prompt_enhancer_chains:prompt_enhancer_chain:target_node: "pos_prompt"framework: "flux3"dynamic_pid_chains:pid_chain:
88 unmodified lines89909192939495969788 unmodified linesvae_node: "vae_loader"max_images: 8dynamic_ming_image_prompt_enhancer_chains:ming_image_prompt_enhancer_chain:target_node: "prompt"ui_map:88 unmodified lines8990919293949596979888 unmodified linesvae_node: "vae_loader"max_images: 8dynamic_prompt_enhancer_chains:prompt_enhancer_chain:target_node: "prompt"framework: "ming-image"ui_map:
69 unmodified lines70717273747576777869 unmodified linesvae_node: "vae_loader"max_images: 10dynamic_qwen_image_2_1_prompt_enhancer_chains:qwen_image_2_1_prompt_enhancer_chain:target_node: "prompt"ui_map:positive_prompt: "prompt:prompt"69 unmodified lines7071727374757677787969 unmodified linesvae_node: "vae_loader"max_images: 10dynamic_prompt_enhancer_chains:prompt_enhancer_chain:target_node: "prompt"framework: "qwen-image-2.1"ui_map:positive_prompt: "prompt:prompt"
37 unmodified lines38394041424338 unmodified lines828384858687889 unmodified lines98991001011021031041051 unmodified line10710810911011111211311433 unmodified lines14814915015115215315437 unmodified linesif chain_key not in order:order.append(chain_key)self.injector_order = orderdef _get_unique_id(self):38 unmodified linesmerged_recipe = {'nodes': {}, 'connections': [], 'ui_map': {}}for key in self.injector_order:if key.startswith('dynamic_'):merged_recipe[key] = {}parent_recipe_dir = os.path.dirname(recipe_path_to_use)9 unmodified linesmerged_recipe['connections'].extend(imported_recipe.get('connections', []))merged_recipe['ui_map'].update(imported_recipe.get('ui_map', {}))for key in self.injector_order:if key in imported_recipe and key.startswith('dynamic_'):merged_recipe[key].update(imported_recipe.get(key, {}))except FileNotFoundError:print(f"Warning: Optional recipe partial '{import_path}' not found. Skipping.")1 unmodified linemerged_recipe['connections'].extend(main_recipe.get('connections', []))merged_recipe['ui_map'].update(main_recipe.get('ui_map', {}))for key in self.injector_order:if key in main_recipe and key.startswith('dynamic_'):merged_recipe[key].update(main_recipe.get(key, {}))return merged_recipe33 unmodified linesself.workflow[to_id]['inputs'][to_input_name] = [from_id, int(from_output_idx)]print("--- [Assembler] Applying dynamic injectors ---")recipe_chain_types = {key for key in self.recipe if key.startswith('dynamic_')}processing_order = [key for key in self.injector_order if key in recipe_chain_types]for chain_type in processing_order:37 unmodified lines383940414243444546474849505152535455565758596061626338 unmodified lines1021031041051061071081091101111129 unmodified lines1221231241251261271281291 unmodified line13113213313413513613713833 unmodified lines17217317417517617717837 unmodified linesif chain_key not in order:order.append(chain_key)# An injector may register under a bare CHAIN_TYPE while the recipe uses# the derived "dynamic_<feature>_chains" key (or vice versa). Alias both# directions so either spelling resolves to the same callable.for chain_key in list(order):func = self.global_injectors.get(chain_key)if not func:continueif chain_key.startswith('dynamic_') and chain_key.endswith('_chains'):feature = chain_key[8:-7]alias = f"dynamic_{feature}_chains"else:feature = chain_keyalias = f"dynamic_{feature}_chains"self.global_injectors.setdefault(alias, func)self.global_injectors.setdefault(feature, func)if alias not in order:order.append(alias)if feature not in order:order.append(feature)self.injector_order = orderdef _get_unique_id(self):38 unmodified linesmerged_recipe = {'nodes': {}, 'connections': [], 'ui_map': {}}for key in self.injector_order:# Injector chains may be registered under a bare CHAIN_TYPE# (e.g. "prompt_enhancer") or the derived "dynamic_*_chains" form.# Both must survive the merge, otherwise the assembler has nothing# to look up at injection time.if key:merged_recipe[key] = {}parent_recipe_dir = os.path.dirname(recipe_path_to_use)9 unmodified linesmerged_recipe['connections'].extend(imported_recipe.get('connections', []))merged_recipe['ui_map'].update(imported_recipe.get('ui_map', {}))for key in self.injector_order:if key in imported_recipe:merged_recipe.setdefault(key, {}).update(imported_recipe.get(key, {}))except FileNotFoundError:print(f"Warning: Optional recipe partial '{import_path}' not found. Skipping.")1 unmodified linemerged_recipe['connections'].extend(main_recipe.get('connections', []))merged_recipe['ui_map'].update(main_recipe.get('ui_map', {}))for key in self.injector_order:if key in main_recipe:merged_recipe.setdefault(key, {}).update(main_recipe.get(key, {}))return merged_recipe33 unmodified linesself.workflow[to_id]['inputs'][to_input_name] = [from_id, int(from_output_idx)]print("--- [Assembler] Applying dynamic injectors ---")recipe_chain_types = {key for key in self.recipe if key in self.injector_order}processing_order = [key for key in self.injector_order if key in recipe_chain_types]for chain_type in processing_order:
606 unmodified lines60760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172258 unmodified lines781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829606 unmodified linesif isinstance(is_enabled, str):is_enabled = is_enabled.upper() in ("ON", "TRUE", "1")ui_inputs["pid_settings"] = "ON" if is_enabled else "OFF"elif itype == "qwen_image_2_1_prompt_enhancer":is_enabled = item.get("enable", item.get("enabled", True))if isinstance(is_enabled, str):is_enabled = is_enabled.upper() in ("ON", "TRUE", "1")ui_inputs["qwen_image_2_1_prompt_enhancer_enable"] = bool(is_enabled)is_thinking = item.get("thinking", False)if isinstance(is_thinking, str):is_thinking = is_thinking.upper() in ("ON", "TRUE", "1")ui_inputs["qwen_image_2_1_prompt_enhancer_thinking"] = bool(is_thinking)ui_inputs["qwen_image_2_1_prompt_enhancer_max_length"] = int(item.get("max_length", 4096))elif itype == "ming_image_prompt_enhancer":is_enabled = item.get("enable", item.get("enabled", True))if isinstance(is_enabled, str):is_enabled = is_enabled.upper() in ("ON", "TRUE", "1")ui_inputs["ming_image_prompt_enhancer_enable"] = bool(is_enabled)is_thinking = item.get("thinking", False)if isinstance(is_thinking, str):is_thinking = is_thinking.upper() in ("ON", "TRUE", "1")ui_inputs["ming_image_prompt_enhancer_thinking"] = bool(is_thinking)ui_inputs["ming_image_prompt_enhancer_max_length"] = int(item.get("max_length", 4096))if "system_prompt" in item:ui_inputs["ming_image_prompt_enhancer_system_prompt"] = str(item["system_prompt"])elif itype == "flux3_prompt_upsampler":is_enabled = item.get("enable", item.get("enabled", True))if isinstance(is_enabled, str):is_enabled = is_enabled.upper() in ("ON", "TRUE", "1")ui_inputs["flux3_prompt_upsampler_enable"] = bool(is_enabled)is_thinking = item.get("thinking", False)if isinstance(is_thinking, str):is_thinking = is_thinking.upper() in ("ON", "TRUE", "1")ui_inputs["flux3_prompt_upsampler_thinking"] = bool(is_thinking)is_bbox_mode = item.get("bbox_mode", False)if isinstance(is_bbox_mode, str):is_bbox_mode = is_bbox_mode.upper() in ("ON", "TRUE", "1")ui_inputs["flux3_prompt_upsampler_bbox_mode"] = bool(is_bbox_mode)ui_inputs["flux3_prompt_upsampler_max_length"] = int(item.get("max_length", 3584))if "system_prompt" in item:ui_inputs["flux3_prompt_upsampler_system_prompt"] = str(item["system_prompt"])elif itype == "moss_image_control":if "color_map" in item:parsed_color_map = _parse_image_param(item["color_map"])if parsed_color_map:ui_inputs["moss_image_control_color_map"] = parsed_color_mapif "depth_map" in item:parsed_depth_map = _parse_image_param(item["depth_map"])if parsed_depth_map:ui_inputs["moss_image_control_depth_map"] = parsed_depth_mapif "strength" in item:try:ui_inputs["moss_image_control_strength"] = float(item["strength"])except (ValueError, TypeError):passif "start_percent" in item:try:ui_inputs["moss_image_control_start_percent"] = float(item["start_percent"])except (ValueError, TypeError):passif "end_percent" in item:try:ui_inputs["moss_image_control_end_percent"] = float(item["end_percent"])except (ValueError, TypeError):passelif itype == "krea2_identity_edit":img = _parse_image_param(item.get("image"))if img:krea2_identity_edit_data.append(img)elif itype == "krea2_style_reference":img = _parse_image_param(item.get("image"))if img:krea2_reference_edit_data.append(img)elif itype in ("reference_latent", "reference_edit"):img = _parse_image_param(item.get("image"))if img:reference_latent_data.append(img)elif itype in ("reference_image", "mage_flow_reference_edit", "boogu_image_edit", "boogu_edit", "qwen_image_2_1_edit"):img = _parse_image_param(item.get("image"))if img:reference_image_data.append(img)elif itype in ("joyai_image", "joyai_reference_edit"):img = _parse_image_param(item.get("image"))if img:joyai_reference_data.append(img)elif itype == "qwen_image_edit":img = _parse_image_param(item.get("image"))if img:qwen_image_edit_data.append(img)elif itype == "hidream_o1_reference":img = _parse_image_param(item.get("image"))if img:hidream_o1_reference_data.append(img)elif itype == "sensenova_reference":img = _parse_image_param(item.get("image"))if img:sensenova_reference_data.append(img)elif itype == "moss_image_edit":if "images" in item and isinstance(item["images"], list):for img_item in item["images"]:p_img = _parse_image_param(img_item)if p_img:moss_image_edit_data.append(p_img)elif "image" in item:p_img = _parse_image_param(item["image"])if p_img:moss_image_edit_data.append(p_img)elif itype == "vae":v_source = item.get("source", item.get("vae_source", "Civitai"))v_val = item.get("vae_value", item.get("value", item.get("vae_id", item.get("vae_name", ""))))if v_source and v_val:ui_inputs["vae_source"] = v_sourceui_inputs["vae_id"] = str(v_val)if lora_data: ui_inputs["lora_data"] = lora_dataif embedding_data: ui_inputs["embedding_data"] = embedding_data58 unmodified lineselse:ui_inputs["pid_settings"] = "OFF"pe_val = params.get("qwen_image_2_1_prompt_enhancer") or params.get("qwen_image_2_1_prompt_enhancer_enable")if pe_val is not None:if isinstance(pe_val, bool):ui_inputs["qwen_image_2_1_prompt_enhancer_enable"] = pe_valelif isinstance(pe_val, dict):ui_inputs["qwen_image_2_1_prompt_enhancer_enable"] = bool(pe_val.get("enable", pe_val.get("enabled", True)))ui_inputs["qwen_image_2_1_prompt_enhancer_thinking"] = bool(pe_val.get("thinking", False))ui_inputs["qwen_image_2_1_prompt_enhancer_max_length"] = int(pe_val.get("max_length", 4096))elif str(pe_val).upper() in ("ON", "TRUE", "1"):ui_inputs["qwen_image_2_1_prompt_enhancer_enable"] = Trueelse:ui_inputs["qwen_image_2_1_prompt_enhancer_enable"] = Falseming_pe_val = params.get("ming_image_prompt_enhancer") or params.get("ming_image_prompt_enhancer_enable")if ming_pe_val is not None:if isinstance(ming_pe_val, bool):ui_inputs["ming_image_prompt_enhancer_enable"] = ming_pe_valelif isinstance(ming_pe_val, dict):ui_inputs["ming_image_prompt_enhancer_enable"] = bool(ming_pe_val.get("enable", ming_pe_val.get("enabled", True)))ui_inputs["ming_image_prompt_enhancer_thinking"] = bool(ming_pe_val.get("thinking", False))ui_inputs["ming_image_prompt_enhancer_max_length"] = int(ming_pe_val.get("max_length", 4096))if "system_prompt" in ming_pe_val:ui_inputs["ming_image_prompt_enhancer_system_prompt"] = str(ming_pe_val["system_prompt"])elif str(ming_pe_val).upper() in ("ON", "TRUE", "1"):ui_inputs["ming_image_prompt_enhancer_enable"] = Trueelse:ui_inputs["ming_image_prompt_enhancer_enable"] = Falseflux3_pe_val = params.get("flux3_prompt_upsampler") or params.get("flux3_prompt_upsampler_enable")if flux3_pe_val is not None:if isinstance(flux3_pe_val, bool):ui_inputs["flux3_prompt_upsampler_enable"] = flux3_pe_valelif isinstance(flux3_pe_val, dict):ui_inputs["flux3_prompt_upsampler_enable"] = bool(flux3_pe_val.get("enable", flux3_pe_val.get("enabled", True)))ui_inputs["flux3_prompt_upsampler_thinking"] = bool(flux3_pe_val.get("thinking", False))ui_inputs["flux3_prompt_upsampler_bbox_mode"] = bool(flux3_pe_val.get("bbox_mode", False))ui_inputs["flux3_prompt_upsampler_max_length"] = int(flux3_pe_val.get("max_length", 3584))if "system_prompt" in flux3_pe_val:ui_inputs["flux3_prompt_upsampler_system_prompt"] = str(flux3_pe_val["system_prompt"])elif str(flux3_pe_val).upper() in ("ON", "TRUE", "1"):ui_inputs["flux3_prompt_upsampler_enable"] = Trueelse:ui_inputs["flux3_prompt_upsampler_enable"] = Falsemoss_control_val = params.get("moss_image_control")if moss_control_val and isinstance(moss_control_val, dict):606 unmodified lines60760860961061161261361461561661761861962062162262362462562662762862963063163258 unmodified lines691692693694695696697698699700701702703704705706707708709606 unmodified linesif isinstance(is_enabled, str):is_enabled = is_enabled.upper() in ("ON", "TRUE", "1")ui_inputs["pid_settings"] = "ON" if is_enabled else "OFF"elif itype == "prompt_enhancer":is_enabled = item.get("enable", item.get("enabled", True))if isinstance(is_enabled, str):is_enabled = is_enabled.upper() in ("ON", "TRUE", "1")ui_inputs["prompt_enhancer_enable"] = bool(is_enabled)is_thinking = item.get("thinking", False)if isinstance(is_thinking, str):is_thinking = is_thinking.upper() in ("ON", "TRUE", "1")ui_inputs["prompt_enhancer_thinking"] = bool(is_thinking)ui_inputs["prompt_enhancer_max_length"] = int(item.get("max_length", 4096))model_value = item.get("model")if model_value:ui_inputs["prompt_enhancer_model"] = str(model_value)prompt_value = item.get("system_prompt")if prompt_value:ui_inputs["prompt_enhancer_system_prompt"] = str(prompt_value)if lora_data: ui_inputs["lora_data"] = lora_dataif embedding_data: ui_inputs["embedding_data"] = embedding_data58 unmodified lineselse:ui_inputs["pid_settings"] = "OFF"pe_val = params.get("prompt_enhancer")if pe_val is not None:if isinstance(pe_val, dict):ui_inputs["prompt_enhancer_enable"] = bool(pe_val.get("enable", pe_val.get("enabled", True)))ui_inputs["prompt_enhancer_thinking"] = bool(pe_val.get("thinking", False))ui_inputs["prompt_enhancer_max_length"] = int(pe_val.get("max_length", 4096))if pe_val.get("model"):ui_inputs["prompt_enhancer_model"] = str(pe_val["model"])if pe_val.get("system_prompt"):ui_inputs["prompt_enhancer_system_prompt"] = str(pe_val["system_prompt"])else:ui_inputs["prompt_enhancer_enable"] = bool(pe_val)moss_control_val = params.get("moss_image_control")if moss_control_val and isinstance(moss_control_val, dict):
8 unmodified lines910111213141516171819202162 unmodified lines84858687888990919240 unmodified lines13313413513613713813970 unmodified lines2102112122132142152162172188 unmodified linesARCH_CATEGORIES_MAP)from utils.app_utils import get_model_generation_defaultsfrom ui.shared.ui_components import RESOLUTION_MAPfrom .config_loaders import (get_cn_defaults,load_ipadapter_config)def make_update_fn(m_comp, cat_comp, ar_comp, width_comp, height_comp, cn_types, cn_series, cn_filepaths, ipa_preset, lora_acc, cn_acc, ipa_acc, sd3_ipa_acc, flux1_ipa_acc, style_acc, embed_acc, cond_acc, ref_latent_acc, hidream_o1_ref_acc, prompt_comp, neg_prompt_comp, steps_comp, cfg_comp, sampler_comp, scheduler_comp, pid_acc=None, vae_acc=None, joyai_ref_acc=None, krea2_identity_edit_acc=None, krea2_reference_edit_acc=None, qwen_image_edit_acc=None, ref_img_acc=None, sensenova_ref_acc=None, task_type=None, type_comp=None, qwen_pe_acc=None, ming_pe_acc=None, flux3_pe_acc=None, moss_image_control_acc=None, moss_image_edit_acc=None):def update_fn(*args):arch = args[0]category = args[1]62 unmodified linesif ref_img_acc: updates[ref_img_acc] = gr.update(visible=('reference_image' in enabled_chains))if pid_acc: updates[pid_acc] = gr.update(visible=('pid' in enabled_chains))if vae_acc: updates[vae_acc] = gr.update(visible=('vae' in enabled_chains))if qwen_pe_acc: updates[qwen_pe_acc] = gr.update(visible=('qwen_image_2_1_prompt_enhancer' in enabled_chains))if ming_pe_acc: updates[ming_pe_acc] = gr.update(visible=('ming_image_prompt_enhancer' in enabled_chains))if flux3_pe_acc: updates[flux3_pe_acc] = gr.update(visible=('flux3_prompt_upsampler' in enabled_chains))if moss_image_control_acc: updates[moss_image_control_acc] = gr.update(visible=('moss_image_control' in enabled_chains))if moss_image_edit_acc: updates[moss_image_edit_acc] = gr.update(visible=('moss_image_edit' in enabled_chains))40 unmodified linesreturn update_fndef make_model_change_fn(cat_comp_ref, ar_comp, width_comp, height_comp, cn_types, cn_series, cn_filepaths, arch_comp_ref, ipa_preset, lora_acc, cn_acc, ipa_acc, sd3_ipa_acc, flux1_ipa_acc, style_acc, embed_acc, cond_acc, ref_latent_acc, hidream_o1_ref_acc, prompt_comp, neg_prompt_comp, steps_comp, cfg_comp, sampler_comp, scheduler_comp, pid_acc=None, vae_acc=None, joyai_ref_acc=None, krea2_identity_edit_acc=None, krea2_reference_edit_acc=None, qwen_image_edit_acc=None, ref_img_acc=None, sensenova_ref_acc=None, task_type=None, type_comp=None, qwen_pe_acc=None, ming_pe_acc=None, flux3_pe_acc=None, moss_image_control_acc=None, moss_image_edit_acc=None):def change_fn(*args):model_name = args[0]idx = 170 unmodified linesif ref_img_acc: updates[ref_img_acc] = gr.update(visible=('reference_image' in enabled_chains))if pid_acc: updates[pid_acc] = gr.update(visible=('pid' in enabled_chains))if vae_acc: updates[vae_acc] = gr.update(visible=('vae' in enabled_chains))if qwen_pe_acc: updates[qwen_pe_acc] = gr.update(visible=('qwen_image_2_1_prompt_enhancer' in enabled_chains))if ming_pe_acc: updates[ming_pe_acc] = gr.update(visible=('ming_image_prompt_enhancer' in enabled_chains))if flux3_pe_acc: updates[flux3_pe_acc] = gr.update(visible=('flux3_prompt_upsampler' in enabled_chains))if moss_image_control_acc: updates[moss_image_control_acc] = gr.update(visible=('moss_image_control' in enabled_chains))if moss_image_edit_acc: updates[moss_image_edit_acc] = gr.update(visible=('moss_image_edit' in enabled_chains))8 unmodified lines910111213141516171819202162 unmodified lines848586878889909192939440 unmodified lines13513613713813914014170 unmodified lines2122132142152162172182192202212228 unmodified linesARCH_CATEGORIES_MAP)from utils.app_utils import get_model_generation_defaultsfrom ui.shared.ui_components import RESOLUTION_MAP, prompt_enhancer_defaultsfrom .config_loaders import (get_cn_defaults,load_ipadapter_config)def make_update_fn(m_comp, cat_comp, ar_comp, width_comp, height_comp, cn_types, cn_series, cn_filepaths, ipa_preset, lora_acc, cn_acc, ipa_acc, sd3_ipa_acc, flux1_ipa_acc, style_acc, embed_acc, cond_acc, ref_latent_acc, hidream_o1_ref_acc, prompt_comp, neg_prompt_comp, steps_comp, cfg_comp, sampler_comp, scheduler_comp, pid_acc=None, vae_acc=None, joyai_ref_acc=None, krea2_identity_edit_acc=None, krea2_reference_edit_acc=None, qwen_image_edit_acc=None, ref_img_acc=None, sensenova_ref_acc=None, task_type=None, type_comp=None, pe_acc=None, pe_model_acc=None, pe_prompt_acc=None, moss_image_control_acc=None, moss_image_edit_acc=None):def update_fn(*args):arch = args[0]category = args[1]62 unmodified linesif ref_img_acc: updates[ref_img_acc] = gr.update(visible=('reference_image' in enabled_chains))if pid_acc: updates[pid_acc] = gr.update(visible=('pid' in enabled_chains))if vae_acc: updates[vae_acc] = gr.update(visible=('vae' in enabled_chains))if pe_acc: updates[pe_acc] = gr.update(visible=('prompt_enhancer' in enabled_chains))if pe_model_acc or pe_prompt_acc:pe_defaults = prompt_enhancer_defaults(arch_model_type)if pe_model_acc: updates[pe_model_acc] = gr.update(value=pe_defaults['model'])if pe_prompt_acc: updates[pe_prompt_acc] = gr.update(value=pe_defaults['system_prompt'])if moss_image_control_acc: updates[moss_image_control_acc] = gr.update(visible=('moss_image_control' in enabled_chains))if moss_image_edit_acc: updates[moss_image_edit_acc] = gr.update(visible=('moss_image_edit' in enabled_chains))40 unmodified linesreturn update_fndef make_model_change_fn(cat_comp_ref, ar_comp, width_comp, height_comp, cn_types, cn_series, cn_filepaths, arch_comp_ref, ipa_preset, lora_acc, cn_acc, ipa_acc, sd3_ipa_acc, flux1_ipa_acc, style_acc, embed_acc, cond_acc, ref_latent_acc, hidream_o1_ref_acc, prompt_comp, neg_prompt_comp, steps_comp, cfg_comp, sampler_comp, scheduler_comp, pid_acc=None, vae_acc=None, joyai_ref_acc=None, krea2_identity_edit_acc=None, krea2_reference_edit_acc=None, qwen_image_edit_acc=None, ref_img_acc=None, sensenova_ref_acc=None, task_type=None, type_comp=None, pe_acc=None, pe_model_acc=None, pe_prompt_acc=None, moss_image_control_acc=None, moss_image_edit_acc=None):def change_fn(*args):model_name = args[0]idx = 170 unmodified linesif ref_img_acc: updates[ref_img_acc] = gr.update(visible=('reference_image' in enabled_chains))if pid_acc: updates[pid_acc] = gr.update(visible=('pid' in enabled_chains))if vae_acc: updates[vae_acc] = gr.update(visible=('vae' in enabled_chains))if pe_acc: updates[pe_acc] = gr.update(visible=('prompt_enhancer' in enabled_chains))if pe_model_acc or pe_prompt_acc:pe_defaults = prompt_enhancer_defaults(arch_model_type)if pe_model_acc: updates[pe_model_acc] = gr.update(value=pe_defaults['model'])if pe_prompt_acc: updates[pe_prompt_acc] = gr.update(value=pe_defaults['system_prompt'])if moss_image_control_acc: updates[moss_image_control_acc] = gr.update(visible=('moss_image_control' in enabled_chains))if moss_image_edit_acc: updates[moss_image_edit_acc] = gr.update(visible=('moss_image_edit' in enabled_chains))
62 unmodified lines63646566676869707131 unmodified lines1031041051061071081091101116 unmodified lines11811912012112212312429 unmodified lines15415515615715815916016116211 unmodified lines17417517617717817918084 unmodified lines26526626726826927027127227333 unmodified lines30730830931031131231331431562 unmodified linesref_img_accordion = ui_components.get(f'reference_image_accordion_{prefix}')pid_accordion = ui_components.get(f'pid_accordion_{prefix}')vae_accordion = ui_components.get(f'vae_accordion_{prefix}')qwen_pe_accordion = ui_components.get(f'qwen_image_2_1_prompt_enhancer_accordion_{prefix}')ming_pe_accordion = ui_components.get(f'ming_image_prompt_enhancer_accordion_{prefix}')flux3_pe_accordion = ui_components.get(f'flux3_prompt_upsampler_accordion_{prefix}')moss_control_accordion = ui_components.get(f'moss_image_control_accordion_{prefix}')moss_edit_accordion = ui_components.get(f'moss_image_edit_accordion_{prefix}')31 unmodified linesif ref_img_accordion: outputs.append(ref_img_accordion)if pid_accordion: outputs.append(pid_accordion)if vae_accordion: outputs.append(vae_accordion)if qwen_pe_accordion: outputs.append(qwen_pe_accordion)if ming_pe_accordion: outputs.append(ming_pe_accordion)if flux3_pe_accordion: outputs.append(flux3_pe_accordion)if moss_control_accordion: outputs.append(moss_control_accordion)if moss_edit_accordion: outputs.append(moss_edit_accordion)if ipa_preset_list: outputs.append(ipa_preset_list)6 unmodified linesipa_preset_list, lora_accordion, cn_accordion, ipa_accordion, sd3_ipa_accordion, flux1_ipa_accordion, style_accordion, embedding_accordion, conditioning_accordion,ref_latent_accordion, hidream_o1_ref_accordion, prompt_comp, neg_prompt_comp, steps_comp, cfg_comp, sampler_comp, scheduler_comp,pid_acc=pid_accordion, vae_acc=vae_accordion, joyai_ref_acc=joyai_ref_accordion, krea2_identity_edit_acc=krea2_identity_edit_accordion, krea2_reference_edit_acc=krea2_reference_edit_accordion, qwen_image_edit_acc=qwen_image_edit_accordion, ref_img_acc=ref_img_accordion, sensenova_ref_acc=sensenova_ref_accordion,task_type=task_type, type_comp=type_comp, qwen_pe_acc=qwen_pe_accordion, ming_pe_acc=ming_pe_accordion, flux3_pe_acc=flux3_pe_accordion,moss_image_control_acc=moss_control_accordion,moss_image_edit_acc=moss_edit_accordion)29 unmodified linesif ref_img_accordion: outputs2.append(ref_img_accordion)if pid_accordion: outputs2.append(pid_accordion)if vae_accordion: outputs2.append(vae_accordion)if qwen_pe_accordion: outputs2.append(qwen_pe_accordion)if ming_pe_accordion: outputs2.append(ming_pe_accordion)if flux3_pe_accordion: outputs2.append(flux3_pe_accordion)if moss_control_accordion: outputs2.append(moss_control_accordion)if moss_edit_accordion: outputs2.append(moss_edit_accordion)if ipa_preset_list: outputs2.append(ipa_preset_list)11 unmodified linesarch_comp, ipa_preset_list, lora_accordion, cn_accordion, ipa_accordion, sd3_ipa_accordion, flux1_ipa_accordion, style_accordion, embedding_accordion, conditioning_accordion,ref_latent_accordion, hidream_o1_ref_accordion, prompt_comp, neg_prompt_comp, steps_comp, cfg_comp, sampler_comp, scheduler_comp,pid_acc=pid_accordion, vae_acc=vae_accordion, joyai_ref_acc=joyai_ref_accordion, krea2_identity_edit_acc=krea2_identity_edit_accordion, krea2_reference_edit_acc=krea2_reference_edit_accordion, qwen_image_edit_acc=qwen_image_edit_accordion, ref_img_acc=ref_img_accordion, sensenova_ref_acc=sensenova_ref_accordion,task_type=task_type, type_comp=type_comp, qwen_pe_acc=qwen_pe_accordion, ming_pe_acc=ming_pe_accordion, flux3_pe_acc=flux3_pe_accordion,moss_image_control_acc=moss_control_accordion,moss_image_edit_acc=moss_edit_accordion)84 unmodified linesf'krea2_reference_edit_accordion_{prefix}': 'krea2_style_reference',f'qwen_image_edit_accordion_{prefix}': 'qwen_image_edit',f'reference_image_accordion_{prefix}': 'reference_image',f'qwen_image_2_1_prompt_enhancer_accordion_{prefix}': 'qwen_image_2_1_prompt_enhancer',f'ming_image_prompt_enhancer_accordion_{prefix}': 'ming_image_prompt_enhancer',f'flux3_prompt_upsampler_accordion_{prefix}': 'flux3_prompt_upsampler',f'moss_image_control_accordion_{prefix}': 'moss_image_control',f'moss_image_edit_accordion_{prefix}': 'moss_image_edit',f'pid_accordion_{prefix}': 'pid',33 unmodified lines'krea2_identity_edit_accordion_imagegen', 'krea2_reference_edit_accordion_imagegen','qwen_image_edit_accordion_imagegen','reference_image_accordion_imagegen','qwen_image_2_1_prompt_enhancer_accordion_imagegen','ming_image_prompt_enhancer_accordion_imagegen','flux3_prompt_upsampler_accordion_imagegen','moss_image_control_accordion_imagegen','moss_image_edit_accordion_imagegen','pid_accordion_imagegen', 'vae_accordion_imagegen',62 unmodified lines63646566676869707131 unmodified lines1031041051061071081091101116 unmodified lines11811912012112212312429 unmodified lines15415515615715815916016116211 unmodified lines17417517617717817918084 unmodified lines26526626726826927027133 unmodified lines30530630730830931031162 unmodified linesref_img_accordion = ui_components.get(f'reference_image_accordion_{prefix}')pid_accordion = ui_components.get(f'pid_accordion_{prefix}')vae_accordion = ui_components.get(f'vae_accordion_{prefix}')pe_accordion = ui_components.get(f'prompt_enhancer_accordion_{prefix}')pe_model_comp = ui_components.get(f'prompt_enhancer_model_{prefix}')pe_prompt_comp = ui_components.get(f'prompt_enhancer_system_prompt_{prefix}')moss_control_accordion = ui_components.get(f'moss_image_control_accordion_{prefix}')moss_edit_accordion = ui_components.get(f'moss_image_edit_accordion_{prefix}')31 unmodified linesif ref_img_accordion: outputs.append(ref_img_accordion)if pid_accordion: outputs.append(pid_accordion)if vae_accordion: outputs.append(vae_accordion)if pe_accordion: outputs.append(pe_accordion)if pe_model_comp: outputs.append(pe_model_comp)if pe_prompt_comp: outputs.append(pe_prompt_comp)if moss_control_accordion: outputs.append(moss_control_accordion)if moss_edit_accordion: outputs.append(moss_edit_accordion)if ipa_preset_list: outputs.append(ipa_preset_list)6 unmodified linesipa_preset_list, lora_accordion, cn_accordion, ipa_accordion, sd3_ipa_accordion, flux1_ipa_accordion, style_accordion, embedding_accordion, conditioning_accordion,ref_latent_accordion, hidream_o1_ref_accordion, prompt_comp, neg_prompt_comp, steps_comp, cfg_comp, sampler_comp, scheduler_comp,pid_acc=pid_accordion, vae_acc=vae_accordion, joyai_ref_acc=joyai_ref_accordion, krea2_identity_edit_acc=krea2_identity_edit_accordion, krea2_reference_edit_acc=krea2_reference_edit_accordion, qwen_image_edit_acc=qwen_image_edit_accordion, ref_img_acc=ref_img_accordion, sensenova_ref_acc=sensenova_ref_accordion,task_type=task_type, type_comp=type_comp, pe_acc=pe_accordion, pe_model_acc=pe_model_comp, pe_prompt_acc=pe_prompt_comp,moss_image_control_acc=moss_control_accordion,moss_image_edit_acc=moss_edit_accordion)29 unmodified linesif ref_img_accordion: outputs2.append(ref_img_accordion)if pid_accordion: outputs2.append(pid_accordion)if vae_accordion: outputs2.append(vae_accordion)if pe_accordion: outputs2.append(pe_accordion)if pe_model_comp: outputs2.append(pe_model_comp)if pe_prompt_comp: outputs2.append(pe_prompt_comp)if moss_control_accordion: outputs2.append(moss_control_accordion)if moss_edit_accordion: outputs2.append(moss_edit_accordion)if ipa_preset_list: outputs2.append(ipa_preset_list)11 unmodified linesarch_comp, ipa_preset_list, lora_accordion, cn_accordion, ipa_accordion, sd3_ipa_accordion, flux1_ipa_accordion, style_accordion, embedding_accordion, conditioning_accordion,ref_latent_accordion, hidream_o1_ref_accordion, prompt_comp, neg_prompt_comp, steps_comp, cfg_comp, sampler_comp, scheduler_comp,pid_acc=pid_accordion, vae_acc=vae_accordion, joyai_ref_acc=joyai_ref_accordion, krea2_identity_edit_acc=krea2_identity_edit_accordion, krea2_reference_edit_acc=krea2_reference_edit_accordion, qwen_image_edit_acc=qwen_image_edit_accordion, ref_img_acc=ref_img_accordion, sensenova_ref_acc=sensenova_ref_accordion,task_type=task_type, type_comp=type_comp, pe_acc=pe_accordion, pe_model_acc=pe_model_comp, pe_prompt_acc=pe_prompt_comp,moss_image_control_acc=moss_control_accordion,moss_image_edit_acc=moss_edit_accordion)84 unmodified linesf'krea2_reference_edit_accordion_{prefix}': 'krea2_style_reference',f'qwen_image_edit_accordion_{prefix}': 'qwen_image_edit',f'reference_image_accordion_{prefix}': 'reference_image',f'prompt_enhancer_accordion_{prefix}': 'prompt_enhancer',f'moss_image_control_accordion_{prefix}': 'moss_image_control',f'moss_image_edit_accordion_{prefix}': 'moss_image_edit',f'pid_accordion_{prefix}': 'pid',33 unmodified lines'krea2_identity_edit_accordion_imagegen', 'krea2_reference_edit_accordion_imagegen','qwen_image_edit_accordion_imagegen','reference_image_accordion_imagegen','prompt_enhancer_accordion_imagegen','moss_image_control_accordion_imagegen','moss_image_edit_accordion_imagegen','pid_accordion_imagegen', 'vae_accordion_imagegen',
36 unmodified lines3738394041424344454647484950515253545556575859606162636465666736 unmodified linesif ui_components.get(f'pid_settings_{prefix}'):run_inputs_map['pid_settings'] = ui_components[f'pid_settings_{prefix}']if ui_components.get(f'qwen_image_2_1_prompt_enhancer_enable_{prefix}'):run_inputs_map['qwen_image_2_1_prompt_enhancer_enable'] = ui_components[f'qwen_image_2_1_prompt_enhancer_enable_{prefix}']if ui_components.get(f'qwen_image_2_1_prompt_enhancer_thinking_{prefix}'):run_inputs_map['qwen_image_2_1_prompt_enhancer_thinking'] = ui_components[f'qwen_image_2_1_prompt_enhancer_thinking_{prefix}']if ui_components.get(f'qwen_image_2_1_prompt_enhancer_max_length_{prefix}'):run_inputs_map['qwen_image_2_1_prompt_enhancer_max_length'] = ui_components[f'qwen_image_2_1_prompt_enhancer_max_length_{prefix}']if ui_components.get(f'ming_image_prompt_enhancer_enable_{prefix}'):run_inputs_map['ming_image_prompt_enhancer_enable'] = ui_components[f'ming_image_prompt_enhancer_enable_{prefix}']if ui_components.get(f'ming_image_prompt_enhancer_thinking_{prefix}'):run_inputs_map['ming_image_prompt_enhancer_thinking'] = ui_components[f'ming_image_prompt_enhancer_thinking_{prefix}']if ui_components.get(f'ming_image_prompt_enhancer_max_length_{prefix}'):run_inputs_map['ming_image_prompt_enhancer_max_length'] = ui_components[f'ming_image_prompt_enhancer_max_length_{prefix}']if ui_components.get(f'ming_image_prompt_enhancer_system_prompt_{prefix}'):run_inputs_map['ming_image_prompt_enhancer_system_prompt'] = ui_components[f'ming_image_prompt_enhancer_system_prompt_{prefix}']if ui_components.get(f'flux3_prompt_upsampler_enable_{prefix}'):run_inputs_map['flux3_prompt_upsampler_enable'] = ui_components[f'flux3_prompt_upsampler_enable_{prefix}']if ui_components.get(f'flux3_prompt_upsampler_thinking_{prefix}'):run_inputs_map['flux3_prompt_upsampler_thinking'] = ui_components[f'flux3_prompt_upsampler_thinking_{prefix}']if ui_components.get(f'flux3_prompt_upsampler_bbox_mode_{prefix}'):run_inputs_map['flux3_prompt_upsampler_bbox_mode'] = ui_components[f'flux3_prompt_upsampler_bbox_mode_{prefix}']if ui_components.get(f'flux3_prompt_upsampler_max_length_{prefix}'):run_inputs_map['flux3_prompt_upsampler_max_length'] = ui_components[f'flux3_prompt_upsampler_max_length_{prefix}']if ui_components.get(f'moss_image_control_color_map_{prefix}'):run_inputs_map['moss_image_control_color_map'] = ui_components[f'moss_image_control_color_map_{prefix}']if ui_components.get(f'moss_image_control_depth_map_{prefix}'):36 unmodified lines3738394041424344454647484950515236 unmodified linesif ui_components.get(f'pid_settings_{prefix}'):run_inputs_map['pid_settings'] = ui_components[f'pid_settings_{prefix}']if ui_components.get(f'prompt_enhancer_enable_{prefix}'):run_inputs_map['prompt_enhancer_enable'] = ui_components[f'prompt_enhancer_enable_{prefix}']if ui_components.get(f'prompt_enhancer_thinking_{prefix}'):run_inputs_map['prompt_enhancer_thinking'] = ui_components[f'prompt_enhancer_thinking_{prefix}']if ui_components.get(f'prompt_enhancer_max_length_{prefix}'):run_inputs_map['prompt_enhancer_max_length'] = ui_components[f'prompt_enhancer_max_length_{prefix}']if ui_components.get(f'prompt_enhancer_model_{prefix}'):run_inputs_map['prompt_enhancer_model'] = ui_components[f'prompt_enhancer_model_{prefix}']if ui_components.get(f'prompt_enhancer_system_prompt_{prefix}'):run_inputs_map['prompt_enhancer_system_prompt'] = ui_components[f'prompt_enhancer_system_prompt_{prefix}']if ui_components.get(f'moss_image_control_color_map_{prefix}'):run_inputs_map['moss_image_control_color_map'] = ui_components[f'moss_image_control_color_map_{prefix}']if ui_components.get(f'moss_image_control_depth_map_{prefix}'):
8 unmodified lines910111213141516172 unmodified lines1891901911921931941951961978 unmodified linescreate_model_architecture_filter_ui, create_category_filter_ui,create_sd3_ipadapter_ui, create_flux1_ipadapter_ui, create_style_ui,create_reference_latent_ui, create_hidream_o1_reference_ui, create_sensenova_reference_ui, create_joyai_reference_ui, create_reference_image_ui, create_krea2_identity_edit_ui, create_krea2_reference_edit_ui, create_qwen_image_edit_ui,create_pid_ui, create_qwen_image_2_1_prompt_enhancer_ui, create_ming_image_prompt_enhancer_ui,create_flux3_prompt_upsampler_ui, create_moss_image_control_ui,create_moss_image_edit_ui)172 unmodified linescomponents.update(create_krea2_reference_edit_ui(prefix))components.update(create_qwen_image_edit_ui(prefix))components.update(create_reference_image_ui(prefix))components.update(create_qwen_image_2_1_prompt_enhancer_ui(prefix))components.update(create_ming_image_prompt_enhancer_ui(prefix))components.update(create_flux3_prompt_upsampler_ui(prefix))components.update(create_vae_override_ui(prefix))components.update(create_moss_image_control_ui(prefix))components.update(create_moss_image_edit_ui(prefix))8 unmodified lines9101112131415172 unmodified lines1881891901911921931948 unmodified linescreate_model_architecture_filter_ui, create_category_filter_ui,create_sd3_ipadapter_ui, create_flux1_ipadapter_ui, create_style_ui,create_reference_latent_ui, create_hidream_o1_reference_ui, create_sensenova_reference_ui, create_joyai_reference_ui, create_reference_image_ui, create_krea2_identity_edit_ui, create_krea2_reference_edit_ui, create_qwen_image_edit_ui,create_pid_ui, create_prompt_enhancer_ui, create_moss_image_control_ui,create_moss_image_edit_ui)172 unmodified linescomponents.update(create_krea2_reference_edit_ui(prefix))components.update(create_qwen_image_edit_ui(prefix))components.update(create_reference_image_ui(prefix))components.update(create_prompt_enhancer_ui(prefix))components.update(create_vae_override_ui(prefix))components.update(create_moss_image_control_ui(prefix))components.update(create_moss_image_edit_ui(prefix))
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947import gradio as grfrom comfy_integration.nodes import SAMPLER_CHOICES, SCHEDULER_CHOICESfrom core.settings import (MAX_LORAS, LORA_SOURCE_CHOICES, MAX_EMBEDDINGS, MAX_CONDITIONINGS,MAX_CONTROLNETS, MAX_IPADAPTERS, MAX_MOSS_IMAGE_EDITS, RESOLUTION_MAP, ARCHITECTURES_CONFIG,MODEL_MAP_CHECKPOINT, MODEL_TYPE_MAP, FEATURES_CONFIG, ARCH_CATEGORIES_MAP,VAE_DIR, MODEL_DEFAULTS_CONFIG)import yamlimport osfrom functools import lru_cachefrom utils.app_utils import save_uploaded_filedefault_model_name = list(MODEL_MAP_CHECKPOINT.keys())[0] if MODEL_MAP_CHECKPOINT else Nonedefault_m_type = MODEL_TYPE_MAP.get(default_model_name, "SDXL") if default_model_name else "SDXL"default_architectures_dict = ARCHITECTURES_CONFIG.get('architectures', {})default_arch_model_type = default_architectures_dict.get(default_m_type, {}).get("model_type", default_m_type.lower().replace(" ", "").replace(".", ""))default_arch_features = FEATURES_CONFIG.get(default_arch_model_type, {})default_enabled_chains = default_arch_features.get('enabled_chains', [])default_vals = MODEL_DEFAULTS_CONFIG.get('Default', {})DEFAULT_STEPS = default_vals.get('steps', 20)DEFAULT_CFG = default_vals.get('cfg', 5.0)DEFAULT_SAMPLER = default_vals.get('sampler_name', 'euler')DEFAULT_SCHEDULER = default_vals.get('scheduler', 'simple')DEFAULT_POS_PROMPT = default_vals.get('positive_prompt', '')DEFAULT_NEG_PROMPT = default_vals.get('negative_prompt', '')@lru_cache(maxsize=1)def get_ipadapter_config_from_yaml():try:_PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))_IPADAPTER_LIST_PATH = os.path.join(_PROJECT_ROOT, 'yaml', 'ipadapter.yaml')with open(_IPADAPTER_LIST_PATH, 'r', encoding='utf-8') as f:config = yaml.safe_load(f)return configexcept Exception as e:print(f"Warning: Could not load ipadapter.yaml for UI components: {e}")return {}def get_ipadapter_presets(arch="SDXL"):config = get_ipadapter_config_from_yaml()presets = []if config:std_presets = config.get("IPAdapter_presets", {}).get(arch, [])face_presets = config.get("IPAdapter_FaceID_presets", {}).get(arch, [])if std_presets:presets.extend(std_presets)if face_presets:presets.extend(face_presets)return presets if presets else ["STANDARD (medium strength)"]def create_model_architecture_filter_ui(prefix):components = {}ordered_architectures = ARCHITECTURES_CONFIG.get("architecture_order", [])choices = ["ALL"] + ordered_architecturescomponents[f'model_arch_{prefix}'] = gr.Radio(label="Model Architecture",choices=choices,value="ALL",interactive=True,visible=True)return componentsdef create_category_filter_ui(prefix):valid_cats = list(set(cat for cats in ARCH_CATEGORIES_MAP.values() for cat in cats))cat_choices = ["ALL"] + sorted(valid_cats)components = {}components[f'model_cat_{prefix}'] = gr.Dropdown(label="Filter Models",choices=cat_choices,value="ALL",interactive=True,scale=1,allow_custom_value=True)return componentsdef create_base_parameter_ui(prefix, defaults=None):if defaults is None:defaults = {}components = {}with gr.Row():components[f'aspect_ratio_{prefix}'] = gr.Dropdown(label="Aspect Ratio",choices=list(RESOLUTION_MAP.get('sdxl', {}).keys()),value="1:1 (Square)",interactive=True,allow_custom_value=True)with gr.Row():components[f'width_{prefix}'] = gr.Number(label="Width", value=defaults.get('w', 1024), interactive=True)components[f'height_{prefix}'] = gr.Number(label="Height", value=defaults.get('h', 1024), interactive=True)with gr.Row():components[f'sampler_{prefix}'] = gr.Dropdown(label="Sampler",choices=SAMPLER_CHOICES,value=DEFAULT_SAMPLER if DEFAULT_SAMPLER in SAMPLER_CHOICES else (SAMPLER_CHOICES[0] if SAMPLER_CHOICES else 'euler'))components[f'scheduler_{prefix}'] = gr.Dropdown(label="Scheduler",choices=SCHEDULER_CHOICES,value=DEFAULT_SCHEDULER if DEFAULT_SCHEDULER in SCHEDULER_CHOICES else (SCHEDULER_CHOICES[0] if SCHEDULER_CHOICES else 'simple'))with gr.Row():components[f'steps_{prefix}'] = gr.Slider(label="Steps", minimum=1, maximum=100, step=1, value=DEFAULT_STEPS)components[f'cfg_{prefix}'] = gr.Slider(label="CFG Scale", minimum=1.0, maximum=20.0, step=0.1, value=DEFAULT_CFG)with gr.Row():components[f'seed_{prefix}'] = gr.Number(label="Seed (-1 for random)", value=-1, precision=0)components[f'batch_size_{prefix}'] = gr.Slider(label="Batch Size", minimum=1, maximum=16, step=1, value=1)with gr.Row():components[f'zero_gpu_{prefix}'] = gr.Number(label="ZeroGPU Duration (s)", value=60, placeholder="Default: 60s", info="Optional: Set how long to reserve the GPU.")return componentsdef create_lora_settings_ui(prefix: str):components = {}lora_rows, lora_sources, lora_ids, lora_scales, lora_uploads = [], [], [], [], []with gr.Accordion("LoRA Settings", open=False, visible=('lora' in default_enabled_chains)) as lora_accordion:components[f'lora_accordion_{prefix}'] = lora_accordiongr.Markdown("💡 **Tip:** When downloading from Civitai, please use the **Version ID**, not the Model ID. You can find the Version ID in the URL (e.g., `civitai.com/models/123?modelVersionId=456`) or under the model's download button. When downloading from Hugging Face, please use the format: `repo_id/filename.extension` or `repo_id/folder_path/filename.extension` (e.g., `lightx2v/Qwen-Image-Lightning/Qwen-Image-Lightning-4steps-V2.0-bf16.safetensors`).")components[f'lora_count_state_{prefix}'] = gr.State(1)for i in range(MAX_LORAS):with gr.Row(visible=i==0) as row:source = gr.Dropdown(label=f"LoRA Source {i+1}", choices=LORA_SOURCE_CHOICES, value=LORA_SOURCE_CHOICES[0], scale=1)lora_id = gr.Textbox(label="Civitai Version ID / HF file / Upload File", scale=2, type="text")scale = gr.Slider(label=f"Scale", minimum=0.0, maximum=2.0, step=0.05, value=1.0, scale=1)upload = gr.UploadButton(label="Upload", file_types=[".safetensors"], scale=1)lora_rows.append(row)lora_sources.append(source)lora_ids.append(lora_id)lora_scales.append(scale)lora_uploads.append(upload)with gr.Row():components[f'add_lora_button_{prefix}'] = gr.Button("Add LoRA", variant="secondary")components[f'delete_lora_button_{prefix}'] = gr.Button("Remove LoRA", variant="secondary", visible=False)components[f'lora_rows_{prefix}'] = lora_rowscomponents[f'lora_sources_{prefix}'] = lora_sourcescomponents[f'lora_ids_{prefix}'] = lora_idscomponents[f'lora_scales_{prefix}'] = lora_scalescomponents[f'lora_uploads_{prefix}'] = lora_uploadsall_lora_components_flat = []for i in range(MAX_LORAS):all_lora_components_flat.extend([lora_sources[i], lora_ids[i], lora_scales[i], lora_uploads[i]])components[f'all_lora_components_flat_{prefix}'] = all_lora_components_flatreturn componentsdef create_controlnet_ui(prefix: str, max_units=MAX_CONTROLNETS):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("ControlNet Settings", open=False, visible=('controlnet' in default_enabled_chains)) as accordion:components[key('controlnet_accordion')] = accordioncn_rows, images, series, types, strengths, filepaths = [], [], [], [], [], []components.update({key('controlnet_rows'): cn_rows,key('controlnet_images'): images,key('controlnet_series'): series,key('controlnet_types'): types,key('controlnet_strengths'): strengths,key('controlnet_filepaths'): filepaths})for i in range(max_units):with gr.Row(visible=(i < 1)) as row:with gr.Column(scale=1):images.append(gr.Image(label=f"Control Image {i+1}", type="pil", sources=["upload"], height=256))with gr.Column(scale=2):types.append(gr.Dropdown(label="Type", choices=[], interactive=True, allow_custom_value=True))series.append(gr.Dropdown(label="Series", choices=[], interactive=True, allow_custom_value=True))strengths.append(gr.Slider(label="Strength", minimum=0.0, maximum=2.0, step=0.05, value=1.0, interactive=True))filepaths.append(gr.State(None))cn_rows.append(row)with gr.Row():components[key('add_controlnet_button')] = gr.Button("✚ Add ControlNet")components[key('delete_controlnet_button')] = gr.Button("➖ Delete ControlNet", visible=False)components[key('controlnet_count_state')] = gr.State(1)all_cn_components_flat = []for i in range(max_units):all_cn_components_flat.extend([images[i], types[i], series[i], strengths[i], filepaths[i]])components[key('all_controlnet_components_flat')] = all_cn_components_flatreturn componentsdef create_ipadapter_ui(prefix: str, max_units=MAX_IPADAPTERS):components = {}key = lambda name: f"{name}_{prefix}"sdxl_presets = get_ipadapter_presets("SDXL")default_preset = sdxl_presets[0] if sdxl_presets else Nonewith gr.Accordion("IPAdapter Settings", open=False, visible=('ipadapter' in default_enabled_chains)) as accordion:components[key('ipadapter_accordion')] = accordiongr.Markdown("💡 **Tip:** Processed using the [cubiq/ComfyUI_IPAdapter_plus](https://github.com/cubiq/ComfyUI_IPAdapter_plus) node.")with gr.Row():components[key('ipadapter_final_preset')] = gr.Dropdown(label="Preset (for all images)",choices=sdxl_presets,value=default_preset,interactive=True,allow_custom_value=True)components[key('ipadapter_embeds_scaling')] = gr.Dropdown(label="Embeds Scaling",choices=['V only', 'K+V', 'K+V w/ C penalty', 'K+mean(V) w/ C penalty'],value='V only',interactive=True)with gr.Row():components[key('ipadapter_combine_method')] = gr.Dropdown(label="Combine Method",choices=["concat", "add", "subtract", "average", "norm average", "max", "min"],value="concat",interactive=True)components[key('ipadapter_final_weight')] = gr.Slider(label="Final Weight", minimum=0.0, maximum=2.0, step=0.05, value=1.0, interactive=True)components[key('ipadapter_final_lora_strength')] = gr.Slider(label="Final LoRA Strength", minimum=0.0, maximum=2.0, step=0.05, value=0.6, interactive=True, visible=False)gr.Markdown("---")ipa_rows, images, weights, lora_strengths = [], [], [], []components.update({key('ipadapter_rows'): ipa_rows,key('ipadapter_images'): images,key('ipadapter_weights'): weights,key('ipadapter_lora_strengths'): lora_strengths})for i in range(max_units):with gr.Row(visible=(i < 1)) as row:with gr.Column(scale=1):images.append(gr.Image(label=f"IPAdapter Image {i+1}", type="pil", sources=["upload"], height=256))with gr.Column(scale=2):weights.append(gr.Slider(label="Weight", minimum=0.0, maximum=2.0, step=0.05, value=1.0, interactive=True))lora_strengths.append(gr.Slider(label="LoRA Strength", minimum=0.0, maximum=2.0, step=0.05, value=0.6, interactive=True, visible=False))ipa_rows.append(row)with gr.Row():components[key('add_ipadapter_button')] = gr.Button("✚ Add IPAdapter")components[key('delete_ipadapter_button')] = gr.Button("➖ Delete IPAdapter", visible=False)components[key('ipadapter_count_state')] = gr.State(1)all_ipa_components_flat = images + weights + lora_strengthsall_ipa_components_flat += [components[key('ipadapter_final_preset')],components[key('ipadapter_final_weight')],components[key('ipadapter_final_lora_strength')],components[key('ipadapter_embeds_scaling')],components[key('ipadapter_combine_method')],]components[key('all_ipadapter_components_flat')] = all_ipa_components_flatreturn componentsdef create_flux1_ipadapter_ui(prefix: str, max_units=MAX_IPADAPTERS):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("IPAdapter Settings (FLUX.1)", open=False, visible=('flux1_ipadapter' in default_enabled_chains)) as accordion:components[key('flux1_ipadapter_accordion')] = accordiongr.Markdown("💡 **Tip:** Processed using the [Shakker-Labs/ComfyUI-IPAdapter-Flux](https://github.com/Shakker-Labs/ComfyUI-IPAdapter-Flux) node.")ipa_rows, images, weights, start_percents, end_percents = [], [], [], [], []components.update({key('flux1_ipadapter_rows'): ipa_rows,key('flux1_ipadapter_images'): images,key('flux1_ipadapter_weights'): weights,key('flux1_ipadapter_start_percents'): start_percents,key('flux1_ipadapter_end_percents'): end_percents,})for i in range(max_units):with gr.Row(visible=(i < 1)) as row:with gr.Column(scale=1):images.append(gr.Image(label=f"IPAdapter Image {i+1}", type="pil", sources=["upload"], height=256))with gr.Column(scale=2):weights.append(gr.Slider(label="Weight", minimum=0.0, maximum=2.0, step=0.05, value=0.6, interactive=True))with gr.Row():start_percents.append(gr.Slider(label="Start At", minimum=0.0, maximum=1.0, step=0.01, value=0.0, interactive=True))end_percents.append(gr.Slider(label="End At", minimum=0.0, maximum=1.0, step=0.01, value=0.6, interactive=True))ipa_rows.append(row)with gr.Row():components[key('add_flux1_ipadapter_button')] = gr.Button("✚ Add IPAdapter (FLUX)")components[key('delete_flux1_ipadapter_button')] = gr.Button("➖ Delete IPAdapter (FLUX)", visible=False)components[key('flux1_ipadapter_count_state')] = gr.State(1)all_flux1_ipa_components_flat = images + weights + start_percents + end_percentscomponents[key('all_flux1_ipadapter_components_flat')] = all_flux1_ipa_components_flatreturn componentsdef create_sd3_ipadapter_ui(prefix: str, max_units=MAX_IPADAPTERS):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("IPAdapter Settings (SD3)", open=False, visible=('sd3_ipadapter' in default_enabled_chains)) as accordion:components[key('sd3_ipadapter_accordion')] = accordiongr.Markdown("💡 **Tip:** Processed using the [Slickytail/ComfyUI-InstantX-IPAdapter-SD3](https://github.com/Slickytail/ComfyUI-InstantX-IPAdapter-SD3) node.")ipa_rows, images, weights, start_percents, end_percents = [], [], [], [], []components.update({key('sd3_ipadapter_rows'): ipa_rows,key('sd3_ipadapter_images'): images,key('sd3_ipadapter_weights'): weights,key('sd3_ipadapter_start_percents'): start_percents,key('sd3_ipadapter_end_percents'): end_percents,})for i in range(max_units):with gr.Row(visible=(i < 1)) as row:with gr.Column(scale=1):images.append(gr.Image(label=f"IPAdapter Image {i+1}", type="pil", sources=["upload"], height=256))with gr.Column(scale=2):weights.append(gr.Slider(label="Weight", minimum=0.0, maximum=2.0, step=0.05, value=0.5, interactive=True))with gr.Row():start_percents.append(gr.Slider(label="Start At", minimum=0.0, maximum=1.0, step=0.01, value=0.0, interactive=True))end_percents.append(gr.Slider(label="End At", minimum=0.0, maximum=1.0, step=0.01, value=1.0, interactive=True))ipa_rows.append(row)with gr.Row():components[key('add_sd3_ipadapter_button')] = gr.Button("✚ Add IPAdapter (SD3)")components[key('delete_sd3_ipadapter_button')] = gr.Button("➖ Delete IPAdapter (SD3)", visible=False)components[key('sd3_ipadapter_count_state')] = gr.State(1)all_sd3_ipa_components_flat = images + weights + start_percents + end_percentscomponents[key('all_sd3_ipadapter_components_flat')] = all_sd3_ipa_components_flatreturn componentsdef create_style_ui(prefix: str):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("Style Settings (FLUX.1)", open=False, visible=('style' in default_enabled_chains)) as accordion:components[key('style_accordion')] = accordionstyle_rows, images, strengths = [], [], []components.update({key('style_rows'): style_rows,key('style_images'): images,key('style_strengths'): strengths})for i in range(5):with gr.Row(visible=(i < 1)) as row:with gr.Column(scale=1):images.append(gr.Image(label=f"Style Image {i+1}", type="pil", sources=["upload"], height=256))with gr.Column(scale=2):strengths.append(gr.Slider(label="Strength", minimum=0.0, maximum=2.0, step=0.05, value=1.0, interactive=True))style_rows.append(row)with gr.Row():components[key('add_style_button')] = gr.Button("✚ Add Style (FLUX)")components[key('delete_style_button')] = gr.Button("➖ Delete Style (FLUX)", visible=False)components[key('style_count_state')] = gr.State(1)all_style_components_flat = images + strengthscomponents[key('all_style_components_flat')] = all_style_components_flatreturn componentsdef create_embedding_ui(prefix: str):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("Embedding Settings", open=False, visible=('embedding' in default_enabled_chains)) as accordion:components[key('embedding_accordion')] = accordiongr.Markdown("💡 **Tip:** When downloading from Civitai, please use the **Version ID**, not the Model ID. You can find the Version ID in the URL (e.g., `civitai.com/models/123?modelVersionId=456`) or under the model's download button. For example, entering the Version ID 456 will automatically save the file as \"civitai/456.safetensors\", and you will need to manually enter `embedding:civitai/456` in either your prompt or negative prompt to activate it. When downloading from Hugging Face, please use the format: repo_id/filename.extension or repo_id/folder_path/filename.extension (e.g., ilikebigturtles/lazypos/lazypos.safetensors or ilikebigturtles/lazyneg/lazyneg.safetensors). For Hugging Face files, you will need to enter embedding:huggingface/filename (e.g., entering embedding:huggingface/lazypos in your positive prompt, or embedding:huggingface/lazyneg in your negative prompt) to activate it. For uploaded files, enter `embedding:upload_file/filename` in either your positive prompt or negative prompt to activate it.")embedding_rows, sources, ids, files, upload_buttons = [], [], [], [], []components.update({key('embedding_rows'): embedding_rows,key('embeddings_sources'): sources,key('embeddings_ids'): ids,key('embeddings_files'): files,key('embeddings_uploads'): upload_buttons})for i in range(MAX_EMBEDDINGS):with gr.Row(visible=(i < 1)) as row:sources.append(gr.Dropdown(label=f"Embedding Source {i+1}", choices=LORA_SOURCE_CHOICES, value="Civitai", scale=1, interactive=True))ids.append(gr.Textbox(label="Civitai Version ID / HF file / Upload File", scale=3, interactive=True, type="text"))upload_btn = gr.UploadButton("Upload", file_types=[".safetensors"], scale=1)files.append(gr.State(None))upload_buttons.append(upload_btn)embedding_rows.append(row)with gr.Row():components[key('add_embedding_button')] = gr.Button("✚ Add Embedding")components[key('delete_embedding_button')] = gr.Button("➖ Delete Embedding", visible=False)components[key('embedding_count_state')] = gr.State(1)all_embedding_components_flat = []for i in range(MAX_EMBEDDINGS):all_embedding_components_flat.extend([sources[i], ids[i], files[i]])components[key('all_embedding_components_flat')] = all_embedding_components_flatreturn componentsdef create_conditioning_ui(prefix: str):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("Conditioning Settings", open=False, visible=('conditioning' in default_enabled_chains)) as accordion:components[key('conditioning_accordion')] = accordiongr.Markdown("💡 **Tip:** Define rectangular areas and assign specific prompts to them. Coordinates (X, Y) start from the top-left corner.")cond_rows, prompts, widths, heights, xs, ys, strengths = [], [], [], [], [], [], []components.update({key('conditioning_rows'): cond_rows,key('conditioning_prompts'): prompts,key('conditioning_widths'): widths,key('conditioning_heights'): heights,key('conditioning_xs'): xs,key('conditioning_ys'): ys,key('conditioning_strengths'): strengths})for i in range(MAX_CONDITIONINGS):with gr.Column(visible=(i < 1)) as row_wrapper:prompts.append(gr.Textbox(label=f"Area Prompt {i+1}", lines=2, interactive=True))with gr.Row():xs.append(gr.Number(label="X", value=0, interactive=True, step=8, scale=1))ys.append(gr.Number(label="Y", value=0, interactive=True, step=8, scale=1))widths.append(gr.Number(label="Width", value=512, interactive=True, step=8, scale=1))heights.append(gr.Number(label="Height", value=512, interactive=True, step=8, scale=1))strengths.append(gr.Slider(label="Strength", minimum=0.1, maximum=2.0, step=0.05, value=1.0, interactive=True, scale=2))cond_rows.append(row_wrapper)with gr.Row():components[key('add_conditioning_button')] = gr.Button("✚ Add Area")components[key('delete_conditioning_button')] = gr.Button("➖ Delete Area", visible=False)components[key('conditioning_count_state')] = gr.State(1)all_cond_components_flat = prompts + widths + heights + xs + ys + strengthscomponents[key('all_conditioning_components_flat')] = all_cond_components_flatreturn componentsdef on_vae_upload(file_obj):if not file_obj:return gr.update(), gr.update(), Noneuploaded_filename = save_uploaded_file(file_obj, VAE_DIR)return uploaded_filename, "Upload File", file_objdef create_vae_override_ui(prefix: str):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("VAE Settings (Override)", open=False, visible=('vae' in default_enabled_chains)) as vae_accordion:components[key('vae_accordion')] = vae_accordiongr.Markdown("💡 **Tip:** When downloading from Civitai, please use the **Version ID**, not the Model ID. You can find the Version ID in the URL (e.g., `civitai.com/models/123?modelVersionId=456`) or under the model's download button. When downloading from Hugging Face, please use the format: `repo_id/filename.extension` or `repo_id/folder_path/filename.extension` (e.g., `madebyollin/sdxl-vae-fp16-fix/sdxl_vae.safetensors`).")with gr.Row():components[key('vae_source')] = gr.Dropdown(label="VAE Source",choices=LORA_SOURCE_CHOICES,value="Civitai",scale=1,interactive=True)components[key('vae_id')] = gr.Textbox(label="Civitai Version ID / HF file / Upload File",scale=3,interactive=True,type="text")upload_btn = gr.UploadButton("Upload",file_types=[".safetensors"],scale=1)components[key('vae_upload_button')] = upload_btncomponents[key('vae_file')] = gr.State(None)upload_btn.upload(fn=on_vae_upload,inputs=[upload_btn],outputs=[components[key('vae_id')], components[key('vae_source')], components[key('vae_file')]])return componentsdef create_reference_latent_ui(prefix: str, max_units=10):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("Reference Edit Settings", open=False, visible=('reference_latent' in default_enabled_chains)) as ref_accordion:components[key('reference_latent_accordion')] = ref_accordiongr.Markdown("💡 **Tip:** For multimodal models, this feature enables powerful editing and combining capabilities. In txt2img mode, adding a single reference image performs an **Image Edit**, while adding multiple images performs an **Image Combine**.")ref_image_groups = []ref_image_inputs = []with gr.Row():for i in range(max_units):with gr.Column(visible=(i < 1), min_width=160) as img_col:img_comp = gr.Image(type="pil", label=f"Ref. {i+1}", sources=["upload"], height=150)ref_image_groups.append(img_col)ref_image_inputs.append(img_comp)components[key('reference_latent_rows')] = ref_image_groupscomponents[key('reference_latent_images')] = ref_image_inputswith gr.Row():components[key('add_reference_latent_button')] = gr.Button("✚ Add Reference Image")components[key('delete_reference_latent_button')] = gr.Button("➖ Delete Reference Image", visible=False)components[key('reference_latent_count_state')] = gr.State(1)components[key('all_reference_latent_components_flat')] = ref_image_inputsreturn componentsdef create_hidream_o1_reference_ui(prefix: str, max_units=10):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("HiDream-O1 Reference Edit Settings", open=False, visible=('hidream_o1_reference' in default_enabled_chains)) as ref_accordion:components[key('hidream_o1_reference_accordion')] = ref_accordiongr.Markdown("💡 **Tip:** Please use **HiDream-O1-Image-Dev** (HiDream-O1-Image will time out), and set the resolution to **4.0MP** (e.g., 2048x2048). In txt2img mode, adding a single reference image performs an **Image Edit**, while adding multiple images performs an **Image Combine**.")ref_image_groups = []ref_image_inputs = []with gr.Row():for i in range(max_units):with gr.Column(visible=(i < 1), min_width=160) as img_col:img_comp = gr.Image(type="pil", label=f"Ref. {i+1}", sources=["upload"], height=150)ref_image_groups.append(img_col)ref_image_inputs.append(img_comp)components[key('hidream_o1_reference_rows')] = ref_image_groupscomponents[key('hidream_o1_reference_images')] = ref_image_inputswith gr.Row():components[key('add_hidream_o1_reference_button')] = gr.Button("✚ Add Reference Image")components[key('delete_hidream_o1_reference_button')] = gr.Button("➖ Delete Reference Image", visible=False)components[key('hidream_o1_reference_count_state')] = gr.State(1)components[key('all_hidream_o1_reference_components_flat')] = ref_image_inputsreturn componentsdef create_sensenova_reference_ui(prefix: str, max_units=10):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("SenseNova Reference Edit Settings", open=False, visible=('sensenova_reference' in default_enabled_chains)) as ref_accordion:components[key('sensenova_reference_accordion')] = ref_accordiongr.Markdown("💡 **Tip:** For SenseNova models, this feature enables reference image editing and combining capabilities. In txt2img mode, adding a single reference image performs an **Image Edit**, while adding multiple images performs an **Image Combine**.")ref_image_groups = []ref_image_inputs = []with gr.Row():for i in range(max_units):with gr.Column(visible=(i < 1), min_width=160) as img_col:img_comp = gr.Image(type="pil", label=f"Ref. {i+1}", sources=["upload"], height=150)ref_image_groups.append(img_col)ref_image_inputs.append(img_comp)components[key('sensenova_reference_rows')] = ref_image_groupscomponents[key('sensenova_reference_images')] = ref_image_inputswith gr.Row():components[key('add_sensenova_reference_button')] = gr.Button("✚ Add Reference Image")components[key('delete_sensenova_reference_button')] = gr.Button("➖ Delete Reference Image", visible=False)components[key('sensenova_reference_count_state')] = gr.State(1)components[key('all_sensenova_reference_components_flat')] = ref_image_inputsreturn componentsdef create_joyai_reference_ui(prefix: str, max_units=2):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("JoyAI Reference Edit Settings", open=False, visible=('joyai_image' in default_enabled_chains)) as ref_accordion:components[key('joyai_reference_accordion')] = ref_accordiongr.Markdown("💡 **Tip:** For multimodal models, this feature enables powerful editing and combining capabilities. In txt2img mode, adding a single reference image performs an **Image Edit** (JoyAI-Image-Edit recommended), while adding multiple images performs an **Image Combine** (JoyAI-Image-Edit-Plus recommended with ZeroGPU Duration (s) set to 120).")ref_image_groups = []ref_image_inputs = []with gr.Row():for i in range(max_units):with gr.Column(visible=(i < 1), min_width=160) as img_col:img_comp = gr.Image(type="pil", label=f"Ref. {i+1}", sources=["upload"], height=150)ref_image_groups.append(img_col)ref_image_inputs.append(img_comp)components[key('joyai_reference_rows')] = ref_image_groupscomponents[key('joyai_reference_images')] = ref_image_inputswith gr.Row():components[key('add_joyai_reference_button')] = gr.Button("✚ Add Reference Image")components[key('delete_joyai_reference_button')] = gr.Button("➖ Delete Reference Image", visible=False)components[key('joyai_reference_count_state')] = gr.State(1)components[key('all_joyai_reference_components_flat')] = ref_image_inputsreturn componentsdef create_reference_image_ui(prefix: str, max_units=10):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("Reference Image Edit Settings", open=False, visible=('reference_image' in default_enabled_chains)) as ref_accordion:components[key('reference_image_accordion')] = ref_accordiongr.Markdown("💡 **Tip:** For multimodal models, this feature enables powerful editing and combining capabilities. In txt2img mode, adding a single reference image performs an **Image Edit**, while adding multiple images performs an **Image Combine**.")ref_image_groups = []ref_image_inputs = []with gr.Row():for i in range(max_units):with gr.Column(visible=(i < 1), min_width=160) as img_col:img_comp = gr.Image(type="pil", label=f"Ref. {i+1}", sources=["upload"], height=150)ref_image_groups.append(img_col)ref_image_inputs.append(img_comp)components[key('reference_image_rows')] = ref_image_groupscomponents[key('reference_image_images')] = ref_image_inputswith gr.Row():components[key('add_reference_image_button')] = gr.Button("✚ Add Reference Image")components[key('delete_reference_image_button')] = gr.Button("➖ Delete Reference Image", visible=False)components[key('reference_image_count_state')] = gr.State(1)components[key('all_reference_image_components_flat')] = ref_image_inputsreturn componentsdef create_moss_image_control_ui(prefix: str):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("MOSS-Image Color/Depth Control Settings", open=False, visible=('moss_image_control' in default_enabled_chains)) as control_accordion:components[key('moss_image_control_accordion')] = control_accordiongr.Markdown("💡 **Tip:** Uses the [darask0/MOSS-Image-color-depth-control](https://huggingface.co/darask0/MOSS-Image-color-depth-control) adapter.")with gr.Row():components[key('moss_image_control_color_map')] = gr.Image(type="pil", label="Color Region Map (Optional)", sources=["upload"], height=200)components[key('moss_image_control_depth_map')] = gr.Image(type="pil", label="Depth Map (Optional, near=white)", sources=["upload"], height=200)with gr.Row():components[key('moss_image_control_strength')] = gr.Slider(label="Control Strength",value=1.0,minimum=0.0,maximum=2.0,step=0.05,interactive=True)components[key('moss_image_control_end_percent')] = gr.Slider(label="End Percent (0.5 for 3D mannequin)",value=0.5,minimum=0.0,maximum=1.0,step=0.01,interactive=True)return componentsdef create_pid_ui(prefix: str):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("PiD Settings", open=False, visible=('pid' in default_enabled_chains)) as pid_accordion:components[key('pid_accordion')] = pid_accordiongr.Markdown("💡 **Tip:** Use PiD (Pixel Diffusion Decoder) instead of the VAE Decoder for 4x decoding.")with gr.Row():components[key('pid_settings')] = gr.Dropdown(label="PiD Mode",choices=["OFF", "ON"],value="OFF",interactive=True)return componentsdef create_krea2_identity_edit_ui(prefix: str, max_units=2):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("Krea2 Identity Edit Settings", open=False, visible=('krea2_identity_edit' in default_enabled_chains)) as ref_accordion:components[key('krea2_identity_edit_accordion')] = ref_accordiongr.Markdown("💡 **Tip:** Processed using the [lbouaraba/comfyui-krea2edit](https://github.com/lbouaraba/comfyui-krea2edit) node. (Krea-2-Turbo recommended, Krea-2-Raw need set ZeroGPU Duration (s) to 120 ) In txt2img mode, adding a single reference image performs an **Image Edit**, while adding multiple images performs an **Image Combine**.")ref_image_groups = []ref_image_inputs = []with gr.Row():for i in range(max_units):with gr.Column(visible=(i < 1), min_width=160) as img_col:img_comp = gr.Image(type="pil", label=f"Ref. {i+1}", sources=["upload"], height=150)ref_image_groups.append(img_col)ref_image_inputs.append(img_comp)components[key('krea2_identity_edit_rows')] = ref_image_groupscomponents[key('krea2_identity_edit_images')] = ref_image_inputswith gr.Row():components[key('add_krea2_identity_edit_button')] = gr.Button("✚ Add Reference Image")components[key('delete_krea2_identity_edit_button')] = gr.Button("➖ Delete Reference Image", visible=False)components[key('krea2_identity_edit_count_state')] = gr.State(1)components[key('all_krea2_identity_edit_components_flat')] = ref_image_inputsreturn componentsdef create_qwen_image_edit_ui(prefix: str, max_units=3):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("Qwen-Image Edit Settings", open=False, visible=('qwen_image_edit' in default_enabled_chains)) as ref_accordion:components[key('qwen_image_edit_accordion')] = ref_accordiongr.Markdown("💡 **Tip:** (lightx2v/Qwen-Image-Edit-2511-Lightning recommended) In txt2img mode, adding a single reference image performs an **Image Edit**, while adding multiple images performs an **Image Combine**.")ref_image_groups = []ref_image_inputs = []with gr.Row():for i in range(max_units):with gr.Column(visible=(i < 1), min_width=160) as img_col:img_comp = gr.Image(type="pil", label=f"Ref. {i+1}", sources=["upload"], height=150)ref_image_groups.append(img_col)ref_image_inputs.append(img_comp)components[key('qwen_image_edit_rows')] = ref_image_groupscomponents[key('qwen_image_edit_images')] = ref_image_inputswith gr.Row():components[key('add_qwen_image_edit_button')] = gr.Button("✚ Add Reference Image")components[key('delete_qwen_image_edit_button')] = gr.Button("➖ Delete Reference Image", visible=False)components[key('qwen_image_edit_count_state')] = gr.State(1)components[key('all_qwen_image_edit_components_flat')] = ref_image_inputsreturn componentsdef create_krea2_reference_edit_ui(prefix: str, max_units=3):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("Krea2 Style Reference Edit Settings", open=False, visible=('krea2_style_reference' in default_enabled_chains)) as ref_accordion:components[key('krea2_reference_edit_accordion')] = ref_accordiongr.Markdown("💡 **Tip:** (Krea-2-Turbo recommended) Add style reference images to perform style reference editing.")ref_image_groups = []ref_image_inputs = []with gr.Row():for i in range(max_units):with gr.Column(visible=(i < 1), min_width=160) as img_col:img_comp = gr.Image(type="pil", label=f"Ref. {i+1}", sources=["upload"], height=150)ref_image_groups.append(img_col)ref_image_inputs.append(img_comp)components[key('krea2_reference_edit_rows')] = ref_image_groupscomponents[key('krea2_reference_edit_images')] = ref_image_inputswith gr.Row():components[key('add_krea2_reference_edit_button')] = gr.Button("✚ Add Reference Image")components[key('delete_krea2_reference_edit_button')] = gr.Button("➖ Delete Reference Image", visible=False)components[key('krea2_reference_edit_count_state')] = gr.State(1)components[key('all_krea2_reference_edit_components_flat')] = ref_image_inputsreturn componentsdef create_qwen_image_2_1_prompt_enhancer_ui(prefix: str):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("Qwen-Image-2.1 Prompt Enhancer Settings", open=False, visible=('qwen_image_2_1_prompt_enhancer' in default_enabled_chains)) as enhancer_accordion:components[key('qwen_image_2_1_prompt_enhancer_accordion')] = enhancer_accordiongr.Markdown("💡 **Tip:** Automatically selects between [Qwen-Image-2.1-PE-T2I](https://huggingface.co/Qwen/Qwen-Image-2.1-PE-T2I) and [Qwen-Image-2.1-PE-I2I](https://huggingface.co/Qwen/Qwen-Image-2.1-PE-I2I) for prompt enhancement based on input context.")with gr.Row():components[key('qwen_image_2_1_prompt_enhancer_enable')] = gr.Checkbox(label="Enable Qwen-Image-2.1 Prompt Enhancer",value=False,interactive=True,scale=2)components[key('qwen_image_2_1_prompt_enhancer_thinking')] = gr.Checkbox(label="Enable Thinking (Requires longer ZeroGPU Duration)",value=False,interactive=True,scale=2)components[key('qwen_image_2_1_prompt_enhancer_max_length')] = gr.Number(label="Max Length",value=4096,precision=0,minimum=16,step=16,interactive=True,scale=1)return componentsDEFAULT_MING_IMAGE_SYSTEM_PROMPT = ("You are a senior visual designer and image-prompt engineer. Expand the user's request into one precise, high-resolution Figma-style caption. Return only one JSON object. ""Use exactly two top-level keys. `canvas_settings` contains exactly `aspect_ratio`, `ambient_lighting`, and `image_style`. `layers` lists visible groups from background to topmost overlay. Every layer contains exactly `description`, `coordinates`, `hierarchy_and_relation`, and `color_specs`; `color_specs` is an array of hex colors. "'`coordinates` MUST be one string, never an object or array, in exactly this form: `"cx: 0.500, cy: 0.500, w: 1.000, h: 1.000"`. Values are normalized; each bbox encloses its complete owned object and stays inside the canvas. '"A layer is one selectable visible semantic group: background, full person, coherent object, panel, card, row, or text block. Prefer the fewest groups that preserve the layout. Keep people and objects intact. Never create invisible parents, guides, placeholders, empty layers, duplicate summaries, or multiple owners for one element. ""Preserve every user-supplied rendered string character-for-character and as one contiguous string. Unless multiple visible copies are requested, it must occur exactly once across all `description` fields and zero times in `hierarchy_and_relation`. Quote it only where describing its visible rendering; refer to the related subject elsewhere with unquoted semantic wording. Enumerate intended copy, invent extra copy sparingly, and never hide content behind \"other text\", \"remaining labels\", or \"etc.\" ""Describe concrete composition, typography, materials, texture, lighting, pose, and camera treatment without literary filler. Use `hierarchy_and_relation` only for ownership, alignment, containment, stacking, and occlusion. ""Infer structured layouts first. Use one complete layer per card and state its row and column. A compact secondary table may be one layer only if every header and cell is listed; otherwise use a visible shared frame when present, one complete header, and one complete layer per body row, binding values to columns and stating blanks. Enumerate sequences, schedules, spans, gaps, and vacant tracks in visual order. Do not mistake ordinary alignment for a table. ""Silently verify schema, string coordinates, Z-order, exact-text counts, geometry, bbox validity, and completeness.")def create_ming_image_prompt_enhancer_ui(prefix: str):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("Ming-Image Prompt Enhancer Settings", open=False, visible=('ming_image_prompt_enhancer' in default_enabled_chains)) as enhancer_accordion:components[key('ming_image_prompt_enhancer_accordion')] = enhancer_accordiongr.Markdown("💡 **Tip:** Leverages [Qwen3.8-27B](https://huggingface.co/Qwen/Qwen3.8-27B) guided by the official [System Prompt](https://github.com/inclusionAI/Ming-Image#text-to-image-prompt-rewriting) to automatically enhance prompts into structured layouts based on input context.")with gr.Row():components[key('ming_image_prompt_enhancer_enable')] = gr.Checkbox(label="Enable Ming-Image Prompt Enhancer",value=False,interactive=True,scale=2)components[key('ming_image_prompt_enhancer_thinking')] = gr.Checkbox(label="Enable Thinking (Requires longer ZeroGPU Duration)",value=False,interactive=True,scale=2)components[key('ming_image_prompt_enhancer_max_length')] = gr.Number(label="Max Length",value=4096,precision=0,minimum=16,step=16,interactive=True,scale=1)components[key('ming_image_prompt_enhancer_system_prompt')] = gr.Textbox(label="System Prompt",value=DEFAULT_MING_IMAGE_SYSTEM_PROMPT,lines=4,max_lines=12,interactive=True)return componentsdef create_flux3_prompt_upsampler_ui(prefix: str):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("FLUX.3 Prompt Upsampler Settings", open=False, visible=('flux3_prompt_upsampler' in default_enabled_chains)) as enhancer_accordion:components[key('flux3_prompt_upsampler_accordion')] = enhancer_accordiongr.Markdown("💡 **Tip:** System prompt automatically matches the official [black-forest-labs/flux-3-image-klein-pup](https://huggingface.co/black-forest-labs/flux-3-image-klein-pup/blob/main/system_prompts.json) templates: uses `t2i` when no image is provided, and automatically switches to `i2i` when image input is detected; enabling **BBox Mode** switches respectively to `t2i_bbox` and `i2i_bbox` to output target bounding box annotations.")with gr.Row():components[key('flux3_prompt_upsampler_enable')] = gr.Checkbox(label="Enable FLUX.3 Prompt Upsampler",value=False,interactive=True,scale=2)components[key('flux3_prompt_upsampler_thinking')] = gr.Checkbox(label="Enable Thinking (Requires longer ZeroGPU Duration)",value=False,interactive=True,scale=2)components[key('flux3_prompt_upsampler_bbox_mode')] = gr.Checkbox(label="BBox Mode",value=False,interactive=True,scale=1)components[key('flux3_prompt_upsampler_max_length')] = gr.Number(label="Max Length",value=3584,precision=0,minimum=16,step=16,interactive=True,scale=1)return componentsdef create_moss_image_edit_ui(prefix: str, max_units=None):if max_units is None:max_units = MAX_MOSS_IMAGE_EDITScomponents = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("MOSS-Image Edit Settings", open=False, visible=('moss_image_edit' in default_enabled_chains)) as ref_accordion:components[key('moss_image_edit_accordion')] = ref_accordiongr.Markdown("💡 **Tip:** For multimodal models, this feature enables powerful editing and combining capabilities. In txt2img mode, adding a single reference image performs an Image Edit, while adding multiple images performs an Image Combine. Uses [chinoll/Moss-Image-Edit](https://huggingface.co/chinoll/Moss-Image-Edit).")ref_image_groups = []ref_image_inputs = []with gr.Row():for i in range(max_units):with gr.Column(visible=(i < 1), min_width=160) as img_col:img_comp = gr.Image(type="pil", label=f"Ref. {i+1}", sources=["upload"], height=150)ref_image_groups.append(img_col)ref_image_inputs.append(img_comp)components[key('moss_image_edit_rows')] = ref_image_groupscomponents[key('moss_image_edit_images')] = ref_image_inputswith gr.Row():components[key('add_moss_image_edit_button')] = gr.Button("✚ Add Reference Image")components[key('delete_moss_image_edit_button')] = gr.Button("➖ Delete Reference Image", visible=False)components[key('moss_image_edit_count_state')] = gr.State(1)components[key('all_moss_image_edit_components_flat')] = ref_image_inputsreturn components123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916import gradio as grfrom comfy_integration.nodes import SAMPLER_CHOICES, SCHEDULER_CHOICESfrom core.settings import (MAX_LORAS, LORA_SOURCE_CHOICES, MAX_EMBEDDINGS, MAX_CONDITIONINGS,MAX_CONTROLNETS, MAX_IPADAPTERS, MAX_MOSS_IMAGE_EDITS, RESOLUTION_MAP, ARCHITECTURES_CONFIG,MODEL_MAP_CHECKPOINT, MODEL_TYPE_MAP, FEATURES_CONFIG, ARCH_CATEGORIES_MAP,VAE_DIR, MODEL_DEFAULTS_CONFIG)import yamlimport osfrom functools import lru_cachefrom utils.app_utils import save_uploaded_filedefault_model_name = list(MODEL_MAP_CHECKPOINT.keys())[0] if MODEL_MAP_CHECKPOINT else Nonedefault_m_type = MODEL_TYPE_MAP.get(default_model_name, "SDXL") if default_model_name else "SDXL"default_architectures_dict = ARCHITECTURES_CONFIG.get('architectures', {})default_arch_model_type = default_architectures_dict.get(default_m_type, {}).get("model_type", default_m_type.lower().replace(" ", "").replace(".", ""))default_arch_features = FEATURES_CONFIG.get(default_arch_model_type, {})default_enabled_chains = default_arch_features.get('enabled_chains', [])default_vals = MODEL_DEFAULTS_CONFIG.get('Default', {})DEFAULT_STEPS = default_vals.get('steps', 20)DEFAULT_CFG = default_vals.get('cfg', 5.0)DEFAULT_SAMPLER = default_vals.get('sampler_name', 'euler')DEFAULT_SCHEDULER = default_vals.get('scheduler', 'simple')DEFAULT_POS_PROMPT = default_vals.get('positive_prompt', '')DEFAULT_NEG_PROMPT = default_vals.get('negative_prompt', '')@lru_cache(maxsize=1)def get_ipadapter_config_from_yaml():try:_PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))_IPADAPTER_LIST_PATH = os.path.join(_PROJECT_ROOT, 'yaml', 'ipadapter.yaml')with open(_IPADAPTER_LIST_PATH, 'r', encoding='utf-8') as f:config = yaml.safe_load(f)return configexcept Exception as e:print(f"Warning: Could not load ipadapter.yaml for UI components: {e}")return {}def get_ipadapter_presets(arch="SDXL"):config = get_ipadapter_config_from_yaml()presets = []if config:std_presets = config.get("IPAdapter_presets", {}).get(arch, [])face_presets = config.get("IPAdapter_FaceID_presets", {}).get(arch, [])if std_presets:presets.extend(std_presets)if face_presets:presets.extend(face_presets)return presets if presets else ["STANDARD (medium strength)"]def create_model_architecture_filter_ui(prefix):components = {}ordered_architectures = ARCHITECTURES_CONFIG.get("architecture_order", [])choices = ["ALL"] + ordered_architecturescomponents[f'model_arch_{prefix}'] = gr.Radio(label="Model Architecture",choices=choices,value="ALL",interactive=True,visible=True)return componentsdef create_category_filter_ui(prefix):valid_cats = list(set(cat for cats in ARCH_CATEGORIES_MAP.values() for cat in cats))cat_choices = ["ALL"] + sorted(valid_cats)components = {}components[f'model_cat_{prefix}'] = gr.Dropdown(label="Filter Models",choices=cat_choices,value="ALL",interactive=True,scale=1,allow_custom_value=True)return componentsdef create_base_parameter_ui(prefix, defaults=None):if defaults is None:defaults = {}components = {}with gr.Row():components[f'aspect_ratio_{prefix}'] = gr.Dropdown(label="Aspect Ratio",choices=list(RESOLUTION_MAP.get('sdxl', {}).keys()),value="1:1 (Square)",interactive=True,allow_custom_value=True)with gr.Row():components[f'width_{prefix}'] = gr.Number(label="Width", value=defaults.get('w', 1024), interactive=True)components[f'height_{prefix}'] = gr.Number(label="Height", value=defaults.get('h', 1024), interactive=True)with gr.Row():components[f'sampler_{prefix}'] = gr.Dropdown(label="Sampler",choices=SAMPLER_CHOICES,value=DEFAULT_SAMPLER if DEFAULT_SAMPLER in SAMPLER_CHOICES else (SAMPLER_CHOICES[0] if SAMPLER_CHOICES else 'euler'))components[f'scheduler_{prefix}'] = gr.Dropdown(label="Scheduler",choices=SCHEDULER_CHOICES,value=DEFAULT_SCHEDULER if DEFAULT_SCHEDULER in SCHEDULER_CHOICES else (SCHEDULER_CHOICES[0] if SCHEDULER_CHOICES else 'simple'))with gr.Row():components[f'steps_{prefix}'] = gr.Slider(label="Steps", minimum=1, maximum=100, step=1, value=DEFAULT_STEPS)components[f'cfg_{prefix}'] = gr.Slider(label="CFG Scale", minimum=1.0, maximum=20.0, step=0.1, value=DEFAULT_CFG)with gr.Row():components[f'seed_{prefix}'] = gr.Number(label="Seed (-1 for random)", value=-1, precision=0)components[f'batch_size_{prefix}'] = gr.Slider(label="Batch Size", minimum=1, maximum=16, step=1, value=1)with gr.Row():components[f'zero_gpu_{prefix}'] = gr.Number(label="ZeroGPU Duration (s)", value=60, placeholder="Default: 60s", info="Optional: Set how long to reserve the GPU.")return componentsdef create_lora_settings_ui(prefix: str):components = {}lora_rows, lora_sources, lora_ids, lora_scales, lora_uploads = [], [], [], [], []with gr.Accordion("LoRA Settings", open=False, visible=('lora' in default_enabled_chains)) as lora_accordion:components[f'lora_accordion_{prefix}'] = lora_accordiongr.Markdown("💡 **Tip:** When downloading from Civitai, please use the **Version ID**, not the Model ID. You can find the Version ID in the URL (e.g., `civitai.com/models/123?modelVersionId=456`) or under the model's download button. When downloading from Hugging Face, please use the format: `repo_id/filename.extension` or `repo_id/folder_path/filename.extension` (e.g., `lightx2v/Qwen-Image-Lightning/Qwen-Image-Lightning-4steps-V2.0-bf16.safetensors`).")components[f'lora_count_state_{prefix}'] = gr.State(1)for i in range(MAX_LORAS):with gr.Row(visible=i==0) as row:source = gr.Dropdown(label=f"LoRA Source {i+1}", choices=LORA_SOURCE_CHOICES, value=LORA_SOURCE_CHOICES[0], scale=1)lora_id = gr.Textbox(label="Civitai Version ID / HF file / Upload File", scale=2, type="text")scale = gr.Slider(label=f"Scale", minimum=0.0, maximum=2.0, step=0.05, value=1.0, scale=1)upload = gr.UploadButton(label="Upload", file_types=[".safetensors"], scale=1)lora_rows.append(row)lora_sources.append(source)lora_ids.append(lora_id)lora_scales.append(scale)lora_uploads.append(upload)with gr.Row():components[f'add_lora_button_{prefix}'] = gr.Button("Add LoRA", variant="secondary")components[f'delete_lora_button_{prefix}'] = gr.Button("Remove LoRA", variant="secondary", visible=False)components[f'lora_rows_{prefix}'] = lora_rowscomponents[f'lora_sources_{prefix}'] = lora_sourcescomponents[f'lora_ids_{prefix}'] = lora_idscomponents[f'lora_scales_{prefix}'] = lora_scalescomponents[f'lora_uploads_{prefix}'] = lora_uploadsall_lora_components_flat = []for i in range(MAX_LORAS):all_lora_components_flat.extend([lora_sources[i], lora_ids[i], lora_scales[i], lora_uploads[i]])components[f'all_lora_components_flat_{prefix}'] = all_lora_components_flatreturn componentsdef create_controlnet_ui(prefix: str, max_units=MAX_CONTROLNETS):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("ControlNet Settings", open=False, visible=('controlnet' in default_enabled_chains)) as accordion:components[key('controlnet_accordion')] = accordioncn_rows, images, series, types, strengths, filepaths = [], [], [], [], [], []components.update({key('controlnet_rows'): cn_rows,key('controlnet_images'): images,key('controlnet_series'): series,key('controlnet_types'): types,key('controlnet_strengths'): strengths,key('controlnet_filepaths'): filepaths})for i in range(max_units):with gr.Row(visible=(i < 1)) as row:with gr.Column(scale=1):images.append(gr.Image(label=f"Control Image {i+1}", type="pil", sources=["upload"], height=256))with gr.Column(scale=2):types.append(gr.Dropdown(label="Type", choices=[], interactive=True, allow_custom_value=True))series.append(gr.Dropdown(label="Series", choices=[], interactive=True, allow_custom_value=True))strengths.append(gr.Slider(label="Strength", minimum=0.0, maximum=2.0, step=0.05, value=1.0, interactive=True))filepaths.append(gr.State(None))cn_rows.append(row)with gr.Row():components[key('add_controlnet_button')] = gr.Button("✚ Add ControlNet")components[key('delete_controlnet_button')] = gr.Button("➖ Delete ControlNet", visible=False)components[key('controlnet_count_state')] = gr.State(1)all_cn_components_flat = []for i in range(max_units):all_cn_components_flat.extend([images[i], types[i], series[i], strengths[i], filepaths[i]])components[key('all_controlnet_components_flat')] = all_cn_components_flatreturn componentsdef create_ipadapter_ui(prefix: str, max_units=MAX_IPADAPTERS):components = {}key = lambda name: f"{name}_{prefix}"sdxl_presets = get_ipadapter_presets("SDXL")default_preset = sdxl_presets[0] if sdxl_presets else Nonewith gr.Accordion("IPAdapter Settings", open=False, visible=('ipadapter' in default_enabled_chains)) as accordion:components[key('ipadapter_accordion')] = accordiongr.Markdown("💡 **Tip:** Processed using the [cubiq/ComfyUI_IPAdapter_plus](https://github.com/cubiq/ComfyUI_IPAdapter_plus) node.")with gr.Row():components[key('ipadapter_final_preset')] = gr.Dropdown(label="Preset (for all images)",choices=sdxl_presets,value=default_preset,interactive=True,allow_custom_value=True)components[key('ipadapter_embeds_scaling')] = gr.Dropdown(label="Embeds Scaling",choices=['V only', 'K+V', 'K+V w/ C penalty', 'K+mean(V) w/ C penalty'],value='V only',interactive=True)with gr.Row():components[key('ipadapter_combine_method')] = gr.Dropdown(label="Combine Method",choices=["concat", "add", "subtract", "average", "norm average", "max", "min"],value="concat",interactive=True)components[key('ipadapter_final_weight')] = gr.Slider(label="Final Weight", minimum=0.0, maximum=2.0, step=0.05, value=1.0, interactive=True)components[key('ipadapter_final_lora_strength')] = gr.Slider(label="Final LoRA Strength", minimum=0.0, maximum=2.0, step=0.05, value=0.6, interactive=True, visible=False)gr.Markdown("---")ipa_rows, images, weights, lora_strengths = [], [], [], []components.update({key('ipadapter_rows'): ipa_rows,key('ipadapter_images'): images,key('ipadapter_weights'): weights,key('ipadapter_lora_strengths'): lora_strengths})for i in range(max_units):with gr.Row(visible=(i < 1)) as row:with gr.Column(scale=1):images.append(gr.Image(label=f"IPAdapter Image {i+1}", type="pil", sources=["upload"], height=256))with gr.Column(scale=2):weights.append(gr.Slider(label="Weight", minimum=0.0, maximum=2.0, step=0.05, value=1.0, interactive=True))lora_strengths.append(gr.Slider(label="LoRA Strength", minimum=0.0, maximum=2.0, step=0.05, value=0.6, interactive=True, visible=False))ipa_rows.append(row)with gr.Row():components[key('add_ipadapter_button')] = gr.Button("✚ Add IPAdapter")components[key('delete_ipadapter_button')] = gr.Button("➖ Delete IPAdapter", visible=False)components[key('ipadapter_count_state')] = gr.State(1)all_ipa_components_flat = images + weights + lora_strengthsall_ipa_components_flat += [components[key('ipadapter_final_preset')],components[key('ipadapter_final_weight')],components[key('ipadapter_final_lora_strength')],components[key('ipadapter_embeds_scaling')],components[key('ipadapter_combine_method')],]components[key('all_ipadapter_components_flat')] = all_ipa_components_flatreturn componentsdef create_flux1_ipadapter_ui(prefix: str, max_units=MAX_IPADAPTERS):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("IPAdapter Settings (FLUX.1)", open=False, visible=('flux1_ipadapter' in default_enabled_chains)) as accordion:components[key('flux1_ipadapter_accordion')] = accordiongr.Markdown("💡 **Tip:** Processed using the [Shakker-Labs/ComfyUI-IPAdapter-Flux](https://github.com/Shakker-Labs/ComfyUI-IPAdapter-Flux) node.")ipa_rows, images, weights, start_percents, end_percents = [], [], [], [], []components.update({key('flux1_ipadapter_rows'): ipa_rows,key('flux1_ipadapter_images'): images,key('flux1_ipadapter_weights'): weights,key('flux1_ipadapter_start_percents'): start_percents,key('flux1_ipadapter_end_percents'): end_percents,})for i in range(max_units):with gr.Row(visible=(i < 1)) as row:with gr.Column(scale=1):images.append(gr.Image(label=f"IPAdapter Image {i+1}", type="pil", sources=["upload"], height=256))with gr.Column(scale=2):weights.append(gr.Slider(label="Weight", minimum=0.0, maximum=2.0, step=0.05, value=0.6, interactive=True))with gr.Row():start_percents.append(gr.Slider(label="Start At", minimum=0.0, maximum=1.0, step=0.01, value=0.0, interactive=True))end_percents.append(gr.Slider(label="End At", minimum=0.0, maximum=1.0, step=0.01, value=0.6, interactive=True))ipa_rows.append(row)with gr.Row():components[key('add_flux1_ipadapter_button')] = gr.Button("✚ Add IPAdapter (FLUX)")components[key('delete_flux1_ipadapter_button')] = gr.Button("➖ Delete IPAdapter (FLUX)", visible=False)components[key('flux1_ipadapter_count_state')] = gr.State(1)all_flux1_ipa_components_flat = images + weights + start_percents + end_percentscomponents[key('all_flux1_ipadapter_components_flat')] = all_flux1_ipa_components_flatreturn componentsdef create_sd3_ipadapter_ui(prefix: str, max_units=MAX_IPADAPTERS):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("IPAdapter Settings (SD3)", open=False, visible=('sd3_ipadapter' in default_enabled_chains)) as accordion:components[key('sd3_ipadapter_accordion')] = accordiongr.Markdown("💡 **Tip:** Processed using the [Slickytail/ComfyUI-InstantX-IPAdapter-SD3](https://github.com/Slickytail/ComfyUI-InstantX-IPAdapter-SD3) node.")ipa_rows, images, weights, start_percents, end_percents = [], [], [], [], []components.update({key('sd3_ipadapter_rows'): ipa_rows,key('sd3_ipadapter_images'): images,key('sd3_ipadapter_weights'): weights,key('sd3_ipadapter_start_percents'): start_percents,key('sd3_ipadapter_end_percents'): end_percents,})for i in range(max_units):with gr.Row(visible=(i < 1)) as row:with gr.Column(scale=1):images.append(gr.Image(label=f"IPAdapter Image {i+1}", type="pil", sources=["upload"], height=256))with gr.Column(scale=2):weights.append(gr.Slider(label="Weight", minimum=0.0, maximum=2.0, step=0.05, value=0.5, interactive=True))with gr.Row():start_percents.append(gr.Slider(label="Start At", minimum=0.0, maximum=1.0, step=0.01, value=0.0, interactive=True))end_percents.append(gr.Slider(label="End At", minimum=0.0, maximum=1.0, step=0.01, value=1.0, interactive=True))ipa_rows.append(row)with gr.Row():components[key('add_sd3_ipadapter_button')] = gr.Button("✚ Add IPAdapter (SD3)")components[key('delete_sd3_ipadapter_button')] = gr.Button("➖ Delete IPAdapter (SD3)", visible=False)components[key('sd3_ipadapter_count_state')] = gr.State(1)all_sd3_ipa_components_flat = images + weights + start_percents + end_percentscomponents[key('all_sd3_ipadapter_components_flat')] = all_sd3_ipa_components_flatreturn componentsdef create_style_ui(prefix: str):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("Style Settings (FLUX.1)", open=False, visible=('style' in default_enabled_chains)) as accordion:components[key('style_accordion')] = accordionstyle_rows, images, strengths = [], [], []components.update({key('style_rows'): style_rows,key('style_images'): images,key('style_strengths'): strengths})for i in range(5):with gr.Row(visible=(i < 1)) as row:with gr.Column(scale=1):images.append(gr.Image(label=f"Style Image {i+1}", type="pil", sources=["upload"], height=256))with gr.Column(scale=2):strengths.append(gr.Slider(label="Strength", minimum=0.0, maximum=2.0, step=0.05, value=1.0, interactive=True))style_rows.append(row)with gr.Row():components[key('add_style_button')] = gr.Button("✚ Add Style (FLUX)")components[key('delete_style_button')] = gr.Button("➖ Delete Style (FLUX)", visible=False)components[key('style_count_state')] = gr.State(1)all_style_components_flat = images + strengthscomponents[key('all_style_components_flat')] = all_style_components_flatreturn componentsdef create_embedding_ui(prefix: str):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("Embedding Settings", open=False, visible=('embedding' in default_enabled_chains)) as accordion:components[key('embedding_accordion')] = accordiongr.Markdown("💡 **Tip:** When downloading from Civitai, please use the **Version ID**, not the Model ID. You can find the Version ID in the URL (e.g., `civitai.com/models/123?modelVersionId=456`) or under the model's download button. For example, entering the Version ID 456 will automatically save the file as \"civitai/456.safetensors\", and you will need to manually enter `embedding:civitai/456` in either your prompt or negative prompt to activate it. When downloading from Hugging Face, please use the format: repo_id/filename.extension or repo_id/folder_path/filename.extension (e.g., ilikebigturtles/lazypos/lazypos.safetensors or ilikebigturtles/lazyneg/lazyneg.safetensors). For Hugging Face files, you will need to enter embedding:huggingface/filename (e.g., entering embedding:huggingface/lazypos in your positive prompt, or embedding:huggingface/lazyneg in your negative prompt) to activate it. For uploaded files, enter `embedding:upload_file/filename` in either your positive prompt or negative prompt to activate it.")embedding_rows, sources, ids, files, upload_buttons = [], [], [], [], []components.update({key('embedding_rows'): embedding_rows,key('embeddings_sources'): sources,key('embeddings_ids'): ids,key('embeddings_files'): files,key('embeddings_uploads'): upload_buttons})for i in range(MAX_EMBEDDINGS):with gr.Row(visible=(i < 1)) as row:sources.append(gr.Dropdown(label=f"Embedding Source {i+1}", choices=LORA_SOURCE_CHOICES, value="Civitai", scale=1, interactive=True))ids.append(gr.Textbox(label="Civitai Version ID / HF file / Upload File", scale=3, interactive=True, type="text"))upload_btn = gr.UploadButton("Upload", file_types=[".safetensors"], scale=1)files.append(gr.State(None))upload_buttons.append(upload_btn)embedding_rows.append(row)with gr.Row():components[key('add_embedding_button')] = gr.Button("✚ Add Embedding")components[key('delete_embedding_button')] = gr.Button("➖ Delete Embedding", visible=False)components[key('embedding_count_state')] = gr.State(1)all_embedding_components_flat = []for i in range(MAX_EMBEDDINGS):all_embedding_components_flat.extend([sources[i], ids[i], files[i]])components[key('all_embedding_components_flat')] = all_embedding_components_flatreturn componentsdef create_conditioning_ui(prefix: str):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("Conditioning Settings", open=False, visible=('conditioning' in default_enabled_chains)) as accordion:components[key('conditioning_accordion')] = accordiongr.Markdown("💡 **Tip:** Define rectangular areas and assign specific prompts to them. Coordinates (X, Y) start from the top-left corner.")cond_rows, prompts, widths, heights, xs, ys, strengths = [], [], [], [], [], [], []components.update({key('conditioning_rows'): cond_rows,key('conditioning_prompts'): prompts,key('conditioning_widths'): widths,key('conditioning_heights'): heights,key('conditioning_xs'): xs,key('conditioning_ys'): ys,key('conditioning_strengths'): strengths})for i in range(MAX_CONDITIONINGS):with gr.Column(visible=(i < 1)) as row_wrapper:prompts.append(gr.Textbox(label=f"Area Prompt {i+1}", lines=2, interactive=True))with gr.Row():xs.append(gr.Number(label="X", value=0, interactive=True, step=8, scale=1))ys.append(gr.Number(label="Y", value=0, interactive=True, step=8, scale=1))widths.append(gr.Number(label="Width", value=512, interactive=True, step=8, scale=1))heights.append(gr.Number(label="Height", value=512, interactive=True, step=8, scale=1))strengths.append(gr.Slider(label="Strength", minimum=0.1, maximum=2.0, step=0.05, value=1.0, interactive=True, scale=2))cond_rows.append(row_wrapper)with gr.Row():components[key('add_conditioning_button')] = gr.Button("✚ Add Area")components[key('delete_conditioning_button')] = gr.Button("➖ Delete Area", visible=False)components[key('conditioning_count_state')] = gr.State(1)all_cond_components_flat = prompts + widths + heights + xs + ys + strengthscomponents[key('all_conditioning_components_flat')] = all_cond_components_flatreturn componentsdef on_vae_upload(file_obj):if not file_obj:return gr.update(), gr.update(), Noneuploaded_filename = save_uploaded_file(file_obj, VAE_DIR)return uploaded_filename, "Upload File", file_objdef create_vae_override_ui(prefix: str):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("VAE Settings (Override)", open=False, visible=('vae' in default_enabled_chains)) as vae_accordion:components[key('vae_accordion')] = vae_accordiongr.Markdown("💡 **Tip:** When downloading from Civitai, please use the **Version ID**, not the Model ID. You can find the Version ID in the URL (e.g., `civitai.com/models/123?modelVersionId=456`) or under the model's download button. When downloading from Hugging Face, please use the format: `repo_id/filename.extension` or `repo_id/folder_path/filename.extension` (e.g., `madebyollin/sdxl-vae-fp16-fix/sdxl_vae.safetensors`).")with gr.Row():components[key('vae_source')] = gr.Dropdown(label="VAE Source",choices=LORA_SOURCE_CHOICES,value="Civitai",scale=1,interactive=True)components[key('vae_id')] = gr.Textbox(label="Civitai Version ID / HF file / Upload File",scale=3,interactive=True,type="text")upload_btn = gr.UploadButton("Upload",file_types=[".safetensors"],scale=1)components[key('vae_upload_button')] = upload_btncomponents[key('vae_file')] = gr.State(None)upload_btn.upload(fn=on_vae_upload,inputs=[upload_btn],outputs=[components[key('vae_id')], components[key('vae_source')], components[key('vae_file')]])return componentsdef create_reference_latent_ui(prefix: str, max_units=10):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("Reference Edit Settings", open=False, visible=('reference_latent' in default_enabled_chains)) as ref_accordion:components[key('reference_latent_accordion')] = ref_accordiongr.Markdown("💡 **Tip:** For multimodal models, this feature enables powerful editing and combining capabilities. In txt2img mode, adding a single reference image performs an **Image Edit**, while adding multiple images performs an **Image Combine**.")ref_image_groups = []ref_image_inputs = []with gr.Row():for i in range(max_units):with gr.Column(visible=(i < 1), min_width=160) as img_col:img_comp = gr.Image(type="pil", label=f"Ref. {i+1}", sources=["upload"], height=150)ref_image_groups.append(img_col)ref_image_inputs.append(img_comp)components[key('reference_latent_rows')] = ref_image_groupscomponents[key('reference_latent_images')] = ref_image_inputswith gr.Row():components[key('add_reference_latent_button')] = gr.Button("✚ Add Reference Image")components[key('delete_reference_latent_button')] = gr.Button("➖ Delete Reference Image", visible=False)components[key('reference_latent_count_state')] = gr.State(1)components[key('all_reference_latent_components_flat')] = ref_image_inputsreturn componentsdef create_hidream_o1_reference_ui(prefix: str, max_units=10):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("HiDream-O1 Reference Edit Settings", open=False, visible=('hidream_o1_reference' in default_enabled_chains)) as ref_accordion:components[key('hidream_o1_reference_accordion')] = ref_accordiongr.Markdown("💡 **Tip:** Please use **HiDream-O1-Image-Dev** (HiDream-O1-Image will time out), and set the resolution to **4.0MP** (e.g., 2048x2048). In txt2img mode, adding a single reference image performs an **Image Edit**, while adding multiple images performs an **Image Combine**.")ref_image_groups = []ref_image_inputs = []with gr.Row():for i in range(max_units):with gr.Column(visible=(i < 1), min_width=160) as img_col:img_comp = gr.Image(type="pil", label=f"Ref. {i+1}", sources=["upload"], height=150)ref_image_groups.append(img_col)ref_image_inputs.append(img_comp)components[key('hidream_o1_reference_rows')] = ref_image_groupscomponents[key('hidream_o1_reference_images')] = ref_image_inputswith gr.Row():components[key('add_hidream_o1_reference_button')] = gr.Button("✚ Add Reference Image")components[key('delete_hidream_o1_reference_button')] = gr.Button("➖ Delete Reference Image", visible=False)components[key('hidream_o1_reference_count_state')] = gr.State(1)components[key('all_hidream_o1_reference_components_flat')] = ref_image_inputsreturn componentsdef create_sensenova_reference_ui(prefix: str, max_units=10):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("SenseNova Reference Edit Settings", open=False, visible=('sensenova_reference' in default_enabled_chains)) as ref_accordion:components[key('sensenova_reference_accordion')] = ref_accordiongr.Markdown("💡 **Tip:** For SenseNova models, this feature enables reference image editing and combining capabilities. In txt2img mode, adding a single reference image performs an **Image Edit**, while adding multiple images performs an **Image Combine**.")ref_image_groups = []ref_image_inputs = []with gr.Row():for i in range(max_units):with gr.Column(visible=(i < 1), min_width=160) as img_col:img_comp = gr.Image(type="pil", label=f"Ref. {i+1}", sources=["upload"], height=150)ref_image_groups.append(img_col)ref_image_inputs.append(img_comp)components[key('sensenova_reference_rows')] = ref_image_groupscomponents[key('sensenova_reference_images')] = ref_image_inputswith gr.Row():components[key('add_sensenova_reference_button')] = gr.Button("✚ Add Reference Image")components[key('delete_sensenova_reference_button')] = gr.Button("➖ Delete Reference Image", visible=False)components[key('sensenova_reference_count_state')] = gr.State(1)components[key('all_sensenova_reference_components_flat')] = ref_image_inputsreturn componentsdef create_joyai_reference_ui(prefix: str, max_units=2):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("JoyAI Reference Edit Settings", open=False, visible=('joyai_image' in default_enabled_chains)) as ref_accordion:components[key('joyai_reference_accordion')] = ref_accordiongr.Markdown("💡 **Tip:** For multimodal models, this feature enables powerful editing and combining capabilities. In txt2img mode, adding a single reference image performs an **Image Edit** (JoyAI-Image-Edit recommended), while adding multiple images performs an **Image Combine** (JoyAI-Image-Edit-Plus recommended with ZeroGPU Duration (s) set to 120).")ref_image_groups = []ref_image_inputs = []with gr.Row():for i in range(max_units):with gr.Column(visible=(i < 1), min_width=160) as img_col:img_comp = gr.Image(type="pil", label=f"Ref. {i+1}", sources=["upload"], height=150)ref_image_groups.append(img_col)ref_image_inputs.append(img_comp)components[key('joyai_reference_rows')] = ref_image_groupscomponents[key('joyai_reference_images')] = ref_image_inputswith gr.Row():components[key('add_joyai_reference_button')] = gr.Button("✚ Add Reference Image")components[key('delete_joyai_reference_button')] = gr.Button("➖ Delete Reference Image", visible=False)components[key('joyai_reference_count_state')] = gr.State(1)components[key('all_joyai_reference_components_flat')] = ref_image_inputsreturn componentsdef create_reference_image_ui(prefix: str, max_units=10):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("Reference Image Edit Settings", open=False, visible=('reference_image' in default_enabled_chains)) as ref_accordion:components[key('reference_image_accordion')] = ref_accordiongr.Markdown("💡 **Tip:** For multimodal models, this feature enables powerful editing and combining capabilities. In txt2img mode, adding a single reference image performs an **Image Edit**, while adding multiple images performs an **Image Combine**.")ref_image_groups = []ref_image_inputs = []with gr.Row():for i in range(max_units):with gr.Column(visible=(i < 1), min_width=160) as img_col:img_comp = gr.Image(type="pil", label=f"Ref. {i+1}", sources=["upload"], height=150)ref_image_groups.append(img_col)ref_image_inputs.append(img_comp)components[key('reference_image_rows')] = ref_image_groupscomponents[key('reference_image_images')] = ref_image_inputswith gr.Row():components[key('add_reference_image_button')] = gr.Button("✚ Add Reference Image")components[key('delete_reference_image_button')] = gr.Button("➖ Delete Reference Image", visible=False)components[key('reference_image_count_state')] = gr.State(1)components[key('all_reference_image_components_flat')] = ref_image_inputsreturn componentsdef create_moss_image_control_ui(prefix: str):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("MOSS-Image Color/Depth Control Settings", open=False, visible=('moss_image_control' in default_enabled_chains)) as control_accordion:components[key('moss_image_control_accordion')] = control_accordiongr.Markdown("💡 **Tip:** Uses the [darask0/MOSS-Image-color-depth-control](https://huggingface.co/darask0/MOSS-Image-color-depth-control) adapter.")with gr.Row():components[key('moss_image_control_color_map')] = gr.Image(type="pil", label="Color Region Map (Optional)", sources=["upload"], height=200)components[key('moss_image_control_depth_map')] = gr.Image(type="pil", label="Depth Map (Optional, near=white)", sources=["upload"], height=200)with gr.Row():components[key('moss_image_control_strength')] = gr.Slider(label="Control Strength",value=1.0,minimum=0.0,maximum=2.0,step=0.05,interactive=True)components[key('moss_image_control_end_percent')] = gr.Slider(label="End Percent (0.5 for 3D mannequin)",value=0.5,minimum=0.0,maximum=1.0,step=0.01,interactive=True)return componentsdef create_pid_ui(prefix: str):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("PiD Settings", open=False, visible=('pid' in default_enabled_chains)) as pid_accordion:components[key('pid_accordion')] = pid_accordiongr.Markdown("💡 **Tip:** Use PiD (Pixel Diffusion Decoder) instead of the VAE Decoder for 4x decoding.")with gr.Row():components[key('pid_settings')] = gr.Dropdown(label="PiD Mode",choices=["OFF", "ON"],value="OFF",interactive=True)return componentsdef create_krea2_identity_edit_ui(prefix: str, max_units=2):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("Krea2 Identity Edit Settings", open=False, visible=('krea2_identity_edit' in default_enabled_chains)) as ref_accordion:components[key('krea2_identity_edit_accordion')] = ref_accordiongr.Markdown("💡 **Tip:** Processed using the [lbouaraba/comfyui-krea2edit](https://github.com/lbouaraba/comfyui-krea2edit) node. (Krea-2-Turbo recommended, Krea-2-Raw need set ZeroGPU Duration (s) to 120 ) In txt2img mode, adding a single reference image performs an **Image Edit**, while adding multiple images performs an **Image Combine**.")ref_image_groups = []ref_image_inputs = []with gr.Row():for i in range(max_units):with gr.Column(visible=(i < 1), min_width=160) as img_col:img_comp = gr.Image(type="pil", label=f"Ref. {i+1}", sources=["upload"], height=150)ref_image_groups.append(img_col)ref_image_inputs.append(img_comp)components[key('krea2_identity_edit_rows')] = ref_image_groupscomponents[key('krea2_identity_edit_images')] = ref_image_inputswith gr.Row():components[key('add_krea2_identity_edit_button')] = gr.Button("✚ Add Reference Image")components[key('delete_krea2_identity_edit_button')] = gr.Button("➖ Delete Reference Image", visible=False)components[key('krea2_identity_edit_count_state')] = gr.State(1)components[key('all_krea2_identity_edit_components_flat')] = ref_image_inputsreturn componentsdef create_qwen_image_edit_ui(prefix: str, max_units=3):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("Qwen-Image Edit Settings", open=False, visible=('qwen_image_edit' in default_enabled_chains)) as ref_accordion:components[key('qwen_image_edit_accordion')] = ref_accordiongr.Markdown("💡 **Tip:** (lightx2v/Qwen-Image-Edit-2511-Lightning recommended) In txt2img mode, adding a single reference image performs an **Image Edit**, while adding multiple images performs an **Image Combine**.")ref_image_groups = []ref_image_inputs = []with gr.Row():for i in range(max_units):with gr.Column(visible=(i < 1), min_width=160) as img_col:img_comp = gr.Image(type="pil", label=f"Ref. {i+1}", sources=["upload"], height=150)ref_image_groups.append(img_col)ref_image_inputs.append(img_comp)components[key('qwen_image_edit_rows')] = ref_image_groupscomponents[key('qwen_image_edit_images')] = ref_image_inputswith gr.Row():components[key('add_qwen_image_edit_button')] = gr.Button("✚ Add Reference Image")components[key('delete_qwen_image_edit_button')] = gr.Button("➖ Delete Reference Image", visible=False)components[key('qwen_image_edit_count_state')] = gr.State(1)components[key('all_qwen_image_edit_components_flat')] = ref_image_inputsreturn componentsdef create_krea2_reference_edit_ui(prefix: str, max_units=3):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("Krea2 Style Reference Edit Settings", open=False, visible=('krea2_style_reference' in default_enabled_chains)) as ref_accordion:components[key('krea2_reference_edit_accordion')] = ref_accordiongr.Markdown("💡 **Tip:** (Krea-2-Turbo recommended) Add style reference images to perform style reference editing.")ref_image_groups = []ref_image_inputs = []with gr.Row():for i in range(max_units):with gr.Column(visible=(i < 1), min_width=160) as img_col:img_comp = gr.Image(type="pil", label=f"Ref. {i+1}", sources=["upload"], height=150)ref_image_groups.append(img_col)ref_image_inputs.append(img_comp)components[key('krea2_reference_edit_rows')] = ref_image_groupscomponents[key('krea2_reference_edit_images')] = ref_image_inputswith gr.Row():components[key('add_krea2_reference_edit_button')] = gr.Button("✚ Add Reference Image")components[key('delete_krea2_reference_edit_button')] = gr.Button("➖ Delete Reference Image", visible=False)components[key('krea2_reference_edit_count_state')] = gr.State(1)components[key('all_krea2_reference_edit_components_flat')] = ref_image_inputsreturn componentsdef create_prompt_enhancer_ui(prefix: str):components = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("Prompt Enhancer Settings", open=False, visible=('prompt_enhancer' in default_enabled_chains)) as enhancer_accordion:components[key('prompt_enhancer_accordion')] = enhancer_accordiongr.Markdown("💡 **Tip:** Automatically selects Prompt Enhancer Model and System Prompt based on the selected Base Model; ""free mixing is also supported.")with gr.Row():components[key('prompt_enhancer_enable')] = gr.Checkbox(label="Enable Prompt Enhancer",value=False,interactive=True,scale=2)components[key('prompt_enhancer_thinking')] = gr.Checkbox(label="Enable Thinking",value=False,interactive=True,scale=2)components[key('prompt_enhancer_max_length')] = gr.Number(label="Max Length",value=4096,precision=0,minimum=16,step=16,interactive=True,scale=1)with gr.Row():components[key('prompt_enhancer_model')] = gr.Dropdown(choices=_prompt_enhancer_choices("model"),value=_prompt_enhancer_initial_defaults()["model"],label="Prompt Enhancer Model",interactive=True,scale=3)components[key('prompt_enhancer_system_prompt')] = gr.Dropdown(choices=_prompt_enhancer_choices("system_prompt"),value=_prompt_enhancer_initial_defaults()["system_prompt"],label="System Prompt",interactive=True,scale=2)return componentsdef _prompt_enhancer_registry():"""Load yaml/prompt_enhancer.yaml once per UI build."""import yamlpath = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "yaml", "prompt_enhancer.yaml")try:with open(path, "r", encoding="utf-8") as f:return yaml.safe_load(f) or {}except Exception as e:print(f"Warning: could not load prompt_enhancer.yaml: {e}")return {}def _prompt_enhancer_choices(kind):cfg = _prompt_enhancer_registry()names = list((cfg.get("clip" if kind == "model" else "system_prompt") or {}).keys())return ["auto"] + namesdef _prompt_enhancer_initial_defaults():"""Seed the dropdowns from the Base Model selected on first page load.``default_arch_model_type`` is resolved at import time from the firstcheckpoint in the model list, so the panel opens on a real selectioninstead of ``auto`` even when Model Architecture is ALL."""return prompt_enhancer_defaults(default_arch_model_type)def prompt_enhancer_defaults(framework):"""Return {model, system_prompt} defaults declared for a model framework."""cfg = _prompt_enhancer_registry()clips = list((cfg.get("clip") or {}).keys())prompts = list((cfg.get("system_prompt") or {}).keys())entry = (cfg.get("architecture") or {}).get(str(framework)) or {}model = entry.get("clip")if model not in clips:model = clips[0] if clips else "auto"prompt = entry.get("system_prompt")if prompt not in prompts:prompt = prompts[0] if prompts else "auto"return {"model": model, "system_prompt": prompt}def create_moss_image_edit_ui(prefix: str, max_units=None):if max_units is None:max_units = MAX_MOSS_IMAGE_EDITScomponents = {}key = lambda name: f"{name}_{prefix}"with gr.Accordion("MOSS-Image Edit Settings", open=False, visible=('moss_image_edit' in default_enabled_chains)) as ref_accordion:components[key('moss_image_edit_accordion')] = ref_accordiongr.Markdown("💡 **Tip:** For multimodal models, this feature enables powerful editing and combining capabilities. In txt2img mode, adding a single reference image performs an Image Edit, while adding multiple images performs an Image Combine. Uses [chinoll/Moss-Image-Edit](https://huggingface.co/chinoll/Moss-Image-Edit).")ref_image_groups = []ref_image_inputs = []with gr.Row():for i in range(max_units):with gr.Column(visible=(i < 1), min_width=160) as img_col:img_comp = gr.Image(type="pil", label=f"Ref. {i+1}", sources=["upload"], height=150)ref_image_groups.append(img_col)ref_image_inputs.append(img_comp)components[key('moss_image_edit_rows')] = ref_image_groupscomponents[key('moss_image_edit_images')] = ref_image_inputswith gr.Row():components[key('add_moss_image_edit_button')] = gr.Button("✚ Add Reference Image")components[key('delete_moss_image_edit_button')] = gr.Button("➖ Delete Reference Image", visible=False)components[key('moss_image_edit_count_state')] = gr.State(1)components[key('all_moss_image_edit_components_flat')] = ref_image_inputsreturn components
477 unmodified lines478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558477 unmodified lines- source- embedding_valueqwen_image_2_1_prompt_enhancer:chains: qwen_image_2_1_prompt_enhancerdisplay_name: "Qwen-Image-2.1 Prompt Enhancer Settings"description: "Enhance prompts using Qwen-Image-2.1 Prompt Enhancer with automatic model selection (T2I vs I2I/reference images) and optional reasoning CoT thinking mode."max_count: 1usage_guideline: "Set enable to true to activate prompt enhancement. Enable thinking to allow reasoning CoT (reasoning tags are automatically stripped from the resulting prompt). Set max_length to control generation length."parameters_schema:type: objectproperties:enable:type: booleandefault: falsedescription: "Enable Qwen-Image-2.1 Prompt Enhancer."thinking:type: booleandefault: falsedescription: "Enable thinking (reasoning CoT). Thought text inside <think> tags will be automatically stripped before passing prompt to downstream text encoding."max_length:type: integerdefault: 4096description: "Maximum generation length for prompt enhancement (default 4096)."ming_image_prompt_enhancer:chains: ming_image_prompt_enhancerdisplay_name: "Ming-Image Prompt Enhancer Settings"description: "Enhance prompts using Ming-Image Prompt Enhancer (Qwen3.8-27B) guided by official Figma-style rewriter System Prompt, with optional reasoning CoT thinking mode."max_count: 1usage_guideline: "Set enable to true to activate Ming-Image prompt enhancement. Supports single/multi-reference images, thinking mode, and custom system prompt."parameters_schema:type: objectproperties:enable:type: booleandefault: falsedescription: "Enable Ming-Image Prompt Enhancer."thinking:type: booleandefault: falsedescription: "Enable thinking (reasoning CoT)."max_length:type: integerdefault: 4096description: "Maximum generation length for prompt enhancement (default 4096)."system_prompt:type: stringdescription: "System prompt for Qwen3.8-27B prompt enhancer (defaults to official Ming-Image Figma-style rewriter prompt)."flux3_prompt_upsampler:chains: flux3_prompt_upsamplerdisplay_name: "FLUX.3 Prompt Upsampler Settings"description: "Expand short prompts into detailed generative captions using FLUX.3 Prompt Upsampler (qwen3.5_9b_flux3_prompt_upsampler_w4a8) with automatic official template selection (t2i, i2i, t2i_bbox, i2i_bbox), multi-reference image stitching, and reasoning CoT thinking mode."max_count: 1usage_guideline: "Set enable to true to activate FLUX.3 prompt upsampler. Automatically selects official BFL t2i or i2i template based on input image detection. Supports bbox_mode, thinking mode, and multi-reference image stitching."parameters_schema:type: objectproperties:enable:type: booleandefault: falsedescription: "Enable FLUX.3 Prompt Upsampler."thinking:type: booleandefault: falsedescription: "Enable thinking (reasoning CoT)."bbox_mode:type: booleandefault: falsedescription: "Enable BBox mode (automatically selects t2i_bbox or i2i_bbox official system prompt templates to output bounding boxes)."max_length:type: integerdefault: 3584description: "Maximum generation length for prompt upsampler (default 3584)."system_prompt:type: stringdescription: "Optional custom system prompt override (defaults to official t2i/i2i or t2i_bbox/i2i_bbox templates)."moss_image_control:chains: moss_image_control477 unmodified lines478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510477 unmodified lines- source- embedding_valueprompt_enhancer:chains: prompt_enhancerdisplay_name: "Prompt Enhancer Settings"description: "Enhance or upsample prompts with any registered prompt-enhancer model (Qwen-Image-2.1 PE T2I/I2I, Qwen3.8-27B, FLUX.3 Prompt Upsampler), optional reasoning CoT thinking mode, and optional system prompt. The clip and system_prompt registries are independent, so they are freely mixable across architectures."max_count: 1usage_guideline: "Set enable to true to activate prompt enhancement. Pick model from the clip registry and system_prompt from the system_prompt registry in yaml/prompt_enhancer.yaml; both lists are global, so any architecture may select any clip paired with any system prompt. Defaults for each framework come from the architecture section and reset when the base model changes. Nothing is auto-detected from images, so an explicit system prompt always wins. Enable thinking for reasoning CoT (reasoning tags are stripped from the result), and set max_length for generation length."parameters_schema:type: objectproperties:enable:type: booleandefault: falsedescription: "Enable prompt enhancement."thinking:type: booleandefault: falsedescription: "Enable thinking (reasoning CoT). Thought text inside <think> tags is automatically stripped before the prompt reaches downstream text encoding."model:type: stringdescription: "Prompt Enhancer Model name from the clip registry in yaml/prompt_enhancer.yaml (e.g. Qwen-Image-2.1-Prompt-Enhancer-T2I, Qwen-Image-2.1-Prompt-Enhancer-I2I, Qwen3.8-27B, Qwen3.5-9B-FLUX.3-Prompt-Upsampler). Any model may select any registered clip regardless of architecture; clip_type travels with the clip. Defaults to the architecture entry for the active framework."system_prompt:type: stringdescription: "System Prompt name from the system_prompt registry in yaml/prompt_enhancer.yaml (e.g. none, Ming-Image-PE-Template, FLUX.3-T2I-PE-Template, FLUX.3-I2I-PE-Template, FLUX.3-T2I-Bbox-PE-Template, FLUX.3-I2I-Bbox-PE-Template). Independent of the selected clip and never inferred from images; an empty prompt means no system prompt."max_length:type: integerdefault: 4096description: "Maximum generation length for prompt enhancement (default 4096)."moss_image_control:chains: moss_image_control
8 unmodified lines910111213141588 unmodified lines1041051061071081091101111121131141151161178 unmodified linesenabled_chains:- lora- reference_latent- flux3_prompt_upsampler- pidminimax-h3-image:88 unmodified linesenabled_chains:- lora- reference_image- ming_image_prompt_enhancerqwen-image-2.1:enabled_chains:- lora- controlnet- reference_image- qwen_image_2_1_prompt_enhancerqwen-image:enabled_chains:8 unmodified lines910111213141588 unmodified lines1041051061071081091101111121131141151161178 unmodified linesenabled_chains:- lora- reference_latent- prompt_enhancer- pidminimax-h3-image:88 unmodified linesenabled_chains:- lora- reference_image- prompt_enhancerqwen-image-2.1:enabled_chains:- lora- controlnet- reference_image- prompt_enhancerqwen-image:enabled_chains:
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465architecture: flux3: clip: "Qwen3.5-9B-FLUX.3-Prompt-Upsampler" system_prompt: "FLUX.3-T2I-PE-Template" ming-image: clip: "Qwen3.8-27B" system_prompt: "Ming-Image-PE-Template" qwen-image-2.1: clip: "Qwen-Image-2.1-Prompt-Enhancer-T2I" system_prompt: "none"
clip: Qwen-Image-2.1-Prompt-Enhancer-T2I: filename: "qwen3.5_9b_qwen_image_2.1_pe_t2i.int8_convrot.safetensors" clip_type: qwen_image Qwen-Image-2.1-Prompt-Enhancer-I2I: filename: "qwen3.5_9b_qwen_image_2.1_pe_i2i.int8_convrot.safetensors" clip_type: qwen_image Qwen3.8-27B: filename: "qwen3.8_27b_w4a8.safetensors" clip_type: qwen_image Qwen3.5-9B-FLUX.3-Prompt-Upsampler: filename: "qwen3.5_9b_flux3_prompt_upsampler_w4a8.safetensors" clip_type: flux3
system_prompt: none: "" Ming-Image-PE-Template: |- You are a senior visual designer and image-prompt engineer. Expand the user's request into one precise, high-resolution Figma-style caption. Return only one JSON object. Use exactly two top-level keys. `canvas_settings` contains exactly `aspect_ratio`, `ambient_lighting`, and `image_style`. `layers` lists visible groups from background to topmost overlay. Every layer contains exactly `description`, `coordinates`, `hierarchy_and_relation`, and `color_specs`; `color_specs` is an array of hex colors. `coordinates` MUST be one string, never an object or array, in exactly this form: `"cx: 0.500, cy: 0.500, w: 1.000, h: 1.000"`. Values are normalized; each bbox encloses its complete owned object and stays inside the canvas. A layer is one selectable visible semantic group: background, full person, coherent object, panel, card, row, or text block. Prefer the fewest groups that preserve the layout. Keep people and objects intact. Never create invisible parents, guides, placeholders, empty layers, duplicate summaries, or multiple owners for one element. Preserve every user-supplied rendered string character-for-character and as one contiguous string. Unless multiple visible copies are requested, it must occur exactly once across all `description` fields and zero times in `hierarchy_and_relation`. Quote it only where describing its visible rendering; refer to the related subject elsewhere with unquoted semantic wording. Enumerate intended copy, invent extra copy sparingly, and never hide content behind "other text", "remaining labels", or "etc." Describe concrete composition, typography, materials, texture, lighting, pose, and camera treatment without literary filler. Use `hierarchy_and_relation` only for ownership, alignment, containment, stacking, and occlusion. Infer structured layouts first. Use one complete layer per card and state its row and column. A compact secondary table may be one layer only if every header and cell is listed; otherwise use a visible shared frame when present, one complete header, and one complete layer per body row, binding values to columns and stating blanks. Enumerate sequences, schedules, spans, gaps, and vacant tracks in visual order. Do not mistake ordinary alignment for a table. Silently verify schema, string coordinates, Z-order, exact-text counts, geometry, bbox validity, and completeness. FLUX.3-T2I-PE-Template: |- You are the prompt upsampler of a text-to-image model. Expand the user's short request into ONE detailed, self-contained caption: the exact text the image model receives. Output only the caption, with no greetings, explanations, refusals, questions, Markdown, headings, JSON, coordinates, ids or angle-bracket tokens, and no quotes around it. If the input is not clearly an image request, caption a visualization of its concept. The request may begin with a "TARGET CANVAS: W:H" line: compose for that canvas (wide spreads content sideways, tall stacks it) and never mention the ratio or the canvas.
Fidelity and planning: keep every explicit subject, attribute, count, spatial constraint, style cue and piece of wording; never contradict, substitute, drop or narrow the request, and keep an abstract concept abstract. Decide everything left open as ONE concrete, consistent plan; never offer alternatives or hedge. Never re-express a stated constraint through another mechanism; add camera optics (depth of field, bokeh, blur) only when asked for or implied. Without a stated style, plan an actual photograph and open with the medium convention ("Full-color outdoor photograph, ...", "Full-color indoor photograph, ...", "Studio photograph, ...", "Close-up photograph, ..."); keep "Photorealistic" for renders, and turn "photorealistic" or "realistic" requests for photos into the photograph convention. Give a photograph a few ordinary, non-ideal specifics drawn from the scene's own objects instead of the stock-photo ideal. Do not invent names, brands, logos or celebrities; keep user-named ones. A long request keeps its content but not its wording: drop appraisal and sales vocabulary, turn moods into observable physical facts, and add only new concrete content with positions. Time of day is lighting, not rendered text.
Caption format: one continuous prose block in the generative voice, never "this image shows", "we can see" or "is visible". Lead with medium and style, then scene, lighting and camera, then the subjects with concrete colors, materials and state. Every person in focus gets an observable profile: ethnicity, gender, age range, skin tone ("fair skin", "brown skin"), hair and clothing. Make the layout reconstructable from words: frame-relative positions (frame-left, frame-right, upper, lower, foreground, midground, background), sentence-initial anchors ("On the left, ...", "In the background, ..."), relations (holds, faces, behind) and a consistent order; describe up to about ten instances one by one, beyond that give the exact count and arrangement. Out-of-focus or distant planes are shapes, colors and silhouettes, never identities or readable text, and the background takes about a sixth of the caption. Be definite: no hedging adverbs, no quality or emotion judgments, no closing sentence about mood; state negations as what is present. Rendered text: transcribe every wording verbatim inside double quotes in its original language and script, keep the line breaks of multi-line text, and give its typography, color and placement; author concrete, domain-correct wording when the request needs text it does not supply, and name canonical structures (calendar, keyboard, periodic table) exactly with their full layout. All prose is English; only quoted text keeps its language. Typical length is 100 to 350 words, more for complex scenes.
Output only the caption. FLUX.3-I2I-PE-Template: |- You are the prompt upsampler of an image-editing model. You see the reference image(s), attached in order (the first image, the second image, ...), and the user's short request. Expand it into ONE detailed, self-contained instruction: the caption the editing model receives together with the same images. Output only the instruction as one continuous English prose block, with no greetings, explanations, Markdown, JSON, coordinates, ids or angle-bracket tokens. Read a vague or conversational request as the most plausible edit of the supplied images.
Pick the voice by task shape. When one reference stays and gets bounded changes, write an imperative editing instruction on it ("Remove the ...", "Change the ... to ...", "Zoom in on ..."); a whole-image transformation opens with its scope ("Convert the entire image into ...", "Apply a ... filter over the entire scene", "Horizontally flip the entire image so that ...", "Shift the camera viewpoint to ...", then where the major elements should now be). When the references are drawn into a newly composed frame (combining subjects, a new scene, a garment, object or style donor), write a generation request ("Create a photograph of ...", "Create an anime-style illustration of ...", "Generate a new image featuring ...") that says what to take from each image, by ordinal, and what is newly generated.
Keep every explicit edit, constraint, count, position, style cue and piece of wording, and decide what is left open as one concrete plan. Ground everything in what is actually visible: identify each referent unambiguously by its real appearance, never mention content that is not there, and use every image the user attached. State every end state concretely (which color, how large, which pose, which material) and give new content enough appearance to be generated. Cover the knock-on effects of the change (shadows, reflections, occlusion, perspective, scale, lighting) and say what fills a removed region. A zoom-in names what stays in frame and which neighbors are cropped out; an outpainting continues the scene in the same medium. Describe the change, not the whole scene, and close an editing instruction with one compact clause naming what stays unchanged; transferred people keep their identity, face and accessories unless asked otherwise. Transcribe on-image text verbatim in its original language inside double quotes, with line breaks as \n, and match the original font, size and color when replacing it. Name recognizable public figures, brands and landmarks you can see. Directions are frame-relative; use no evaluative or quality words. Typical length is 50 to 150 words.
Output only the instruction. FLUX.3-T2I-Bbox-PE-Template: |- You are the prompt upsampler of a text-to-image model. Plan the full image the user's short request implies and output ONE structured caption on a single line: the global caption paragraph, one space, then ONE JSON array, the element table that places every cited element with a bounding box in the image to be generated. Output nothing else (no Markdown fences, commentary or refusals); visualize the concept of a non-image input. The request may begin with a "TARGET CANVAS: W:H" line: compose for that canvas and never mention it. Boxes live on a 0-1000 grid stretched onto the canvas: an element of physical width-to-height ratio a gets an x-span of about y-span x a x H/W.
Planning: keep every explicit subject, attribute, count, spatial constraint, style cue and piece of wording, and decide everything left open as ONE concrete composition that the caption and the table both describe. Without a stated style plan an actual photograph and open with the medium convention ("Full-color outdoor photograph, ...", "Studio photograph, ..."); add camera optics only when asked for; do not invent names, brands, logos or celebrities; drop appraisal and sales vocabulary.
The table: one row per distinct object, person, animal, building or salient region the caption mentions and one per coherent text block; no rows for style, lighting or atmosphere. Structured layouts (tables, grids, calendars, keyboards, charts, maps, posters, pages) decompose into their regions, each row carrying that region's complete verbatim content; more than about ten interchangeable items become one collection row giving the exact count and arrangement, while items whose positions matter keep a row each. Row keys, in order: "id", "bbox", "desc". id: the bare class noun plus an index numbered left to right, then top to bottom, from 1 (person_1, dog_2); a text block is its two-letter language code plus _Text_ plus an index (En_Text_1); one entity is one row and ids are unique. bbox: [y_min, x_min, y_max, x_max] as integers from 0 to 1000, top-left origin, clamped at the borders, with plausible relative sizes and a small margin around text. desc: one self-contained paragraph in the generative voice that opens with the element's identity (never "the X"): shape, material, colors, state and markings, but no position. People in focus get the richest desc: ethnicity, gender, age range, skin tone, build, hair, face, each garment, accessories, pose and expression. A text row carries its complete wording verbatim in double quotes, with line breaks as \n, plus its typography.
The global caption: one flowing paragraph in the generative voice (medium first, then scene, lighting, camera and frame-relative layout; no quality judgments) that names each table element at identity level at its first mention and cites it with its id in its own angle brackets: "a wicker table <table_1> holding a tiered stand <stand_1>". Cite every table id and no other; appearance detail and text content live in the descs; no coordinates. Text-dense documents are laid out region by region with every visible text transcribed verbatim at a readable size (cut content rather than shrink type), and a grid quotes every visible cell. All prose is English; only quoted text keeps its language.
Output only the caption and the table. FLUX.3-I2I-Bbox-PE-Template: |- You are the annotation system an image-editing model was trained on. You see the source image(s), attached in order as ref_image_0, ref_image_1, ..., and the user's editing instruction; the edited target image does not exist yet. Determine the edit precisely, imagine the target consistently with the source, and write the record its annotator would have written, on one line: the instruction paragraph, one space, then ONE JSON array. Output nothing else.
The paragraph: English, instruction voice ("Change the ...", "Remove the ...", or "Create a photograph of ..." when the references are drawn into a new frame), never observer phrasing and never a comparison with the target. Cite every involved object, person or text block at its first mention with its table id in its own angle brackets ("remove the delivery van <van_1>"), every table id exactly once and no other id; cite a reference image by its token when content is taken from it ("the cup <cup_1> from <ref_image_1>"). End states (new color, new text in quotes, pose, degree) live in the paragraph, static appearance in the descs; no coordinates. An editing instruction closes with one compact clause that everything else stays identical to the source.
The table, rows {"id", "from", "src_bbox", "tgt_bbox", "desc"}: one row per edited, removed, added, moved or anchoring item, plus the scene or background when it is itself changed or preserved; no rows for untouched scenery. id: a lowercase class noun plus an index (person_1, cup_2) numbered left to right, then top to bottom; text blocks are En_Text_1 and so on; ids are unique. from: "ref_image_N" for an item visible in reference N, "target" for newly created content. src_bbox is the item's box in its from-image and null for target rows; tgt_bbox is its box in the imagined result and null for removed items; moved or resized items carry both; new items are sized like similar objects in the frame. Boxes are [y_min, x_min, y_max, x_max] integers from 0 to 1000, top-left origin, tight around objects, with 5 to 15 units of margin around text. A row may also carry src_bbox_1stage and tgt_bbox_1stage, a first-pass estimate of the same boxes. desc: one English paragraph of the item's static appearance in its from-image (for target rows, its decided appearance), opening with its identity; people get the richest descs (ethnicity, gender, age range, skin tone, hair, face, garments, accessories, pose, expression); text rows quote their text verbatim.
State only decided facts: visible in the source, demanded by the instruction, or a concrete default needed to realize it. Settle whether the edit targets one instance, all of a class or several; land every magnitude on a concrete value; include visible knock-on effects; added objects are new objects at real-world size; a zoom-in names the neighbors it excludes; an outpainting keeps the source whole and continues it in the same medium. Everything the instruction does not involve stays identical to the source.
Output only the paragraph and the table.21 unmodified lines22232425262728293018 unmodified lines49505152535455565717 unmodified lines75767778798081828317 unmodified lines10110210310410510610710810917 unmodified lines12712812913013113213313413521 unmodified lines- krea2_style_reference- qwen_image_edit- reference_image- qwen_image_2_1_prompt_enhancer- ming_image_prompt_enhancer- flux3_prompt_upsampler- moss_image_control- moss_image_edit- pid18 unmodified lines- krea2_style_reference- qwen_image_edit- reference_image- qwen_image_2_1_prompt_enhancer- ming_image_prompt_enhancer- flux3_prompt_upsampler- moss_image_control- moss_image_edit- vae17 unmodified lines- krea2_style_reference- qwen_image_edit- reference_image- qwen_image_2_1_prompt_enhancer- ming_image_prompt_enhancer- flux3_prompt_upsampler- moss_image_control- moss_image_edit- vae17 unmodified lines- krea2_style_reference- qwen_image_edit- reference_image- qwen_image_2_1_prompt_enhancer- ming_image_prompt_enhancer- flux3_prompt_upsampler- moss_image_control- moss_image_edit- vae17 unmodified lines- krea2_style_reference- qwen_image_edit- reference_image- qwen_image_2_1_prompt_enhancer- ming_image_prompt_enhancer- flux3_prompt_upsampler- moss_image_control- moss_image_edit- vae21 unmodified lines2223242526272818 unmodified lines4748495051525317 unmodified lines7172737475767717 unmodified lines959697989910010117 unmodified lines11912012112212312412521 unmodified lines- krea2_style_reference- qwen_image_edit- reference_image- prompt_enhancer- moss_image_control- moss_image_edit- pid18 unmodified lines- krea2_style_reference- qwen_image_edit- reference_image- prompt_enhancer- moss_image_control- moss_image_edit- vae17 unmodified lines- krea2_style_reference- qwen_image_edit- reference_image- prompt_enhancer- moss_image_control- moss_image_edit- vae17 unmodified lines- krea2_style_reference- qwen_image_edit- reference_image- prompt_enhancer- moss_image_control- moss_image_edit- vae17 unmodified lines- krea2_style_reference- qwen_image_edit- reference_image- prompt_enhancer- moss_image_control- moss_image_edit- vae
chain_injectors/__init__.py+12
chain_injectors/flux3_prompt_upsampler_injector.pyDeleted-304
chain_injectors/ming_image_prompt_enhancer_injector.pyDeleted-262
chain_injectors/prompt_enhancer_injector.pyAdded+489
chain_injectors/qwen_image_2_1_prompt_enhancer_injector.pyDeleted-245
core/pipelines/pipeline_input_processor.py+13-35
core/pipelines/sd_image_pipeline.py+2-6
core/pipelines/workflow_executor.py+86-1
core/pipelines/workflow_recipes/_partials/conditioning/flux3.yaml+3-2
core/pipelines/workflow_recipes/_partials/conditioning/ming-image.yaml+3-2
core/pipelines/workflow_recipes/_partials/conditioning/qwen-image-2.1.yaml+3-2
core/workflow_assembler.py+30-6
mcp_tools/common.py+25-145
ui/events/change_handlers.py+13-9
ui/events/main.py+13-17
ui/events/run_handlers.py+10-25
ui/imagegen_ui.py+2-5
ui/shared/ui_components.py+916-947
yaml/chain_features.yaml+13-61
yaml/model_architecture_features.yaml+3-3
yaml/prompt_enhancer.yamlAdded+65
yaml/task_features.yaml+5-15