Skip to content

Transform your 3D texturing workflow with the power of generative AI, directly within Blender!

add qwen image 2.1 architecture and configurable prompt templates

sakalond33e8207916fa
diff --git a/stablegen/cameras/geometry.py b/stablegen/cameras/geometry.py
index 26d6d47..03330ff 100644
--- a/stablegen/cameras/geometry.py
+++ b/stablegen/cameras/geometry.py
@@ -791,9 +791,11 @@ def _resolution_from_aspect(aspect, total_px, align=8):
def _get_resolution_align(context):
- """Return the resolution alignment step: 112 for Qwen with alignment
- enabled, 8 otherwise."""
- if (context.scene.model_architecture.startswith('qwen')
+ """Use each Qwen encoder's image grid for camera resolution planning."""
+ architecture = context.scene.model_architecture
+ if architecture == 'qwen_image_21':
+ return 32
+ if (architecture == 'qwen_image_edit'
and getattr(context.scene, 'qwen_rescale_alignment', False)):
return 112
return 8
diff --git a/stablegen/comfy_workflow_export.py b/stablegen/comfy_workflow_export.py
new file mode 100644
index 0000000..ed0b771
--- /dev/null
+++ b/stablegen/comfy_workflow_export.py
@@ -0,0 +1,298 @@
+"""Create editable ComfyUI workflow files from StableGen Qwen 2.1 prompts."""
+
+from __future__ import annotations
+
+from copy import deepcopy
+import uuid
+
+
+_OUTPUTS = {
+ 'UNETLoader': [('MODEL', 'MODEL')],
+ 'CLIPLoader': [('CLIP', 'CLIP')],
+ 'VAELoader': [('VAE', 'VAE')],
+ 'QwenImage21Cache': [('MODEL', 'MODEL')],
+ 'TextEncodeQwenImage21': [
+ ('positive', 'CONDITIONING'),
+ ('negative', 'CONDITIONING'),
+ ('latent', 'LATENT'),
+ ],
+ 'KSampler': [('LATENT', 'LATENT')],
+ 'VAEDecode': [('IMAGE', 'IMAGE')],
+ 'SaveImage': [('images', 'IMAGE')],
+ 'SaveImageWebsocket': [],
+ 'LoadImage': [('IMAGE', 'IMAGE'), ('MASK', 'MASK')],
+ 'ImageScaleToTotalPixels': [('IMAGE', 'IMAGE')],
+}
+
+_WIDGETS = {
+ 'UNETLoader': ['unet_name', 'weight_dtype'],
+ 'CLIPLoader': ['clip_name', 'type', 'device'],
+ 'VAELoader': ['vae_name'],
+ 'QwenImage21Cache': ['device', 'dtype'],
+ 'TextEncodeQwenImage21': ['prompt', 'negative_prompt', 'resolution'],
+ 'KSampler': [
+ 'seed', 'steps', 'cfg', 'sampler_name', 'scheduler', 'denoise'
+ ],
+ 'SaveImage': ['filename_prefix'],
+ 'LoadImage': ['image'],
+ 'ImageScaleToTotalPixels': [
+ 'upscale_method', 'megapixels', 'resolution_steps'
+ ],
+}
+
+_LINK_INPUT_TYPES = {
+ 'QwenImage21Cache': {'model': 'MODEL'},
+ 'TextEncodeQwenImage21': {
+ 'clip': 'CLIP',
+ 'vae': 'VAE',
+ **{f'images.image_{index}': 'IMAGE' for index in range(1, 17)},
+ },
+ 'KSampler': {
+ 'model': 'MODEL',
+ 'positive': 'CONDITIONING',
+ 'negative': 'CONDITIONING',
+ 'latent_image': 'LATENT',
+ },
+ 'VAEDecode': {'samples': 'LATENT', 'vae': 'VAE'},
+ 'SaveImage': {'images': 'IMAGE'},
+ 'ImageScaleToTotalPixels': {'image': 'IMAGE'},
+}
+
+_INPUT_ORDER = {
+ 'QwenImage21Cache': ['model', 'device', 'dtype'],
+ 'TextEncodeQwenImage21': [
+ 'clip', 'images.image_1', 'vae',
+ 'prompt', 'negative_prompt', 'resolution',
+ *[f'images.image_{index}' for index in range(2, 17)],
+ ],
+ 'KSampler': [
+ 'model', 'seed', 'steps', 'cfg', 'sampler_name', 'scheduler',
+ 'positive', 'negative', 'latent_image', 'denoise',
+ ],
+ 'VAEDecode': ['samples', 'vae'],
+ 'SaveImage': ['images', 'filename_prefix'],
+ 'ImageScaleToTotalPixels': [
+ 'upscale_method', 'megapixels', 'resolution_steps', 'image'
+ ],
+}
+
+_WIDGET_TYPES = {
+ 'seed': 'INT',
+ 'steps': 'INT',
+ 'cfg': 'FLOAT',
+ 'denoise': 'FLOAT',
+ 'resolution': 'INT',
+ 'megapixels': 'FLOAT',
+ 'resolution_steps': 'INT',
+ 'prompt': 'STRING',
+ 'negative_prompt': 'STRING',
+ 'filename_prefix': 'STRING',
+}
+
+_POSITIONS = {
+ 'UNETLoader': (0, 0),
+ 'CLIPLoader': (0, 180),
+ 'VAELoader': (0, 360),
+ 'LoadImage': (0, 580),
+ 'ImageScaleToTotalPixels': (330, 650),
+ 'QwenImage21Cache': (360, 0),
+ 'TextEncodeQwenImage21': (360, 220),
+ 'KSampler': (920, 0),
+ 'VAEDecode': (1260, 0),
+ 'SaveImage': (1540, 0),
+}
+
+
+def _is_link(value):
+ return (
+ isinstance(value, list)
+ and len(value) == 2
+ and isinstance(value[0], (str, int))
+ and isinstance(value[1], int)
+ )
+
+
+def _integer_node_id(node_id):
+ try:
+ return int(node_id)
+ except (TypeError, ValueError):
+ return None
+
+
+def _widget_value(class_type, name, api_inputs):
+ if class_type == 'SaveImage' and name == 'filename_prefix':
+ return api_inputs.get(name, 'StableGen_test')
+ return api_inputs.get(name)
+
+
+def _node_size(class_type):
+ if class_type == 'TextEncodeQwenImage21':
+ return [500, 610]
+ if class_type == 'LoadImage':
+ return [300, 300]
+ if class_type == 'KSampler':
+ return [310, 270]
+ return [300, 120]
+
+
+def qwen_image_21_ui_workflow(prompt):
+ """Return a frontend workflow for a Qwen 2.1 API prompt, or ``None``.
+
+ ComfyUI API prompts normally import through ``loadApiJson``. Frontend
+ 1.53.x currently throws while reconstructing Qwen 2.1's COMFY_AUTOGROW_V3
+ image sockets. An explicit UI workflow bypasses that conversion path and
+ remains editable and runnable in the browser.
+ """
+ if not any(
+ node.get('class_type') == 'TextEncodeQwenImage21'
+ for node in prompt.values()
+ if isinstance(node, dict)
+ ):
+ return None
+
+ api_graph = deepcopy(prompt)
+ numeric_ids = [
+ value for value in (_integer_node_id(key) for key in api_graph)
+ if value is not None
+ ]
+ next_id = max(numeric_ids or [0]) + 1
+
+ # The websocket-only output is useful to StableGen but inconvenient in an
+ # interactive graph. Replace it with a normal SaveImage node.
+ for node in api_graph.values():
+ if node.get('class_type') == 'SaveImageWebsocket':
+ node['class_type'] = 'SaveImage'
+ node.setdefault('inputs', {})['filename_prefix'] = 'StableGen_test'
+ node.setdefault('_meta', {})['title'] = 'Save Image'
+
+ nodes = []
+ node_by_id = {}
+ type_offsets = {}
+ for raw_id, api_node in sorted(
+ api_graph.items(),
+ key=lambda item: (_integer_node_id(item[0]) is None,
+ _integer_node_id(item[0]) or 0),
+ ):
+ node_id = _integer_node_id(raw_id)
+ if node_id is None:
+ node_id = next_id
+ next_id += 1
+ class_type = api_node.get('class_type', '')
+ if class_type not in _OUTPUTS:
+ continue
+ api_inputs = api_node.get('inputs', {})
+ widgets = _WIDGETS.get(class_type, [])
+ input_order = _INPUT_ORDER.get(class_type, [])
+ link_types = _LINK_INPUT_TYPES.get(class_type, {})
+ ui_inputs = []
+ for name in input_order:
+ if name in link_types:
+ ui_inputs.append({
+ 'name': name,
+ 'type': link_types[name],
+ 'link': None,
+ **({'shape': 7} if name.startswith('images.') else {}),
+ })
+ elif name in widgets:
+ ui_inputs.append({
+ 'name': name,
+ 'type': _WIDGET_TYPES.get(name, 'COMBO'),
+ 'widget': {'name': name},
+ 'link': None,
+ })
+
+ count = type_offsets.get(class_type, 0)
+ type_offsets[class_type] = count + 1
+ base_x, base_y = _POSITIONS.get(class_type, (0, 0))
+ base_y += count * (360 if class_type == 'LoadImage' else 160)
+
+ outputs = [
+ {'name': name, 'type': output_type, 'links': []}
+ for name, output_type in _OUTPUTS[class_type]
+ ]
+ widget_values = [
+ _widget_value(class_type, name, api_inputs) for name in widgets
+ ]
+ if class_type == 'KSampler':
+ widget_values.insert(1, 'fixed')
+ if class_type == 'LoadImage':
+ widget_values.append('image')
+
+ title = api_node.get('_meta', {}).get('title')
+ ui_node = {
+ 'id': node_id,
+ 'type': class_type,
+ 'pos': [base_x, base_y],
+ 'size': _node_size(class_type),
+ 'flags': {},
+ 'order': len(nodes),
+ 'mode': 0,
+ 'inputs': ui_inputs,
+ 'outputs': outputs,
+ 'properties': {
+ 'Node name for S&R': class_type,
+ # Anything Everywhere releases written for the old group-node
+ # API call GroupNodeHandler.getGroupData for every ordinary
+ # node unless it opts out. Current ComfyUI removed that API,
+ # so imported test workflows otherwise produce a continuous
+ # frontend error even though the graph itself is valid.
+ 'rejects_ue_links': True,
+ },
+ 'widgets_values': widget_values,
+ 'widgets_values_named': {
+ name: _widget_value(class_type, name, api_inputs)
+ for name in widgets
+ },
+ }
+ if title and title != class_type:
+ ui_node['title'] = title
+ nodes.append(ui_node)
+ node_by_id[str(raw_id)] = ui_node
+
+ links = []
+ next_link_id = 1
+ for raw_id, api_node in api_graph.items():
+ target = node_by_id.get(str(raw_id))
+ if target is None:
+ continue
+ class_type = api_node.get('class_type', '')
+ for input_name, value in api_node.get('inputs', {}).items():
+ if not _is_link(value):
+ continue
+ source = node_by_id.get(str(value[0]))
+ if source is None:
+ continue
+ target_slot = next((
+ index for index, spec in enumerate(target['inputs'])
+ if spec['name'] == input_name
+ ), None)
+ source_slot = int(value[1])
+ if target_slot is None or source_slot >= len(source['outputs']):
+ continue
+ link_type = _LINK_INPUT_TYPES.get(class_type, {}).get(input_name)
+ if link_type is None:
+ continue
+ link_id = next_link_id
+ next_link_id += 1
+ target['inputs'][target_slot]['link'] = link_id
+ source['outputs'][source_slot]['links'].append(link_id)
+ links.append([
+ link_id, source['id'], source_slot,
+ target['id'], target_slot, link_type,
+ ])
+
+ return {
+ 'id': str(uuid.uuid4()),
+ 'revision': 0,
+ 'last_node_id': max((node['id'] for node in nodes), default=0),
+ 'last_link_id': max((link[0] for link in links), default=0),
+ 'nodes': nodes,
+ 'links': links,
+ 'groups': [],
+ 'config': {},
+ 'extra': {
+ 'ds': {'scale': 0.75, 'offset': [120.0, 120.0]},
+ 'frontendVersion': '1.53.6',
+ },
+ 'version': 0.4,
+ }
diff --git a/stablegen/core/callbacks.py b/stablegen/core/callbacks.py
index 588b4ea..1b955df 100644
--- a/stablegen/core/callbacks.py
+++ b/stablegen/core/callbacks.py
@@ -22,10 +22,135 @@ from .server_api import (
check_trellis2_available,
)
from ..timeout_config import get_timeout
+from ..texturing.qwen_models import QWEN_PROMPT_TEMPLATE_ITEMS
# ── Architecture-mode helpers ──────────────────────────────────────────────
+_QWEN_DEFAULT_PROMPT_TEMPLATES = {
+ 'qwen_image_edit': 'QWEN_EDIT_LEGACY',
+ 'qwen_image_21': 'QWEN_21_DEFAULT',
+}
+_QWEN_PROMPT_FIELDS = (
+ ('qwen_custom_prompt_initial', True, None),
+ ('qwen_custom_prompt_seq_none', False, 'NONE'),
+ ('qwen_custom_prompt_seq_replace', False, 'REPLACE_STYLE'),
+ ('qwen_custom_prompt_seq_additional', False, 'ADDITIONAL'),
+)
+_qwen_prompt_sync_active = False
+
+
+def _qwen_template_prompt_values(scene, template_id):
+ """Return all editable stage prompts for one prepared template."""
+ from types import SimpleNamespace
+ from ..workflows import WorkflowManager
+
+ context = SimpleNamespace(scene=scene)
+ manager = WorkflowManager(SimpleNamespace())
+ return {
+ field: manager._get_qwen_default_prompts(
+ context,
+ is_initial_image=is_initial,
+ template_id=template_id,
+ context_mode_override=context_mode,
+ )
+ for field, is_initial, context_mode in _QWEN_PROMPT_FIELDS
+ }
+
+
+def refresh_qwen_prompt_template_fields(scene):
+ """Populate editable prompt fields from the selected prepared template."""
+ global _qwen_prompt_sync_active
+ if _qwen_prompt_sync_active:
+ return
+ if getattr(scene, 'model_architecture', '') not in {
+ 'qwen_image_edit', 'qwen_image_21'
+ }:
+ return
+ template_id = getattr(scene, 'qwen_prompt_template', 'CUSTOM')
+ if template_id == 'CUSTOM':
+ return
+ try:
+ values = _qwen_template_prompt_values(scene, template_id)
+ except (AttributeError, ValueError):
+ return
+ _qwen_prompt_sync_active = True
+ try:
+ for field, value in values.items():
+ if getattr(scene, field) != value:
+ setattr(scene, field, value)
+ finally:
+ _qwen_prompt_sync_active = False
+
+
+def update_qwen_prompt_template(self, context):
+ """Refresh visible prompts when the user chooses a prepared template."""
+ if _qwen_prompt_sync_active:
+ return
+ refresh_qwen_prompt_template_fields(context.scene)
+ update_parameters(self, context)
+
+
+def update_qwen_prompt_field(self, context):
+ """Recognize a prepared template after any visible prompt is edited."""
+ global _qwen_prompt_sync_active
+ if _qwen_prompt_sync_active:
+ return
+ scene = context.scene
+ if getattr(scene, 'model_architecture', '') not in {
+ 'qwen_image_edit', 'qwen_image_21'
+ }:
+ update_parameters(self, context)
+ return
+
+ current_values = {
+ field: getattr(scene, field)
+ for field, _is_initial, _context_mode in _QWEN_PROMPT_FIELDS
+ }
+ native_default = _QWEN_DEFAULT_PROMPT_TEMPLATES[scene.model_architecture]
+ candidates = [native_default]
+ candidates.extend(
+ identifier
+ for identifier, _name, _description in QWEN_PROMPT_TEMPLATE_ITEMS
+ if identifier not in {'CUSTOM', native_default}
+ )
+ matched = 'CUSTOM'
+ for template_id in candidates:
+ try:
+ if current_values == _qwen_template_prompt_values(
+ scene, template_id
+ ):
+ matched = template_id
+ break
+ except ValueError:
+ continue
+
+ if scene.qwen_prompt_template != matched:
+ _qwen_prompt_sync_active = True
+ try:
+ scene.qwen_prompt_template = matched
+ finally:
+ _qwen_prompt_sync_active = False
+ update_parameters(self, context)
+
+
+def update_qwen_prompt_dependencies(self, context):
+ """Refresh prepared prompts after settings that change their image roles."""
+ refresh_qwen_prompt_template_fields(context.scene)
+ update_parameters(self, context)
+
+
+def _sync_default_qwen_prompt_template(scene, architecture):
+ """Follow architecture changes only while a native default is selected."""
+ target = _QWEN_DEFAULT_PROMPT_TEMPLATES.get(architecture)
+ if not target or not hasattr(scene, 'qwen_prompt_template'):
+ return
+ current = scene.qwen_prompt_template
+ if current in {
+ '', 'STABLEGEN_DEFAULT', 'QWEN_EDIT_LEGACY', 'QWEN_21_DEFAULT'
+ } and current != target:
+ scene.qwen_prompt_template = target
+
def update_architecture_mode(self, context):
"""Called when the user changes the architecture_mode dropdown."""
scene = context.scene
@@ -43,7 +168,7 @@ def update_architecture_mode(self, context):
def _sync_trellis2_backbone(scene):
"""Pick the right diffusion backbone for the current TRELLIS.2 state."""
tex_mode = getattr(scene, 'trellis2_texture_mode', 'native')
- if tex_mode in ('sdxl', 'flux1', 'qwen_image_edit', 'flux2_klein'):
+ if tex_mode in ('sdxl', 'flux1', 'qwen_image_edit', 'qwen_image_21', 'flux2_klein'):
target = tex_mode
elif getattr(scene, 'trellis2_generate_from', 'image') == 'prompt':
target = getattr(scene, 'trellis2_initial_image_arch', 'sdxl')
@@ -94,6 +219,11 @@ def update_combined(self, context):
# Import lazily to avoid circular ref at module level
from .load_handlers import load_handler
+ _sync_default_qwen_prompt_template(
+ context.scene, context.scene.model_architecture
+ )
+ refresh_qwen_prompt_template_fields(context.scene)
+
prefs = context.preferences.addons[ADDON_PKG].preferences
raw_address = prefs.server_address
diff --git a/stablegen/core/load_handlers.py b/stablegen/core/load_handlers.py
index 2a26295..b691b3c 100644
--- a/stablegen/core/load_handlers.py
+++ b/stablegen/core/load_handlers.py
@@ -25,6 +25,65 @@ def load_handler(dummy):
scene = bpy.context.scene
+ # Builds saved while Qwen-Image 2.1 shared the Qwen-Image-Edit enum need a
+ # one-time architecture migration. The filename is used only here for
+ # compatibility; new generations dispatch exclusively by architecture.
+ from ..texturing.qwen_models import is_qwen_image_21_model
+ saved_model_name = (
+ getattr(scene, "sg_model_name_backup", "")
+ or getattr(scene, "model_name", "")
+ )
+ if not getattr(scene, "sg_qwen_21_architecture_migrated", False):
+ if (getattr(scene, "model_architecture", "") == 'qwen_image_edit'
+ and is_qwen_image_21_model(saved_model_name)):
+ scene.model_architecture = 'qwen_image_21'
+ if getattr(scene, "architecture_mode", "") == 'qwen_image_edit':
+ scene.architecture_mode = 'qwen_image_21'
+ elif getattr(scene, "architecture_mode", "") == 'trellis2':
+ if getattr(scene, "trellis2_texture_mode", "") == 'qwen_image_edit':
+ scene.trellis2_texture_mode = 'qwen_image_21'
+ if getattr(scene, "trellis2_initial_image_arch", "") == 'qwen_image_edit':
+ scene.trellis2_initial_image_arch = 'qwen_image_21'
+ print("[StableGen] Migrated saved Qwen-Image 2.1 model to its dedicated architecture.")
+ scene.sg_qwen_21_architecture_migrated = True
+
+ # The old Qwen UI stored custom/default as a boolean. Preserve that
+ # choice once when opening an existing file, then let the enum be the
+ # single source of truth for both Qwen architectures. Klein continues to
+ # use the legacy boolean and is intentionally excluded.
+ for loaded_scene in bpy.data.scenes:
+ if getattr(loaded_scene, "sg_qwen_prompt_template_migrated", False):
+ continue
+ template_was_saved = loaded_scene.is_property_set(
+ "qwen_prompt_template"
+ )
+ architecture = getattr(loaded_scene, "model_architecture", "")
+ current_template = getattr(
+ loaded_scene, "qwen_prompt_template", ""
+ )
+ if architecture in {'qwen_image_edit', 'qwen_image_21'}:
+ valid_templates = {
+ 'QWEN_EDIT_LEGACY', 'QWEN_21_DEFAULT', 'CANVAS_EDIT',
+ 'REFERENCE_RECONSTRUCTION', 'CONCISE_TRANSFER',
+ 'RESULT_DESCRIPTION', 'CANVAS_AUTHORITY', 'MINIMAL_EDIT',
+ 'CUSTOM',
+ }
+ needs_legacy_migration = (
+ not template_was_saved or current_template not in valid_templates
+ )
+ if (needs_legacy_migration
+ and getattr(
+ loaded_scene, "qwen_use_custom_prompts", False
+ )):
+ loaded_scene.qwen_prompt_template = 'CUSTOM'
+ elif needs_legacy_migration:
+ loaded_scene.qwen_prompt_template = (
+ 'QWEN_21_DEFAULT'
+ if architecture == 'qwen_image_21'
+ else 'QWEN_EDIT_LEGACY'
+ )
+ loaded_scene.sg_qwen_prompt_template_migrated = True
+
# Modal operators and worker sockets cannot survive loading a .blend.
# Older files may nevertheless contain the serialized transient value
# "running" or "waiting", which leaves the Generate button permanently
diff --git a/stablegen/core/properties.py b/stablegen/core/properties.py
index 6ce7270..d287cbf 100644
--- a/stablegen/core/properties.py
+++ b/stablegen/core/properties.py
@@ -17,9 +17,13 @@ from .callbacks import (
update_trellis2_texture_mode,
update_print_preset,
update_print_dithered,
+ update_qwen_prompt_dependencies,
+ update_qwen_prompt_field,
+ update_qwen_prompt_template,
)
from . import ADDON_PKG
from ..feature_flags import TEXTURING_DEFAULTS
+from ..texturing.qwen_models import QWEN_PROMPT_TEMPLATE_ITEMS
# ── Helper(s) used by properties ───────────────────────────────────────────
@@ -318,7 +322,7 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,
)
bpy.types.Scene.model_name = bpy.props.EnumProperty(
name="Model Name",
- description="Select the SDXL checkpoint",
+ description="Select a checkpoint or diffusion model compatible with the selected architecture",
items=update_model_list,
update=update_parameters
)
@@ -328,6 +332,18 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,
default="",
options={'HIDDEN'},
)
+ bpy.types.Scene.sg_qwen_21_architecture_migrated = bpy.props.BoolProperty(
+ name="Qwen 2.1 Architecture Migration Complete",
+ description="Internal: prevents compatibility migration from affecting later architecture changes",
+ default=False,
+ options={'HIDDEN'},
+ )
+ bpy.types.Scene.sg_qwen_prompt_template_migrated = bpy.props.BoolProperty(
+ name="Qwen Prompt Template Migration Complete",
+ description="Internal: records migration from the former custom prompt toggle",
+ default=False,
+ options={'HIDDEN'},
+ )
bpy.types.Scene.seed = bpy.props.IntProperty(
name="Seed",
description="Seed for image generation",
@@ -400,14 +416,22 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,
default=True, update=update_parameters
)
bpy.types.Scene.qwen_rescale_alignment = bpy.props.BoolProperty(
- name="Qwen VL-Aligned Rescale",
- description="Round resolution to multiples of 112 instead of 8 when auto-rescaling. "
- "112 is the window size used by the Qwen2.5-VL vision encoder "
- "(LCM of VAE factor 8, ViT patch 14, spatial merge 28). "
- "The official diffusers pipeline rounds to 32; using 112 is stricter "
- "and may reduce subtle zoom / pixel-shift artifacts in some cases",
+ name="Qwen Image Edit VL-Aligned Rescale",
+ description="For Qwen Image Edit, align auto-rescaled dimensions to the "
+ "112px Qwen2.5-VL vision window instead of 8px. Qwen Image "
+ "2.1 always uses its separate 32px alignment",
default=True, update=update_parameters
)
+ bpy.types.Scene.qwen_image_21_native_rgba = bpy.props.BoolProperty(
+ name="Native RGBA Output",
+ description=(
+ "Wrap Qwen-Image 2.1 prompts with the native transparency instruction. "
+ "When enabled, transparent generated pixels are excluded from texture "
+ "projection. Disable it to let the prompt and model choose the background"
+ ),
+ default=True,
+ update=update_parameters,
+ )
bpy.types.Scene.auto_rescale_target_mp = bpy.props.FloatProperty(
name="Target Megapixels",
description=(
@@ -471,7 +495,7 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,
bpy.types.Scene.sequential_ipadapter = bpy.props.BoolProperty(
name="Use IPAdapter",
description="Uses IPAdapter to improve consistency between images.\n\n - Applicable for Separate, Sequential and Refine modes.\n - Uses either the first generated image or the most recent one as a reference for the rest of the images.\n - If 'Regenerate IPAdapter' is enabled, the first viewpoint will be regenerated with IPAdapter to match the rest of the images.\n - If 'Use IPAdapter (External Image)' is enabled, this setting is effectively overriden.",
- default=False, update=update_parameters
+ default=False, update=update_qwen_prompt_dependencies
)
bpy.types.Scene.sequential_ipadapter_mode = bpy.props.EnumProperty(
name="IPAdapter Mode",
@@ -931,7 +955,8 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,
items=[
('sdxl', 'SDXL', ''),
('flux1', 'FLUX.1', ''),
- ('qwen_image_edit', 'Qwen Image Edit', ''),
+ ('qwen_image_edit', 'Qwen Image Edit', 'Qwen-Image-Edit checkpoints'),
+ ('qwen_image_21', 'Qwen Image 2.1', 'Qwen-Image 2.1 checkpoints'),
('flux2_klein', 'FLUX.2 Klein', '')
],
default='sdxl',
@@ -943,7 +968,8 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,
items=[
('sdxl', 'SDXL', 'Stable Diffusion XL'),
('flux1', 'FLUX.1', 'FLUX.1 architecture'),
- ('qwen_image_edit', 'Qwen Image Edit', 'Qwen Image Edit architecture'),
+ ('qwen_image_edit', 'Qwen Image Edit', 'Qwen-Image-Edit checkpoints'),
+ ('qwen_image_21', 'Qwen Image 2.1', 'Qwen-Image 2.1 checkpoints'),
('flux2_klein', 'FLUX.2 Klein', 'FLUX.2 Klein multi-reference edit model (Apache 2.0)'),
('trellis2', 'TRELLIS.2', 'Image to 3D mesh generation with TRELLIS.2'),
],
@@ -967,7 +993,8 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,
('native', 'Native (TRELLIS.2)', 'Use TRELLIS.2 built-in texture generation'),
('sdxl', 'SDXL', 'Use SDXL for camera-based texture projection'),
('flux1', 'FLUX.1', 'Use FLUX.1 for camera-based texture projection'),
- ('qwen_image_edit', 'Qwen Image Edit', 'Use Qwen for camera-based texture projection'),
+ ('qwen_image_edit', 'Qwen Image Edit', 'Use Qwen-Image-Edit for camera-based texture projection'),
+ ('qwen_image_21', 'Qwen Image 2.1', 'Use Qwen-Image 2.1 for camera-based texture projection'),
('flux2_klein', 'FLUX.2 Klein', 'Use FLUX.2 Klein for camera-based texture projection'),
],
default='native', update=update_trellis2_texture_mode
@@ -978,7 +1005,8 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,
items=[
('sdxl', 'SDXL', 'Stable Diffusion XL'),
('flux1', 'FLUX.1', 'FLUX.1 architecture'),
- ('qwen_image_edit', 'Qwen Image Edit', 'Qwen Image Edit architecture'),
+ ('qwen_image_edit', 'Qwen Image Edit', 'Qwen-Image-Edit'),
+ ('qwen_image_21', 'Qwen Image 2.1', 'Qwen-Image 2.1'),
('flux2_klein', 'FLUX.2 Klein', 'FLUX.2 Klein multi-reference edit'),
],
default='sdxl', update=update_trellis2_initial_image_arch
@@ -1118,7 +1146,7 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,
bpy.types.Scene.qwen_use_external_style_image = bpy.props.BoolProperty(
name="Use External Style Image",
description="Use a separate, external image as the style reference for all viewpoints",
- default=False, update=update_parameters
+ default=False, update=update_qwen_prompt_dependencies
)
bpy.types.Scene.qwen_external_style_image = bpy.props.StringProperty(
name="Style Reference Image", description="Path to the external style reference image",
@@ -1127,36 +1155,43 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,
bpy.types.Scene.qwen_external_style_initial_only = bpy.props.BoolProperty(
name="External for Initial Only",
description="Use the external style image for the first image, then use the previously generated image for subsequent images",
- default=False, update=update_parameters
+ default=False, update=update_qwen_prompt_dependencies
)
bpy.types.Scene.qwen_use_custom_prompts = bpy.props.BoolProperty(
name="Use Custom Qwen Prompts",
- description="Enable to override the default guidance prompts for the Qwen Image Edit workflow",
+ description="Legacy custom prompt control retained for saved files and FLUX.2 Klein",
default=False, update=update_parameters
)
+ bpy.types.Scene.qwen_prompt_template = bpy.props.EnumProperty(
+ name="Prompt Template",
+ description="Prepared guidance wording used by Qwen Image Edit and Qwen Image 2.1",
+ items=QWEN_PROMPT_TEMPLATE_ITEMS,
+ default='QWEN_EDIT_LEGACY',
+ update=update_qwen_prompt_template,
+ )
bpy.types.Scene.qwen_custom_prompt_initial = bpy.props.StringProperty(
name="Initial Image Prompt",
description="Custom prompt for the first generated image. Use {main_prompt} to insert the main prompt text.",
default="Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2",
- update=update_parameters
+ update=update_qwen_prompt_field
)
bpy.types.Scene.qwen_custom_prompt_seq_none = bpy.props.StringProperty(
name="Sequential Prompt (No Context)",
description="Custom prompt for subsequent images when Context Render is 'Disabled'. Use {main_prompt} to insert the main prompt text.",
default="Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2",
- update=update_parameters
+ update=update_qwen_prompt_field
)
bpy.types.Scene.qwen_custom_prompt_seq_replace = bpy.props.StringProperty(
name="Sequential Prompt (Replace Style)",
description="Custom prompt for subsequent images when Context Render is 'Replace Style'. Use {main_prompt} to insert the main prompt text.",
default="Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.",
- update=update_parameters
+ update=update_qwen_prompt_field
)
bpy.types.Scene.qwen_custom_prompt_seq_additional = bpy.props.StringProperty(
name="Sequential Prompt (Additional Context)",
description="Custom prompt for subsequent images when Context Render is 'Additional Context'. Use {main_prompt} to insert the main prompt text.",
default="Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.",
- update=update_parameters
+ update=update_qwen_prompt_field
)
bpy.types.Scene.qwen_guidance_fallback_color = bpy.props.FloatVectorProperty(
name="Guidance Fallback Color", description="Color used for fallback regions in the Qwen context render",
@@ -1243,7 +1278,7 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,
bpy.types.Scene.qwen_prompt_gray_background = bpy.props.BoolProperty(
name="Gray Background Prompt",
description="Include 'Replace the background with solid gray' in the default context-render prompt. Disable to let the model choose the background freely",
- default=True, update=update_parameters
+ default=True, update=update_qwen_prompt_dependencies
)
# ── Misc ───────────────────────────────────────────────────────────
@@ -1419,12 +1454,12 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,
bpy.types.Scene.qwen_use_trellis2_style = bpy.props.BoolProperty(
name="Use TRELLIS.2 Input as Style",
description="Use the TRELLIS.2 input image as the Qwen style reference",
- default=False, update=update_parameters
+ default=False, update=update_qwen_prompt_dependencies
)
bpy.types.Scene.qwen_trellis2_style_initial_only = bpy.props.BoolProperty(
name="TRELLIS.2 Style for Initial Only",
description="Use the TRELLIS.2 input image only for the first image, then fall back to sequential style for subsequent images",
- default=False, update=update_parameters
+ default=False, update=update_qwen_prompt_dependencies
)
bpy.types.Scene.trellis2_pipeline_active = bpy.props.BoolProperty(
name="TRELLIS.2 Pipeline Active",
diff --git a/stablegen/core/server_api.py b/stablegen/core/server_api.py
index 8d55148..c137ae6 100644
--- a/stablegen/core/server_api.py
+++ b/stablegen/core/server_api.py
@@ -191,6 +191,15 @@ def fetch_from_comfyui_api(context, endpoint):
return []
+def fetch_diffusion_models(server_address):
+ """Merge optional GGUF and standard diffusion-model folders independently."""
+ gguf = _fetch_api_list(server_address, '/models/unet_gguf')
+ diffusion = _fetch_api_list(server_address, '/models/diffusion_models')
+ if gguf is None and diffusion is None:
+ return None
+ return sorted(set((gguf or []) + (diffusion or [])))
+
+
def _fetch_api_list(server_address, endpoint):
"""Thread-safe variant of *fetch_from_comfyui_api* — takes an explicit
*server_address* instead of reading from bpy context, so it can run in a
diff --git a/stablegen/dae_import/batch_texture.py b/stablegen/dae_import/batch_texture.py
index 0e82b1e..e79a934 100644
--- a/stablegen/dae_import/batch_texture.py
+++ b/stablegen/dae_import/batch_texture.py
@@ -491,7 +491,7 @@ def _do_set_ref_image():
if arch == 'sdxl':
scene.use_ipadapter = True
scene.ipadapter_image = ref
- elif arch in ('qwen_image_edit', 'flux2_klein'):
+ elif arch in ('qwen_image_edit', 'qwen_image_21', 'flux2_klein'):
scene.qwen_use_external_style_image = True
scene.qwen_external_style_image = ref
elif arch == 'flux1':
diff --git a/stablegen/mesh_gen/trellis2.py b/stablegen/mesh_gen/trellis2.py
index 29a9a9e..0ce7189 100644
--- a/stablegen/mesh_gen/trellis2.py
+++ b/stablegen/mesh_gen/trellis2.py
@@ -1338,7 +1338,7 @@ class Trellis2Generate(bpy.types.Operator):
# 3-tier progress init
has_txt2img = (gen_from == 'prompt')
- has_texturing = (tex_mode in ('sdxl', 'flux1', 'qwen_image_edit', 'flux2_klein'))
+ has_texturing = (tex_mode in ('sdxl', 'flux1', 'qwen_image_edit', 'qwen_image_21', 'flux2_klein'))
has_autorig = bool(getattr(scene, 'trellis2_autorig_enabled', False))
if has_txt2img and has_autorig and has_texturing:
self._total_phases = 4
@@ -1754,7 +1754,7 @@ class Trellis2Generate(bpy.types.Operator):
self._setup_studio_lighting(context, target_bu)
# --- Phase 3: If diffusion texturing, auto-place cameras + start generation ---
- if tex_mode in ('sdxl', 'flux1', 'qwen_image_edit', 'flux2_klein'):
+ if tex_mode in ('sdxl', 'flux1', 'qwen_image_edit', 'qwen_image_21', 'flux2_klein'):
# Place cameras NOW (while operator context is still valid)
camera_count = getattr(context.scene, 'trellis2_camera_count', 8)
imported_objects = [obj for obj in context.selected_objects]
diff --git a/stablegen/prompt_archive.py b/stablegen/prompt_archive.py
index 881b136..61858ed 100644
--- a/stablegen/prompt_archive.py
+++ b/stablegen/prompt_archive.py
@@ -8,6 +8,19 @@ from pathlib import Path
import re
from typing import Mapping
+try:
+ from .comfy_workflow_export import qwen_image_21_ui_workflow
+except ImportError: # Standalone unit-test import without loading Blender package.
+ import importlib.util
+ _converter_path = Path(__file__).with_name("comfy_workflow_export.py")
+ _converter_spec = importlib.util.spec_from_file_location(
+ "stablegen_comfy_workflow_export", _converter_path
+ )
+ _converter_module = importlib.util.module_from_spec(_converter_spec)
+ assert _converter_spec.loader is not None
+ _converter_spec.loader.exec_module(_converter_module)
+ qwen_image_21_ui_workflow = _converter_module.qwen_image_21_ui_workflow
+
_UNSAFE_FILENAME_CHARS = re.compile(r"[^A-Za-z0-9._-]+")
@@ -42,6 +55,7 @@ def archive_prompt(
submissions for the same view receive a numeric suffix.
"""
output_path = Path(output_dir)
+ editable_workflow = qwen_image_21_ui_workflow(prompt)
latest_path = output_path / "prompt.json"
archive_dir = output_path / "prompts"
@@ -62,6 +76,16 @@ def archive_prompt(
archive_path = archive_dir / f"{stem}_{suffix:02d}.json"
suffix += 1
- _write_json_atomic(latest_path, prompt)
- _write_json_atomic(archive_path, prompt)
+ if editable_workflow is None:
+ _write_json_atomic(latest_path, prompt)
+ _write_json_atomic(archive_path, prompt)
+ else:
+ # ``prompt.json`` remains the file users can drag into ComfyUI. Keep
+ # the exact backend graph beside it for API/debug use.
+ api_latest_path = output_path / "prompt_api.json"
+ api_archive_path = archive_dir / f"{archive_path.stem}_api.json"
+ _write_json_atomic(latest_path, editable_workflow)
+ _write_json_atomic(archive_path, editable_workflow)
+ _write_json_atomic(api_latest_path, prompt)
+ _write_json_atomic(api_archive_path, prompt)
return latest_path, archive_path
diff --git a/stablegen/texturing/generator.py b/stablegen/texturing/generator.py
index 575bae7..ec86cb9 100644
--- a/stablegen/texturing/generator.py
+++ b/stablegen/texturing/generator.py
@@ -26,7 +26,7 @@ from gpu_extras.batch import batch_for_shader # pylint: disable=import-error
from ..util.workflow_templates import prompt_text, prompt_text_img2img, prompt_text_qwen_image_edit
from .rendering import export_emit_image, export_visibility, export_canny, bake_texture, prepare_baking, unwrap, export_render, export_viewport, render_edge_feather_mask, apply_uv_inpaint_texture, flatten_projection_material_for_refine, _RenderStateTransaction, _legacy_render_dither, _prepare_compositor_render, _finish_compositor_render
-from ..cameras.geometry import _SGCameraResolution, _get_camera_resolution
+from ..cameras.geometry import _SGCameraResolution, _get_camera_resolution, _get_resolution_align
from ..cameras.overlays import _sg_restore_square_display, _sg_remove_crop_overlay, _sg_ensure_crop_overlay, _sg_hide_label_overlay, _sg_restore_label_overlay
from .projection import project_image, reinstate_compare_nodes, _bake_visibility_weights, reset_projection_material_nodes, _is_projection_mesh
from ..utils import get_last_material_index, get_generation_dirs, get_file_path, get_dir_path, remove_empty_dirs, get_compositor_node_tree, configure_output_node_paths, get_eevee_engine_id, sg_modal_active
@@ -471,6 +471,11 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
if context.scene.qwen_context_render_mode in {'REPLACE_STYLE', 'ADDITIONAL'}:
fallback = tuple(context.scene.qwen_guidance_fallback_color)
background = tuple(context.scene.qwen_guidance_background_color)
+ if context.scene.model_architecture == 'qwen_image_21':
+ # Qwen 2.1 VAE-encodes projected context as its edit target and
+ # otherwise preserves a magenta canvas. Keep magenta only for
+ # unknown surface regions and make the outer background neutral.
+ background = (0.5, 0.5, 0.5)
return fallback, background
def _apply_qwen_binary_context_mask(self, context, camera_id, fallback_color):
@@ -796,7 +801,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
else:
print("[StableGen] Standard texturing; no research options active")
- if context.scene.model_architecture in ('qwen_image_edit', 'flux2_klein') and not context.scene.generation_mode == 'project_only':
+ if context.scene.model_architecture in ('qwen_image_edit', 'qwen_image_21', 'flux2_klein') and not context.scene.generation_mode == 'project_only':
context.scene.generation_method = 'sequential' # Force sequential for edit models
render = bpy.context.scene.render
@@ -815,16 +820,11 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
resolution_y = render.resolution_y
total_pixels = resolution_x * resolution_y
- # Qwen Image Edit benefits from 112-aligned resolution (LCM of VAE=8,
- # ViT patch=14, spatial merge=2×14=28, ViT window=112) to avoid
- # subtle pixel shifts between the latent, VAE and CLIP grids.
- # FLUX.2 Klein uses 16x latent downscale, so 16-aligned is needed.
- use_qwen_alignment = (
- context.scene.model_architecture.startswith('qwen')
- and getattr(context.scene, 'qwen_rescale_alignment', False)
- )
- if use_qwen_alignment:
- align_step = 112
+ # Qwen Image Edit's optional 112px grid follows Qwen2.5-VL; Qwen
+ # Image 2.1 uses Qwen3-VL and ComfyUI's native 32px image grid.
+ # FLUX.2 Klein uses 16x latent downscale.
+ if context.scene.model_architecture.startswith('qwen'):
+ align_step = _get_resolution_align(context)
elif context.scene.model_architecture == 'flux2_klein':
align_step = 16
else:
@@ -1363,7 +1363,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
applicable = (
getattr(self, '_generation_method_on_start', None) == 'sequential'
- or context.scene.model_architecture in ('qwen_image_edit', 'flux2_klein')
+ or context.scene.model_architecture in ('qwen_image_edit', 'qwen_image_21', 'flux2_klein')
)
reset_angle = (
context.scene.discard_factor_after_generation
@@ -1560,7 +1560,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
need_depth = (
any(u["unit_type"] == "depth" for u in controlnet_units)
or (context.scene.use_flux_lora and context.scene.model_architecture == 'flux1')
- or (context.scene.model_architecture in ('qwen_image_edit', 'flux2_klein')
+ or (context.scene.model_architecture in ('qwen_image_edit', 'qwen_image_21', 'flux2_klein')
and context.scene.qwen_guidance_map_type == 'depth')
or (context.scene.model_architecture.startswith('qwen')
and context.scene.qwen_generation_method in ('refine', 'local_edit')
@@ -1609,7 +1609,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
need_normal = (
any(u["unit_type"] == "normal" for u in controlnet_units)
- or (context.scene.model_architecture in ('qwen_image_edit', 'flux2_klein')
+ or (context.scene.model_architecture in ('qwen_image_edit', 'qwen_image_21', 'flux2_klein')
and context.scene.qwen_guidance_map_type == 'normal')
)
if need_normal and context.scene.generation_method != 'uv_inpaint':
@@ -1630,10 +1630,15 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
return
# Qwen guidance using Workbench
- if (context.scene.model_architecture in ('qwen_image_edit', 'flux2_klein')
+ if (context.scene.model_architecture in ('qwen_image_edit', 'qwen_image_21', 'flux2_klein')
and context.scene.qwen_guidance_map_type == 'workbench'
and context.scene.generation_method != 'uv_inpaint'):
workbench_dir = get_dir_path(context, "controlnet")["workbench"]
+ guide_background = (
+ (0.5, 0.5, 0.5)
+ if context.scene.model_architecture == 'qwen_image_21'
+ else None
+ )
for i, camera in enumerate(cameras):
self._stage = f"Rendering Workbench ({i+1}/{len(cameras)})"
_i, _cam = i, camera
@@ -1641,7 +1646,8 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
self._activate_view(context, _i)
with _SGCameraResolution(context, _cam):
export_render(context, camera_id=_i,
- output_dir=workbench_dir, filename=f"render{_i}")
+ output_dir=workbench_dir, filename=f"render{_i}",
+ background_color=guide_background)
self._run_on_main_thread(_render_wb)
if self._error:
return
@@ -1652,10 +1658,15 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
return
# Qwen guidance using Viewport
- elif (context.scene.model_architecture in ('qwen_image_edit', 'flux2_klein')
+ elif (context.scene.model_architecture in ('qwen_image_edit', 'qwen_image_21', 'flux2_klein')
and context.scene.qwen_guidance_map_type == 'viewport'
and context.scene.generation_method != 'uv_inpaint'):
viewport_dir = get_dir_path(context, "controlnet")["viewport"]
+ guide_background = (
+ (0.5, 0.5, 0.5)
+ if context.scene.model_architecture == 'qwen_image_21'
+ else None
+ )
for i, camera in enumerate(cameras):
self._stage = f"Rendering Viewport ({i+1}/{len(cameras)})"
_i, _cam = i, camera
@@ -1663,7 +1674,8 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
self._activate_view(context, _i)
with _SGCameraResolution(context, _cam):
export_viewport(context, camera_id=_i,
- output_dir=viewport_dir, filename=f"viewport{_i}")
+ output_dir=viewport_dir, filename=f"viewport{_i}",
+ background_color=guide_background)
self._run_on_main_thread(_render_vp)
if self._error:
return
@@ -1847,7 +1859,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
if self._current_image == 0:
if context.scene.model_architecture == 'flux1':
image = self.workflow_manager.generate_flux(context, controlnet_info=controlnet_info, ipadapter_ref_info=ipadapter_ref_info)
- elif context.scene.model_architecture == 'qwen_image_edit':
+ elif context.scene.model_architecture in ('qwen_image_edit', 'qwen_image_21'):
image = self.workflow_manager.generate_qwen_edit(context, camera_id=camera_id)
elif context.scene.model_architecture == 'flux2_klein':
image = self.workflow_manager.generate_flux2_klein(context, camera_id=camera_id)
@@ -1880,7 +1892,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
)
_emit_cam = _cur_cam
with _SGCameraResolution(context, _emit_cam):
- if context.scene.model_architecture in ('qwen_image_edit', 'flux2_klein'): # export custom bg and fallback for Qwen/Klein image edit
+ if context.scene.model_architecture in ('qwen_image_edit', 'qwen_image_21', 'flux2_klein'): # export custom bg and fallback for Qwen/Klein image edit
fallback_color, background_color = self._get_qwen_context_colors(context)
export_emit_image(context, self._to_texture, camera_id=self._current_image, bg_color=background_color, fallback_color=fallback_color) # Export render for next view
if getattr(context.scene, 'qwen_use_confidence_context', False):
@@ -1915,7 +1927,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
if context.scene.model_architecture == 'flux1':
image = self.workflow_manager.refine_flux(context, controlnet_info=controlnet_info, render_info=render_info, mask_info=mask_info, ipadapter_ref_info=ipadapter_ref_info)
- elif context.scene.model_architecture == 'qwen_image_edit':
+ elif context.scene.model_architecture in ('qwen_image_edit', 'qwen_image_21'):
image = self.workflow_manager.generate_qwen_edit(context, camera_id=camera_id)
elif context.scene.model_architecture == 'flux2_klein':
image = self.workflow_manager.generate_flux2_klein(context, camera_id=camera_id)
@@ -1924,7 +1936,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
else: # Grid or Separate
if context.scene.model_architecture == 'flux1':
image = self.workflow_manager.generate_flux(context, controlnet_info=controlnet_info, ipadapter_ref_info=ipadapter_ref_info)
- elif context.scene.model_architecture == 'qwen_image_edit':
+ elif context.scene.model_architecture in ('qwen_image_edit', 'qwen_image_21'):
image = self.workflow_manager.generate_qwen_edit(context, camera_id=camera_id)
elif context.scene.model_architecture == 'flux2_klein':
image = self.workflow_manager.generate_flux2_klein(context, camera_id=camera_id)
@@ -1936,7 +1948,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
self._error = "Connection to ComfyUI server failed."
return # Error message set
- if (context.scene.model_architecture in ('qwen_image_edit', 'flux2_klein')
+ if (context.scene.model_architecture in ('qwen_image_edit', 'qwen_image_21', 'flux2_klein')
and context.scene.generation_method == 'sequential'
and self._current_image > 0
and not getattr(context.scene, 'qwen_use_confidence_context', False)
@@ -1955,7 +1967,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
with open(image_path, 'wb') as f:
f.write(image)
- if (context.scene.model_architecture == 'qwen_image_edit'
+ if (context.scene.model_architecture.startswith('qwen')
and context.scene.generation_method == 'sequential'
and self._current_image > 0):
fallback_color, _ = self._get_qwen_context_colors(context)
@@ -2704,7 +2716,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
is_recent_mode_ref = (
file_type == "generated" and
context.scene.sequential_ipadapter_mode == 'recent' and
- (context.scene.sequential_ipadapter or context.scene.model_architecture in ('qwen_image_edit', 'flux2_klein'))
+ (context.scene.sequential_ipadapter or context.scene.model_architecture in ('qwen_image_edit', 'qwen_image_21', 'flux2_klein'))
)
temp_image_path = None
diff --git a/stablegen/texturing/graph_validation.py b/stablegen/texturing/graph_validation.py
index f7c9b26..527cf67 100644
--- a/stablegen/texturing/graph_validation.py
+++ b/stablegen/texturing/graph_validation.py
@@ -36,11 +36,15 @@ def validate_workflow_graph(prompt: Mapping, semantic_node_ids=()) -> list[str]:
issues.append(f"semantic text encoder node {node_id} is missing")
continue
inputs = node.get("inputs", {})
- slots = {
- key: tuple(inputs[key])
- for key in ("image1", "image2", "image3")
- if key in inputs and _is_node_reference(inputs[key])
- }
+ slot_names = ("image1", "image2", "image3")
+ # Qwen-Image-Edit exposes fixed image1/image2/image3 sockets. Qwen
+ # Image 2.1 uses ComfyUI's dynamic images.image_N sockets instead.
+ slots = {}
+ for index, legacy_name in enumerate(slot_names, 1):
+ dynamic_name = f"images.image_{index}"
+ key = dynamic_name if dynamic_name in inputs else legacy_name
+ if key in inputs and _is_node_reference(inputs[key]):
+ slots[legacy_name] = tuple(inputs[key])
reverse = {}
for slot, reference in slots.items():
reverse.setdefault(reference, []).append(slot)
diff --git a/stablegen/texturing/projection.py b/stablegen/texturing/projection.py
index f044c59..e2b6506 100644
--- a/stablegen/texturing/projection.py
+++ b/stablegen/texturing/projection.py
@@ -47,6 +47,19 @@ def _scene_projection_scale(context):
)
+def _multiply_projection_weight_by_alpha(
+ nodes, links, weight_node, image_node, label
+):
+ """Return a projection weight multiplied by an image's alpha channel."""
+ alpha_weighted = nodes.new("ShaderNodeMath")
+ alpha_weighted.operation = 'MULTIPLY'
+ alpha_weighted.label = label
+ links.new(weight_node.outputs[0], alpha_weighted.inputs[0])
+ links.new(image_node.outputs["Alpha"], alpha_weighted.inputs[1])
+ return alpha_weighted
+
+
+
def _camera_world_location(camera):
@@ -1710,6 +1723,7 @@ def project_image(
getattr(context.scene, 'qwen_use_confidence_context', False),
experimental_enabled(context.scene, 'qwen_use_projection_write_masks'),
context.scene.model_architecture == 'sdxl',
+ context.scene.model_architecture == 'qwen_image_21',
))
legacy_incremental_update = (
((context.scene.generation_method == 'sequential' and stop_index > 0)
@@ -1929,12 +1943,12 @@ def project_image(
return guard_weight
# Voronoi mode flag: keep natural weights for non-generated cameras
- voronoi_active = (context.scene.model_architecture in ('qwen_image_edit', 'flux2_klein')
+ voronoi_active = (context.scene.model_architecture in ('qwen_image_edit', 'qwen_image_21', 'flux2_klein')
and getattr(context.scene, 'qwen_voronoi_mode', False)
and context.scene.generation_method == 'sequential')
confidence_context_active = (
getattr(context.scene, 'qwen_use_confidence_context', False)
- and context.scene.model_architecture == 'qwen_image_edit'
+ and context.scene.model_architecture.startswith('qwen')
and context.scene.generation_method == 'sequential'
and context.scene.qwen_generation_method == 'generate'
and context.scene.qwen_context_render_mode
@@ -2308,7 +2322,7 @@ def project_image(
use_qwen_write_mask = (
i > 0
and i <= stop_index
- and context.scene.model_architecture == 'qwen_image_edit'
+ and context.scene.model_architecture.startswith('qwen')
and context.scene.generation_method == 'sequential'
and context.scene.qwen_generation_method == 'generate'
and context.scene.qwen_context_render_mode in {'REPLACE_STYLE', 'ADDITIONAL'}
@@ -2318,6 +2332,10 @@ def project_image(
use_sdxl_write_mask = (
i > 0 and i <= stop_index and (context.scene.model_architecture == 'sdxl') and (context.scene.generation_method == 'sequential')
)
+ use_qwen21_generated_alpha = (
+ i <= stop_index
+ and context.scene.model_architecture == 'qwen_image_21'
+ )
if (use_qwen_write_mask or use_sdxl_write_mask) and script_nodes_outputs:
current_weight = script_nodes_outputs[-1]
if not isinstance(current_weight, tuple):
@@ -2335,14 +2353,20 @@ def project_image(
links.new(write_weight.outputs[0], masked_weight.inputs[1])
script_nodes_outputs[-1] = masked_weight
- if (use_sdxl_write_mask and script_nodes_outputs
+ if ((use_sdxl_write_mask or use_qwen21_generated_alpha)
+ and script_nodes_outputs
and not isinstance(script_nodes_outputs[-1], tuple)):
- alpha_weighted = nodes.new("ShaderNodeMath")
- alpha_weighted.operation = 'MULTIPLY'
- alpha_weighted.label = f"SDXLFeatherAlpha-{i}-{mat_id}"
- links.new(script_nodes_outputs[-1].outputs[0], alpha_weighted.inputs[0])
- links.new(tex_image_nodes[i].outputs["Alpha"], alpha_weighted.inputs[1])
- script_nodes_outputs[-1] = alpha_weighted
+ script_nodes_outputs[-1] = _multiply_projection_weight_by_alpha(
+ nodes,
+ links,
+ script_nodes_outputs[-1],
+ tex_image_nodes[i],
+ (
+ f"Qwen21GeneratedAlpha-{i}-{mat_id}"
+ if use_qwen21_generated_alpha
+ else f"SDXLFeatherAlpha-{i}-{mat_id}"
+ ),
+ )
if script_nodes_outputs and not isinstance(script_nodes_outputs[-1], tuple):
guard_weight = _create_projection_guard_weight(i, mat_id)
diff --git a/stablegen/texturing/qwen_models.py b/stablegen/texturing/qwen_models.py
new file mode 100644
index 0000000..22a6342
--- /dev/null
+++ b/stablegen/texturing/qwen_models.py
@@ -0,0 +1,274 @@
+"""Model-family detection and defaults for StableGen's Qwen workflows."""
+
+from __future__ import annotations
+
+import re
+
+
+QWEN_IMAGE_21_TEXT_ENCODER = "qwen3vl_8b_w4a8.safetensors"
+QWEN_IMAGE_21_VAE = "qwen_image_2.1_vae_bf16.safetensors"
+QWEN_IMAGE_EDIT_ARCHITECTURE = "qwen_image_edit"
+QWEN_IMAGE_21_ARCHITECTURE = "qwen_image_21"
+QWEN_IMAGE_21_RGBA_PREFIX = "This is an RGBA format image with transparency."
+QWEN_IMAGE_21_RGBA_SUFFIX = (
+ "The image has an alpha channel and a transparent background."
+)
+
+QWEN_PROMPT_TEMPLATE_ITEMS = (
+ (
+ "QWEN_EDIT_LEGACY",
+ "Qwen Image Edit Legacy",
+ "Use the original StableGen Qwen-Image-Edit transfer wording",
+ ),
+ (
+ "QWEN_21_DEFAULT",
+ "Qwen 2.1 Default",
+ "Use the newer Qwen-Image 2.1 create-and-guide wording used by the sampler tests",
+ ),
+ (
+ "CANVAS_EDIT",
+ "Canvas Edit",
+ "Treat the target view as the canvas and transfer appearance while preserving its geometry",
+ ),
+ (
+ "REFERENCE_RECONSTRUCTION",
+ "Reference Reconstruction",
+ "Reconstruct the requested subject in the target view using explicit image roles",
+ ),
+ (
+ "CONCISE_TRANSFER",
+ "Concise Transfer",
+ "Use a short appearance-transfer instruction with strong target-view preservation",
+ ),
+ (
+ "RESULT_DESCRIPTION",
+ "Result Description",
+ "Describe the desired result while assigning structure and appearance references",
+ ),
+ (
+ "CANVAS_AUTHORITY",
+ "Canvas Authority",
+ "State which image controls geometry and which image controls appearance",
+ ),
+ (
+ "MINIMAL_EDIT",
+ "Minimal Edit",
+ "Use the strongest concise general-purpose variant from the Qwen 2.1 prompt tests",
+ ),
+ (
+ "CUSTOM",
+ "Custom",
+ "Write separate guidance prompts for initial and sequential views",
+ ),
+)
+
+QWEN_PROMPT_TEMPLATE_IDS = frozenset(item[0] for item in QWEN_PROMPT_TEMPLATE_ITEMS)
+
+
+def is_qwen_image_21_model(model_name: str) -> bool:
+ """Return whether a selected diffusion model belongs to Qwen-Image 2.1.
+
+ Model files in ComfyUI can be nested in folders and community conversions
+ use dots, dashes, or underscores in the version. Filename detection is
+ retained for filtering model choices and migrating files saved before the
+ dedicated architecture existed; generation dispatch uses the architecture.
+ """
+ normalized = (model_name or "").replace("\\", "/").rsplit("/", 1)[-1].lower()
+ return bool(re.search(r"qwen[-_. ]*image[-_. ]*2[-_. ]*1(?:\D|$)", normalized))
+
+
+def is_qwen_architecture(architecture: str) -> bool:
+ """Return whether *architecture* uses StableGen's shared Qwen UI path."""
+ return architecture in {
+ QWEN_IMAGE_EDIT_ARCHITECTURE,
+ QWEN_IMAGE_21_ARCHITECTURE,
+ }
+
+
+def qwen_prepared_prompt(
+ template_id: str,
+ *,
+ canvas_image: int,
+ structure_image: int | None = None,
+ appearance_image: int | None = None,
+ has_magenta_regions: bool = False,
+ gray_background: bool = False,
+) -> str:
+ """Build one of the prompt variants evaluated for Qwen image guidance.
+
+ Image numbers use StableGen's semantic Qwen-Image-Edit ordering. The
+ Qwen-Image 2.1 graph adapter remaps them after it makes projected context
+ image 1, so a single template remains correct for both architectures.
+ The returned string deliberately keeps ``{main_prompt}`` for the caller.
+ """
+ if template_id not in QWEN_PROMPT_TEMPLATE_IDS:
+ template_id = "QWEN_EDIT_LEGACY"
+ if template_id in {"QWEN_EDIT_LEGACY", "QWEN_21_DEFAULT", "CUSTOM"}:
+ raise ValueError(f"{template_id} is not a prepared prompt template")
+
+ canvas = f"image {canvas_image}"
+ structure = (
+ f"image {structure_image}"
+ if structure_image is not None and structure_image != canvas_image
+ else None
+ )
+ appearance = (
+ f"image {appearance_image}"
+ if appearance_image is not None and appearance_image != canvas_image
+ else None
+ )
+
+ preservation = (
+ f"Preserve {canvas}'s camera viewpoint, subject orientation, pose, "
+ "silhouette, proportions, framing, and background."
+ )
+ structure_role = (
+ f" Use {structure} only as the geometry and composition guide."
+ if structure
+ else ""
+ )
+ appearance_role = (
+ f" Use {appearance} only as the identity and appearance reference "
+ "for the subject."
+ if appearance
+ else ""
+ )
+ completion = ""
+ if has_magenta_regions:
+ completion = (
+ " Preserve its existing textured regions and replace every solid "
+ "magenta region with texture that seamlessly continues the "
+ "surrounding surface."
+ )
+ background = " Replace the background with solid gray." if gray_background else ""
+
+ if template_id == "MINIMAL_EDIT":
+ return (
+ f"Edit {canvas} to satisfy this instruction: {{main_prompt}}. "
+ f"{preservation}{completion}{structure_role}{appearance_role}{background}"
+ )
+
+ if template_id == "CANVAS_AUTHORITY":
+ prompt = (
+ f"Use {canvas} as the canvas. Apply this edit: {{main_prompt}}. "
+ f"{canvas} is authoritative for the camera viewpoint, subject "
+ "orientation, pose, silhouette, proportions, framing, and background."
+ )
+ if structure:
+ prompt += f" {structure} is authoritative for geometry and composition."
+ if appearance:
+ prompt += (
+ f" {appearance} is authoritative for the subject's identity, "
+ "styling, colors, materials, clothing design, and surface detail."
+ )
+ return (
+ f"{prompt}{completion}{background} Produce a coherent, fully textured "
+ "version of the canvas."
+ )
+
+ if template_id == "CANVAS_EDIT":
+ prompt = (
+ f"Edit {canvas} as the canvas. Preserve its exact camera viewpoint, "
+ "framing, subject orientation, pose, silhouette, proportions, and "
+ "background. Apply this instruction: {main_prompt}."
+ )
+ if appearance:
+ prompt += (
+ f" Transfer the identity, styling, colors, materials, and surface "
+ f"details from {appearance}, fitting them to the visible surfaces "
+ f"of {canvas}."
+ )
+ return f"{prompt}{completion}{structure_role}{background}"
+
+ if template_id == "REFERENCE_RECONSTRUCTION":
+ prompt = (
+ f"Reconstruct {{main_prompt}} in the exact camera view shown by {canvas}. "
+ f"Use {canvas} for the camera, pose, proportions, silhouette, framing, "
+ "and background."
+ )
+ if appearance:
+ prompt += (
+ f" Use {appearance} for identity, styling, colors, materials, and "
+ "surface detail."
+ )
+ return (
+ f"{prompt}{completion}{structure_role}{background} Produce a coherent "
+ "render with the requested appearance correctly resolved in this view."
+ )
+
+ if template_id == "CONCISE_TRANSFER":
+ if appearance:
+ lead = (
+ f"Apply the identity and appearance from {appearance} to {canvas} "
+ "while satisfying this instruction: {main_prompt}."
+ )
+ else:
+ lead = f"Apply this instruction to {canvas}: {{main_prompt}}."
+ return f"{lead} {preservation}{completion}{structure_role}{background}"
+
+ # RESULT_DESCRIPTION
+ prompt = (
+ f"Create a coherent render of {{main_prompt}} that follows the camera "
+ f"viewpoint, pose, silhouette, proportions, framing, and background of {canvas}."
+ )
+ if appearance:
+ prompt += (
+ f" Depict the same identity, styling, colors, materials, and surface "
+ f"details shown in {appearance}."
+ )
+ return f"{prompt}{completion}{structure_role}{background}"
+
+
+def qwen_image_21_prompt(text: str) -> str:
+ """Convert legacy ``Image 1`` references to Qwen 2.1 image tokens."""
+ return re.sub(
+ r"(?<!<)\bimage\s*([1-9]\d*)\b(?!>)",
+ lambda match: f"<image{match.group(1)}>",
+ text,
+ flags=re.IGNORECASE,
+ )
+
+
+def qwen_image_21_rgba_prompt(text: str) -> str:
+ """Wrap a Qwen 2.1 prompt for native transparent RGBA output.
+
+ The wording follows the official Qwen-Image 2.1 ComfyUI template. Keep
+ this idempotent because custom prompts and archived workflows may already
+ include the wrapper.
+ """
+ prompt = re.sub(
+ r"\s*(?:keep|replace)\s+the\s+background\s+"
+ r"(?:with\s+)?solid(?:\s+neutral)?\s+gray\.?",
+ "",
+ (text or "").strip(),
+ flags=re.IGNORECASE,
+ ).strip()
+ lowered = prompt.casefold()
+ has_prefix = "rgba format image with transparency" in lowered
+ has_suffix = (
+ "alpha channel" in lowered and "transparent background" in lowered
+ )
+ if not has_prefix:
+ prompt = f"{QWEN_IMAGE_21_RGBA_PREFIX} {prompt}".strip()
+ if not has_suffix:
+ prompt = f"{prompt} {QWEN_IMAGE_21_RGBA_SUFFIX}".strip()
+ return prompt
+
+
+def remap_qwen_image_21_prompt(text: str, image_mapping: dict[int, int]) -> str:
+ """Convert image references and renumber them without replacement clashes.
+
+ StableGen's original Qwen Edit workflow uses image 1 as a structure guide
+ and image 2 as projected context. Qwen-Image 2.1 instead treats its first
+ image as the edit target, so later context-guided views swap those slots.
+ This helper keeps custom driving prompts aligned with the swapped images.
+ """
+ converted = qwen_image_21_prompt(text)
+ return re.sub(
+ r"<image([1-9]\d*)>",
+ lambda match: (
+ f"<image{image_mapping.get(int(match.group(1)), int(match.group(1)))}>"
+ ),
+ converted,
+ flags=re.IGNORECASE,
+ )
diff --git a/stablegen/texturing/rendering.py b/stablegen/texturing/rendering.py
index b6a9088..e3afbf0 100644
--- a/stablegen/texturing/rendering.py
+++ b/stablegen/texturing/rendering.py
@@ -174,6 +174,10 @@ class _RenderStateTransaction:
"material_override": getattr(self.context.view_layer, "material_override", None),
"shading_light": scene.display.shading.light,
"shading_color_type": scene.display.shading.color_type,
+ "shading_background_type": scene.display.shading.background_type,
+ "shading_background_color": tuple(
+ scene.display.shading.background_color
+ ),
}
self.pass_state = {
name: getattr(self.context.view_layer, name)
@@ -267,6 +271,8 @@ class _RenderStateTransaction:
self.context.view_layer.material_override = state["material_override"]
scene.display.shading.light = state["shading_light"]
scene.display.shading.color_type = state["shading_color_type"]
+ scene.display.shading.background_type = state["shading_background_type"]
+ scene.display.shading.background_color = state["shading_background_color"]
for name, value in self.pass_state.items():
setattr(self.context.view_layer, name, value)
scene.frame_set(state["frame"])
@@ -1136,7 +1142,10 @@ def export_emit_image(context, to_export, camera_id=None, bg_color=(0.5, 0.5, 0.
)
-def _export_render_impl(context, camera_id=None, output_dir=None, filename=None):
+def _export_render_impl(
+ context, camera_id=None, output_dir=None, filename=None,
+ background_color=None,
+):
"""
Renders the scene from a camera's perspective using Workbench.
Creates temporary materials for consistent rendering.
@@ -1163,7 +1172,11 @@ def _export_render_impl(context, camera_id=None, output_dir=None, filename=None)
original_engine = context.scene.render.engine
original_workbench_settings = {
'lighting': context.scene.display.shading.light,
- 'color_type': context.scene.display.shading.color_type
+ 'color_type': context.scene.display.shading.color_type,
+ 'background_type': context.scene.display.shading.background_type,
+ 'background_color': tuple(
+ context.scene.display.shading.background_color
+ ),
}
original_render_filepath = context.scene.render.filepath
original_image_settings = context.scene.render.image_settings.file_format
@@ -1175,6 +1188,14 @@ def _export_render_impl(context, camera_id=None, output_dir=None, filename=None)
# Configure Workbench for a flat, consistent look if needed
context.scene.display.shading.light = 'STUDIO'
context.scene.display.shading.color_type = 'SINGLE'
+ if background_color is not None:
+ context.scene.display.shading.background_type = 'VIEWPORT'
+ context.scene.display.shading.background_color = background_color
+ # Camera Workbench renders use World.color even when the viewport
+ # background mode says VIEWPORT. The transaction around this export
+ # restores the user's world color afterwards.
+ if context.scene.world is not None:
+ context.scene.world.color = background_color
render_layer = context.view_layer
original_combined = render_layer.use_pass_combined
@@ -1208,20 +1229,29 @@ def _export_render_impl(context, camera_id=None, output_dir=None, filename=None)
context.scene.render.engine = original_engine
context.scene.display.shading.light = original_workbench_settings['lighting']
context.scene.display.shading.color_type = original_workbench_settings['color_type']
+ context.scene.display.shading.background_type = original_workbench_settings['background_type']
+ context.scene.display.shading.background_color = original_workbench_settings['background_color']
context.scene.render.filepath = original_render_filepath
context.scene.render.image_settings.file_format = original_image_settings
context.scene.render.use_compositing = original_use_compositing
-def export_render(context, camera_id=None, output_dir=None, filename=None):
+def export_render(
+ context, camera_id=None, output_dir=None, filename=None,
+ background_color=None,
+):
objects = [obj for obj in context.view_layer.objects if obj.type == 'MESH']
with _RenderStateTransaction(context, objects):
return _export_render_impl(
- context, camera_id=camera_id, output_dir=output_dir, filename=filename
+ context, camera_id=camera_id, output_dir=output_dir,
+ filename=filename, background_color=background_color,
)
-def _export_viewport_impl(context, camera_id=None, output_dir=None, filename=None):
+def _export_viewport_impl(
+ context, camera_id=None, output_dir=None, filename=None,
+ background_color=None,
+):
"""
Renders the scene using viewport OpenGL render to include overlays.
:param context: Blender context.
@@ -1281,11 +1311,20 @@ def _export_viewport_impl(context, camera_id=None, output_dir=None, filename=Non
# Store viewport settings
original_view_perspective = viewport_region_3d.view_perspective
original_shading_type = viewport_space.shading.type
+ original_background_type = viewport_space.shading.background_type
+ original_background_color = tuple(viewport_space.shading.background_color)
original_overlay_show = viewport_space.overlay.show_overlays
# Configure viewport for camera render with overlays
viewport_region_3d.view_perspective = 'CAMERA'
viewport_space.shading.type = 'RENDERED'
+ if background_color is not None:
+ viewport_space.shading.background_type = 'VIEWPORT'
+ viewport_space.shading.background_color = background_color
+ context.scene.display.shading.background_type = 'VIEWPORT'
+ context.scene.display.shading.background_color = background_color
+ if context.scene.world is not None:
+ context.scene.world.color = background_color
viewport_space.overlay.show_overlays = True
# Configure output filepath
@@ -1307,6 +1346,8 @@ def _export_viewport_impl(context, camera_id=None, output_dir=None, filename=Non
# Restore viewport settings
viewport_region_3d.view_perspective = original_view_perspective
viewport_space.shading.type = original_shading_type
+ viewport_space.shading.background_type = original_background_type
+ viewport_space.shading.background_color = original_background_color
viewport_space.overlay.show_overlays = original_overlay_show
# Restore original render settings
@@ -1318,12 +1359,16 @@ def _export_viewport_impl(context, camera_id=None, output_dir=None, filename=Non
print(f"[StableGen] Viewport render saved to: {os.path.join(output_dir, output_file)}.png")
-def export_viewport(context, camera_id=None, output_dir=None, filename=None):
+def export_viewport(
+ context, camera_id=None, output_dir=None, filename=None,
+ background_color=None,
+):
"""Viewport export with full scene-state restoration on every exit path."""
objects = [obj for obj in context.view_layer.objects if obj.type == 'MESH']
with _RenderStateTransaction(context, objects):
return _export_viewport_impl(
- context, camera_id=camera_id, output_dir=output_dir, filename=filename
+ context, camera_id=camera_id, output_dir=output_dir,
+ filename=filename, background_color=background_color,
)
def export_canny(context, camera_id=None, low_threshold=0, high_threshold=80):
diff --git a/stablegen/texturing/workflows.py b/stablegen/texturing/workflows.py
index 361fedd..96bf880 100644
--- a/stablegen/texturing/workflows.py
+++ b/stablegen/texturing/workflows.py
@@ -18,6 +18,14 @@ from .graph_validation import (
attach_qwen_latent_lock,
sdxl_final_mask_reference,
)
+from .qwen_models import (
+ QWEN_IMAGE_21_TEXT_ENCODER,
+ QWEN_IMAGE_21_VAE,
+ qwen_prepared_prompt,
+ qwen_image_21_prompt,
+ qwen_image_21_rgba_prompt,
+ remap_qwen_image_21_prompt,
+)
from io import BytesIO
import numpy as np
@@ -91,6 +99,150 @@ class _TexturingWorkflowMixin:
"""Texturing workflow methods for WorkflowManager."""
+ def _convert_to_qwen_image_21(
+ self, prompt, nodes, context, *, projected_context_target=False
+ ):
+ """Replace the legacy Qwen Edit graph with Qwen-Image 2.1 nodes.
+
+ The caller first performs StableGen's normal reference routing. This
+ adapter reads those semantic image slots, retains their loader/resize
+ dependencies, and swaps only the ComfyUI model layer. Camera planning,
+ magenta guides, depth references and sequential projection therefore
+ remain shared with the established Qwen path.
+ """
+ old_encoder = prompt[nodes['pos_prompt']]
+ old_inputs = old_encoder.get('inputs', {})
+ image_refs = [
+ old_inputs[key]
+ for key in ('image1', 'image2', 'image3')
+ if key in old_inputs
+ ]
+ prompt_text = old_inputs.get('prompt', '')
+ if projected_context_target and len(image_refs) >= 2:
+ # The legacy graph routes structure/depth as image 1 and projected
+ # context as image 2. Qwen 2.1 VAE-encodes image 1 as the output
+ # target, so put the context there and retain structure as image 2.
+ image_refs[0], image_refs[1] = image_refs[1], image_refs[0]
+ final_prompt = remap_qwen_image_21_prompt(
+ prompt_text, {1: 2, 2: 1}
+ )
+ else:
+ final_prompt = qwen_image_21_prompt(prompt_text)
+ if getattr(context.scene, 'qwen_image_21_native_rgba', True):
+ final_prompt = qwen_image_21_rgba_prompt(final_prompt)
+
+ graph = {
+ nodes['unet_loader']: {
+ 'inputs': {
+ 'unet_name': context.scene.model_name,
+ 'weight_dtype': 'default',
+ },
+ 'class_type': 'UNETLoader',
+ '_meta': {'title': 'Load Qwen-Image 2.1 Diffusion Model'},
+ },
+ '3': {
+ 'inputs': {
+ 'clip_name': QWEN_IMAGE_21_TEXT_ENCODER,
+ 'type': 'qwen_image',
+ 'device': 'default',
+ },
+ 'class_type': 'CLIPLoader',
+ '_meta': {'title': 'Load Qwen3-VL 8B Text Encoder'},
+ },
+ '4': {
+ 'inputs': {'vae_name': QWEN_IMAGE_21_VAE},
+ 'class_type': 'VAELoader',
+ '_meta': {'title': 'Load Qwen-Image 2.1 VAE'},
+ },
+ nodes['pos_prompt']: {
+ 'inputs': {
+ 'clip': ['3', 0],
+ 'prompt': final_prompt,
+ 'negative_prompt': getattr(
+ context.scene, 'comfyui_negative_prompt', ''
+ ),
+ # A camera reference defines the output canvas. Preserve
+ # its 32px-aligned size instead of rescaling it to 1 MP.
+ # Text-only generation has no reference size, so retain
+ # ComfyUI's explicit 1024px square latent fallback.
+ 'resolution': 0 if image_refs else 1024,
+ 'vae': ['4', 0],
+ },
+ 'class_type': 'TextEncodeQwenImage21',
+ '_meta': {'title': 'Qwen-Image 2.1 Multi-Image Conditioning'},
+ },
+ nodes['model_sampler']: {
+ 'inputs': {
+ 'model': [nodes['unet_loader'], 0],
+ 'device': 'auto',
+ 'dtype': 'default',
+ },
+ 'class_type': 'QwenImage21Cache',
+ '_meta': {'title': 'Qwen-Image 2.1 Cache'},
+ },
+ nodes['sampler']: {
+ 'inputs': {
+ 'model': [nodes['model_sampler'], 0],
+ 'seed': context.scene.seed,
+ 'steps': context.scene.steps,
+ 'cfg': context.scene.cfg,
+ 'sampler_name': context.scene.sampler,
+ 'scheduler': context.scene.scheduler,
+ 'positive': [nodes['pos_prompt'], 0],
+ 'negative': [nodes['pos_prompt'], 1],
+ 'latent_image': [nodes['pos_prompt'], 2],
+ 'denoise': 1.0,
+ },
+ 'class_type': 'KSampler',
+ '_meta': {'title': 'Qwen-Image 2.1 Sampler'},
+ },
+ '2': {
+ 'inputs': {
+ 'samples': [nodes['sampler'], 0],
+ 'vae': ['4', 0],
+ },
+ 'class_type': 'VAEDecode',
+ '_meta': {'title': 'VAE Decode'},
+ },
+ nodes['save_image']: {
+ 'inputs': {'images': ['2', 0]},
+ 'class_type': 'SaveImageWebsocket',
+ '_meta': {'title': 'SaveImageWebsocket'},
+ },
+ }
+
+ # Dynamic Qwen 2.1 image inputs are named images.image_1, etc. Copy
+ # any resize/load chain used by a semantic slot into the replacement
+ # graph so external-style scaling continues to work.
+ def retain_reference(reference):
+ node_id = str(reference[0])
+ if node_id in graph:
+ return
+ source = prompt.get(node_id)
+ if source is None:
+ return
+ graph[node_id] = source
+ for value in source.get('inputs', {}).values():
+ if (
+ isinstance(value, list)
+ and len(value) == 2
+ and isinstance(value[0], (str, int))
+ and isinstance(value[1], int)
+ ):
+ retain_reference(value)
+
+ for index, reference in enumerate(image_refs, 1):
+ retain_reference(reference)
+ graph[nodes['pos_prompt']]['inputs'][f'images.image_{index}'] = reference
+
+ prompt.clear()
+ prompt.update(graph)
+ print(
+ '[StableGen] Qwen-Image 2.1 architecture: using '
+ f'{QWEN_IMAGE_21_TEXT_ENCODER}, {QWEN_IMAGE_21_VAE}, '
+ f'{graph[nodes["sampler"]]["inputs"]["steps"]} steps and no legacy LoRA.'
+ )
+
def _crop_and_vignette(
self,
img_bytes,
@@ -428,8 +580,18 @@ class _TexturingWorkflowMixin:
else:
return "Reskin this into {main_prompt}{camera_suffix}, while preserve identity keep likeness replica contour, adopting the visual style from image 2."
- def _get_qwen_default_prompts(self, context, is_initial_image):
- """Gets the default Qwen prompts based on the current context."""
+ def _get_qwen_default_prompts(
+ self,
+ context,
+ is_initial_image,
+ template_id=None,
+ context_mode_override=None,
+ ):
+ """Get the selected Qwen guidance template for the current image roles.
+
+ ``template_id`` is mainly used by the reset operator to retrieve the
+ architecture's built-in wording while the UI is set to Custom.
+ """
# Check if we are in a real generation context vs. just resetting a prompt
is_generating = hasattr(self.operator, '_current_image')
is_subsequent_in_sequence = is_generating and self.operator._current_image > 0
@@ -439,6 +601,11 @@ class _TexturingWorkflowMixin:
getattr(context.scene, 'architecture_mode', '') == 'trellis2'
and getattr(context.scene, 'qwen_use_trellis2_style', False)
)
+ context_mode = (
+ context_mode_override
+ if context_mode_override is not None
+ else context.scene.qwen_context_render_mode
+ )
if is_initial_image:
# First frame has a style reference from an external image or the TRELLIS.2 input.
@@ -452,14 +619,106 @@ class _TexturingWorkflowMixin:
style_image_provided = (
context.scene.qwen_use_external_style_image or
context.scene.sequential_ipadapter or
- context.scene.qwen_context_render_mode in {'REPLACE_STYLE', 'ADDITIONAL'} or
+ context_mode in {'REPLACE_STYLE', 'ADDITIONAL'} or
(_t2_style and not getattr(context.scene, 'qwen_trellis2_style_initial_only', False))
)
- context_mode = context.scene.qwen_context_render_mode
+ is_qwen21 = context.scene.model_architecture == 'qwen_image_21'
+
+ architecture_default = (
+ 'QWEN_21_DEFAULT' if is_qwen21 else 'QWEN_EDIT_LEGACY'
+ )
+ selected_template = template_id or getattr(
+ context.scene, 'qwen_prompt_template', architecture_default
+ )
+ # Compatibility with scenes saved by the short-lived combined entry.
+ if selected_template == 'STABLEGEN_DEFAULT':
+ selected_template = architecture_default
+ if selected_template == 'CUSTOM':
+ if is_initial_image:
+ return context.scene.qwen_custom_prompt_initial
+ if context_mode == 'ADDITIONAL':
+ return context.scene.qwen_custom_prompt_seq_additional
+ if context_mode == 'REPLACE_STYLE':
+ return context.scene.qwen_custom_prompt_seq_replace
+ return context.scene.qwen_custom_prompt_seq_none
+
+ if selected_template not in {
+ 'QWEN_EDIT_LEGACY', 'QWEN_21_DEFAULT'
+ }:
+ # Initial-only TRELLIS styling falls back to the first generated
+ # view on later cameras, so an appearance reference still exists.
+ trellis_style_available = _t2_style
+ appearance_reference = (
+ context.scene.qwen_use_external_style_image
+ or trellis_style_available
+ or (
+ not is_initial_image
+ and context.scene.sequential_ipadapter
+ )
+ )
+ has_context_canvas = (
+ not is_initial_image
+ and context_mode in {'REPLACE_STYLE', 'ADDITIONAL'}
+ )
+ return qwen_prepared_prompt(
+ selected_template,
+ canvas_image=2 if has_context_canvas else 1,
+ structure_image=1 if has_context_canvas else None,
+ appearance_image=(
+ 3 if has_context_canvas and context_mode == 'ADDITIONAL'
+ and appearance_reference
+ else 2 if not has_context_canvas and appearance_reference
+ else None
+ ),
+ has_magenta_regions=has_context_canvas,
+ gray_background=(
+ has_context_canvas
+ and not is_qwen21
+ and getattr(
+ context.scene, 'qwen_prompt_gray_background', True
+ )
+ ),
+ )
# Optional sentence injected into context-render prompts.
gray_bg = " Replace the background with solid gray." if getattr(context.scene, 'qwen_prompt_gray_background', True) else ""
+ if selected_template == 'QWEN_21_DEFAULT' and not is_initial_image and context_mode in {
+ 'REPLACE_STYLE', 'ADDITIONAL'
+ }:
+ # These refer to the legacy semantic slots before conversion:
+ # image 2 is projected context, image 1 is structure. The Qwen 2.1
+ # adapter swaps them so the context becomes its required image-1
+ # edit target and also renumbers custom/default prompt references.
+ prompt = (
+ "Edit image 2 into '{main_prompt}'. Preserve its existing "
+ "non-magenta textured regions. Replace every solid magenta "
+ "region with texture that seamlessly continues the surrounding "
+ "surface. Use image 1 only as a geometry and composition guide."
+ )
+ if context_mode == 'ADDITIONAL':
+ prompt += " Use image 3 as the overall appearance reference."
+ return prompt
+
+ if selected_template == 'QWEN_21_DEFAULT' and is_initial_image:
+ prompt = (
+ "Create '{main_prompt}' using image 1 as the geometry and "
+ "composition guide."
+ )
+ if style_image_provided:
+ prompt += " Use image 2 as the overall appearance reference."
+ return prompt
+
+ if (selected_template == 'QWEN_21_DEFAULT'
+ and context_mode not in {'REPLACE_STYLE', 'ADDITIONAL'}):
+ prompt = (
+ "Create '{main_prompt}' using image 1 as the geometry and "
+ "composition guide."
+ )
+ if style_image_provided:
+ prompt += " Use image 2 as the overall appearance reference."
+ return prompt
+
if is_initial_image:
if not style_image_provided:
return "Change the format of image 1 to '{main_prompt}'"
@@ -498,22 +757,27 @@ class _TexturingWorkflowMixin:
'style_map_loader': "15", # Image 2 (style)
'context_render_loader': "16", # Image 3 (context render)
}
+ is_qwen21 = context.scene.model_architecture == 'qwen_image_21'
# --- Build LoRA chain ---
- initial_model_input = [NODES['unet_loader'], 0]
- dummy_clip_input = [NODES['unet_loader'], 0]
-
- is_nunchaku = context.scene.model_name.lower().endswith('.safetensors')
- lora_class = "NunchakuQwenImageLoraLoader" if is_nunchaku else "LoraLoaderModelOnly"
-
- prompt, final_lora_model_out, _ = self._build_lora_chain(
- prompt, context,
- initial_model_input, dummy_clip_input,
- start_node_id=500,
- lora_class_type=lora_class
+ is_nunchaku = (
+ not is_qwen21
+ and context.scene.model_name.lower().endswith('.safetensors')
)
-
- prompt[NODES['model_sampler']]['inputs']['model'] = final_lora_model_out
+ if not is_qwen21:
+ initial_model_input = [NODES['unet_loader'], 0]
+ dummy_clip_input = [NODES['unet_loader'], 0]
+ lora_class = (
+ "NunchakuQwenImageLoraLoader"
+ if is_nunchaku else "LoraLoaderModelOnly"
+ )
+ prompt, final_lora_model_out, _ = self._build_lora_chain(
+ prompt, context,
+ initial_model_input, dummy_clip_input,
+ start_node_id=500,
+ lora_class_type=lora_class,
+ )
+ prompt[NODES['model_sampler']]['inputs']['model'] = final_lora_model_out
# --- Configure Inputs ---
# Image 1: The current render (structure)
@@ -572,19 +836,23 @@ class _TexturingWorkflowMixin:
user_prompt = _texturing_prompt(context.scene)
final_prompt = f"Modify image1 to {user_prompt}"
if depth_info:
- final_prompt += ". Use image3 as depth map reference."
+ final_prompt += "\n\nImage3 is a depth map of the same view; use it to preserve scene geometry."
prompt[NODES['pos_prompt']]['inputs']['prompt'] = final_prompt
- # --- Reference Latent chain (Qwen unzoom fix) ---
- self._build_qwen_reference_latent_chain(prompt, NODES)
-
- prompt[NODES['sampler']]['inputs']['seed'] = context.scene.seed
- prompt[NODES['sampler']]['inputs']['steps'] = context.scene.steps
- prompt[NODES['sampler']]['inputs']['cfg'] = context.scene.cfg
- prompt[NODES['sampler']]['inputs']['sampler_name'] = context.scene.sampler
- prompt[NODES['sampler']]['inputs']['scheduler'] = context.scene.scheduler
- prompt[NODES['sampler']]['inputs']['denoise'] = 1.0
+ if is_qwen21:
+ self._convert_to_qwen_image_21(prompt, NODES, context)
+ else:
+ # --- Reference Latent chain (Qwen unzoom fix) ---
+ self._build_qwen_reference_latent_chain(
+ prompt, NODES,
+ )
+ prompt[NODES['sampler']]['inputs']['seed'] = context.scene.seed
+ prompt[NODES['sampler']]['inputs']['steps'] = context.scene.steps
+ prompt[NODES['sampler']]['inputs']['cfg'] = context.scene.cfg
+ prompt[NODES['sampler']]['inputs']['sampler_name'] = context.scene.sampler
+ prompt[NODES['sampler']]['inputs']['scheduler'] = context.scene.scheduler
+ prompt[NODES['sampler']]['inputs']['denoise'] = 1.0
if is_nunchaku:
prompt[NODES['unet_loader']] = {
@@ -597,11 +865,13 @@ class _TexturingWorkflowMixin:
"class_type": "NunchakuQwenImageDiTLoader",
"_meta": {"title": "Nunchaku Qwen-Image DiT Loader"},
}
- else:
+ elif not is_qwen21:
prompt[NODES['unet_loader']]['inputs']['unet_name'] = context.scene.model_name
graph_issues = (validate_workflow_graph(
- prompt, (NODES['pos_prompt'], NODES['neg_prompt'])
+ prompt,
+ ((NODES['pos_prompt'],) if is_qwen21
+ else (NODES['pos_prompt'], NODES['neg_prompt'])),
))
if graph_issues:
self.operator._error = "Invalid Qwen refine workflow: " + "; ".join(graph_issues)
@@ -650,25 +920,30 @@ class _TexturingWorkflowMixin:
'style_map_loader': "15", # Image 2 (style)
'context_render_loader': "16", # Image 3 (context render)
}
+ is_qwen21 = context.scene.model_architecture == 'qwen_image_21'
# --- Build LoRA chain ---
# The Qwen workflow uses model-only LoRAs. We can reuse the existing
# chain builder by providing a dummy CLIP input that won't be used.
- initial_model_input = [NODES['unet_loader'], 0]
- dummy_clip_input = [NODES['unet_loader'], 0] # Dummy, not used by LoraLoaderModelOnly
-
- is_nunchaku = context.scene.model_name.lower().endswith('.safetensors')
- lora_class = "NunchakuQwenImageLoraLoader" if is_nunchaku else "LoraLoaderModelOnly"
-
- prompt, final_lora_model_out, _ = self._build_lora_chain(
- prompt, context,
- initial_model_input, dummy_clip_input,
- start_node_id=500, # Use a high starting ID to avoid conflicts
- lora_class_type=lora_class # Specify model-only loader
+ is_nunchaku = (
+ not is_qwen21
+ and context.scene.model_name.lower().endswith('.safetensors')
)
-
- # Connect the output of the LoRA chain to the next node in the model path
- prompt[NODES['model_sampler']]['inputs']['model'] = final_lora_model_out
+ if not is_qwen21:
+ initial_model_input = [NODES['unet_loader'], 0]
+ dummy_clip_input = [NODES['unet_loader'], 0]
+ lora_class = (
+ "NunchakuQwenImageLoraLoader"
+ if is_nunchaku else "LoraLoaderModelOnly"
+ )
+ prompt, final_lora_model_out, _ = self._build_lora_chain(
+ prompt, context,
+ initial_model_input, dummy_clip_input,
+ start_node_id=500,
+ lora_class_type=lora_class,
+ )
+ # Connect the output of the LoRA chain to the next model node.
+ prompt[NODES['model_sampler']]['inputs']['model'] = final_lora_model_out
# --- Configure Inputs ---
@@ -707,10 +982,9 @@ class _TexturingWorkflowMixin:
NODES['context_render_loader'], NODES['style_map_loader'] = NODES['style_map_loader'], NODES['context_render_loader']
prompt[NODES['context_render_loader']]['inputs']['image'] = context_render_info['name']
# The prompt needs to reference image 3
- if context.scene.qwen_use_custom_prompts:
- pos_prompt_text = context.scene.qwen_custom_prompt_seq_additional.format(main_prompt=user_prompt)
- else:
- pos_prompt_text = self._get_qwen_default_prompts(context, is_initial_image).format(main_prompt=user_prompt)
+ pos_prompt_text = self._get_qwen_default_prompts(
+ context, is_initial_image
+ ).format(main_prompt=user_prompt)
prompt[NODES['pos_prompt']]['inputs']['prompt'] = pos_prompt_text
# If mode is REPLACE_STYLE, we will handle it in the style image section below.
else:
@@ -739,16 +1013,14 @@ class _TexturingWorkflowMixin:
self.operator._error = "External style image enabled, but file not found or could not be uploaded."
return {"error": "conn_failed"}
if context_mode != 'ADDITIONAL':
- if context.scene.qwen_use_custom_prompts:
- pos_prompt_text = (context.scene.qwen_custom_prompt_initial if is_initial_image else context.scene.qwen_custom_prompt_seq_none).format(main_prompt=user_prompt)
- else:
- pos_prompt_text = self._get_qwen_default_prompts(context, is_initial_image).format(main_prompt=user_prompt)
+ pos_prompt_text = self._get_qwen_default_prompts(
+ context, is_initial_image
+ ).format(main_prompt=user_prompt)
prompt[NODES['pos_prompt']]['inputs']['prompt'] = pos_prompt_text
else: # Additional mode
- if context.scene.qwen_use_custom_prompts:
- pos_prompt_text = (context.scene.qwen_custom_prompt_seq_additional if not is_initial_image else context.scene.qwen_custom_prompt_initial).format(main_prompt=user_prompt)
- else:
- pos_prompt_text = self._get_qwen_default_prompts(context, is_initial_image).format(main_prompt=user_prompt)
+ pos_prompt_text = self._get_qwen_default_prompts(
+ context, is_initial_image
+ ).format(main_prompt=user_prompt)
prompt[NODES['pos_prompt']]['inputs']['prompt'] = pos_prompt_text
# Case 1b: TRELLIS.2 input image as style (when no external style configured)
@@ -767,32 +1039,23 @@ class _TexturingWorkflowMixin:
if t2_path and os.path.exists(bpy.path.abspath(t2_path)):
style_image_info = self.operator._get_uploaded_image_info(context, "custom", filename=bpy.path.abspath(t2_path))
if style_image_info:
- if context.scene.qwen_use_custom_prompts:
- pos_prompt_text = (context.scene.qwen_custom_prompt_initial).format(main_prompt=user_prompt)
- else:
- pos_prompt_text = self._get_qwen_default_prompts(context, is_initial_image).format(main_prompt=user_prompt)
+ pos_prompt_text = self._get_qwen_default_prompts(
+ context, is_initial_image
+ ).format(main_prompt=user_prompt)
prompt[NODES['pos_prompt']]['inputs']['prompt'] = pos_prompt_text
# Case 2: Sequential generation (after first image). The rigging
# branch used an ``elif`` after the TRELLIS branch, so an enabled
# initial-only TRELLIS style did not fall through on later views.
# Preserve that quirk unless the corrected routing experiment is on.
- if getattr(context.scene, 'sg_rework_qwen_workflow', False):
- use_sequential_style = style_image_info is None and not is_initial_image
- else:
- use_sequential_style = (
- not use_external_this_frame
- and not trellis_style_branch
- and not is_initial_image
- )
+ use_sequential_style = style_image_info is None and not is_initial_image
if use_sequential_style:
if context_mode == 'REPLACE_STYLE':
# The context render becomes the style image
style_image_info = context_render_info
- if context.scene.qwen_use_custom_prompts:
- pos_prompt_text = context.scene.qwen_custom_prompt_seq_replace.format(main_prompt=user_prompt)
- else:
- pos_prompt_text = self._get_qwen_default_prompts(context, is_initial_image).format(main_prompt=user_prompt)
+ pos_prompt_text = self._get_qwen_default_prompts(
+ context, is_initial_image
+ ).format(main_prompt=user_prompt)
prompt[NODES['pos_prompt']]['inputs']['prompt'] = pos_prompt_text
elif context.scene.sequential_ipadapter: # Use previous generated image
if context.scene.sequential_ipadapter_mode == 'original_render':
@@ -806,10 +1069,9 @@ class _TexturingWorkflowMixin:
self.operator._error = f"Sequential mode error: Could not find previous image for camera {ref_cam_id} to use as style."
return {"error": "conn_failed"}
if context_mode != 'ADDITIONAL':
- if context.scene.qwen_use_custom_prompts:
- pos_prompt_text = context.scene.qwen_custom_prompt_seq_none.format(main_prompt=user_prompt)
- else:
- pos_prompt_text = self._get_qwen_default_prompts(context, is_initial_image).format(main_prompt=user_prompt)
+ pos_prompt_text = self._get_qwen_default_prompts(
+ context, is_initial_image
+ ).format(main_prompt=user_prompt)
prompt[NODES['pos_prompt']]['inputs']['prompt'] = pos_prompt_text
# If neither of the above, style_image_info remains None, handled below
@@ -828,10 +1090,9 @@ class _TexturingWorkflowMixin:
else:
del prompt[NODES['pos_prompt']]['inputs']['image2']
del prompt[NODES['neg_prompt']]['inputs']['image2']
- if context.scene.qwen_use_custom_prompts:
- pos_prompt_text = (context.scene.qwen_custom_prompt_initial if is_initial_image else context.scene.qwen_custom_prompt_seq_none).format(main_prompt=user_prompt)
- else:
- pos_prompt_text = self._get_qwen_default_prompts(context, is_initial_image).format(main_prompt=user_prompt)
+ pos_prompt_text = self._get_qwen_default_prompts(
+ context, is_initial_image
+ ).format(main_prompt=user_prompt)
prompt[NODES['pos_prompt']]['inputs']['prompt'] = pos_prompt_text
else:
# A style image is provided, so set the loader input.
@@ -865,22 +1126,41 @@ class _TexturingWorkflowMixin:
prompt[NODES['pos_prompt']]['inputs'][style_slot] = [scale_node_key, 0]
prompt[NODES['neg_prompt']]['inputs'][style_slot] = [scale_node_key, 0]
- # --- Reference Latent chain (Qwen unzoom fix) ---
- latent_slots = qwen_reference_latent_slots(
- context_mode,
- is_initial_image,
- getattr(context.scene, 'qwen_global_style_vlm_only', False),
- )
- if 'image3' not in latent_slots and 'image3' in prompt[NODES['pos_prompt']]['inputs']:
- print(
- "[StableGen] Qwen Image 3 global style is VLM-only; "
- "skipping its ReferenceLatent"
+ if is_qwen21:
+ self._convert_to_qwen_image_21(
+ prompt,
+ NODES,
+ context,
+ projected_context_target=(
+ not is_initial_image
+ and context_mode in {'REPLACE_STYLE', 'ADDITIONAL'}
+ and context_render_info is not None
+ ),
+ )
+ else:
+ # --- Reference Latent chain (Qwen unzoom fix) ---
+ latent_slots = qwen_reference_latent_slots(
+ context_mode,
+ is_initial_image,
+ experimental_enabled(context.scene, 'qwen_global_style_vlm_only'),
+ bool(
+ experimental_enabled(context.scene, 'qwen_context_vlm_only')
+ and context_render_info
+ and (context_mode == 'ADDITIONAL' or style_image_info == context_render_info)
+ ),
+ )
+ if 'image2' not in latent_slots and 'image2' in prompt[NODES['pos_prompt']]['inputs']:
+ print("[StableGen] Qwen projected context is VLM-only; skipping its ReferenceLatent")
+ if 'image3' not in latent_slots and 'image3' in prompt[NODES['pos_prompt']]['inputs']:
+ print(
+ "[StableGen] Qwen Image 3 global style is VLM-only; "
+ "skipping its ReferenceLatent"
+ )
+ self._build_qwen_reference_latent_chain(
+ prompt,
+ NODES,
+ latent_slots=latent_slots,
)
- self._build_qwen_reference_latent_chain(
- prompt,
- NODES,
- latent_slots=latent_slots,
- )
# --- Sampler-level latent-locked context inpainting ---
# Unlike the RGB/magenta conditioning alone, this makes the exported
@@ -933,12 +1213,13 @@ class _TexturingWorkflowMixin:
)
# --- Configure Sampler ---
- prompt[NODES['sampler']]['inputs']['seed'] = context.scene.seed
- prompt[NODES['sampler']]['inputs']['steps'] = context.scene.steps
- prompt[NODES['sampler']]['inputs']['cfg'] = context.scene.cfg
- prompt[NODES['sampler']]['inputs']['sampler_name'] = context.scene.sampler
- prompt[NODES['sampler']]['inputs']['scheduler'] = context.scene.scheduler
- prompt[NODES['sampler']]['inputs']['denoise'] = 1.0 # Typically 1.0 for this kind of edit
+ if not is_qwen21:
+ prompt[NODES['sampler']]['inputs']['seed'] = context.scene.seed
+ prompt[NODES['sampler']]['inputs']['steps'] = context.scene.steps
+ prompt[NODES['sampler']]['inputs']['cfg'] = context.scene.cfg
+ prompt[NODES['sampler']]['inputs']['sampler_name'] = context.scene.sampler
+ prompt[NODES['sampler']]['inputs']['scheduler'] = context.scene.scheduler
+ prompt[NODES['sampler']]['inputs']['denoise'] = 1.0
# --- Set UNET model ---
if is_nunchaku:
@@ -954,11 +1235,13 @@ class _TexturingWorkflowMixin:
"title": "Nunchaku Qwen-Image DiT Loader"
}
}
- else:
+ elif not is_qwen21:
prompt[NODES['unet_loader']]['inputs']['unet_name'] = context.scene.model_name
graph_issues = (validate_workflow_graph(
- prompt, (NODES['pos_prompt'], NODES['neg_prompt'])
+ prompt,
+ ((NODES['pos_prompt'],) if is_qwen21
+ else (NODES['pos_prompt'], NODES['neg_prompt'])),
))
if graph_issues:
self.operator._error = "Invalid Qwen edit workflow: " + "; ".join(graph_issues)
@@ -1308,10 +1591,12 @@ class _TexturingWorkflowMixin:
# Double-check here in case the property wasn't synced yet.
if getattr(scene, 'architecture_mode', '') == 'trellis2':
tex_mode = getattr(scene, 'trellis2_texture_mode', 'native')
- if tex_mode not in ('sdxl', 'flux1', 'qwen_image_edit', 'flux2_klein'):
+ if tex_mode not in ('sdxl', 'flux1', 'qwen_image_edit', 'qwen_image_21', 'flux2_klein'):
architecture = getattr(scene, 'trellis2_initial_image_arch', 'sdxl')
- if architecture == 'qwen_image_edit':
+ if architecture == 'qwen_image_21':
+ prompt, save_node = self._build_qwen_image_21_txt2img(context)
+ elif architecture == 'qwen_image_edit':
prompt, save_node = self._build_qwen_txt2img(context)
elif architecture == 'flux1':
prompt, save_node = self._build_flux_txt2img(context)
@@ -2028,6 +2313,35 @@ class _TexturingWorkflowMixin:
return prompt, "7"
+ def _build_qwen_image_21_txt2img(self, context):
+ """Return a native Qwen-Image 2.1 text-to-image graph."""
+ prompt = json.loads(prompt_text_qwen_image_edit)
+ nodes = {
+ 'sampler': "1",
+ 'save_image': "5",
+ 'model_sampler': "6",
+ 'pos_prompt': "12",
+ 'neg_prompt': "11",
+ 'unet_loader': "13",
+ 'guidance_map_loader': "14",
+ 'style_map_loader': "15",
+ 'context_render_loader': "16",
+ }
+
+ prompt[nodes['pos_prompt']]['inputs']['prompt'] = _generation_prompt(context.scene)
+ for encoder_id in (nodes['pos_prompt'], nodes['neg_prompt']):
+ for slot in ('image1', 'image2', 'image3'):
+ prompt[encoder_id]['inputs'].pop(slot, None)
+ for loader_id in (
+ nodes['guidance_map_loader'],
+ nodes['style_map_loader'],
+ nodes['context_render_loader'],
+ ):
+ prompt.pop(loader_id, None)
+
+ self._convert_to_qwen_image_21(prompt, nodes, context)
+ return prompt, nodes['save_image']
+
def _create_base_prompt(self, context):
"""Creates and configures the base prompt with user settings."""
from ..util.workflow_templates import prompt_text
diff --git a/stablegen/ui/model_units.py b/stablegen/ui/model_units.py
index 4ffedc3..4f736f9 100644
--- a/stablegen/ui/model_units.py
+++ b/stablegen/ui/model_units.py
@@ -14,7 +14,8 @@ import bpy # pylint: disable=import-error
from .presets import update_parameters
from ..utils import sg_modal_active
from ..core import ADDON_PKG
-from ..core.server_api import _fetch_api_list
+from ..core.server_api import _fetch_api_list, fetch_diffusion_models
+from ..texturing.qwen_models import is_qwen_image_21_model
from ..core.state import (
_cached_checkpoint_list,
_cached_checkpoint_architecture,
@@ -208,13 +209,19 @@ class RefreshCheckpointList(bpy.types.Operator):
if architecture == 'sdxl':
model_list = _fetch_api_list(server_address, "/models/checkpoints")
model_type_desc = "Checkpoint"
- elif architecture in ('flux1', 'qwen_image_edit'):
- model_list = _fetch_api_list(server_address, "/models/unet_gguf")
- if model_list is not None:
- extra = _fetch_api_list(server_address, "/models/diffusion_models")
- if extra:
- model_list.extend(extra)
- model_type_desc = "UNET" if architecture == 'flux1' else "UNET (GGUF/Safetensors)"
+ elif architecture in ('flux1', 'qwen_image_edit', 'qwen_image_21'):
+ model_list = fetch_diffusion_models(server_address)
+ if model_list is not None and architecture == 'qwen_image_21':
+ model_list = [name for name in model_list
+ if is_qwen_image_21_model(name)]
+ elif model_list is not None and architecture == 'qwen_image_edit':
+ model_list = [name for name in model_list
+ if not is_qwen_image_21_model(name)]
+ model_type_desc = (
+ "UNET" if architecture == 'flux1'
+ else "Qwen-Image 2.1 model" if architecture == 'qwen_image_21'
+ else "Qwen-Image-Edit model"
+ )
elif architecture == 'flux2_klein':
model_list = _fetch_api_list(server_address, "/models/diffusion_models")
model_type_desc = "Diffusion Model"
diff --git a/stablegen/ui/panel.py b/stablegen/ui/panel.py
index 7c1159b..346bd0b 100644
--- a/stablegen/ui/panel.py
+++ b/stablegen/ui/panel.py
@@ -45,7 +45,8 @@ _PRESET_DIFF_CORE = [
_DISPLAY_NAMES = {
'sdxl': 'SDXL',
'flux1': 'FLUX.1',
- 'qwen_image_edit': 'Qwen',
+ 'qwen_image_edit': 'Qwen Image Edit',
+ 'qwen_image_21': 'Qwen Image 2.1',
'flux2_klein': 'FLUX.2 Klein',
'trellis2': 'TRELLIS.2',
'standard': 'Standard',
@@ -659,7 +660,7 @@ class StableGenPanel(bpy.types.Panel):
is_trellis2 = getattr(scene, 'architecture_mode', 'sdxl') == 'trellis2'
trellis2_tex_mode = getattr(scene, 'trellis2_texture_mode', 'native')
- trellis2_diffusion_texturing = is_trellis2 and trellis2_tex_mode in ('sdxl', 'flux1', 'qwen_image_edit', 'flux2_klein')
+ trellis2_diffusion_texturing = is_trellis2 and trellis2_tex_mode in ('sdxl', 'flux1', 'qwen_image_edit', 'qwen_image_21', 'flux2_klein')
main_params_box = layout.box()
main_params_col = main_params_box.column()
@@ -1207,12 +1208,27 @@ class StableGenPanel(bpy.types.Panel):
split.prop(scene, "scheduler", text="")
if 'scheduler' in _diff_props:
split.label(text="→ " + _diff_props['scheduler'])
+
+ if scene.model_architecture == 'qwen_image_21':
+ row = content_box.row()
+ if 'qwen_image_21_native_rgba' in _diff_props:
+ row.alert = True
+ row.prop(
+ scene,
+ "qwen_image_21_native_rgba",
+ text="Native RGBA Output",
+ toggle=True,
+ )
+ if 'qwen_image_21_native_rgba' in _diff_props:
+ row.label(text="→ " + _diff_props['qwen_image_21_native_rgba'])
- row = content_box.row()
- row.prop(scene, "clip_skip", text="Clip Skip")
+ if scene.model_architecture != 'qwen_image_21':
+ row = content_box.row()
+ row.prop(scene, "clip_skip", text="Clip Skip")
# --- LoRA Settings ---
- if _show_diffusion_sections or _show_initial_image_settings:
+ if ((_show_diffusion_sections or _show_initial_image_settings)
+ and scene.model_architecture != 'qwen_image_21'):
content_box = draw_collapsible_section(advanced_params_box, "show_lora_settings", "LoRA Management", icon="MODIFIER")
else:
content_box = None
@@ -1315,8 +1331,8 @@ class StableGenPanel(bpy.types.Panel):
sub.label(text="→" + _diff_props['weight_exponent'])
# Row 2 & 3: Reset toggles and values (only for sequential / qwen)
- if scene.generation_method == 'sequential' or scene.model_architecture in ('qwen_image_edit', 'flux2_klein'):
- split = content_box.split(factor=0.5, align=True)
+ if scene.generation_method == 'sequential' or scene.model_architecture in ('qwen_image_edit', 'qwen_image_21', 'flux2_klein'):
+ split = content_box.split(factor=0.5, align=False)
split.prop(scene, "discard_factor_generation_only", text="Reset Angle", toggle=True)
split.prop(scene, "weight_exponent_generation_only", text="Reset Exponent", toggle=True)
@@ -1498,9 +1514,11 @@ class StableGenPanel(bpy.types.Panel):
sub_box_rescale = content_box.box()
row = sub_box_rescale.row()
row.prop(scene, "auto_rescale_target_mp", text="Target Megapixels")
- if scene.model_architecture.startswith('qwen'):
+ if scene.model_architecture == 'qwen_image_edit':
row = sub_box_rescale.row()
row.prop(scene, "qwen_rescale_alignment", text="Qwen VL-Aligned Rescale (112px)", toggle=True, icon="SNAP_INCREMENT")
+ elif scene.model_architecture == 'qwen_image_21':
+ sub_box_rescale.label(text="Qwen 2.1 aligns to 32px", icon="SNAP_INCREMENT")
row = content_box.row()
if 'overwrite_material' in _diff_props:
row.alert = True
@@ -1514,12 +1532,12 @@ class StableGenPanel(bpy.types.Panel):
content_box = draw_collapsible_section(advanced_params_box, "show_image_guidance_settings", "Image Guidance (IPAdapter & ControlNet)", icon="MODIFIER")
elif scene.model_architecture == 'flux2_klein':
content_box = draw_collapsible_section(advanced_params_box, "show_image_guidance_settings", "FLUX.2 Klein Guidance", icon="MODIFIER")
- else: # Qwen Image Edit
- content_box = draw_collapsible_section(advanced_params_box, "show_image_guidance_settings", "Qwen-Image-Edit Guidance", icon="MODIFIER")
+ else: # Qwen Image
+ content_box = draw_collapsible_section(advanced_params_box, "show_image_guidance_settings", "Qwen Image Guidance", icon="MODIFIER")
else:
content_box = None
if content_box:
- if scene.model_architecture in ('qwen_image_edit', 'flux2_klein'):
+ if scene.model_architecture in ('qwen_image_edit', 'qwen_image_21', 'flux2_klein'):
if scene.model_architecture == 'flux2_klein' or scene.qwen_generation_method == 'generate':
split = content_box.split(factor=0.5)
split.label(text="Guidance Map:")
@@ -1606,9 +1624,20 @@ class StableGenPanel(bpy.types.Panel):
row = content_box.row()
row.prop(scene, "qwen_timestep_zero_ref", text="Timestep-Zero References (color shift fix)", toggle=True, icon="COLORSET_08_VEC")
- row = content_box.row()
- row.prop(scene, "qwen_use_custom_prompts", text="Custom Guidance Prompts", toggle=True, icon="TEXT")
- if scene.qwen_use_custom_prompts:
+ if scene.model_architecture in {'qwen_image_edit', 'qwen_image_21'}:
+ split = content_box.split(factor=0.5)
+ split.label(text="Prompt Template:")
+ split.prop(scene, "qwen_prompt_template", text="")
+ custom_guidance_enabled = scene.qwen_prompt_template == 'CUSTOM'
+ else:
+ # FLUX.2 Klein still uses the legacy custom/default control.
+ row = content_box.row()
+ row.prop(scene, "qwen_use_custom_prompts", text="Custom Guidance Prompts", toggle=True, icon="TEXT")
+ custom_guidance_enabled = scene.qwen_use_custom_prompts
+
+ if (scene.model_architecture in {
+ 'qwen_image_edit', 'qwen_image_21'
+ } or custom_guidance_enabled):
custom_prompt_box = content_box.box()
# Initial Image Prompt
@@ -1646,10 +1675,11 @@ class StableGenPanel(bpy.types.Panel):
context_box = content_box.box()
context_box.label(text="Context Render Options")
- row = context_box.row()
- row.prop(scene, "qwen_prompt_gray_background", text="Prompt: Gray Background", toggle=True)
+ if scene.model_architecture != 'qwen_image_21':
+ row = context_box.row()
+ row.prop(scene, "qwen_prompt_gray_background", text="Prompt: Gray Background", toggle=True)
- if scene.qwen_use_custom_prompts:
+ if custom_guidance_enabled:
colors_box = context_box.box()
colors_box.label(text="Context Render Colors")
row = colors_box.row()
@@ -1753,7 +1783,7 @@ class StableGenPanel(bpy.types.Panel):
cn_box.operator("stablegen.add_controlnet_unit", text="Add ControlNet Unit", icon="ADD")
cn_box.operator("stablegen.remove_controlnet_unit", text="Remove Last ControlNet Unit", icon="REMOVE")
- if _show_diffusion_sections and scene.model_architecture not in ('qwen_image_edit', 'flux2_klein'):
+ if _show_diffusion_sections and scene.model_architecture not in ('qwen_image_edit', 'qwen_image_21', 'flux2_klein'):
# --- Inpainting Options (Conditional) ---
if scene.generation_method == 'uv_inpaint' or scene.generation_method == 'sequential':
content_box = draw_collapsible_section(advanced_params_box, "show_masking_inpainting_settings", "Inpainting Options", icon="MOD_MASK")
@@ -1924,7 +1954,7 @@ class StableGenPanel(bpy.types.Panel):
sub_ip_box_separate.prop(scene, "sequential_desaturate_factor", text="Desaturate")
sub_ip_box_separate.prop(scene, "sequential_contrast_factor", text="Reduce Contrast")
- if context.scene.model_architecture not in ('qwen_image_edit', 'flux2_klein'):
+ if context.scene.model_architecture not in ('qwen_image_edit', 'qwen_image_21', 'flux2_klein'):
split = sub_ip_box_separate.split(factor=0.5)
if context.scene.model_architecture == 'sdxl':
split.label(text="Weight Type:")
@@ -2124,7 +2154,7 @@ class StableGenPanel(bpy.types.Panel):
sub_ip_seq_box.prop(scene, "sequential_desaturate_factor", text="Desaturate")
sub_ip_seq_box.prop(scene, "sequential_contrast_factor", text="Reduce Contrast")
- if context.scene.model_architecture not in ('qwen_image_edit', 'flux2_klein'):
+ if context.scene.model_architecture not in ('qwen_image_edit', 'qwen_image_21', 'flux2_klein'):
split = sub_ip_seq_box.split(factor=0.5)
if context.scene.model_architecture == 'sdxl':
split.label(text="Weight Type:")
diff --git a/stablegen/ui/presets.py b/stablegen/ui/presets.py
index 1027d23..e009337 100644
--- a/stablegen/ui/presets.py
+++ b/stablegen/ui/presets.py
@@ -15,7 +15,7 @@ PRESETS = {
"UV INPAINTING": {"description": "Recommended UV Inpainting setup. It is recommended to bake texutures manually before running the generation to fine-tune unwrapping and avoid lag when generating.", "control_after_generate": "fixed", "model_architecture": "sdxl", "steps": 10, "cfg": 1.5, "sampler": "dpmpp_2s_ancestral", "scheduler": "sgm_uniform", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 80.0, "weight_exponent": 3.0, "weight_exponent_generation_only": False, "weight_exponent_after_generation": 15.0, "clip_skip": 1, "auto_rescale": True, "overwrite_material": True, "generation_method": "uv_inpaint", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 0.8, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "3,0,1,2", "sequential_factor": 0.6000000238418579, "sequential_factor_smooth": 0.11000001430511475, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "sequential_ipadapter_mode": "first", "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 3, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "pbr_decomposition": False, "lora_units": [{'model_name': 'sdxl_lightning_8step_lora.safetensors', 'model_strength': 1.0, 'clip_strength': 1.0}]}, # No ControlNet for UV Inpainting by default
"ARCHITECTURE": {"description": "Prioritizes only the most straight-on camera for each point. This means details generated on flat surfaces will not get blurred by getting generated differently from two or more viewpoints. Does not use visibility masking. Each picture will get generated as new, consistency depends on IPAdapter + geometry.", "control_after_generate": "fixed", "model_architecture": "sdxl", "steps": 8, "cfg": 1.5, "sampler": "dpmpp_2s_ancestral", "scheduler": "sgm_uniform", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 80.0, "weight_exponent": 10.0, "weight_exponent_generation_only": False, "weight_exponent_after_generation": 15.0, "clip_skip": 1, "auto_rescale": True, "overwrite_material": True, "generation_method": "separate", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 0.8, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": False, "sequential_custom_camera_order": "", "sequential_factor": 0.75, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "sequential_ipadapter_mode": "first", "ipadapter_weight_type": "style", "ipadapter_strength": 0.800000011920929, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "differential_diffusion": True, "differential_noise": False, "blur_mask": True, "blur_mask_radius": 3, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "pbr_decomposition": False, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.6000000238418579, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}], "lora_units": [{'model_name': 'sdxl_lightning_8step_lora.safetensors', 'model_strength': 1.0, 'clip_strength': 1.0}]},
"QWEN PRECISE": {"description": "Precise detail when camera overlap is good. Relies on context renders plus the prompt, so sparse coverage can still introduce artifacts.", "control_after_generate": "fixed", "model_architecture": "qwen_image_edit","qwen_generation_method": "generate", "steps": 4, "cfg": 1.0, "sampler": "euler", "scheduler": "simple", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 70.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 90.0, "weight_exponent": 3.0, "weight_exponent_generation_only": False, "weight_exponent_after_generation": 15.0, "qwen_voronoi_mode": False, "clip_skip": 1, "auto_rescale": True, "overwrite_material": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 0.8, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.699999988079071, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": False, "sequential_ipadapter_mode": "first", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.0, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "REPLACE_STYLE", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change the format of image 1 to '{main_prompt}'", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 0.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_prompt_gray_background": True, "qwen_rescale_alignment": True, "pbr_decomposition": False, "lora_units": [{'model_name': 'Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors', 'model_strength': 1.0, 'clip_strength': 0.0}]},
- "QWEN SAFE": {"description": "Safer fallback when coverage is limited. Uses the previous view (recent mode) instead of context renders to keep global look coherent, at the cost of some fine-detail persistence.", "control_after_generate": "fixed", "model_architecture": "qwen_image_edit", "qwen_generation_method": "generate", "steps": 4, "cfg": 1.0, "sampler": "euler", "scheduler": "simple", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 70.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 90.0, "weight_exponent": 6.0, "weight_exponent_generation_only": False, "weight_exponent_after_generation": 15.0, "qwen_voronoi_mode": False, "clip_skip": 1, "auto_rescale": True, "overwrite_material": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 0.8, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.699999988079071, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "sequential_ipadapter_mode": "first", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.10000000149011612, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "early_priority": False, "early_priority_strength": 0.5, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "NONE", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change the format of image 1 to '{main_prompt}'", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 0.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_prompt_gray_background": True, "qwen_rescale_alignment": True, "pbr_decomposition": False, "lora_units": [{'model_name': 'Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors', 'model_strength': 1.0, 'clip_strength': 0.0}]},
+ "QWEN SAFE": {"description": "Safer fallback when coverage is limited. Uses the initial generated view as the reference for every later camera instead of context renders, improving global appearance consistency at the cost of extra conditioning time.", "control_after_generate": "fixed", "model_architecture": "qwen_image_edit", "qwen_generation_method": "generate", "steps": 4, "cfg": 1.0, "sampler": "euler", "scheduler": "simple", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 70.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 90.0, "weight_exponent": 6.0, "weight_exponent_generation_only": False, "weight_exponent_after_generation": 15.0, "qwen_voronoi_mode": False, "clip_skip": 1, "auto_rescale": True, "overwrite_material": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 0.8, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.699999988079071, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "sequential_ipadapter_mode": "first", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.10000000149011612, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "early_priority": False, "early_priority_strength": 0.5, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "NONE", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change the format of image 1 to '{main_prompt}'", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 0.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_prompt_gray_background": True, "qwen_rescale_alignment": True, "pbr_decomposition": False, "lora_units": [{'model_name': 'Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors', 'model_strength': 1.0, 'clip_strength': 0.0}]},
"QWEN ALT": {"description": "Balanced option that mixes additional context renders with sequential references to smooth out coverage while keeping detail reasonable.", "control_after_generate": "fixed", "model_architecture": "qwen_image_edit", "qwen_generation_method": "generate", "steps": 4, "cfg": 1.0, "sampler": "euler", "scheduler": "simple", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 70.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 90.0, "weight_exponent": 3.0, "weight_exponent_generation_only": False, "weight_exponent_after_generation": 15.0, "qwen_voronoi_mode": False, "clip_skip": 1, "auto_rescale": True, "overwrite_material": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 0.8, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.699999988079071, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "sequential_ipadapter_mode": "recent", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.10000000149011612, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "ADDITIONAL", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change the format of image 1 to '{main_prompt}'", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 0.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_prompt_gray_background": True, "qwen_rescale_alignment": True, "early_priority": True, "early_priority_strength": 0.5, "pbr_decomposition": False, "lora_units": [{'model_name': 'Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors', 'model_strength': 1.0, 'clip_strength': 0.0}]},
"QWEN VORONOI": {"description": "Voronoi projection mode with exponent 1000 for hard camera segmentation during generation, then resets to 15 for softer blending. Each surface point is dominated by its closest camera. Based on Qwen Precise.", "control_after_generate": "fixed", "model_architecture": "qwen_image_edit", "qwen_generation_method": "generate", "steps": 4, "cfg": 1.0, "sampler": "euler", "scheduler": "simple", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 70.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 90.0, "weight_exponent": 1000.0, "weight_exponent_generation_only": True, "weight_exponent_after_generation": 15.0, "qwen_voronoi_mode": True, "clip_skip": 1, "auto_rescale": True, "overwrite_material": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 0.8, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.699999988079071, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": False, "sequential_ipadapter_mode": "first", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.0, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "REPLACE_STYLE", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change the format of image 1 to '{main_prompt}'", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 0.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_prompt_gray_background": True, "qwen_rescale_alignment": True, "pbr_decomposition": False, "lora_units": [{'model_name': 'Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors', 'model_strength': 1.0, 'clip_strength': 0.0}]},
"QWEN PRECISE (NUNCHAKU)": {"description": "Precise detail using Nunchaku. Meant to be used with the Nunchaku model which has the 4-step Lightning LoRA included. Requires Nunchaku nodes.", "control_after_generate": "fixed", "model_architecture": "qwen_image_edit", "qwen_generation_method": "generate", "steps": 4, "cfg": 1.0, "sampler": "euler", "scheduler": "simple", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 70.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 90.0, "weight_exponent": 3.0, "weight_exponent_generation_only": False, "weight_exponent_after_generation": 15.0, "qwen_voronoi_mode": False, "clip_skip": 1, "auto_rescale": True, "overwrite_material": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 0.8, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.699999988079071, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": False, "sequential_ipadapter_mode": "first", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.0, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "REPLACE_STYLE", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change the format of image 1 to '{main_prompt}'", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 0.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_prompt_gray_background": True, "qwen_rescale_alignment": True, "pbr_decomposition": False, "lora_units": []},
@@ -71,6 +71,119 @@ PRESETS["QWEN PRECISE+"] = {
**EXPERIMENTAL_FEATURE_DEFAULTS,
}
+# Qwen-Image 2.1 has its own architecture and native sampler presets. These
+# retain the evaluated StableGen view/context strategies and use the sampler
+# combination that performed best in the projection-oriented comparison.
+PRESETS["QWEN 2.1 PRECISE"] = {
+ **PRESETS["QWEN PRECISE"],
+ "weight_exponent": 7.0,
+ "description": (
+ "Qwen-Image 2.1 multi-view texturing using projected context renders "
+ "to preserve already textured regions and repair uncovered areas. "
+ "Uses the tested projection-oriented configuration of 20 steps, CFG 1, "
+ "DPM++ SDE and SGM Uniform with no Lightning LoRA. This combination "
+ "produced broad, coherent panels that followed the model silhouette and "
+ "continued well into later views. Best when adjacent cameras overlap "
+ "well; sparse coverage can still introduce artifacts. Qwen 2.1 is also "
+ "prompted to generate native RGBA views, independently of the sampler, "
+ "and transparent pixels are excluded from texture projection."
+ ),
+ "model_architecture": "qwen_image_21",
+ "steps": 20,
+ "cfg": 1.0,
+ "sampler": "dpmpp_sde",
+ "scheduler": "sgm_uniform",
+ "qwen_image_21_native_rgba": True,
+ "qwen_guidance_background_color": mathutils.Color((0.5, 0.5, 0.5)),
+ "lora_units": [],
+}
+
+PRESETS["QWEN 2.1 SAFE"] = {
+ **PRESETS["QWEN SAFE"],
+ "weight_exponent": 7.0,
+ "description": (
+ "Qwen-Image 2.1 multi-view texturing that supplies the initial generated "
+ "view as an appearance reference for every later camera. This was the "
+ "strongest evaluated reference strategy for retaining distinctive colors "
+ "and details around the object. Uses the tested projection-oriented "
+ "configuration of 20 steps, CFG 1, DPM++ SDE and SGM Uniform with no "
+ "Lightning LoRA. It favors broad, geometry-following texture regions. "
+ "Qwen 2.1 is prompted to generate native RGBA views independently of the "
+ "sampler, and transparent pixels are excluded from texture projection. "
+ "It is slower when the initial reference is tall or large."
+ ),
+ "model_architecture": "qwen_image_21",
+ "steps": 20,
+ "cfg": 1.0,
+ "sampler": "dpmpp_sde",
+ "scheduler": "sgm_uniform",
+ "qwen_image_21_native_rgba": True,
+ "sequential_ipadapter": True,
+ "sequential_ipadapter_mode": "first",
+ "qwen_context_render_mode": "NONE",
+ "qwen_guidance_background_color": mathutils.Color((0.5, 0.5, 0.5)),
+ "lora_units": [],
+}
+
+PRESETS["QWEN 2.1 CONTEXT + REFERENCE"] = {
+ **PRESETS["QWEN 2.1 PRECISE"],
+ "description": (
+ "Qwen-Image 2.1 sequential texturing combining the live projected context "
+ "with the first generated view as a persistent appearance reference. "
+ "Uses Additional Context and the Qwen 2.1 Default prompt template: the "
+ "model fills magenta regions while retaining existing texture, with a "
+ "depth guide for geometry and the initial view for overall appearance. "
+ "A 50-degree discard angle excludes grazing projections during generation, "
+ "then resets to 90 degrees for the final material; blending exponent is 7. "
+ "Uses 20 steps, CFG 1.0, DPM++ SDE, SGM Uniform, native RGBA output and no "
+ "LoRA. Transparent generated pixels are excluded from projection. "
+ "Confidence-Gated Context, Acquisition Quality Weighting and Depth/Part "
+ "Projection Guard are off; legacy fallback dilation is 1 px, cleanup is "
+ "off and backface projection is allowed. Captures the current manually "
+ "tuned setup; intended for comparing context coverage and appearance "
+ "consistency across overlapping views."
+ ),
+ "architecture_mode": "qwen_image_21",
+ "generation_mode": "standard",
+ "discard_factor": 50.0,
+ "sequential_ipadapter": True,
+ "sequential_ipadapter_mode": "first",
+ "qwen_context_render_mode": "ADDITIONAL",
+ "qwen_timestep_zero_ref": False,
+ "auto_rescale_target_mp": 1.0,
+ "early_priority": False,
+ "early_priority_strength": 0.5,
+ "view_blend_use_color_match": False,
+ "view_blend_color_match_method": "hm-mvgd-hm",
+ "view_blend_color_match_strength": 1.0,
+ "allow_modify_existing_textures": False,
+ "weight_exponent_mask": False,
+ "mask_blocky": False,
+ "sg_silhouette_margin": 3,
+ "sg_silhouette_depth": 0.05,
+ "sg_silhouette_rays": "4",
+ "qwen_use_trellis2_style": False,
+ **TEXTURING_DEFAULTS,
+}
+
+# Stock presets select their architecture's native guidance wording. Including
+# the enum makes applying one reset a previously selected comparison template.
+for _preset_values in PRESETS.values():
+ _preset_architecture = _preset_values.get("model_architecture")
+ if _preset_architecture == "qwen_image_edit":
+ _preset_values.setdefault("qwen_prompt_template", "QWEN_EDIT_LEGACY")
+ elif _preset_architecture == "qwen_image_21":
+ _preset_values.setdefault("qwen_prompt_template", "QWEN_21_DEFAULT")
+ if _preset_architecture in {"qwen_image_edit", "qwen_image_21"}:
+ # Prepared-template fields are derived live. Keeping stale copies in a
+ # stock preset would overwrite them after the template is selected.
+ for _prompt_field in (
+ "qwen_custom_prompt_initial",
+ "qwen_custom_prompt_seq_none",
+ "qwen_custom_prompt_seq_replace",
+ "qwen_custom_prompt_seq_additional",
+ ):
+ _preset_values.pop(_prompt_field, None)
# Global list of all generation parameter names to check for a preset.
GEN_PARAMETERS = [
@@ -146,6 +259,7 @@ GEN_PARAMETERS = [
'qwen_context_render_mode',
'qwen_external_style_initial_only',
'qwen_use_custom_prompts',
+ 'qwen_prompt_template',
'qwen_custom_prompt_initial',
'qwen_custom_prompt_seq_none',
'qwen_custom_prompt_seq_replace',
@@ -169,6 +283,7 @@ GEN_PARAMETERS = [
'qwen_residual_fallback_tolerance',
'qwen_prompt_gray_background',
'qwen_rescale_alignment',
+ 'qwen_image_21_native_rgba',
'qwen_generation_method',
'qwen_refine_use_prev_ref',
'qwen_refine_use_depth',
@@ -269,6 +384,7 @@ def get_preset_items(self, context):
_ARCH_GROUP_ORDER = [
('sdxl', 'SDXL / FLUX.1'),
('qwen_image_edit', 'Qwen Image Edit'),
+ ('qwen_image_21', 'Qwen Image 2.1'),
('flux2_klein', 'FLUX.2 Klein'),
('trellis2', 'TRELLIS.2 Pipeline'),
]
@@ -429,18 +545,35 @@ class ResetQwenPrompt(bpy.types.Operator):
is_klein = getattr(context.scene, 'model_architecture', '') == 'flux2_klein'
get_defaults = wm._get_klein_default_prompts if is_klein else wm._get_qwen_default_prompts
+ def built_in_prompt(is_initial, context_mode=None):
+ if is_klein:
+ return get_defaults(context, is_initial_image=is_initial)
+ selected = context.scene.qwen_prompt_template
+ if selected == 'CUSTOM':
+ selected = (
+ 'QWEN_21_DEFAULT'
+ if context.scene.model_architecture == 'qwen_image_21'
+ else 'QWEN_EDIT_LEGACY'
+ )
+ return get_defaults(
+ context,
+ is_initial_image=is_initial,
+ template_id=selected,
+ context_mode_override=context_mode,
+ )
+
# Determine which prompt to reset
if self.prompt_type == 'initial':
- default_prompt = get_defaults(context, is_initial_image=True)
+ default_prompt = built_in_prompt(True)
context.scene.qwen_custom_prompt_initial = default_prompt
elif self.prompt_type == 'seq_none':
- default_prompt = get_defaults(context, is_initial_image=False)
+ default_prompt = built_in_prompt(False, 'NONE')
context.scene.qwen_custom_prompt_seq_none = default_prompt
elif self.prompt_type == 'seq_replace':
- default_prompt = get_defaults(context, is_initial_image=False)
+ default_prompt = built_in_prompt(False, 'REPLACE_STYLE')
context.scene.qwen_custom_prompt_seq_replace = default_prompt
elif self.prompt_type == 'seq_additional':
- default_prompt = get_defaults(context, is_initial_image=False)
+ default_prompt = built_in_prompt(False, 'ADDITIONAL')
context.scene.qwen_custom_prompt_seq_additional = default_prompt
self.report({'INFO'}, "Prompt reset to default.")
@@ -566,7 +699,7 @@ class ApplyPreset(bpy.types.Operator):
# include architecture_mode, update the visible dropdown to match.
if "architecture_mode" not in values:
arch = context.scene.model_architecture
- if arch in ('sdxl', 'flux1', 'qwen_image_edit', 'flux2_klein'):
+ if arch in ('sdxl', 'flux1', 'qwen_image_edit', 'qwen_image_21', 'flux2_klein'):
context.scene.architecture_mode = arch
if skipped:
diff --git a/stablegen/ui/queue.py b/stablegen/ui/queue.py
index eafad48..da830ee 100644
--- a/stablegen/ui/queue.py
+++ b/stablegen/ui/queue.py
@@ -840,7 +840,7 @@ def _queue_tick():
# Trellis2Generate finished — enter settling phase to wait for
# _schedule_texture_generation / _deferred_generate to fire.
- if tex_mode in ('sdxl', 'flux1', 'qwen_image_edit', 'flux2_klein'):
+ if tex_mode in ('sdxl', 'flux1', 'qwen_image_edit', 'qwen_image_21', 'flux2_klein'):
_queue_phase = 'settling'
_queue_settle_deadline = _time.monotonic() + 15.0 # generous: server may need VRAM flush
_queue_texturing_seen = False