Models / test_qwen_edit.py
Dervlex's picture
Upload test_qwen_edit.py
057578d verified
Raw History Blame Contribute Delete
9.52 kB
#!/usr/bin/env python3
"""
Qwen Image Edit Test Script mit UI
Testet die offizielle Qwen-Image-Edit-2509 Implementation
"""
import os
import sys
import torch
from PIL import Image
import gradio as gr
import tempfile
import numpy as np
import random
import base64
import json
# Echte Qwen-Image-Edit-2509 Implementation
try:
from qwenimage.pipeline_qwenimage_edit_plus import QwenImageEditPlusPipeline
from qwenimage.transformer_qwenimage import QwenImageTransformer2DModel
from qwenimage.qwen_fa3_processor import QwenDoubleStreamAttnProcessorFA3
from optimization import optimize_pipeline_
print("✅ Echte Qwen-Image-Edit-2509 Implementation gefunden!")
QWEN_AVAILABLE = True
except ImportError as e:
print(f"❌ Qwen-Image-Edit-2509 nicht verfügbar: {e}")
print("💡 Installiere: pip install qwenimage")
QWEN_AVAILABLE = False
class QwenImageEditTester:
def __init__(self):
self.pipeline = None
self.device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Using device: {self.device}")
def load_pipeline(self):
"""Lädt die echte Qwen-Image-Edit-2509 Pipeline"""
try:
if not QWEN_AVAILABLE:
return "❌ Qwen-Image-Edit-2509 nicht verfügbar! Installiere: pip install qwenimage"
print("🔄 Lade echte Qwen-Image-Edit-2509 Pipeline...")
# Lade die echte QwenImageEditPlusPipeline
self.pipeline = QwenImageEditPlusPipeline.from_pretrained(
"Qwen/Qwen-Image-Edit-2509",
torch_dtype=torch.bfloat16,
device_map="auto"
)
print("✅ Qwen-Image-Edit-2509 Pipeline geladen!")
# Optimiere die Pipeline für bessere Performance
try:
self.pipeline = optimize_pipeline_(self.pipeline)
print("✅ Pipeline optimiert!")
except Exception as e:
print(f"⚠️ Pipeline-Optimierung fehlgeschlagen: {e}")
# Pipeline konfigurieren
self.pipeline.to(self.device)
self.pipeline.set_progress_bar_config(disable=None)
print("✅ Pipeline erfolgreich konfiguriert!")
return "✅ Echte Qwen-Image-Edit-2509 Pipeline erfolgreich geladen!"
except Exception as e:
error_msg = f"❌ Fehler beim Laden der Pipeline: {str(e)}"
print(error_msg)
return error_msg
def test_image_edit(self, image, prompt, cfg_scale, steps, seed, negative_prompt):
"""Testet die Bildbearbeitung mit verschiedenen Einstellungen"""
if self.pipeline is None:
return None, "❌ Pipeline nicht geladen! Bitte zuerst 'Pipeline laden' klicken."
if image is None:
return None, "❌ Bitte ein Bild hochladen!"
try:
print(f"Testing with: CFG={cfg_scale}, Steps={steps}, Seed={seed}")
# Bild konvertieren falls nötig
if isinstance(image, str):
image = Image.open(image)
# RGB konvertieren
image = image.convert("RGB")
# Generator für deterministische Ergebnisse
generator = torch.manual_seed(seed) if seed > 0 else None
# Verwende die echte QwenImageEditPlusPipeline
print("🔄 Verwende echte Qwen-Image-Edit-2509 Pipeline...")
# Generator für deterministische Ergebnisse
if seed > 0:
generator = torch.manual_seed(seed)
else:
generator = torch.Generator().manual_seed(random.randint(0, 2**32-1))
# Pipeline Inputs für QwenImageEditPlusPipeline
inputs = {
"image": image,
"prompt": prompt,
"generator": generator,
"true_cfg_scale": float(cfg_scale),
"negative_prompt": negative_prompt if negative_prompt.strip() else " ",
"num_inference_steps": int(steps),
}
print(f"Qwen-2509 inputs: {inputs}")
# Führe die echte Qwen-Image-Edit-2509 Pipeline aus
with torch.inference_mode():
output = self.pipeline(**inputs)
result_image = output.images[0]
print("✅ Bildbearbeitung erfolgreich!")
return result_image, "✅ Bildbearbeitung erfolgreich!"
except Exception as e:
error_msg = f"❌ Fehler bei der Bildbearbeitung: {str(e)}"
print(error_msg)
return None, error_msg
def create_ui(self):
"""Erstellt die Gradio UI"""
with gr.Blocks(title="Qwen Image Edit Test", theme=gr.themes.Soft()) as demo:
gr.Markdown("# 🎨 Qwen Image Edit Test")
gr.Markdown("Testet die offizielle Qwen-Image-Edit-2509 Implementation")
with gr.Row():
with gr.Column():
# Pipeline Status
pipeline_status = gr.Textbox(
label="Pipeline Status",
value="Pipeline nicht geladen",
interactive=False
)
load_btn = gr.Button("🔄 Pipeline laden", variant="primary")
# Bild Upload
input_image = gr.Image(
label="Input Bild",
type="pil",
height=300
)
# Prompt
prompt = gr.Textbox(
label="Prompt",
value="Change the style of this image into realistic photography",
lines=3
)
# Negative Prompt
negative_prompt = gr.Textbox(
label="Negative Prompt",
value=" ",
lines=2
)
with gr.Column():
# Parameter
cfg_scale = gr.Slider(
label="CFG Scale",
minimum=1.0,
maximum=10.0,
value=4.0,
step=0.1
)
steps = gr.Slider(
label="Steps",
minimum=1,
maximum=100,
value=50,
step=1
)
seed = gr.Number(
label="Seed",
value=0,
precision=0
)
# Buttons
generate_btn = gr.Button("🎨 Bild bearbeiten", variant="primary")
# Output
output_image = gr.Image(
label="Output Bild",
height=300
)
output_status = gr.Textbox(
label="Status",
interactive=False
)
# Event Handlers
load_btn.click(
fn=self.load_pipeline,
outputs=[pipeline_status]
)
generate_btn.click(
fn=self.test_image_edit,
inputs=[
input_image,
prompt,
cfg_scale,
steps,
seed,
negative_prompt
],
outputs=[output_image, output_status]
)
# Beispiel Prompts
gr.Markdown("""
### 💡 Beispiel Prompts:
- "Change the style of this image into realistic photography"
- "Make this image look like a watercolor painting"
- "Convert this to a cartoon style"
- "Change the background to a beach scene"
""")
return demo
def main():
"""Hauptfunktion"""
print("🚀 Starte Qwen Image Edit Test...")
# Prüfe CUDA
if torch.cuda.is_available():
print(f"✅ CUDA verfügbar: {torch.cuda.get_device_name()}")
print(f"✅ CUDA Memory: {torch.cuda.get_device_properties(0).total_memory / 1024**3:.1f} GB")
else:
print("⚠️ CUDA nicht verfügbar, verwende CPU")
# Tester erstellen
tester = QwenImageEditTester()
# UI erstellen und starten
demo = tester.create_ui()
print("🌐 Starte Web-Interface...")
demo.launch(
server_name="0.0.0.0",
server_port=8188,
share=False,
show_error=True
)
if __name__ == "__main__":
main()