Spaces:
Running on Zero
Running on Zero
Download app.py from AparnaVelvet/High-Speed-ImageGen: direct link, hf CLI and curl.
- Browser
- Download file 13.1 kB
-
https://huggingface.co/spaces/AparnaVelvet/High-Speed-ImageGen/resolve/main/app.py
- Command line
-
hf download hf://spaces/AparnaVelvet/High-Speed-ImageGen/app.py
-
curl -L -o app.py https://huggingface.co/spaces/AparnaVelvet/High-Speed-ImageGen/resolve/main/app.py
13.1 kB
| import os | |
| import tempfile | |
| import zipfile | |
| import torch | |
| import spaces | |
| import gradio as gr | |
| from diffusers import DiffusionPipeline | |
| MODEL_ID = "Tongyi-MAI/Z-Image-Turbo" | |
| # ========================================== | |
| # 1. Load the Model | |
| # ========================================== | |
| print("Loading Z-Image-Turbo pipeline...") | |
| pipe = DiffusionPipeline.from_pretrained( | |
| MODEL_ID, | |
| torch_dtype=torch.bfloat16, | |
| low_cpu_mem_usage=False, | |
| ) | |
| pipe.to("cuda") | |
| print("Pipeline loaded successfully!") | |
| # ========================================== | |
| # 2. Core Generation Function | |
| # ========================================== | |
| def generate_single_image(prompt, seed): | |
| generator = torch.Generator("cuda").manual_seed(int(seed)) | |
| negative_prompt = "overlapping fingers, deformed hands, extra limbs, fused fingers, mutated hands, malformed limbs, bad anatomy, disfigured, low quality, worst quality" | |
| image = pipe( | |
| prompt=prompt, | |
| negative_prompt=negative_prompt, | |
| num_inference_steps=9, | |
| guidance_scale=0.0, | |
| height=720, | |
| width=1280, | |
| generator=generator, | |
| ).images[0] | |
| return image | |
| # ========================================== | |
| # 3. Logic for Single Mode | |
| # ========================================== | |
| def generate_one_ui(prompt, randomize_seed, manual_seed): | |
| if not prompt.strip(): | |
| return None, "⚠️ ERROR: INPUT REQUIRED." | |
| if randomize_seed: | |
| seed = torch.randint(0, 2**32 - 1, (1,)).item() | |
| else: | |
| seed = int(manual_seed) | |
| image = generate_single_image(prompt, seed) | |
| return image, f"✅ EXECUTION COMPLETE. SEED: {seed}" | |
| # ========================================== | |
| # 4. Chunked Batch Processing Logic | |
| # ========================================== | |
| def process_chunk(remaining_prompts, all_generated_files, session_dir, randomize_seed, batch_num, progress=gr.Progress()): | |
| chunk = remaining_prompts[:10] | |
| new_remaining = remaining_prompts[10:] | |
| chunk_files = [] | |
| for i, prompt in enumerate(chunk): | |
| progress((i, len(chunk)), desc=f"Generating {i+1}/{len(chunk)} in Batch {batch_num}...") | |
| seed = torch.randint(0, 2**32 - 1, (1,)).item() if randomize_seed else 42 | |
| image = generate_single_image(prompt, seed) | |
| img_idx = len(all_generated_files) + i + 1 | |
| filename = f"{img_idx:04d}.png" | |
| filepath = os.path.join(session_dir, filename) | |
| image.save(filepath) | |
| chunk_files.append(filepath) | |
| all_generated_files.extend(chunk_files) | |
| # Create ZIP for this specific chunk | |
| zip_path = os.path.join(session_dir, f"batch_{batch_num}.zip") | |
| with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zipf: | |
| for fpath in chunk_files: | |
| zipf.write(fpath, arcname=os.path.basename(fpath)) | |
| full_zip_path = None | |
| status = f"✅ Batch {batch_num} complete ({len(chunk_files)} images)." | |
| # Check if we are completely done | |
| if not new_remaining: | |
| status = f"✅ ALL BATCHES COMPLETE. Total: {len(all_generated_files)} images." | |
| full_zip_path = os.path.join(session_dir, "FULL_ARCHIVE.zip") | |
| with zipfile.ZipFile(full_zip_path, "w", zipfile.ZIP_DEFLATED) as zipf: | |
| for fpath in all_generated_files: | |
| zipf.write(fpath, arcname=os.path.basename(fpath)) | |
| zipf.write(os.path.join(session_dir, "prompts.txt"), arcname="original_prompts.txt") | |
| continue_visible = False | |
| else: | |
| status += f" {len(new_remaining)} prompts remaining. Click Continue." | |
| continue_visible = True | |
| return ( | |
| gr.update(value=chunk_files, visible=True), | |
| gr.update(value=zip_path, visible=True), | |
| gr.update(value=full_zip_path, visible=full_zip_path is not None), | |
| status, | |
| gr.update(visible=continue_visible), | |
| new_remaining, | |
| all_generated_files, | |
| batch_num + 1 | |
| ) | |
| def start_batch_wrapper(txt_file, randomize_seed): | |
| if txt_file is None: | |
| return [], None, None, "⚠️ ERROR: NO DATA FILE.", gr.update(visible=False), [], [], 1, "" | |
| with open(txt_file.name, "r", encoding="utf-8") as f: | |
| content = f.read() | |
| raw_prompts = content.split('*') | |
| prompts = [p.replace('\n', ' ').replace('\r', ' ').strip() for p in raw_prompts if p.strip()] | |
| if not prompts: | |
| return [], None, None, "⚠️ ERROR: INVALID FORMAT. USE *PROMPT*.", gr.update(visible=False), [], [], 1, "" | |
| session_dir = tempfile.mkdtemp() | |
| with open(os.path.join(session_dir, "prompts.txt"), "w", encoding="utf-8") as f: | |
| f.write("\n".join(prompts)) | |
| res = process_chunk(prompts, [], session_dir, randomize_seed, 1) | |
| return (*res, session_dir) | |
| def continue_batch_wrapper(state_remaining, state_all_files, state_session_dir, randomize_seed, state_batch_num): | |
| res = process_chunk(state_remaining, state_all_files, state_session_dir, randomize_seed, state_batch_num) | |
| return (*res, state_session_dir) | |
| # ========================================== | |
| # 5. The Cyberpunk HUD CSS | |
| # ========================================== | |
| custom_css = """ | |
| body, .gradio-container, .main { | |
| background-color: #050505 !important; | |
| background-image: linear-gradient(rgba(255, 0, 60, 0.05) 1px, transparent 1px), linear-gradient(90deg, rgba(255, 0, 60, 0.05) 1px, transparent 1px) !important; | |
| background-size: 20px 20px !important; | |
| color: #ff3333 !important; | |
| font-family: 'Courier New', monospace !important; | |
| } | |
| .block, .form, .wrap, fieldset, .panel { background: transparent !important; border: none !important; box-shadow: none !important; } | |
| .glass-panel { | |
| background: rgba(15, 0, 0, 0.7) !important; | |
| backdrop-filter: blur(10px) !important; | |
| border: 1px solid rgba(255, 0, 60, 0.3) !important; | |
| box-shadow: 0 0 15px rgba(255, 0, 60, 0.1), inset 0 0 20px rgba(255, 0, 60, 0.05) !important; | |
| border-radius: 4px !important; | |
| margin-bottom: 15px !important; | |
| padding: 15px !important; | |
| } | |
| h1, h2, h3, .prose h1, .prose h3 { color: #ff003c !important; text-transform: uppercase !important; letter-spacing: 2px !important; text-shadow: 0 0 10px rgba(255, 0, 60, 0.7) !important; text-align: center !important; } | |
| .gr-radio-group { display: flex !important; flex-direction: row !important; gap: 10px !important; width: 100% !important; background: transparent !important; justify-content: center !important; } | |
| .gr-radio-group .wrap { display: flex !important; flex-direction: row !important; gap: 10px !important; width: 100% !important; background: transparent !important; } | |
| .gr-radio-group label { background: rgba(30, 0, 0, 0.8) !important; border: 1px solid #550000 !important; color: #ff6666 !important; padding: 10px 15px !important; border-radius: 4px !important; cursor: pointer !important; flex: 1 !important; text-align: center !important; transition: all 0.3s !important; box-shadow: none !important; } | |
| .gr-radio-group label.selected { background: rgba(255, 0, 60, 0.2) !important; border-color: #ff003c !important; color: #ffffff !important; box-shadow: 0 0 15px #ff003c !important; } | |
| .gr-radio-group input[type="radio"] { display: none !important; } | |
| input[type="checkbox"] { accent-color: #ff003c !important; background-color: #000 !important; border: 1px solid #ff003c !important; } | |
| button.primary, .gr-button-primary { background: linear-gradient(90deg, #550000, #ff003c, #550000) !important; background-size: 200% auto !important; border: 1px solid #ff003c !important; color: #ffffff !important; box-shadow: 0 0 15px rgba(255, 0, 60, 0.5) !important; font-weight: bold !important; text-transform: uppercase !important; letter-spacing: 2px !important; transition: 0.5s !important; } | |
| button.primary:hover, .gr-button-primary:hover { background-position: right center !important; box-shadow: 0 0 30px #ff003c !important; } | |
| textarea, input[type="text"], input[type="number"] { background: rgba(0, 0, 0, 0.9) !important; border: 1px solid #800000 !important; color: #ff003c !important; font-family: monospace !important; box-shadow: inset 0 0 10px rgba(255,0,0,0.2) !important; } | |
| textarea:focus, input:focus { border-color: #ff003c !important; box-shadow: 0 0 15px #ff003c !important; } | |
| .file-preview { border: 1px dashed #ff003c !important; background: rgba(10, 0, 0, 0.8) !important; } | |
| footer { display: none !important; } | |
| """ | |
| # ========================================== | |
| # 6. Gradio UI Construction | |
| # ========================================== | |
| with gr.Blocks(theme=gr.themes.Base(), css=custom_css, title="Aparna's High-Speed ImageGen") as demo: | |
| with gr.Column(elem_classes="glass-panel"): | |
| gr.Markdown("# ⬡ APARNA'S HIGH-SPEED IMAGEGEN ⬡\n*SYSTEM STATUS: ONLINE // AWAITING INPUT*") | |
| mode_selector = gr.Radio(choices=["🖼️ SINGLE IMAGE", "📦 BATCH GENERATE"], value="🖼️ SINGLE IMAGE", label="SELECT OPERATION MODE", interactive=True, elem_classes="gr-radio-group") | |
| # --- SINGLE MODE --- | |
| with gr.Column(visible=True, elem_classes="glass-panel") as single_view: | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| single_prompt = gr.Textbox(label="PROMPT INPUT", placeholder="Enter target description...", lines=4) | |
| with gr.Accordion("⚙️ SYSTEM PARAMETERS", open=False): | |
| single_randomize = gr.Checkbox(label="RANDOMIZE SEED", value=True) | |
| single_seed = gr.Number(label="MANUAL SEED", value=42, precision=0) | |
| single_btn = gr.Button("⚡ INITIALIZE GENERATION", variant="primary") | |
| with gr.Column(scale=1): | |
| single_output_img = gr.Image(label="VISUAL OUTPUT", interactive=False) | |
| single_status = gr.Textbox(label="SYSTEM LOG", interactive=False) | |
| single_btn.click(fn=generate_one_ui, inputs=[single_prompt, single_randomize, single_seed], outputs=[single_output_img, single_status]) | |
| # --- BATCH MODE --- | |
| with gr.Column(visible=False, elem_classes="glass-panel") as batch_view: | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| # Instructions are now safe inside a collapsible Accordion! | |
| with gr.Accordion("📁 HOW TO BATCH GENERATE: (Click to Expand and Read the Steps)", open=False): | |
| gr.Markdown( | |
| """ | |
| **STEP 1:** Open your phone's Notes app or any text editor. | |
| **STEP 2:** Type your prompts. You must wrap **every single prompt** in asterisks (`*`). | |
| **Example:** `*A cyberpunk city* *A glowing dragon* *A neon forest*` | |
| **STEP 3:** Save the file as a `.txt` file and upload it below. | |
| ⚠️ **SYSTEM LIMIT:** The GPU processes **10 images at a time** to prevent crashing. | |
| After the first 10, click the **"▶️ CONTINUE NEXT 10"** button and it will start generating the next 10 if your txt has more than 10 images. At the very end, you will get a **FULL ARCHIVE ZIP** with everything inside it in order! | |
| """ | |
| ) | |
| txt_input = gr.File(label="UPLOAD TXT FILE", file_types=[".txt"]) | |
| randomize_cb = gr.Checkbox(label="RANDOMIZE SEED", value=True) | |
| with gr.Row(): | |
| run_btn = gr.Button("⚡ START BATCH", variant="primary") | |
| continue_btn = gr.Button("▶️ CONTINUE NEXT 10", variant="primary", visible=False) | |
| with gr.Column(scale=1): | |
| status_text = gr.Textbox(label="SYSTEM LOG", interactive=False, lines=3) | |
| with gr.Row(): | |
| zip_chunk = gr.File(label="BATCH ZIP", interactive=False) | |
| zip_full = gr.File(label="FULL ARCHIVE ZIP", interactive=False, visible=False) | |
| gallery_output = gr.Gallery(label="LIVE PREVIEW", columns=4, visible=True) | |
| # Hidden State Variables | |
| state_remaining = gr.State([]) | |
| state_all_files = gr.State([]) | |
| state_session_dir = gr.State("") | |
| state_batch_num = gr.State(1) | |
| # Event Handlers | |
| outputs_list = [gallery_output, zip_chunk, zip_full, status_text, continue_btn, state_remaining, state_all_files, state_batch_num, state_session_dir] | |
| run_btn.click(fn=start_batch_wrapper, inputs=[txt_input, randomize_cb], outputs=outputs_list) | |
| continue_btn.click(fn=continue_batch_wrapper, inputs=[state_remaining, state_all_files, state_session_dir, randomize_cb, state_batch_num], outputs=outputs_list) | |
| # --- THE SWITCH LOGIC --- | |
| def toggle_view(mode): | |
| if mode == "🖼️ SINGLE IMAGE": | |
| return gr.update(visible=True), gr.update(visible=False) | |
| else: | |
| return gr.update(visible=False), gr.update(visible=True) | |
| mode_selector.change(fn=toggle_view, inputs=[mode_selector], outputs=[single_view, batch_view]) | |
| if __name__ == "__main__": | |
| demo.launch(footer_links=[]) |