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+
import spaces
|
| 5 |
+
from config import (
|
| 6 |
+
EDIT_MODEL_ID,
|
| 7 |
+
IMAGE_MODEL_ID,
|
| 8 |
+
LIGHTNING_LORA_PATH,
|
| 9 |
+
MAX_IMAGE_SIZE,
|
| 10 |
+
DEFAULT_STEPS_EDIT,
|
| 11 |
+
DEFAULT_STEPS_IMAGE
|
| 12 |
+
)
|
| 13 |
+
from models import load_models, combine_images, enhance_image
|
| 14 |
+
from utils import validate_images, resize_image_if_needed
|
| 15 |
+
|
| 16 |
+
# Load models at startup
|
| 17 |
+
edit_pipeline, image_pipeline = load_models()
|
| 18 |
+
|
| 19 |
+
# AoT Compilation for better performance
|
| 20 |
+
@spaces.GPU(duration=1500)
|
| 21 |
+
def compile_models():
|
| 22 |
+
"""Compile both models with AoT for better performance"""
|
| 23 |
+
print("Compiling models for optimal performance...")
|
| 24 |
+
|
| 25 |
+
# Compile the edit pipeline
|
| 26 |
+
if hasattr(edit_pipeline, 'transformer'):
|
| 27 |
+
with spaces.aoti_capture(edit_pipeline.transformer) as call:
|
| 28 |
+
dummy_images = [Image.new('RGB', (512, 512), color='white')] * 2
|
| 29 |
+
edit_pipeline(
|
| 30 |
+
image=dummy_images,
|
| 31 |
+
prompt="test prompt",
|
| 32 |
+
num_inference_steps=1
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
exported = torch.export.export(
|
| 36 |
+
edit_pipeline.transformer,
|
| 37 |
+
args=call.args,
|
| 38 |
+
kwargs=call.kwargs,
|
| 39 |
+
)
|
| 40 |
+
compiled_transformer = spaces.aoti_compile(exported)
|
| 41 |
+
spaces.aoti_apply(compiled_transformer, edit_pipeline.transformer)
|
| 42 |
+
print("Edit pipeline compiled successfully")
|
| 43 |
+
|
| 44 |
+
# Compile the image generation pipeline
|
| 45 |
+
if hasattr(image_pipeline, 'transformer'):
|
| 46 |
+
with spaces.aoti_capture(image_pipeline.transformer) as call:
|
| 47 |
+
image_pipeline("test prompt", num_inference_steps=1)
|
| 48 |
+
|
| 49 |
+
exported = torch.export.export(
|
| 50 |
+
image_pipeline.transformer,
|
| 51 |
+
args=call.args,
|
| 52 |
+
kwargs=call.kwargs,
|
| 53 |
+
)
|
| 54 |
+
compiled_transformer = spaces.aoti_compile(exported)
|
| 55 |
+
spaces.aoti_apply(compiled_transformer, image_pipeline.transformer)
|
| 56 |
+
print("Image pipeline compiled successfully")
|
| 57 |
+
|
| 58 |
+
# Compile models
|
| 59 |
+
compile_models()
|
| 60 |
+
|
| 61 |
+
@spaces.GPU(duration=120)
|
| 62 |
+
def process_images(image1, image2, prompt, negative_prompt="", steps_edit=DEFAULT_STEPS_EDIT,
|
| 63 |
+
steps_image=DEFAULT_STEPS_IMAGE, cfg_scale=1.0, seed=42):
|
| 64 |
+
"""
|
| 65 |
+
Process two images by combining them with Qwen-Image-Edit and then enhancing with Qwen-Image
|
| 66 |
+
"""
|
| 67 |
+
try:
|
| 68 |
+
# Validate inputs
|
| 69 |
+
if image1 is None or image2 is None:
|
| 70 |
+
raise gr.Error("Please upload both images")
|
| 71 |
+
|
| 72 |
+
if not prompt.strip():
|
| 73 |
+
raise gr.Error("Please enter a prompt")
|
| 74 |
+
|
| 75 |
+
# Validate image formats
|
| 76 |
+
validated_images = validate_images(image1, image2)
|
| 77 |
+
|
| 78 |
+
# Resize images if needed
|
| 79 |
+
resized_images = []
|
| 80 |
+
for img in validated_images:
|
| 81 |
+
resized_img = resize_image_if_needed(img, MAX_IMAGE_SIZE)
|
| 82 |
+
resized_images.append(resized_img)
|
| 83 |
+
|
| 84 |
+
# Step 1: Combine images using Qwen-Image-Edit-2509
|
| 85 |
+
gr.Info("Step 1: Combining images...")
|
| 86 |
+
combined_image = combine_images(
|
| 87 |
+
edit_pipeline,
|
| 88 |
+
resized_images[0],
|
| 89 |
+
resized_images[1],
|
| 90 |
+
prompt,
|
| 91 |
+
negative_prompt,
|
| 92 |
+
steps_edit,
|
| 93 |
+
seed
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
# Step 2: Enhance the combined image using Qwen-Image
|
| 97 |
+
gr.Info("Step 2: Enhancing image based on prompt...")
|
| 98 |
+
final_image = enhance_image(
|
| 99 |
+
image_pipeline,
|
| 100 |
+
combined_image,
|
| 101 |
+
prompt,
|
| 102 |
+
negative_prompt,
|
| 103 |
+
steps_image,
|
| 104 |
+
cfg_scale,
|
| 105 |
+
seed
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
return final_image, "Processing completed successfully!"
|
| 109 |
+
|
| 110 |
+
except Exception as e:
|
| 111 |
+
raise gr.Error(f"Error processing images: {str(e)}")
|
| 112 |
+
|
| 113 |
+
# Create the Gradio interface
|
| 114 |
+
with gr.Blocks(
|
| 115 |
+
title="Qwen Image Combiner & Enhancer",
|
| 116 |
+
theme=gr.themes.Soft(),
|
| 117 |
+
css="""
|
| 118 |
+
.gradio-container {
|
| 119 |
+
max-width: 1200px;
|
| 120 |
+
margin: auto;
|
| 121 |
+
}
|
| 122 |
+
.main-header {
|
| 123 |
+
text-align: center;
|
| 124 |
+
margin-bottom: 2rem;
|
| 125 |
+
}
|
| 126 |
+
.input-section {
|
| 127 |
+
border: 1px solid #e0e0e0;
|
| 128 |
+
border-radius: 10px;
|
| 129 |
+
padding: 1rem;
|
| 130 |
+
margin-bottom: 1rem;
|
| 131 |
+
}
|
| 132 |
+
.output-section {
|
| 133 |
+
border: 1px solid #e0e0e0;
|
| 134 |
+
border-radius: 10px;
|
| 135 |
+
padding: 1rem;
|
| 136 |
+
}
|
| 137 |
+
"""
|
| 138 |
+
) as demo:
|
| 139 |
+
|
| 140 |
+
# Header
|
| 141 |
+
gr.HTML("""
|
| 142 |
+
<div class="main-header">
|
| 143 |
+
<h1>🎨 Qwen Image Combiner & Enhancer</h1>
|
| 144 |
+
<p>Combine two images using Qwen-Image-Edit-2509 and enhance them with Qwen-Image</p>
|
| 145 |
+
<p><a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank">Built with anycoder</a></p>
|
| 146 |
+
</div>
|
| 147 |
+
""")
|
| 148 |
+
|
| 149 |
+
with gr.Row():
|
| 150 |
+
with gr.Column(scale=1):
|
| 151 |
+
# Input section
|
| 152 |
+
gr.Markdown("### 📸 Input Images")
|
| 153 |
+
|
| 154 |
+
with gr.Row():
|
| 155 |
+
with gr.Column():
|
| 156 |
+
input1 = gr.Image(
|
| 157 |
+
label="First Image",
|
| 158 |
+
type="pil",
|
| 159 |
+
sources=["upload", "clipboard"],
|
| 160 |
+
file_types=[".png", ".webp", ".jpg", ".jpeg"]
|
| 161 |
+
)
|
| 162 |
+
with gr.Column():
|
| 163 |
+
input2 = gr.Image(
|
| 164 |
+
label="Second Image",
|
| 165 |
+
type="pil",
|
| 166 |
+
sources=["upload", "clipboard"],
|
| 167 |
+
file_types=[".png", ".webp", ".jpg", ".jpeg"]
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
gr.Markdown("### ✍️ Prompt Settings")
|
| 171 |
+
|
| 172 |
+
prompt_input = gr.Textbox(
|
| 173 |
+
label="Prompt",
|
| 174 |
+
placeholder="Describe how you want to combine and enhance the images...",
|
| 175 |
+
lines=3,
|
| 176 |
+
value="A magical fusion of both elements in a stunning landscape"
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
negative_prompt_input = gr.Textbox(
|
| 180 |
+
label="Negative Prompt (Optional)",
|
| 181 |
+
placeholder="What you don't want in the image...",
|
| 182 |
+
lines=2,
|
| 183 |
+
value="blurry, low quality, distorted"
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
with gr.Accordion("Advanced Settings", open=False):
|
| 187 |
+
with gr.Row():
|
| 188 |
+
steps_edit = gr.Slider(
|
| 189 |
+
label="Edit Steps",
|
| 190 |
+
minimum=10,
|
| 191 |
+
maximum=60,
|
| 192 |
+
step=5,
|
| 193 |
+
value=DEFAULT_STEPS_EDIT,
|
| 194 |
+
info="Steps for image combination"
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
steps_image = gr.Slider(
|
| 198 |
+
label="Enhancement Steps",
|
| 199 |
+
minimum=4,
|
| 200 |
+
maximum=20,
|
| 201 |
+
step=1,
|
| 202 |
+
value=DEFAULT_STEPS_IMAGE,
|
| 203 |
+
info="Steps for image enhancement"
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
with gr.Row():
|
| 207 |
+
cfg_scale = gr.Slider(
|
| 208 |
+
label="CFG Scale",
|
| 209 |
+
minimum=0.5,
|
| 210 |
+
maximum=3.0,
|
| 211 |
+
step=0.1,
|
| 212 |
+
value=1.0,
|
| 213 |
+
info="Guidance scale for enhancement"
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
seed = gr.Number(
|
| 217 |
+
label="Seed",
|
| 218 |
+
value=42,
|
| 219 |
+
precision=0,
|
| 220 |
+
info="Random seed for reproducible results"
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
generate_btn = gr.Button(
|
| 224 |
+
"🚀 Generate Combined Image",
|
| 225 |
+
variant="primary",
|
| 226 |
+
size="lg"
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
with gr.Column(scale=1):
|
| 230 |
+
# Output section
|
| 231 |
+
gr.Markdown("### 🖼️ Output")
|
| 232 |
+
|
| 233 |
+
output_image = gr.Image(
|
| 234 |
+
label="Generated Image",
|
| 235 |
+
type="pil",
|
| 236 |
+
interactive=False,
|
| 237 |
+
show_download_button=True,
|
| 238 |
+
show_share_button=True
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
status_message = gr.Textbox(
|
| 242 |
+
label="Status",
|
| 243 |
+
interactive=False,
|
| 244 |
+
show_label=False
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
# Examples
|
| 248 |
+
gr.Markdown("### 💡 Examples")
|
| 249 |
+
gr.Examples(
|
| 250 |
+
examples=[
|
| 251 |
+
[
|
| 252 |
+
"examples/astronaut.jpg",
|
| 253 |
+
"examples/egg.jpg",
|
| 254 |
+
"a tiny astronaut hatching from an egg on the moon, Ultra HD, 4K, cinematic composition",
|
| 255 |
+
"blurry, low quality",
|
| 256 |
+
40, 8, 1.0, 42
|
| 257 |
+
],
|
| 258 |
+
[
|
| 259 |
+
"examples/bear1.jpg",
|
| 260 |
+
"examples/bear2.jpg",
|
| 261 |
+
"The magician bear is on the left, the alchemist bear is on the right, facing each other in the central park square",
|
| 262 |
+
"distorted, ugly",
|
| 263 |
+
40, 8, 1.0, 123
|
| 264 |
+
]
|
| 265 |
+
],
|
| 266 |
+
inputs=[input1, input2, prompt_input, negative_prompt_input, steps_edit, steps_image, cfg_scale, seed],
|
| 267 |
+
outputs=[output_image, status_message],
|
| 268 |
+
fn=process_images,
|
| 269 |
+
cache_examples=False
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
# Instructions
|
| 273 |
+
with gr.Accordion("📖 Instructions", open=False):
|
| 274 |
+
gr.Markdown("""
|
| 275 |
+
### How to use:
|
| 276 |
+
1. **Upload two images** in PNG, WebP, JPG, or JPEG format
|
| 277 |
+
2. **Enter a prompt** describing how you want to combine and enhance the images
|
| 278 |
+
3. **Optional:** Add a negative prompt to specify what to avoid
|
| 279 |
+
4. **Adjust settings** in the Advanced section if needed
|
| 280 |
+
5. **Click Generate** to create your combined and enhanced image
|
| 281 |
+
|
| 282 |
+
### Process:
|
| 283 |
+
- **Step 1:** The two images are combined using Qwen-Image-Edit-2509
|
| 284 |
+
- **Step 2:** The combined image is enhanced based on your prompt using Qwen-Image
|
| 285 |
+
|
| 286 |
+
### Tips:
|
| 287 |
+
- Use descriptive prompts for better results
|
| 288 |
+
- Higher step counts may improve quality but take longer
|
| 289 |
+
- The CFG scale affects how closely the model follows your prompt
|
| 290 |
+
- Use the same seed for reproducible results
|
| 291 |
+
""")
|
| 292 |
+
|
| 293 |
+
# Event handlers
|
| 294 |
+
generate_btn.click(
|
| 295 |
+
fn=process_images,
|
| 296 |
+
inputs=[
|
| 297 |
+
input1,
|
| 298 |
+
input2,
|
| 299 |
+
prompt_input,
|
| 300 |
+
negative_prompt_input,
|
| 301 |
+
steps_edit,
|
| 302 |
+
steps_image,
|
| 303 |
+
cfg_scale,
|
| 304 |
+
seed
|
| 305 |
+
],
|
| 306 |
+
outputs=[output_image, status_message],
|
| 307 |
+
show_progress=True
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
if __name__ == "__main__":
|
| 311 |
+
demo.launch()
|
config.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Configuration settings for the Qwen Image Combiner & Enhancer application
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
# Model configurations
|
| 6 |
+
EDIT_MODEL_ID = "Qwen/Qwen-Image-Edit-2509"
|
| 7 |
+
IMAGE_MODEL_ID = "Qwen/Qwen-Image"
|
| 8 |
+
LIGHTNING_LORA_PATH = "lightx2v/Qwen-Image-Lightning"
|
| 9 |
+
LIGHTNING_WEIGHT_NAME = "Qwen-Image-Lightning-8steps-V1.0.safetensors"
|
| 10 |
+
|
| 11 |
+
# Image processing settings
|
| 12 |
+
MAX_IMAGE_SIZE = 1024 # Maximum dimension for input images
|
| 13 |
+
SUPPORTED_FORMATS = [".png", ".webp", ".jpg", ".jpeg"]
|
| 14 |
+
|
| 15 |
+
# Default inference parameters
|
| 16 |
+
DEFAULT_STEPS_EDIT = 40 # Default steps for image combination
|
| 17 |
+
DEFAULT_STEPS_IMAGE = 8 # Default steps for image enhancement (with Lightning LoRA)
|
| 18 |
+
DEFAULT_CFG_SCALE = 1.0
|
| 19 |
+
DEFAULT_SEED = 42
|
| 20 |
+
|
| 21 |
+
# GPU settings
|
| 22 |
+
TORCH_DTYPE = torch.bfloat16 # Use bfloat16 for better performance
|
| 23 |
+
|
| 24 |
+
# Scheduler configuration for Qwen-Image
|
| 25 |
+
import math
|
| 26 |
+
SCHEDULER_CONFIG = {
|
| 27 |
+
"base_image_seq_len": 256,
|
| 28 |
+
"base_shift": math.log(3), # We use shift=3 in distillation
|
| 29 |
+
"invert_sigmas": False,
|
| 30 |
+
"max_image_seq_len": 8192,
|
| 31 |
+
"max_shift": math.log(3), # We use shift=3 in distillation
|
| 32 |
+
"num_train_timesteps": 1000,
|
| 33 |
+
"shift": 1.0,
|
| 34 |
+
"shift_terminal": None, # set shift_terminal to None
|
| 35 |
+
"stochastic_sampling": False,
|
| 36 |
+
"time_shift_type": "exponential",
|
| 37 |
+
"use_beta_sigmas": False,
|
| 38 |
+
"use_dynamic_shifting": True,
|
| 39 |
+
"use_exponential_sigmas": False,
|
| 40 |
+
"use_karras_sigmas": False,
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
# UI Settings
|
| 44 |
+
APP_TITLE = "Qwen Image Combiner & Enhancer"
|
| 45 |
+
APP_DESCRIPTION = "Combine two images using Qwen-Image-Edit-2509 and enhance them with Qwen-Image"
|
models.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Model loading and inference functions for Qwen Image models
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import math
|
| 7 |
+
from PIL import Image
|
| 8 |
+
from diffusers import (
|
| 9 |
+
QwenImageEditPlusPipeline,
|
| 10 |
+
DiffusionPipeline,
|
| 11 |
+
FlowMatchEulerDiscreteScheduler
|
| 12 |
+
)
|
| 13 |
+
from config import (
|
| 14 |
+
EDIT_MODEL_ID,
|
| 15 |
+
IMAGE_MODEL_ID,
|
| 16 |
+
LIGHTNING_LORA_PATH,
|
| 17 |
+
LIGHTNING_WEIGHT_NAME,
|
| 18 |
+
SCHEDULER_CONFIG,
|
| 19 |
+
TORCH_DTYPE
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
def load_models():
|
| 23 |
+
"""Load both Qwen models"""
|
| 24 |
+
print("Loading Qwen-Image-Edit-2509...")
|
| 25 |
+
edit_pipeline = QwenImageEditPlusPipeline.from_pretrained(
|
| 26 |
+
EDIT_MODEL_ID,
|
| 27 |
+
torch_dtype=TORCH_DTYPE
|
| 28 |
+
)
|
| 29 |
+
edit_pipeline.to("cuda")
|
| 30 |
+
edit_pipeline.set_progress_bar_config(disable=None)
|
| 31 |
+
print("Qwen-Image-Edit-2509 loaded successfully")
|
| 32 |
+
|
| 33 |
+
print("Loading Qwen-Image with Lightning LoRA...")
|
| 34 |
+
scheduler = FlowMatchEulerDiscreteScheduler.from_config(SCHEDULER_CONFIG)
|
| 35 |
+
image_pipeline = DiffusionPipeline.from_pretrained(
|
| 36 |
+
IMAGE_MODEL_ID,
|
| 37 |
+
scheduler=scheduler,
|
| 38 |
+
torch_dtype=TORCH_DTYPE
|
| 39 |
+
).to("cuda")
|
| 40 |
+
|
| 41 |
+
# Load Lightning LoRA for faster inference
|
| 42 |
+
image_pipeline.load_lora_weights(
|
| 43 |
+
LIGHTNING_LORA_PATH,
|
| 44 |
+
weight_name=LIGHTNING_WEIGHT_NAME
|
| 45 |
+
)
|
| 46 |
+
print("Qwen-Image with Lightning LoRA loaded successfully")
|
| 47 |
+
|
| 48 |
+
return edit_pipeline, image_pipeline
|
| 49 |
+
|
| 50 |
+
def combine_images(pipeline, image1, image2, prompt, negative_prompt, num_inference_steps, seed):
|
| 51 |
+
"""
|
| 52 |
+
Combine two images using Qwen-Image-Edit-2509
|
| 53 |
+
|
| 54 |
+
Args:
|
| 55 |
+
pipeline: QwenImageEditPlusPipeline
|
| 56 |
+
image1: First PIL Image
|
| 57 |
+
image2: Second PIL Image
|
| 58 |
+
prompt: Text prompt describing the combination
|
| 59 |
+
negative_prompt: Negative prompt
|
| 60 |
+
num_inference_steps: Number of inference steps
|
| 61 |
+
seed: Random seed
|
| 62 |
+
|
| 63 |
+
Returns:
|
| 64 |
+
Combined PIL Image
|
| 65 |
+
"""
|
| 66 |
+
inputs = {
|
| 67 |
+
"image": [image1, image2],
|
| 68 |
+
"prompt": prompt,
|
| 69 |
+
"negative_prompt": negative_prompt,
|
| 70 |
+
"generator": torch.manual_seed(seed),
|
| 71 |
+
"true_cfg_scale": 4.0,
|
| 72 |
+
"num_inference_steps": num_inference_steps,
|
| 73 |
+
"guidance_scale": 1.0,
|
| 74 |
+
"num_images_per_prompt": 1,
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
with torch.inference_mode():
|
| 78 |
+
output = pipeline(**inputs)
|
| 79 |
+
combined_image = output.images[0]
|
| 80 |
+
|
| 81 |
+
return combined_image
|
| 82 |
+
|
| 83 |
+
def enhance_image(pipeline, image, prompt, negative_prompt, num_inference_steps, cfg_scale, seed):
|
| 84 |
+
"""
|
| 85 |
+
Enhance an image using Qwen-Image with prompt
|
| 86 |
+
|
| 87 |
+
Args:
|
| 88 |
+
pipeline: DiffusionPipeline with Qwen-Image
|
| 89 |
+
image: Input PIL Image
|
| 90 |
+
prompt: Text prompt for enhancement
|
| 91 |
+
negative_prompt: Negative prompt
|
| 92 |
+
num_inference_steps: Number of inference steps
|
| 93 |
+
cfg_scale: CFG scale
|
| 94 |
+
seed: Random seed
|
| 95 |
+
|
| 96 |
+
Returns:
|
| 97 |
+
Enhanced PIL Image
|
| 98 |
+
"""
|
| 99 |
+
# Prepare input for img2img
|
| 100 |
+
enhanced_image = pipeline(
|
| 101 |
+
prompt=prompt,
|
| 102 |
+
negative_prompt=negative_prompt,
|
| 103 |
+
image=image,
|
| 104 |
+
width=image.width,
|
| 105 |
+
height=image.height,
|
| 106 |
+
num_inference_steps=num_inference_steps,
|
| 107 |
+
true_cfg_scale=cfg_scale,
|
| 108 |
+
generator=torch.manual_seed(seed),
|
| 109 |
+
).images[0]
|
| 110 |
+
|
| 111 |
+
return enhanced_image
|
requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
torch
|
| 3 |
+
diffusers
|
| 4 |
+
transformers
|
| 5 |
+
accelerate
|
| 6 |
+
spaces
|
| 7 |
+
Pillow
|
| 8 |
+
numpy
|
utils.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Utility functions for image processing and validation
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
from PIL import Image
|
| 7 |
+
from config import SUPPORTED_FORMATS, MAX_IMAGE_SIZE
|
| 8 |
+
|
| 9 |
+
def validate_images(image1, image2):
|
| 10 |
+
"""
|
| 11 |
+
Validate that both images are in supported formats
|
| 12 |
+
|
| 13 |
+
Args:
|
| 14 |
+
image1: First PIL Image
|
| 15 |
+
image2: Second PIL Image
|
| 16 |
+
|
| 17 |
+
Returns:
|
| 18 |
+
Tuple of validated PIL Images
|
| 19 |
+
|
| 20 |
+
Raises:
|
| 21 |
+
ValueError: If images are not in supported formats
|
| 22 |
+
"""
|
| 23 |
+
if image1 is None or image2 is None:
|
| 24 |
+
raise ValueError("Both images must be provided")
|
| 25 |
+
|
| 26 |
+
# Convert to RGB if necessary
|
| 27 |
+
if image1.mode != 'RGB':
|
| 28 |
+
image1 = image1.convert('RGB')
|
| 29 |
+
|
| 30 |
+
if image2.mode != 'RGB':
|
| 31 |
+
image2 = image2.convert('RGB')
|
| 32 |
+
|
| 33 |
+
return image1, image2
|
| 34 |
+
|
| 35 |
+
def resize_image_if_needed(image, max_size):
|
| 36 |
+
"""
|
| 37 |
+
Resize image if it exceeds maximum dimensions while maintaining aspect ratio
|
| 38 |
+
|
| 39 |
+
Args:
|
| 40 |
+
image: PIL Image
|
| 41 |
+
max_size: Maximum dimension (width or height)
|
| 42 |
+
|
| 43 |
+
Returns:
|
| 44 |
+
Resized PIL Image
|
| 45 |
+
"""
|
| 46 |
+
width, height = image.size
|
| 47 |
+
|
| 48 |
+
# Check if resizing is needed
|
| 49 |
+
if max(width, height) <= max_size:
|
| 50 |
+
return image
|
| 51 |
+
|
| 52 |
+
# Calculate new dimensions
|
| 53 |
+
if width > height:
|
| 54 |
+
new_width = max_size
|
| 55 |
+
new_height = int(height * max_size / width)
|
| 56 |
+
else:
|
| 57 |
+
new_height = max_size
|
| 58 |
+
new_width = int(width * max_size / height)
|
| 59 |
+
|
| 60 |
+
# Resize image
|
| 61 |
+
resized_image = image.resize((new_width, new_height), Image.Resampling.LANCZOS)
|
| 62 |
+
|
| 63 |
+
print(f"Resized image from {width}x{height} to {new_width}x{new_height}")
|
| 64 |
+
return resized_image
|
| 65 |
+
|
| 66 |
+
def get_image_info(image):
|
| 67 |
+
"""
|
| 68 |
+
Get basic information about an image
|
| 69 |
+
|
| 70 |
+
Args:
|
| 71 |
+
image: PIL Image
|
| 72 |
+
|
| 73 |
+
Returns:
|
| 74 |
+
Dictionary with image information
|
| 75 |
+
"""
|
| 76 |
+
return {
|
| 77 |
+
"size": image.size,
|
| 78 |
+
"mode": image.mode,
|
| 79 |
+
"format": image.format
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
def create_example_images():
|
| 83 |
+
"""
|
| 84 |
+
Create example images for testing (if they don't exist)
|
| 85 |
+
"""
|
| 86 |
+
os.makedirs("examples", exist_ok=True)
|
| 87 |
+
|
| 88 |
+
# Create simple example images if they don't exist
|
| 89 |
+
example_files = [
|
| 90 |
+
("examples/astronaut.jpg", "Astronaut in space suit"),
|
| 91 |
+
("examples/egg.jpg", "Egg on moon surface"),
|
| 92 |
+
("examples/bear1.jpg", "Magician bear"),
|
| 93 |
+
("examples/bear2.jpg", "Alchemist bear")
|
| 94 |
+
]
|
| 95 |
+
|
| 96 |
+
for file_path, description in example_files:
|
| 97 |
+
if not os.path.exists(file_path):
|
| 98 |
+
# Create a placeholder image
|
| 99 |
+
img = Image.new('RGB', (512, 512), color='lightblue')
|
| 100 |
+
# In a real application, you would have actual example images
|
| 101 |
+
# For now, we'll just create empty files
|
| 102 |
+
img.save(file_path)
|
| 103 |
+
print(f"Created placeholder: {file_path}")
|