Update app.py
Browse files
app.py
CHANGED
|
@@ -5,75 +5,27 @@ import random
|
|
| 5 |
import tempfile
|
| 6 |
import spaces
|
| 7 |
import zipfile
|
| 8 |
-
from PIL import Image
|
| 9 |
from diffusers import QwenImageLayeredPipeline
|
| 10 |
import torch
|
| 11 |
-
from pptx import Presentation
|
| 12 |
import gradio as gr
|
| 13 |
|
| 14 |
-
|
| 15 |
LOG_DIR = "/tmp/local"
|
| 16 |
MAX_SEED = np.iinfo(np.int32).max
|
| 17 |
-
HF_TOKEN=os.environ.get('HF_TOKEN')
|
| 18 |
from huggingface_hub import login
|
| 19 |
login(token=os.environ.get('hf'))
|
| 20 |
|
| 21 |
dtype = torch.bfloat16
|
| 22 |
device = "cuda"
|
| 23 |
pipeline = QwenImageLayeredPipeline.from_pretrained("Qwen/Qwen-Image-Layered", torch_dtype=dtype).to(device)
|
| 24 |
-
# pipeline.set_progress_bar_config(disable=None)
|
| 25 |
|
| 26 |
def ensure_dirname(path: str):
|
| 27 |
if path and not os.path.exists(path):
|
| 28 |
os.makedirs(path, exist_ok=True)
|
| 29 |
|
| 30 |
-
def random_str(length=8):
|
| 31 |
-
return uuid.uuid4().hex[:length]
|
| 32 |
-
|
| 33 |
-
def imagelist_to_pptx(img_files):
|
| 34 |
-
with Image.open(img_files[0]) as img:
|
| 35 |
-
img_width_px, img_height_px = img.size
|
| 36 |
-
|
| 37 |
-
def px_to_emu(px, dpi=96):
|
| 38 |
-
inch = px / dpi
|
| 39 |
-
emu = inch * 914400
|
| 40 |
-
return int(emu)
|
| 41 |
-
|
| 42 |
-
prs = Presentation()
|
| 43 |
-
prs.slide_width = px_to_emu(img_width_px)
|
| 44 |
-
prs.slide_height = px_to_emu(img_height_px)
|
| 45 |
-
|
| 46 |
-
slide = prs.slides.add_slide(prs.slide_layouts[6])
|
| 47 |
-
|
| 48 |
-
left = top = 0
|
| 49 |
-
for img_path in img_files:
|
| 50 |
-
slide.shapes.add_picture(img_path, left, top, width=px_to_emu(img_width_px), height=px_to_emu(img_height_px))
|
| 51 |
-
|
| 52 |
-
with tempfile.NamedTemporaryFile(suffix=".pptx", delete=False) as tmp:
|
| 53 |
-
prs.save(tmp.name)
|
| 54 |
-
return tmp.name
|
| 55 |
-
|
| 56 |
-
def export_gallery(images):
|
| 57 |
-
# images: list of image file paths
|
| 58 |
-
images = [e[0] for e in images]
|
| 59 |
-
pptx_path = imagelist_to_pptx(images)
|
| 60 |
-
return pptx_path
|
| 61 |
-
|
| 62 |
-
def export_gallery_zip(images):
|
| 63 |
-
# images: list of tuples (file_path, caption)
|
| 64 |
-
images = [e[0] for e in images]
|
| 65 |
-
|
| 66 |
-
with tempfile.NamedTemporaryFile(suffix=".zip", delete=False) as tmp:
|
| 67 |
-
with zipfile.ZipFile(tmp.name, 'w', zipfile.ZIP_DEFLATED) as zipf:
|
| 68 |
-
for i, img_path in enumerate(images):
|
| 69 |
-
# Get the file extension from original file
|
| 70 |
-
ext = os.path.splitext(img_path)[1] or '.png'
|
| 71 |
-
# Add each image to the zip with a numbered filename
|
| 72 |
-
zipf.write(img_path, f"layer_{i+1}{ext}")
|
| 73 |
-
return tmp.name
|
| 74 |
-
|
| 75 |
@spaces.GPU(duration=300)
|
| 76 |
-
def infer(
|
| 77 |
seed=777,
|
| 78 |
randomize_seed=False,
|
| 79 |
prompt=None,
|
|
@@ -84,82 +36,82 @@ def infer(input_image,
|
|
| 84 |
cfg_norm=True,
|
| 85 |
use_en_prompt=True):
|
| 86 |
|
| 87 |
-
if
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
|
| 130 |
-
|
| 131 |
-
|
| 132 |
|
| 133 |
-
#
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
with tempfile.NamedTemporaryFile(suffix=".zip", delete=False) as tmp:
|
| 137 |
-
with zipfile.ZipFile(tmp.name, 'w', zipfile.ZIP_DEFLATED) as zipf:
|
| 138 |
-
for idx, img_path in enumerate(temp_files):
|
| 139 |
-
zipf.write(img_path, f"layer_{idx+1}.png")
|
| 140 |
-
zip_path = tmp.name
|
| 141 |
-
|
| 142 |
-
# Final yield includes the downloadable files
|
| 143 |
-
yield output_gallery, pptx_path, zip_path
|
| 144 |
|
| 145 |
ensure_dirname(LOG_DIR)
|
| 146 |
|
| 147 |
-
|
| 148 |
with gr.Blocks() as demo:
|
| 149 |
with gr.Column(elem_id="col-container"):
|
| 150 |
gr.HTML('<img src="https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-Image/layered/qwen-image-layered-logo.png" alt="Qwen-Image-Layered Logo" width="600" style="display: block; margin: 0 auto;">')
|
| 151 |
gr.Markdown("""
|
| 152 |
-
|
| 153 |
""")
|
| 154 |
with gr.Row():
|
| 155 |
with gr.Column(scale=1):
|
| 156 |
-
|
| 157 |
-
|
| 158 |
|
| 159 |
with gr.Accordion("Advanced Settings", open=False):
|
| 160 |
prompt = gr.Textbox(
|
| 161 |
label="Prompt (Optional)",
|
| 162 |
-
placeholder="Please enter the prompt to
|
| 163 |
value="",
|
| 164 |
lines=2,
|
| 165 |
)
|
|
@@ -206,19 +158,16 @@ with gr.Blocks() as demo:
|
|
| 206 |
cfg_norm = gr.Checkbox(label="Whether enable CFG normalization", value=True)
|
| 207 |
use_en_prompt = gr.Checkbox(label="Automatic caption language if no prompt provided, True for EN, False for ZH", value=True)
|
| 208 |
|
| 209 |
-
run_button = gr.Button("Decompose!", variant="primary")
|
| 210 |
|
| 211 |
with gr.Column(scale=2):
|
| 212 |
-
gallery = gr.Gallery(label="Layers", columns=4, rows=4, format="png")
|
| 213 |
-
|
| 214 |
-
export_file = gr.File(label="Download PPTX")
|
| 215 |
-
export_zip_file = gr.File(label="Download ZIP")
|
| 216 |
-
|
| 217 |
|
| 218 |
run_button.click(
|
| 219 |
fn=infer,
|
| 220 |
inputs=[
|
| 221 |
-
|
| 222 |
seed,
|
| 223 |
randomize_seed,
|
| 224 |
prompt,
|
|
@@ -229,7 +178,7 @@ with gr.Blocks() as demo:
|
|
| 229 |
cfg_norm,
|
| 230 |
use_en_prompt,
|
| 231 |
],
|
| 232 |
-
outputs=[gallery,
|
| 233 |
)
|
| 234 |
|
| 235 |
if __name__ == "__main__":
|
|
|
|
| 5 |
import tempfile
|
| 6 |
import spaces
|
| 7 |
import zipfile
|
| 8 |
+
from PIL import Image, ImageSequence
|
| 9 |
from diffusers import QwenImageLayeredPipeline
|
| 10 |
import torch
|
|
|
|
| 11 |
import gradio as gr
|
| 12 |
|
|
|
|
| 13 |
LOG_DIR = "/tmp/local"
|
| 14 |
MAX_SEED = np.iinfo(np.int32).max
|
| 15 |
+
HF_TOKEN = os.environ.get('HF_TOKEN')
|
| 16 |
from huggingface_hub import login
|
| 17 |
login(token=os.environ.get('hf'))
|
| 18 |
|
| 19 |
dtype = torch.bfloat16
|
| 20 |
device = "cuda"
|
| 21 |
pipeline = QwenImageLayeredPipeline.from_pretrained("Qwen/Qwen-Image-Layered", torch_dtype=dtype).to(device)
|
|
|
|
| 22 |
|
| 23 |
def ensure_dirname(path: str):
|
| 24 |
if path and not os.path.exists(path):
|
| 25 |
os.makedirs(path, exist_ok=True)
|
| 26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
@spaces.GPU(duration=300)
|
| 28 |
+
def infer(input_files,
|
| 29 |
seed=777,
|
| 30 |
randomize_seed=False,
|
| 31 |
prompt=None,
|
|
|
|
| 36 |
cfg_norm=True,
|
| 37 |
use_en_prompt=True):
|
| 38 |
|
| 39 |
+
if not input_files:
|
| 40 |
+
yield [], None
|
| 41 |
+
return
|
| 42 |
+
|
| 43 |
+
# Extract all frames from GIFs and gather regular images
|
| 44 |
+
frames = []
|
| 45 |
+
for file_path in input_files:
|
| 46 |
+
if file_path.lower().endswith('.gif'):
|
| 47 |
+
with Image.open(file_path) as img:
|
| 48 |
+
for frame in ImageSequence.Iterator(img):
|
| 49 |
+
frames.append(frame.copy().convert("RGB").convert("RGBA"))
|
| 50 |
+
else:
|
| 51 |
+
frames.append(Image.open(file_path).convert("RGB").convert("RGBA"))
|
| 52 |
+
|
| 53 |
+
all_layers_gallery = []
|
| 54 |
+
master_zip_path = tempfile.NamedTemporaryFile(suffix=".zip", delete=False).name
|
| 55 |
|
| 56 |
+
with zipfile.ZipFile(master_zip_path, 'w', zipfile.ZIP_DEFLATED) as master_zip:
|
| 57 |
+
for frame_idx, pil_image in enumerate(frames):
|
| 58 |
+
current_seed = seed + frame_idx if not randomize_seed else random.randint(0, MAX_SEED)
|
| 59 |
+
|
| 60 |
+
inputs = {
|
| 61 |
+
"image": pil_image,
|
| 62 |
+
"generator": torch.Generator(device='cuda').manual_seed(current_seed),
|
| 63 |
+
"true_cfg_scale": true_guidance_scale,
|
| 64 |
+
"prompt": prompt,
|
| 65 |
+
"negative_prompt": neg_prompt,
|
| 66 |
+
"num_inference_steps": num_inference_steps,
|
| 67 |
+
"num_images_per_prompt": 1,
|
| 68 |
+
"layers": layer,
|
| 69 |
+
"resolution": 640,
|
| 70 |
+
"cfg_normalize": cfg_norm,
|
| 71 |
+
"use_en_prompt": use_en_prompt,
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
with torch.inference_mode():
|
| 75 |
+
output = pipeline(**inputs)
|
| 76 |
+
output_images = output.images
|
| 77 |
+
|
| 78 |
+
# Zip layers for this specific frame
|
| 79 |
+
frame_zip_path = tempfile.NamedTemporaryFile(suffix=".zip", delete=False).name
|
| 80 |
+
with zipfile.ZipFile(frame_zip_path, 'w', zipfile.ZIP_DEFLATED) as frame_zip:
|
| 81 |
+
for layer_idx, img in enumerate(output_images):
|
| 82 |
+
all_layers_gallery.append(img)
|
| 83 |
+
|
| 84 |
+
tmp_img = tempfile.NamedTemporaryFile(suffix=".png", delete=False).name
|
| 85 |
+
img.save(tmp_img)
|
| 86 |
+
frame_zip.write(tmp_img, f"layer_{layer_idx+1}.png")
|
| 87 |
+
os.remove(tmp_img) # clean up png temp file
|
| 88 |
+
|
| 89 |
+
# Add the frame zip to the master zip
|
| 90 |
+
master_zip.write(frame_zip_path, f"frame_{frame_idx+1:03d}_layers.zip")
|
| 91 |
+
os.remove(frame_zip_path) # clean up inner zip temp file
|
| 92 |
|
| 93 |
+
# Yield progress to the UI
|
| 94 |
+
yield all_layers_gallery, None
|
| 95 |
|
| 96 |
+
# Final yield with the master download file
|
| 97 |
+
yield all_layers_gallery, master_zip_path
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
|
| 99 |
ensure_dirname(LOG_DIR)
|
| 100 |
|
|
|
|
| 101 |
with gr.Blocks() as demo:
|
| 102 |
with gr.Column(elem_id="col-container"):
|
| 103 |
gr.HTML('<img src="https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-Image/layered/qwen-image-layered-logo.png" alt="Qwen-Image-Layered Logo" width="600" style="display: block; margin: 0 auto;">')
|
| 104 |
gr.Markdown("""
|
| 105 |
+
Upload a batch of images or a GIF. The model will process every frame, zip each frame's layers, and bundle those ZIPs into a single master ZIP file for download.
|
| 106 |
""")
|
| 107 |
with gr.Row():
|
| 108 |
with gr.Column(scale=1):
|
| 109 |
+
input_files = gr.File(label="Upload Image(s) or GIF", file_count="multiple", type="filepath")
|
|
|
|
| 110 |
|
| 111 |
with gr.Accordion("Advanced Settings", open=False):
|
| 112 |
prompt = gr.Textbox(
|
| 113 |
label="Prompt (Optional)",
|
| 114 |
+
placeholder="Please enter the prompt to describe the image. (Optional)",
|
| 115 |
value="",
|
| 116 |
lines=2,
|
| 117 |
)
|
|
|
|
| 158 |
cfg_norm = gr.Checkbox(label="Whether enable CFG normalization", value=True)
|
| 159 |
use_en_prompt = gr.Checkbox(label="Automatic caption language if no prompt provided, True for EN, False for ZH", value=True)
|
| 160 |
|
| 161 |
+
run_button = gr.Button("Decompose Batch!", variant="primary")
|
| 162 |
|
| 163 |
with gr.Column(scale=2):
|
| 164 |
+
gallery = gr.Gallery(label="Extracted Layers", columns=4, rows=4, format="png")
|
| 165 |
+
export_master_zip = gr.File(label="Download Master ZIP")
|
|
|
|
|
|
|
|
|
|
| 166 |
|
| 167 |
run_button.click(
|
| 168 |
fn=infer,
|
| 169 |
inputs=[
|
| 170 |
+
input_files,
|
| 171 |
seed,
|
| 172 |
randomize_seed,
|
| 173 |
prompt,
|
|
|
|
| 178 |
cfg_norm,
|
| 179 |
use_en_prompt,
|
| 180 |
],
|
| 181 |
+
outputs=[gallery, export_master_zip],
|
| 182 |
)
|
| 183 |
|
| 184 |
if __name__ == "__main__":
|