Wasi8 commited on
Commit
6c41afa
·
verified ·
1 Parent(s): af0c8c4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +156 -132
app.py CHANGED
@@ -1,154 +1,178 @@
 
 
 
 
 
1
  import gradio as gr
2
- import numpy as np
3
- import random
4
 
5
- # import spaces #[uncomment to use ZeroGPU]
6
- from diffusers import DiffusionPipeline
7
  import torch
8
-
9
- device = "cuda" if torch.cuda.is_available() else "cpu"
10
- model_repo_id = "stabilityai/sdxl-turbo" # Replace to the model you would like to use
11
-
12
- if torch.cuda.is_available():
13
- torch_dtype = torch.float16
14
- else:
15
- torch_dtype = torch.float32
16
-
17
- pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype)
18
- pipe = pipe.to(device)
19
-
20
- MAX_SEED = np.iinfo(np.int32).max
21
- MAX_IMAGE_SIZE = 1024
22
-
23
-
24
- # @spaces.GPU #[uncomment to use ZeroGPU]
25
- def infer(
26
- prompt,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  negative_prompt,
28
- seed,
29
- randomize_seed,
30
  width,
31
  height,
32
  guidance_scale,
33
  num_inference_steps,
34
- progress=gr.Progress(track_tqdm=True),
 
35
  ):
36
- if randomize_seed:
37
- seed = random.randint(0, MAX_SEED)
38
-
39
- generator = torch.Generator().manual_seed(seed)
40
-
41
- image = pipe(
42
- prompt=prompt,
43
- negative_prompt=negative_prompt,
44
- guidance_scale=guidance_scale,
45
- num_inference_steps=num_inference_steps,
46
- width=width,
47
- height=height,
48
- generator=generator,
49
- ).images[0]
50
-
51
- return image, seed
52
-
53
-
54
- examples = [
55
- "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
56
- "An astronaut riding a green horse",
57
- "A delicious ceviche cheesecake slice",
58
- ]
59
-
60
- css = """
61
- #col-container {
62
- margin: 0 auto;
63
- max-width: 640px;
64
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  """
66
 
67
- with gr.Blocks(css=css) as demo:
68
- with gr.Column(elem_id="col-container"):
69
- gr.Markdown(" # Text-to-Image Gradio Template")
70
-
71
- with gr.Row():
72
- prompt = gr.Text(
73
- label="Prompt",
74
- show_label=False,
75
- max_lines=1,
76
- placeholder="Enter your prompt",
77
- container=False,
78
- )
79
-
80
- run_button = gr.Button("Run", scale=0, variant="primary")
81
 
82
- result = gr.Image(label="Result", show_label=False)
83
-
84
- with gr.Accordion("Advanced Settings", open=False):
85
- negative_prompt = gr.Text(
86
- label="Negative prompt",
87
- max_lines=1,
88
- placeholder="Enter a negative prompt",
89
- visible=False,
90
  )
91
-
92
- seed = gr.Slider(
93
- label="Seed",
94
- minimum=0,
95
- maximum=MAX_SEED,
96
- step=1,
97
- value=0,
 
 
 
 
 
 
 
 
 
 
98
  )
99
-
100
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
101
 
102
  with gr.Row():
103
- width = gr.Slider(
104
- label="Width",
105
- minimum=256,
106
- maximum=MAX_IMAGE_SIZE,
107
- step=32,
108
- value=1024, # Replace with defaults that work for your model
109
- )
110
-
111
- height = gr.Slider(
112
- label="Height",
113
- minimum=256,
114
- maximum=MAX_IMAGE_SIZE,
115
- step=32,
116
- value=1024, # Replace with defaults that work for your model
117
- )
118
 
119
  with gr.Row():
