multimodalart HF Staff commited on
Commit
3664cbf
·
verified ·
1 Parent(s): 998b3e0

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +131 -0
app.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+ import gradio as gr
4
+ import numpy as np
5
+ import spaces
6
+ import torch
7
+ from diffusers import DiffusionPipeline
8
+
9
+ MODEL_NAME = "NucleusAI/Nucleus-Image"
10
+ MAX_SEED = np.iinfo(np.int32).max
11
+
12
+ dtype = torch.bfloat16
13
+ device = "cuda" if torch.cuda.is_available() else "cpu"
14
+
15
+ # Load pipeline at startup (weights downloaded once, moved to GPU inside the @spaces.GPU function)
16
+ pipe = DiffusionPipeline.from_pretrained(MODEL_NAME, torch_dtype=dtype)
17
+
18
+ # Try to enable Text KV cache (optional — falls back gracefully if unavailable)
19
+ try:
20
+ from diffusers import TextKVCacheConfig
21
+ config = TextKVCacheConfig()
22
+ pipe.transformer.enable_cache(config)
23
+ print("Text KV cache enabled.")
24
+ except Exception as e:
25
+ print(f"Text KV cache not enabled: {e}")
26
+
27
+ pipe.to(device)
28
+
29
+ ASPECT_RATIOS = {
30
+ "1:1 (1024x1024)": (1024, 1024),
31
+ "16:9 (1344x768)": (1344, 768),
32
+ "9:16 (768x1344)": (768, 1344),
33
+ "4:3 (1184x896)": (1184, 896),
34
+ "3:4 (896x1184)": (896, 1184),
35
+ "3:2 (1248x832)": (1248, 832),
36
+ "2:3 (832x1248)": (832, 1248),
37
+ }
38
+
39
+
40
+ @spaces.GPU(duration=120)
41
+ def generate(
42
+ prompt: str,
43
+ aspect_ratio: str,
44
+ num_inference_steps: int,
45
+ guidance_scale: float,
46
+ seed: int,
47
+ randomize_seed: bool,
48
+ progress=gr.Progress(track_tqdm=True),
49
+ ):
50
+ if not prompt or not prompt.strip():
51
+ raise gr.Error("Please enter a prompt.")
52
+
53
+ if randomize_seed:
54
+ seed = random.randint(0, MAX_SEED)
55
+
56
+ width, height = ASPECT_RATIOS[aspect_ratio]
57
+ generator = torch.Generator(device=device).manual_seed(int(seed))
58
+
59
+ image = pipe(
60
+ prompt=prompt,
61
+ width=width,
62
+ height=height,
63
+ num_inference_steps=int(num_inference_steps),
64
+ guidance_scale=float(guidance_scale),
65
+ generator=generator,
66
+ ).images[0]
67
+
68
+ return image, seed
69
+
70
+
71
+ EXAMPLES = [
72
+ "A weathered lighthouse on a rocky coastline at golden hour, waves crashing against the rocks below, seagulls circling overhead, dramatic clouds painted in shades of amber and violet",
73
+ "A cozy cabin in a snowy pine forest at night, warm light glowing from the windows, aurora borealis dancing in the sky above",
74
+ "A futuristic cyberpunk city street at night, neon signs reflecting in puddles, flying cars, dense fog, cinematic lighting",
75
+ "A tiny astronaut exploring a giant mushroom forest on an alien planet, bioluminescent plants, dreamlike atmosphere, highly detailed",
76
+ "Portrait of a wise old wizard with a long white beard, intricate robes, holding a glowing crystal staff, fantasy art, painterly style",
77
+ ]
78
+
79
+ CSS = """
80
+ #col-container { max-width: 960px; margin: 0 auto; }
81
+ """
82
+
83
+ with gr.Blocks(css=CSS, theme=gr.themes.Soft()) as demo:
84
+ with gr.Column(elem_id="col-container"):
85
+ gr.Markdown(
86
+ """
87
+ # 🖼️ Nucleus-Image (ZeroGPU)
88
+ Generate images with [`NucleusAI/Nucleus-Image`](https://huggingface.co/NucleusAI/Nucleus-Image).
89
+ """
90
+ )
91
+
92
+ with gr.Row():
93
+ prompt = gr.Textbox(
94
+ label="Prompt",
95
+ placeholder="Describe the image you want to generate...",
96
+ lines=3,
97
+ scale=4,
98
+ )
99
+ run_btn = gr.Button("Generate", variant="primary", scale=1)
100
+
101
+ result = gr.Image(label="Result", show_label=False, format="png")
102
+
103
+ with gr.Accordion("Advanced Settings", open=False):
104
+ aspect_ratio = gr.Dropdown(
105
+ label="Aspect Ratio",
106
+ choices=list(ASPECT_RATIOS.keys()),
107
+ value="16:9 (1344x768)",
108
+ )
109
+ with gr.Row():
110
+ num_inference_steps = gr.Slider(
111
+ label="Inference Steps", minimum=10, maximum=80, step=1, value=50
112
+ )
113
+ guidance_scale = gr.Slider(
114
+ label="Guidance Scale", minimum=1.0, maximum=15.0, step=0.5, value=8.0
115
+ )
116
+ with gr.Row():
117
+ seed = gr.Slider(
118
+ label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=42
119
+ )
120
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
121
+
122
+ gr.Examples(examples=EXAMPLES, inputs=prompt, label="Example prompts")
123
+
124
+ inputs = [prompt, aspect_ratio, num_inference_steps, guidance_scale, seed, randomize_seed]
125
+ outputs = [result, seed]
126
+
127
+ run_btn.click(generate, inputs=inputs, outputs=outputs)
128
+ prompt.submit(generate, inputs=inputs, outputs=outputs)
129
+
130
+ if __name__ == "__main__":
131
+ demo.queue().launch()