feat: add Qwen-Image-2.1 prompt enhancer
Browse filesFiles changed (17)
- README.md+2
- chain_injectors/qwen_image_2_1_prompt_enhancer_injector.pyAdded+259
- core/model_manager.py+13-6
- core/pipelines/pipeline_input_processor.py+10
- core/pipelines/sd_image_pipeline.py+14
- core/pipelines/workflow_recipes/_partials/conditioning/qwen-image-2.1.yaml+4
- mcp_tools/common.py+23
- ui/events/change_handlers.py+4-2
- ui/events/main.py+9-3
- ui/events/run_handlers.py+7
- ui/imagegen_ui.py+2-1
- ui/shared/ui_components.py+33
- yaml/chain_features.yaml+22
- yaml/file_list.yaml+9-4
- yaml/model_architecture_features.yaml+1
- yaml/model_list.yaml+2-2
- yaml/task_features.yaml+5
171 unmodified lines172173174175176177171 unmodified lines- Qwen/Qwen-Image- Qwen/Qwen-Image-2512- Qwen/Qwen-Image-2.1- Qwen/Qwen-Image-Edit- Qwen/Qwen-Image-Edit-2509- Qwen/Qwen-Image-Edit-2511171 unmodified lines172173174175176177178179171 unmodified lines- Qwen/Qwen-Image- Qwen/Qwen-Image-2512- Qwen/Qwen-Image-2.1- Qwen/Qwen-Image-2.1-PE-I2I- Qwen/Qwen-Image-2.1-PE-T2I- Qwen/Qwen-Image-Edit- Qwen/Qwen-Image-Edit-2509- Qwen/Qwen-Image-Edit-2511
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259"""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) with automatic reasoning tag stripping via RegexReplace (^.*?</think>\\s*) to prevent thought chain text from contaminating downstream image conditioning."""
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 = 512 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. Insert Replace Text (Regex) node if thinking is enabled to strip reasoning tags if thinking_enabled: regex_node_id = assembler._get_unique_id() regex_node = create_node(assembler, "RegexReplace", "Replace Text (Regex)") regex_node['inputs'] = { "string": [text_gen_node_id, 0], "regex_pattern": "^.*?</think>\\s*", "replace": "", "case_insensitive": True, "multiline": False, "dotall": True, "count": 0 } assembler.workflow[regex_node_id] = regex_node target_node['inputs']['prompt'] = [regex_node_id, 0] print(f"[Injector] Qwen-Image-2.1 Prompt Enhancer applied successfully with RegexReplace ({'I2I' if has_load_image else 'T2I'}, clip='{clip_model_name}', thinking=True).") else: 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=False).")1234567811 unmodified lines20212223242526272829303132import gcfrom typing import Listimport gradio as grfrom utils.app_utils import _ensure_model_downloadedfrom core.settings import ALL_MODEL_MAPclass ModelManager:_instance = None11 unmodified linesdef ensure_models_downloaded(self, required_models: List[str], progress):print(f"--- [ModelManager] Ensuring models are downloaded: {required_models} ---")for i, display_name in enumerate(required_models):if progress and hasattr(progress, '__call__'):progress(i / max(len(required_models), 1), desc=f"Checking file: {display_name}")try:_ensure_model_downloaded(display_name, progress)except Exception as e:raise gr.Error(f"Failed to download model '{display_name}'. Reason: {e}")print(f"--- [ModelManager] ✅ All required models are present on disk. ---")model_manager = ModelManager()1234567811 unmodified lines2021222324252627282930313233343536373839import gcfrom typing import Listimport gradio as grfrom utils.app_utils import _ensure_model_downloaded, ensure_file_downloadedfrom core.settings import ALL_MODEL_MAP, ALL_FILE_DOWNLOAD_MAPclass ModelManager:_instance = None11 unmodified linesdef ensure_models_downloaded(self, required_models: List[str], progress):print(f"--- [ModelManager] Ensuring models are downloaded: {required_models} ---")for i, item in enumerate(required_models):if not item:continueif progress and hasattr(progress, '__call__'):progress(i / max(len(required_models), 1), desc=f"Checking file: {item}")try:if item in ALL_MODEL_MAP:_ensure_model_downloaded(item, progress)elif item in ALL_FILE_DOWNLOAD_MAP:ensure_file_downloaded(item, progress)else:_ensure_model_downloaded(item, progress)except Exception as e:raise gr.Error(f"Failed to download model '{item}'. Reason: {e}")print(f"--- [ModelManager] ✅ All required models are present on disk. ---")model_manager = ModelManager()
456 unmodified lines45745845946046146214 unmodified lines477478479480481456 unmodified lines"x": int(xs[i]), "y": int(ys[i]), "strength": float(strengths[i])})return {"active_loras_for_gpu": active_loras_for_gpu,"active_loras_for_meta": active_loras_for_meta,14 unmodified lines"active_qwen_image_edit": active_qwen_image_edit,"active_reference_images": active_reference_images,"active_conditioning": active_conditioning,"temp_files_to_clean": temp_files_to_clean}456 unmodified lines45745845946046146246346446546646746846947047114 unmodified lines486487488489490491456 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', 512))})return {"active_loras_for_gpu": active_loras_for_gpu,"active_loras_for_meta": active_loras_for_meta,14 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,"temp_files_to_clean": temp_files_to_clean}
121 unmodified lines12212312412512612754 unmodified lines18218318418518618725 unmodified lines213214215216217218121 unmodified linesactive_qwen_image_edit = processed.get("active_qwen_image_edit", [])active_reference_images = processed.get("active_reference_images", [])active_conditioning = processed["active_conditioning"]loras_string = f"LoRAs: [{', '.join(active_loras_for_meta)}]" if active_loras_for_meta else ""54 unmodified lines"krea2_style_reference_chain": active_krea2_reference_edit,"qwen_image_edit_chain": active_qwen_image_edit,"reference_image_chain": active_reference_images,"vae_chain": [ui_inputs.get('vae_name')] if (ui_inputs.get('vae_name') and 'vae' in enabled_chains) else [],"hidream_o1_smoothing_chain": hidream_o1_smoothing_data,"pid_chain": [ui_inputs.get('pid_settings', 'OFF')] if is_pid_enabled else [],25 unmodified linesworkflow_inputs['height'] = ui_inputs['height']workflow = assembler.assemble(workflow_inputs)progress(1.0, desc="All models ready. Requesting GPU for generation...")121 unmodified lines12212312412512612712854 unmodified lines18318418518618718818925 unmodified lines215216217218219220221222223224225226227228229230231232121 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", [])loras_string = f"LoRAs: [{', '.join(active_loras_for_meta)}]" if active_loras_for_meta else ""54 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,"vae_chain": [ui_inputs.get('vae_name')] if (ui_inputs.get('vae_name') and 'vae' in enabled_chains) else [],"hidream_o1_smoothing_chain": hidream_o1_smoothing_data,"pid_chain": [ui_inputs.get('pid_settings', 'OFF')] if is_pid_enabled else [],25 unmodified linesworkflow_inputs['height'] = ui_inputs['height']workflow = assembler.assemble(workflow_inputs)post_assembled_models = []for node_id, node in workflow.items():if not isinstance(node, dict):continueinputs = node.get('inputs', {})for k, v in inputs.items():if isinstance(v, str) and v in ALL_FILE_DOWNLOAD_MAP:if v not in required_models and v not in post_assembled_models:post_assembled_models.append(v)if post_assembled_models:self.model_manager.ensure_models_downloaded(post_assembled_models, progress=progress)progress(1.0, desc="All models ready. Requesting GPU for generation...")
69 unmodified lines70717273747569 unmodified linesvae_node: "vae_loader"max_images: 10ui_map:positive_prompt: "prompt:prompt"negative_prompt: "prompt:negative_prompt"69 unmodified lines7071727374757677787969 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"negative_prompt: "prompt:negative_prompt"
669 unmodified lines67067167267367467597 unmodified lines773774775776777778669 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 == "krea2_identity_edit":img = _parse_image_param(item.get("image"))if img:97 unmodified lineselse:ui_inputs["pid_settings"] = "OFF"_TASKS_DB[task_id]["progress"] = 50# Execute Pipeline669 unmodified lines67067167267367467567667767867968068168268368468597 unmodified lines783784785786787788789790791792793794795796797798799800801669 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", 512))elif itype == "krea2_identity_edit":img = _parse_image_param(item.get("image"))if img:97 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", 512))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"] = False_TASKS_DB[task_id]["progress"] = 50# Execute Pipeline
17 unmodified lines1819202122232465 unmodified lines90919293949561 unmodified lines15715815916016116216373 unmodified lines23723823924024124217 unmodified linesload_ipadapter_config)def make_update_fn(m_comp, cat_comp, ar_comp, width_comp, height_comp, cn_types, cn_series, cn_filepaths, anima_cn_types, anima_cn_series, anima_cn_filepaths, diffsynth_cn_types, diffsynth_cn_series, diffsynth_cn_filepaths, krea2_cn_types, krea2_cn_series, krea2_cn_filepaths, ipa_preset, lora_acc, cn_acc, anima_cn_acc, diffsynth_cn_acc, krea2_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):def update_fn(*args):arch = args[0]category = args[1]65 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 ar_comp:res_key = arch_model_type61 unmodified linesreturn update_fndef make_model_change_fn(cat_comp_ref, ar_comp, width_comp, height_comp, cn_types, cn_series, cn_filepaths, anima_cn_types, anima_cn_series, anima_cn_filepaths, diffsynth_cn_types, diffsynth_cn_series, diffsynth_cn_filepaths, krea2_cn_types, krea2_cn_series, krea2_cn_filepaths, arch_comp_ref, ipa_preset, lora_acc, cn_acc, anima_cn_acc, diffsynth_cn_acc, krea2_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):def change_fn(*args):model_name = args[0]idx = 173 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 ar_comp:res_key = arch_model_type17 unmodified lines1819202122232465 unmodified lines9091929394959661 unmodified lines15815916016116216316473 unmodified lines23823924024124224324417 unmodified linesload_ipadapter_config)def make_update_fn(m_comp, cat_comp, ar_comp, width_comp, height_comp, cn_types, cn_series, cn_filepaths, anima_cn_types, anima_cn_series, anima_cn_filepaths, diffsynth_cn_types, diffsynth_cn_series, diffsynth_cn_filepaths, krea2_cn_types, krea2_cn_series, krea2_cn_filepaths, ipa_preset, lora_acc, cn_acc, anima_cn_acc, diffsynth_cn_acc, krea2_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):def update_fn(*args):arch = args[0]category = args[1]65 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 ar_comp:res_key = arch_model_type61 unmodified linesreturn update_fndef make_model_change_fn(cat_comp_ref, ar_comp, width_comp, height_comp, cn_types, cn_series, cn_filepaths, anima_cn_types, anima_cn_series, anima_cn_filepaths, diffsynth_cn_types, diffsynth_cn_series, diffsynth_cn_filepaths, krea2_cn_types, krea2_cn_series, krea2_cn_filepaths, arch_comp_ref, ipa_preset, lora_acc, cn_acc, anima_cn_acc, diffsynth_cn_acc, krea2_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):def change_fn(*args):model_name = args[0]idx = 173 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 ar_comp:res_key = arch_model_type
79 unmodified lines80818283848535 unmodified lines1211221231241251267 unmodified lines13413513613713813914033 unmodified lines17417517617717817912 unmodified lines19219319419519619719887 unmodified lines28628728828929029131 unmodified lines32332432532632732832979 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}')ipa_preset_list = ui_components.get(f'ipadapter_final_preset_{prefix}')35 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 ipa_preset_list: outputs.append(ipa_preset_list)outputs.extend(valid_extra_comps)7 unmodified linesipa_preset_list, lora_accordion, cn_accordion, anima_cn_accordion, diffsynth_cn_accordion, krea2_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)inputs = [arch_comp, cat_comp]if aspect_ratio_comp:33 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 ipa_preset_list: outputs2.append(ipa_preset_list)outputs2.extend(valid_extra_comps)12 unmodified linesarch_comp, ipa_preset_list, lora_accordion, cn_accordion, anima_cn_accordion, diffsynth_cn_accordion, krea2_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)if type_comp:inputs2.append(type_comp)87 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'pid_accordion_{prefix}': 'pid',f'vae_accordion_{prefix}': 'vae',}31 unmodified lines'hidream_o1_reference_accordion_imagegen', 'sensenova_reference_accordion_imagegen', 'joyai_reference_accordion_imagegen','krea2_identity_edit_accordion_imagegen', 'krea2_reference_edit_accordion_imagegen','qwen_image_edit_accordion_imagegen','reference_image_accordion_imagegen', 'pid_accordion_imagegen', 'vae_accordion_imagegen',]for key in accordion_keys:if key in ui_components:79 unmodified lines8081828384858635 unmodified lines1221231241251261271287 unmodified lines13613713813914014114233 unmodified lines17617717817918018118212 unmodified lines19519619719819920020187 unmodified lines28929029129229329429531 unmodified lines32732832933033133233333433579 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}')ipa_preset_list = ui_components.get(f'ipadapter_final_preset_{prefix}')35 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 ipa_preset_list: outputs.append(ipa_preset_list)outputs.extend(valid_extra_comps)7 unmodified linesipa_preset_list, lora_accordion, cn_accordion, anima_cn_accordion, diffsynth_cn_accordion, krea2_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)inputs = [arch_comp, cat_comp]if aspect_ratio_comp:33 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 ipa_preset_list: outputs2.append(ipa_preset_list)outputs2.extend(valid_extra_comps)12 unmodified linesarch_comp, ipa_preset_list, lora_accordion, cn_accordion, anima_cn_accordion, diffsynth_cn_accordion, krea2_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)if type_comp:inputs2.append(type_comp)87 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'pid_accordion_{prefix}': 'pid',f'vae_accordion_{prefix}': 'vae',}31 unmodified lines'hidream_o1_reference_accordion_imagegen', 'sensenova_reference_accordion_imagegen', 'joyai_reference_accordion_imagegen','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','pid_accordion_imagegen', 'vae_accordion_imagegen',]for key in accordion_keys:if key in ui_components:
36 unmodified lines37383940414236 unmodified linesif ui_components.get(f'pid_settings_{prefix}'):run_inputs_map['pid_settings'] = ui_components[f'pid_settings_{prefix}']# Generic / Txt2Img inputsif ui_components.get(f'width_{prefix}') or ui_components.get(f'{prefix}_width'):run_inputs_map['width'] = ui_components.get(f'width_{prefix}') or ui_components.get(f'{prefix}_width')36 unmodified lines3738394041424344454647484936 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}']# Generic / Txt2Img inputsif ui_components.get(f'width_{prefix}') or ui_components.get(f'{prefix}_width'):run_inputs_map['width'] = ui_components.get(f'width_{prefix}') or ui_components.get(f'{prefix}_width')
8 unmodified lines9101112131415174 unmodified lines1901911921931941958 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)default_vals = MODEL_DEFAULTS_CONFIG.get('Default', {})174 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_vae_override_ui(prefix))components.update(create_pid_ui(prefix))components[f'accordion_wrapper_{prefix}'] = accordion_wrapper8 unmodified lines9101112131415174 unmodified lines1901911921931941951968 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)default_vals = MODEL_DEFAULTS_CONFIG.get('Default', {})174 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_vae_override_ui(prefix))components.update(create_pid_ui(prefix))components[f'accordion_wrapper_{prefix}'] = accordion_wrapper
881 unmodified lines882883884885881 unmodified linescomponents[key('all_krea2_reference_edit_components_flat')] = ref_image_inputsreturn components881 unmodified lines882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918881 unmodified linescomponents[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 (Reasoning CoT)",value=False,interactive=True,scale=2)components[key('qwen_image_2_1_prompt_enhancer_max_length')] = gr.Number(label="Max Length",value=512,precision=0,minimum=16,step=16,interactive=True,scale=1)return components
524 unmodified lines525526527524 unmodified linesrequired:- source- embedding_value524 unmodified lines525526527528529530531532533534535536537538539540541542543544545546547548549524 unmodified linesrequired:- 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: 512description: "Maximum generation length for prompt enhancement."
910 unmodified lines91191291391491591689 unmodified lines1006100710081009101010111012101310141015910 unmodified linessource: "hf"repo_id: "Comfy-Org/Ideogram-4"repository_file_path: "text_encoders/qwen3vl_8b_nvfp4.safetensors"# PixelDiT- filename: "gemma_2_2b_it_elm_fp8_scaled.safetensors"source: "hf"89 unmodified linessource: "hf"repo_id: "Comfy-Org/Omnigen2_ComfyUI_repackaged"repository_file_path: "split_files/text_encoders/qwen_2.5_vl_fp16.safetensors"- filename: "qwen3vl_8b_w4a8.safetensors"source: "hf"repo_id: "Comfy-Org/Qwen-Image-2.1"repository_file_path: "text_encoders/qwen3vl_8b_w4a8.safetensors"vae:- filename: "wan_2.1_vae.safetensors"source: "hf"910 unmodified lines91191291391491591691791891992092192292392492589 unmodified lines101510161017101810191020910 unmodified linessource: "hf"repo_id: "Comfy-Org/Ideogram-4"repository_file_path: "text_encoders/qwen3vl_8b_nvfp4.safetensors"# Qwen-Image-2.1 Prompt Enhancers- filename: "qwen3.5_9b_qwen_image_2.1_pe_i2i.int8_convrot.safetensors"source: "hf"repo_id: "Comfy-Org/Qwen-Image-2.1"repository_file_path: "text_encoders/qwen3.5_9b_qwen_image_2.1_pe_i2i.int8_convrot.safetensors"- filename: "qwen3.5_9b_qwen_image_2.1_pe_t2i.int8_convrot.safetensors"source: "hf"repo_id: "Comfy-Org/Qwen-Image-2.1"repository_file_path: "text_encoders/qwen3.5_9b_qwen_image_2.1_pe_t2i.int8_convrot.safetensors"# PixelDiT- filename: "gemma_2_2b_it_elm_fp8_scaled.safetensors"source: "hf"89 unmodified linessource: "hf"repo_id: "Comfy-Org/Omnigen2_ComfyUI_repackaged"repository_file_path: "split_files/text_encoders/qwen_2.5_vl_fp16.safetensors"vae:- filename: "wan_2.1_vae.safetensors"source: "hf"
73 unmodified lines74757677787973 unmodified linesenabled_chains:- lora- reference_imageqwen-image:enabled_chains:73 unmodified lines7475767778798073 unmodified linesenabled_chains:- lora- reference_image- qwen_image_2_1_prompt_enhancerqwen-image:enabled_chains:
18 unmodified lines19202122232425293 unmodified lines31932032132232332432518 unmodified linescomponents:unet: "qwen_image_2.1_int8_convrot.safetensors"vae: "qwen_image_2.1_vae_bf16.safetensors"clip: "qwen3vl_8b_w4a8.safetensors"SenseNova-U1.5:latent_type: hidream_o1_latentmodels:293 unmodified linesunet: "novaAnimeAM_v40.safetensors"vae: "qwen_image_vae.safetensors"clip: "qwen_3_06b_base.safetensors"- display_name: "RAMTHRUST/RAMTHRUST'S-NSFW-PINK-ALCHEMY-ANIMA-v3.1"components:unet: "ramthrustsNSFWPINK_v31RAMSDelicious.safetensors"vae: "qwen_image_vae.safetensors"18 unmodified lines19202122232425293 unmodified lines31932032132232332432518 unmodified linescomponents:unet: "qwen_image_2.1_int8_convrot.safetensors"vae: "qwen_image_2.1_vae_bf16.safetensors"clip: "qwen3vl_8b_nvfp4.safetensors"SenseNova-U1.5:latent_type: hidream_o1_latentmodels:293 unmodified linesunet: "novaAnimeAM_v40.safetensors"vae: "qwen_image_vae.safetensors"clip: "qwen_3_06b_base.safetensors"- display_name: "Crody/RAMTHRUST'S-NSFW-PINK-ALCHEMY-ANIMA-v3.1"components:unet: "ramthrustsNSFWPINK_v31RAMSDelicious.safetensors"vae: "qwen_image_vae.safetensors"
24 unmodified lines25262728293019 unmodified lines50515253545518 unmodified lines74757677787918 unmodified lines989910010110210318 unmodified lines12212312412524 unmodified lines- krea2_style_reference- qwen_image_edit- reference_image- pid- vae19 unmodified lines- krea2_style_reference- qwen_image_edit- reference_image- vaeinpaint:18 unmodified lines- krea2_style_reference- qwen_image_edit- reference_image- vaeoutpaint:18 unmodified lines- krea2_style_reference- qwen_image_edit- reference_image- vaehires_fix:18 unmodified lines- krea2_style_reference- qwen_image_edit- reference_image- vae24 unmodified lines2526272829303119 unmodified lines5152535455565718 unmodified lines7677787980818218 unmodified lines10110210310410510610718 unmodified lines12612712812913024 unmodified lines- krea2_style_reference- qwen_image_edit- reference_image- qwen_image_2_1_prompt_enhancer- pid- vae19 unmodified lines- krea2_style_reference- qwen_image_edit- reference_image- qwen_image_2_1_prompt_enhancer- vaeinpaint:18 unmodified lines- krea2_style_reference- qwen_image_edit- reference_image- qwen_image_2_1_prompt_enhancer- vaeoutpaint:18 unmodified lines- krea2_style_reference- qwen_image_edit- reference_image- qwen_image_2_1_prompt_enhancer- vaehires_fix:18 unmodified lines- krea2_style_reference- qwen_image_edit- reference_image- qwen_image_2_1_prompt_enhancer- vae
README.md+2
chain_injectors/qwen_image_2_1_prompt_enhancer_injector.pyAdded+259
core/model_manager.py+13-6
core/pipelines/pipeline_input_processor.py+10
core/pipelines/sd_image_pipeline.py+14
core/pipelines/workflow_recipes/_partials/conditioning/qwen-image-2.1.yaml+4
mcp_tools/common.py+23
ui/events/change_handlers.py+4-2
ui/events/main.py+9-3
ui/events/run_handlers.py+7
ui/imagegen_ui.py+2-1
ui/shared/ui_components.py+33
yaml/chain_features.yaml+22
yaml/file_list.yaml+9-4
yaml/model_architecture_features.yaml+1
yaml/model_list.yaml+2-2
yaml/task_features.yaml+5