Team Ai
Apppublic

anycoderapps/Z-Image-Turbo

sourceHugging Faceupdated 10mo agoView on Hugging Face
237likes
app.py360 linesDownload Raw Back to root
1import spaces2import gradio as gr3import torch4from diffusers import ZImagePipeline5import os6from pathlib import Path7 8# Load the model directly at startup9print("Loading Z-Image Turbo model...")10print("This may take a few minutes on first run while the model downloads...")11 12 13# Load the pipeline with optimal settings14pipe = ZImagePipeline.from_pretrained(15    "Tongyi-MAI/Z-Image-Turbo",16    torch_dtype=torch.bfloat16,17    low_cpu_mem_usage=False,18)19    20# Move to GPU if available21device = "cuda" if torch.cuda.is_available() else "cpu"22pipe.to(device)23print(f"Model loaded on {device}")24    25print("Model loaded successfully!")26 27@spaces.GPU()28def generate_image(29    prompt,30    progress=gr.Progress(track_tqdm=True)31):32    """33    Generate an image using Z-Image Turbo model.34    35    Args:36        prompt: Text description of the desired image37    38    Returns:39        Generated PIL Image40    """41    global pipe42    43    if pipe is None:44        raise gr.Error("Model failed to load on startup. Please restart the application.")45    46    if not prompt.strip():47        raise gr.Error("Please enter a prompt to generate an image.")48    49    # Determine device50    device = "cuda" if torch.cuda.is_available() else "cpu"51    52    # Set random seed for reproducibility53    generator = torch.Generator(device).manual_seed(42)54    55    # Generate the image with optimal settings56    progress(0.1, desc="Generating image...")57    58    try:59        result = pipe(60            prompt=prompt,61            negative_prompt=None,62            height=1024,63            width=1024,64            num_inference_steps=9,65            guidance_scale=0.0,66            generator=generator,67        )68        69        image = result.images[0]70        progress(1.0, desc="Complete!")71        72        return image73    74    except Exception as e:75        raise gr.Error(f"Generation failed: {str(e)}")76 77# Apple-style CSS78apple_css = """79/* Global Styles */80.gradio-container {81    max-width: 980px !important;82    margin: 0 auto !important;83    padding: 48px 20px !important;84    font-family: -apple-system, BlinkMacSystemFont, 'Inter', 'Segoe UI', 'Roboto', sans-serif !important;85}86 87/* Header */88.header-container {89    text-align: center;90    margin-bottom: 48px;91}92 93.main-title {94    font-size: 56px !important;95    font-weight: 600 !important;96    letter-spacing: -0.02em !important;97    line-height: 1.07 !important;98    color: #1d1d1f !important;99    margin: 0 0 12px 0 !important;100}101 102.subtitle {103    font-size: 21px !important;104    font-weight: 400 !important;105    line-height: 1.38 !important;106    color: #6e6e73 !important;107    margin: 0 0 24px 0 !important;108}109 110.attribution-link {111    display: inline-block;112    font-size: 14px !important;113    color: #0071e3 !important;114    text-decoration: none !important;115    font-weight: 400 !important;116    transition: color 0.2s ease !important;117}118 119.attribution-link:hover {120    color: #0077ed !important;121    text-decoration: underline !important;122}123 124/* Input Section */125.input-section {126    background: #ffffff;127    border-radius: 18px;128    padding: 32px;129    margin-bottom: 24px;130    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);131}132 133/* Textbox */134textarea {135    font-size: 17px !important;136    line-height: 1.47 !important;137    border-radius: 12px !important;138    border: 1px solid #d2d2d7 !important;139    padding: 12px 16px !important;140    transition: all 0.2s ease !important;141    background: #ffffff !important;142    font-family: -apple-system, BlinkMacSystemFont, 'Inter', sans-serif !important;143}144 145textarea:focus {146    border-color: #0071e3 !important;147    box-shadow: 0 0 0 4px rgba(0, 113, 227, 0.15) !important;148    outline: none !important;149}150 151textarea::placeholder {152    color: #86868b !important;153}154 155/* Button */156button.primary {157    font-size: 17px !important;158    font-weight: 400 !important;159    padding: 12px 32px !important;160    border-radius: 980px !important;161    background: #0071e3 !important;162    border: none !important;163    color: #ffffff !important;164    min-height: 44px !important;165    transition: all 0.2s ease !important;166    letter-spacing: -0.01em !important;167    cursor: pointer !important;168}169 170button.primary:hover {171    background: #0077ed !important;172    transform: scale(1.02) !important;173}174 175button.primary:active {176    transform: scale(0.98) !important;177}178 179/* Output Section */180.output-section {181    background: #ffffff;182    border-radius: 18px;183    padding: 32px;184    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);185    overflow: hidden;186}187 188.output-section img {189    border-radius: 12px !important;190    width: 100% !important;191    height: auto !important;192}193 194/* Footer */195.footer-text {196    text-align: center;197    margin-top: 48px;198    font-size: 14px !important;199    color: #86868b !important;200    line-height: 1.43 !important;201}202 203/* Progress */204.progress-bar {205    background: #0071e3 !important;206    border-radius: 4px !important;207}208 209/* Dark Mode */210.dark .main-title {211    color: #f5f5f7 !important;212}213 214.dark .subtitle {215    color: #a1a1a6 !important;216}217 218.dark .input-section,219.dark .output-section {220    background: #1d1d1f;221    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.4);222}223 224.dark textarea {225    background: #1d1d1f !important;226    border-color: #424245 !important;227    color: #f5f5f7 !important;228}229 230.dark textarea::placeholder {231    color: #86868b !important;232}233 234/* Responsive */235@media (max-width: 734px) {236    .main-title {237        font-size: 40px !important;238    }239    240    .subtitle {241        font-size: 19px !important;242    }243    244    .gradio-container {245        padding: 32px 16px !important;246    }247    248    .input-section,249    .output-section {250        padding: 24px !important;251    }252}253 254/* Remove default Gradio styling */255.contain {256    padding: 0 !important;257}258"""259 260# Create the interface261with gr.Blocks(262    title="Z-Image Turbo",263    fill_height=False,264) as demo:265    266    # Header267    gr.HTML("""268        <div class="header-container">269            <h1 class="main-title">Z-Image Turbo</h1>270            <p class="subtitle">Transform your ideas into stunning visuals with AI</p>271            <a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank" class="attribution-link">272                Built with anycoder273            </a>274        </div>275    """)276    277    # Input Section278    with gr.Column(elem_classes="input-section"):279        prompt = gr.Textbox(280            placeholder="Describe the image you want to create...",281            lines=3,282            max_lines=6,283            label="",284            show_label=False,285            container=False,286        )287        288        generate_btn = gr.Button(289            "Generate",290            variant="primary",291            size="lg",292            elem_classes="primary"293        )294    295    # Output Section296    with gr.Column(elem_classes="output-section"):297        output_image = gr.Image(298            type="pil",299            label="",300            show_label=False,301            container=False,302            buttons=["download"],303        )304    305    # Footer306    gr.HTML("""307        <div class="footer-text">308            <p>Powered by Z-Image Turbo from Tongyi-MAI</p>309        </div>310    """)311    312    # Event handlers313    generate_btn.click(314        fn=generate_image,315        inputs=prompt,316        outputs=output_image,317        api_visibility="public"318    )319    320    prompt.submit(321        fn=generate_image,322        inputs=prompt,323        outputs=output_image,324        api_visibility="public"325    )326 327if __name__ == "__main__":328    demo.launch(329        share=False,330        show_error=True,331        theme=gr.themes.Soft(332            primary_hue=gr.themes.colors.blue,333            secondary_hue=gr.themes.colors.slate,334            neutral_hue=gr.themes.colors.gray,335            spacing_size=gr.themes.sizes.spacing_lg,336            radius_size=gr.themes.sizes.radius_lg,337            text_size=gr.themes.sizes.text_md,338            font=[gr.themes.GoogleFont("Inter"), "SF Pro Display", "-apple-system", "BlinkMacSystemFont", "system-ui", "sans-serif"],339            font_mono=[gr.themes.GoogleFont("JetBrains Mono"), "SF Mono", "ui-monospace", "monospace"],340        ).set(341            body_background_fill='#f5f5f7',342            body_background_fill_dark='#000000',343            button_primary_background_fill='#0071e3',344            button_primary_background_fill_hover='#0077ed',345            button_primary_text_color='#ffffff',346            block_background_fill='#ffffff',347            block_background_fill_dark='#1d1d1f',348            block_border_width='0px',349            block_shadow='0 2px 12px rgba(0, 0, 0, 0.08)',350            block_shadow_dark='0 2px 12px rgba(0, 0, 0, 0.4)',351            input_background_fill='#ffffff',352            input_background_fill_dark='#1d1d1f',353            input_border_width='1px',354            input_border_color='#d2d2d7',355            input_border_color_dark='#424245',356            input_shadow='none',357            input_shadow_focus='0 0 0 4px rgba(0, 113, 227, 0.15)',358        ),359        css=apple_css,360    )