120
- guidance_scale = gr.Slider(
121
- label="Guidance scale",
122
- minimum=0.0,
123
- maximum=10.0,
124
- step=0.1,
125
- value=0.0, # Replace with defaults that work for your model
126
- )
127
-
128
- num_inference_steps = gr.Slider(
129
- label="Number of inference steps",
130
- minimum=1,
131
- maximum=50,
132
- step=1,
133
- value=2, # Replace with defaults that work for your model
134
- )
135
-
136
- gr.Examples(examples=examples, inputs=[prompt])
137
- gr.on(
138
- triggers=[run_button.click, prompt.submit],
139
- fn=infer,
140
- inputs=[
141
- prompt,
142
- negative_prompt,
143
- seed,
144
- randomize_seed,
145
- width,
146
- height,
147
- guidance_scale,
148
- num_inference_steps,
149
- ],
150
- outputs=[result, seed],
151
  )
152
 
153
  if __name__ == "__main__":
154
  demo.launch()
 
 
1
+ import os
2
+ import io
3
+ import zipfile
4
+ from datetime import datetime
5
+
6
  import gradio as gr
7
+ from PIL import Image
 
8
 
 
 
9
  import torch
10
+ from diffusers import AutoPipelineForText2Image, DPMSolverMultistepScheduler
11
+
12
+ # --------- Helper: load model ----------
13
+ @torch.inference_mode()
14
+ def load_pipeline(model_id: str, torch_dtype=torch.float16, device=None):
15
+ pipe = AutoPipelineForText2Image.from_pretrained(
16
+ model_id,
17
+ torch_dtype=torch_dtype,
18
+ use_safetensors=True
19
+ )
20
+ pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
21
+ if device is None:
22
+ device = "cuda" if torch.cuda.is_available() else "cpu"
23
+ pipe = pipe.to(device)
24
+ # small memory tweaks
25
+ if device == "cuda":
26
+ pipe.enable_attention_slicing()
27
+ pipe.enable_vae_slicing()
28
+ return pipe, device
29
+
30
+ # Cache of loaded models so switching is fast
31
+ _PIPELINES = {}
32
+
33
+ def get_pipe(model_id: str):
34
+ if model_id not in _PIPELINES:
35
+ _PIPELINES[model_id], _ = load_pipeline(model_id)
36
+ return _PIPELINES[model_id]
37
+
38
+ # --------- Core generation ----------
39
+ def parse_prompts(text: str):
40
+ # Split by comma, strip whitespace, drop empties
41
+ parts = [p.strip() for p in text.split(",")]
42
+ return [p for p in parts if p]
43
+
44
+ def generate_images(
45
+ prompts_text,
46
  negative_prompt,
47
+ model_id,
 
48
  width,
49
  height,
50
  guidance_scale,
51
  num_inference_steps,
52
+ batch_per_prompt,
53
+ seed
54
  ):
55
+ prompts = parse_prompts(prompts_text)
56
+ if not prompts:
57
+ return [], None, "Please enter at least one prompt (use commas to separate)."
58
+
59
+ pipe = get_pipe(model_id)
60
+
61
+ # Seeding
62
+ if seed is None or str(seed).strip() == "":
63
+ generator = torch.Generator(device=pipe.device).manual_seed(torch.seed())
64
+ else:
65
+ try:
66
+ seed_val = int(seed)
67
+ except:
68
+ seed_val = torch.seed()
69
+ generator = torch.Generator(device=pipe.device).manual_seed(seed_val)
70
+
71
+ all_images = []
72
+ names = []
73
+ for i, p in enumerate(prompts, start=1):
74
+ images = pipe(
75
+ prompt=p,
76
+ negative_prompt=negative_prompt if negative_prompt else None,
77
+ width=width,
78
+ height=height,
79
+ guidance_scale=guidance_scale,
80
+ num_inference_steps=num_inference_steps,
81
+ num_images_per_prompt=batch_per_prompt,
82
+ generator=generator
83
+ ).images
84
+
85
+ # Collect and name
86
+ for j, img in enumerate(images, start=1):
87
+ all_images.append(img)
88
+ safe_prompt = "".join(c for c in p[:40] if c.isalnum() or c in "-_ ").strip().replace(" ", "_")
89
+ if not safe_prompt:
90
+ safe_prompt = f"prompt_{i}"
91
+ names.append(f"{safe_prompt}_{j}.png")
92
+
93
+ # Build ZIP in-memory
94
+ buf = io.BytesIO()
95
+ with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
96
+ for img, name in zip(all_images, names):
97
+ bio = io.BytesIO()
98
+ img.save(bio, format="PNG")
99
+ bio.seek(0)
100
+ zf.writestr(name, bio.read())
101
+ buf.seek(0)
102
+
103
+ zip_name = f"images_{datetime.now().strftime('%Y%m%d_%H%M%S')}.zip"
104
+ return all_images, (zip_name, buf), f"Generated {len(all_images)} image(s) from {len(prompts)} prompt(s)."
105
+
106
+ # --------- UI ----------
107
+ CSS = """
108
+ .gradio-container {max-width: 1100px !important}
109
  """
