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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import tempfile
|
| 3 |
+
import zipfile
|
| 4 |
+
import torch
|
| 5 |
+
import spaces
|
| 6 |
+
import gradio as gr
|
| 7 |
+
from diffusers import DiffusionPipeline
|
| 8 |
+
|
| 9 |
+
MODEL_ID = "Tongyi-MAI/Z-Image-Turbo"
|
| 10 |
+
|
| 11 |
+
# ==========================================
|
| 12 |
+
# 1. Load the Model at Startup
|
| 13 |
+
# ==========================================
|
| 14 |
+
print("Loading Z-Image-Turbo pipeline...")
|
| 15 |
+
pipe = DiffusionPipeline.from_pretrained(
|
| 16 |
+
MODEL_ID,
|
| 17 |
+
torch_dtype=torch.bfloat16,
|
| 18 |
+
low_cpu_mem_usage=False,
|
| 19 |
+
)
|
| 20 |
+
pipe.to("cuda")
|
| 21 |
+
print("Pipeline loaded successfully!")
|
| 22 |
+
|
| 23 |
+
# ==========================================
|
| 24 |
+
# 2. Core Generation Function (The Worker)
|
| 25 |
+
# ==========================================
|
| 26 |
+
@spaces.GPU(duration=30)
|
| 27 |
+
def generate_single_image(prompt, seed):
|
| 28 |
+
"""Generates a single image and returns it."""
|
| 29 |
+
generator = torch.Generator("cuda").manual_seed(int(seed))
|
| 30 |
+
image = pipe(
|
| 31 |
+
prompt=prompt,
|
| 32 |
+
num_inference_steps=9,
|
| 33 |
+
guidance_scale=0.0,
|
| 34 |
+
generator=generator,
|
| 35 |
+
).images[0]
|
| 36 |
+
return image
|
| 37 |
+
|
| 38 |
+
# ==========================================
|
| 39 |
+
# 3. Single Image Logic
|
| 40 |
+
# ==========================================
|
| 41 |
+
def generate_one_ui(prompt, randomize_seed, manual_seed):
|
| 42 |
+
if not prompt.strip():
|
| 43 |
+
return None, "⚠️ Please enter a prompt."
|
| 44 |
+
|
| 45 |
+
if randomize_seed:
|
| 46 |
+
seed = torch.randint(0, 2**32 - 1, (1,)).item()
|
| 47 |
+
else:
|
| 48 |
+
seed = int(manual_seed)
|
| 49 |
+
|
| 50 |
+
image = generate_single_image(prompt, seed)
|
| 51 |
+
return image, f"✅ Success! (Seed used: {seed})"
|
| 52 |
+
|
| 53 |
+
# ==========================================
|
| 54 |
+
# 4. Batch Processing Logic
|
| 55 |
+
# ==========================================
|
| 56 |
+
def batch_process(txt_file, randomize_seed, progress=gr.Progress()):
|
| 57 |
+
if txt_file is None:
|
| 58 |
+
return None, "⚠️ Please upload a TXT file first."
|
| 59 |
+
|
| 60 |
+
with open(txt_file.name, "r", encoding="utf-8") as f:
|
| 61 |
+
content = f.read()
|
| 62 |
+
|
| 63 |
+
raw_prompts = content.split('*')
|
| 64 |
+
|
| 65 |
+
prompts = []
|
| 66 |
+
for p in raw_prompts:
|
| 67 |
+
cleaned = p.replace('\n', ' ').replace('\r', ' ').strip()
|
| 68 |
+
if cleaned:
|
| 69 |
+
prompts.append(cleaned)
|
| 70 |
+
|
| 71 |
+
if not prompts:
|
| 72 |
+
return None, "⚠️ No valid prompts found. Make sure to wrap them in *asterisks*."
|
| 73 |
+
|
| 74 |
+
total = len(prompts)
|
| 75 |
+
temp_dir = tempfile.mkdtemp()
|
| 76 |
+
generated_files = []
|
| 77 |
+
|
| 78 |
+
for i, prompt in enumerate(prompts):
|
| 79 |
+
progress((i, total), desc=f"Hacking the mainframe... Generating {i+1} of {total}...")
|
| 80 |
+
|
| 81 |
+
if randomize_seed:
|
| 82 |
+
seed = torch.randint(0, 2**32 - 1, (1,)).item()
|
| 83 |
+
else:
|
| 84 |
+
seed = 42
|
| 85 |
+
|
| 86 |
+
image = generate_single_image(prompt, seed)
|
| 87 |
+
|
| 88 |
+
filename = f"{i+1:04d}.png"
|
| 89 |
+
filepath = os.path.join(temp_dir, filename)
|
| 90 |
+
image.save(filepath)
|
| 91 |
+
generated_files.append(filepath)
|
| 92 |
+
|
| 93 |
+
zip_path = os.path.join(temp_dir, "batch_images.zip")
|
| 94 |
+
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
|
| 95 |
+
for filepath in generated_files:
|
| 96 |
+
zipf.write(filepath, arcname=os.path.basename(filepath))
|
| 97 |
+
zipf.write(txt_file.name, arcname="original_prompts.txt")
|
| 98 |
+
|
| 99 |
+
return zip_path, f"✅ Success! Generated {total} images and packed them into a ZIP."
|
| 100 |
+
|
| 101 |
+
# ==========================================
|
| 102 |
+
# 5. Custom Maroon Hacker Glassmorphism CSS
|
| 103 |
+
# ==========================================
|
| 104 |
+
custom_css = """
|
| 105 |
+
body, .gradio-container {
|
| 106 |
+
background: radial-gradient(circle at top left, #2b0000, #000000) !important;
|
| 107 |
+
color: #ffcccc !important;
|
| 108 |
+
font-family: 'Courier New', Courier, monospace !important;
|
| 109 |
+
}
|
| 110 |
+
.glass-panel {
|
| 111 |
+
background: rgba(60, 0, 0, 0.4) !important;
|
| 112 |
+
backdrop-filter: blur(12px) !important;
|
| 113 |
+
-webkit-backdrop-filter: blur(12px) !important;
|
| 114 |
+
border: 1px solid rgba(255, 0, 60, 0.3) !important;
|
| 115 |
+
box-shadow: 0 8px 32px 0 rgba(255, 0, 60, 0.15) !important;
|
| 116 |
+
border-radius: 15px !important;
|
| 117 |
+
padding: 20px !important;
|
| 118 |
+
margin-bottom: 20px !important;
|
| 119 |
+
}
|
| 120 |
+
.gr-button-primary {
|
| 121 |
+
background: linear-gradient(45deg, #800000, #ff003c) !important;
|
| 122 |
+
border: none !important;
|
| 123 |
+
color: white !important;
|
| 124 |
+
box-shadow: 0 0 10px #ff003c !important;
|
| 125 |
+
font-weight: bold !important;
|
| 126 |
+
text-transform: uppercase !important;
|
| 127 |
+
letter-spacing: 2px !important;
|
| 128 |
+
transition: all 0.3s ease !important;
|
| 129 |
+
}
|
| 130 |
+
.gr-button-primary:hover {
|
| 131 |
+
box-shadow: 0 0 20px #ff003c, 0 0 40px #ff003c !important;
|
| 132 |
+
transform: scale(1.02) !important;
|
| 133 |
+
}
|
| 134 |
+
textarea, input[type="text"] {
|
| 135 |
+
background: rgba(0, 0, 0, 0.7) !important;
|
| 136 |
+
border: 1px solid #800000 !important;
|
| 137 |
+
color: #00ffcc !important;
|
| 138 |
+
font-family: monospace !important;
|
| 139 |
+
}
|
| 140 |
+
.file-preview {
|
| 141 |
+
background: rgba(0, 0, 0, 0.5) !important;
|
| 142 |
+
border: 1px dashed #ff003c !important;
|
| 143 |
+
}
|
| 144 |
+
"""
|
| 145 |
+
|
| 146 |
+
# ==========================================
|
| 147 |
+
# 6. Gradio User Interface
|
| 148 |
+
# ==========================================
|
| 149 |
+
with gr.Blocks(css=custom_css, title="Aparna's Batch Image Generator") as demo:
|
| 150 |
+
|
| 151 |
+
with gr.Column(elem_classes="glass-panel"):
|
| 152 |
+
gr.Markdown(
|
| 153 |
+
"""
|
| 154 |
+
# 🖤 Aparna's Image Generator 🖤
|
| 155 |
+
*System Status: Online. Awaiting input.*
|
| 156 |
+
|
| 157 |
+
Use the **Single Image** tab for quick creations, or the **Batch Generate** tab to process massive lists!
|
| 158 |
+
"""
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
with gr.Tabs():
|
| 162 |
+
# ----------------------------------
|
| 163 |
+
# TAB 1: SINGLE IMAGE
|
| 164 |
+
# ----------------------------------
|
| 165 |
+
with gr.Tab("🖼️ Single Image"):
|
| 166 |
+
with gr.Row():
|
| 167 |
+
with gr.Column(scale=1, elem_classes="glass-panel"):
|
| 168 |
+
single_prompt = gr.Textbox(
|
| 169 |
+
label="Prompt",
|
| 170 |
+
placeholder="Describe your image here...",
|
| 171 |
+
lines=4
|
| 172 |
+
)
|
| 173 |
+
with gr.Accordion("Advanced Settings", open=False):
|
| 174 |
+
single_randomize = gr.Checkbox(label="Randomize Seed", value=True)
|
| 175 |
+
single_seed = gr.Number(label="Manual Seed", value=42, precision=0)
|
| 176 |
+
|
| 177 |
+
single_btn = gr.Button("⚡ Generate Image", variant="primary")
|
| 178 |
+
|
| 179 |
+
with gr.Column(scale=1, elem_classes="glass-panel"):
|
| 180 |
+
single_output_img = gr.Image(label="Result", interactive=False)
|
| 181 |
+
single_status = gr.Textbox(label="Status", interactive=False)
|
| 182 |
+
|
| 183 |
+
# Connect Single Tab
|
| 184 |
+
single_btn.click(
|
| 185 |
+
fn=generate_one_ui,
|
| 186 |
+
inputs=[single_prompt, single_randomize, single_seed],
|
| 187 |
+
outputs=[single_output_img, single_status]
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
# ----------------------------------
|
| 191 |
+
# TAB 2: BATCH GENERATE
|
| 192 |
+
# ----------------------------------
|
| 193 |
+
with gr.Tab("📦 Batch Generate"):
|
| 194 |
+
with gr.Row():
|
| 195 |
+
with gr.Column(scale=1, elem_classes="glass-panel"):
|
| 196 |
+
gr.Markdown(
|
| 197 |
+
"""
|
| 198 |
+
### 🛠️ How to Use Batch:
|
| 199 |
+
1. Wrap **each prompt** in asterisks.
|
| 200 |
+
*(Example: `*A cyberpunk city* *A dragon*`)*
|
| 201 |
+
2. Save as a `.txt` file and upload.
|
| 202 |
+
"""
|
| 203 |
+
)
|
| 204 |
+
txt_input = gr.File(label="📁 Upload Prompts (.txt)", file_types=[".txt"])
|
| 205 |
+
randomize_cb = gr.Checkbox(label="🎲 Randomize Seed", value=True)
|
| 206 |
+
run_btn = gr.Button("⚡ Initialize Batch", variant="primary")
|
| 207 |
+
|
| 208 |
+
with gr.Column(scale=1, elem_classes="glass-panel"):
|
| 209 |
+
status_text = gr.Textbox(label="System Log", interactive=False, lines=3)
|
| 210 |
+
zip_output = gr.File(label="📦 Download Data (ZIP)", interactive=False)
|
| 211 |
+
|
| 212 |
+
# Connect Batch Tab
|
| 213 |
+
run_btn.click(
|
| 214 |
+
fn=batch_process,
|
| 215 |
+
inputs=[txt_input, randomize_cb],
|
| 216 |
+
outputs=[zip_output, status_text]
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
if __name__ == "__main__":
|
| 220 |
+
demo.launch()
|