110
 
111
+ with gr.Blocks(css=CSS, theme=gr.themes.Soft()) as demo:
112
+ gr.Markdown("# 🖼️ Multi-Prompt Text-to-Image (Hugging Face Space)")
113
+ gr.Markdown("Enter **comma-separated prompts** to generate multiple images at once. Choose size, batch count, and download all results as a ZIP.")
 
 
 
 
 
 
 
 
 
 
 
114
 
115
+ with gr.Row():
116
+ with gr.Column():
117
+ prompts_text = gr.Textbox(
118
+ label="Prompts (comma-separated)",
119
+ placeholder="A futuristic city at sunset, A cozy cabin in the woods, A portrait of a cyberpunk samurai",
120
+ lines=4
 
 
121
  )
122
+ negative_prompt = gr.Textbox(
123
+ label="Negative prompt (optional)",
124
+ placeholder="blurry, low quality, distorted"
125
+ )
126
+ model_id = gr.Dropdown(
127
+ label="Model",
128
+ value="stabilityai/sdxl-turbo",
129
+ choices=[
130
+ "stabilityai/sdxl-turbo", # very fast SDXL
131
+ "runwayml/stable-diffusion-v1-5",
132
+ "stabilityai/stable-diffusion-2-1"
133
+ ]
134
+ )
135
+ size = gr.Dropdown(
136
+ label="Image Size",
137
+ value="1024x1024",
138
+ choices=["512x512", "768x768", "1024x1024", "768x1024 (portrait)", "1024x768 (landscape)"]
139
  )
 
 
140
 
141
  with gr.Row():
142
+ guidance_scale = gr.Slider(0.0, 12.0, value=2.0, step=0.5, label="Guidance scale (SDXL-Turbo likes low)")
143
+ steps = gr.Slider(2, 50, value=8, step=1, label="Steps")
 
 
 
 
 
 
 
 
 
 
 
 
 
144
 
145
  with gr.Row():
146
+ batch_per_prompt = gr.Slider(1, 6, value=2, step=1, label="Images per prompt")
147
+ seed = gr.Textbox(label="Seed (optional, integer)")
148
+
149
+ run_btn = gr.Button("Generate", variant="primary")
150
+
151
+ with gr.Column():
152
+ gallery = gr.Gallery(label="Results", show_label=True, columns=3, height=520)
153
+ zip_file = gr.File(label="Download all images (.zip)")
154
+ status = gr.Markdown("")
155
+
156
+ def on_size_change(s):
157
+ if "x" in s and s.count("x") == 1 and "(" not in s:
158
+ w, h = s.split("x")
159
+ return int(w), int(h)
160
+ if s == "768x1024 (portrait)":
161
+ return 768, 1024
162
+ if s == "1024x768 (landscape)":
163
+ return 1024, 768
164
+ return 1024, 1024
165
+
166
+ width = gr.State(1024)
167
+ height = gr.State(1024)
168
+ size.change(fn=on_size_change, inputs=size, outputs=[width, height])
169
+
170
+ run_btn.click(
171
+ fn=generate_images,
172
+ inputs=[prompts_text, negative_prompt, model_id, width, height, guidance_scale, steps, batch_per_prompt, seed],
173
+ outputs=[gallery, zip_file, status]
 
 
 
174
  )
175
 
176
  if __name__ == "__main__":
177
  demo.launch()
178
+